Logistics Service

Guides (don't use)

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

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)

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)


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:

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

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):

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:

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

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

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
└ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘

4.2 Escrow + delivery codes (proof of handover)

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):

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

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

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:


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):

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.

Guides (don't use)

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:

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:

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

3.2 File format (what the seeder reads)

{
  "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
-- 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

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

4.2 Config

# 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).


5. Database

5.1 Entity relationships

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)

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):

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.

{
  "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)
-- 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

7.2 Buyer addresses

7.3 Recent locations

7.4 Orders / snapshots

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

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
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
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)

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:


11. Client behaviour (Android · iOS · Web)

11.1 Location permission

┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
┆           📍                  ┆
   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

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

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)


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


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.
Guides (don't use)

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)

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

Agreement rules

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 , " (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).

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

4.5 Estimation

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

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)

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

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

Installments


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


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

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

On the ride

Control

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

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)

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)

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

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

8.3 Fees


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

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):

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


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

12.2 When money moves

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


14. Reviews, reliability, auto-pause


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.

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"

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

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


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
Guides (don't use)

# 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

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.

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.

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.

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.

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.

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.

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.

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.

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

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)

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

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

Check: scenarios J and K.

Step 12 — Free shipping

Check: scenario I; campaign budget never overspent under parallel checkouts; refund returns budget.

Step 13 — Bolt integration

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

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:


Standard Response Format

Success

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

Error (coded refusal)

{
  "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).

Field Type Description
success boolean true for success, false for errors
httpStatus string HTTP status name
message string Human-readable result, safe to show
action_time string When the response was made
data object/string Payload, or error details

HTTP Method Badge Standards


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)

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:

level identified by
REGION regionCode
DISTRICT regionCode + districtCode
WARD wardId

1.4 Two kinds of places people own

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

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:

{
  "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:

{ "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


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: GET {base_url}/locations/resolve

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

Authentication: Bearer token

Query Parameters:

Parameter Type Required Description Validation Default
lat number Yes Latitude of the pin -90 … 90, not 0,0 —
lng number Yes Longitude of the pin -180 … 180 —

Success Response JSON Sample (covered):

{
  "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:

Field Description
covered false = no ward within 500 m: disable Confirm
matchType CONTAINED inside a ward, NEAREST just outside one (≤ 500 m)
distanceM metres to the ward when NEAREST
ward the ward with its district and region
areaLabel the name to show: "Ward, District, Region"
reason only when not covered

Errors: INVALID_COORDINATES, WARD_DATA_UNAVAILABLE.


2. List regions

Purpose: First level of the area picker.

Endpoint: GET {base_url}/locations/regions

Access Level: 🔒 Protected

Success Response JSON Sample:

{
  "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: GET {base_url}/locations/regions/{regionCode}/districts

Access Level: 🔒 Protected

Path Parameters:

Parameter Type Required Description
regionCode string Yes e.g. 07

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


4. List a district's wards

Endpoint: GET {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.


5. Search areas

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

Endpoint: GET {base_url}/locations/areas/search?q=sin

Access Level: 🔒 Protected

Query Parameters:

Parameter Type Required Description Validation
q string Yes Part of a region, district or ward name at least 2 letters

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

[
  { "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: PUT {base_url}/e-commerce/shops/{shopId}/location

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

Request JSON Sample:

{
  "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:

Parameter Type Required Description Validation
lat / lng number Yes The pin must be inside a ward (or ≤ 500 m)
landmark string Yes How to find the shop max 300
building string No Building / shop number max 100
officialAddress string No Anwani za Makazi max 100
deviceLat / deviceLng number No The phone's own position, only to warn when the pin is far —

Success Response (message "Shop location saved"): the shop location (as in Get), 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: GET {base_url}/e-commerce/shops/{shopId}/location

Access Level: 🌐 Public (no login)

Success Response JSON Sample:

{
  "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: GET {base_url}/locations/addresses

Access Level: 🔒 Protected (own addresses only)

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

[
  {
    "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: POST {base_url}/locations/addresses

Access Level: 🔒 Protected

Request JSON Sample:

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

Request Body Parameters:

Parameter Type Required Description Validation
lat / lng number Yes The pin inside a ward
labelType enum Yes HOME, WORK, OTHER HOME / WORK once each
customLabel string for OTHER The name for an OTHER address max 40
directions string No How to find the place max 300
makeDefault boolean No Make it the default —
allowNearDuplicate boolean No Save even if within 50 m of another address —

Success Response: the saved address (shape as in My addresses).

Rules:

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


10. Edit an address

Endpoint: PUT {base_url}/locations/addresses/{addressId}

Access Level: 🔒 Protected (own address)

Same body and rules as Save — send the whole address. Orders already placed are not affected.


11. Delete an address

Endpoint: DELETE {base_url}/locations/addresses/{addressId}

Access Level: 🔒 Protected (own address)


12. Make an address the default

Endpoint: POST {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: GET {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:

Access Level: 🔒 Protected


Part 3 — Codes and values

Error codes (HTTP 409, data.code)

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

Values

Value Meaning
MatchType CONTAINED / NEAREST pin inside a ward / within 500 m of one
AddressLabel HOME / WORK / OTHER HOME and WORK once each; OTHER needs customLabel
PlaceSource where a snapshot came from: SHOP_LOCATION, SAVED_ADDRESS, RECENT, NEW_PIN, STATION
AreaLevel REGION / DISTRICT / WARD the three kinds of area

Limits

Limit Value
Nearest-ward distance 500 m
Saved addresses per user 10
Recent pins per user / kept 5 / 60 days
Same place (duplicate / recent refresh) 50 m
Shop pin far from the phone (warning) 1 km
Area search results 20

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.

Hints:


Standard Response Format

Success

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

Error (coded refusal)

{
  "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" }
}
Field Type Description
success boolean true for success, false for errors
httpStatus string HTTP status name
message string Human-readable result, safe to show
action_time string When the response was made
data object/string Payload, or { code, reason, details? } for a coded refusal

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


Contents


Part 1 — How shipping works

1.1 The people

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

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 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)
Stage Endpoint Rules
Estimation POST /shipping/estimations one call per list screen with the header "Deliver to"; cached ~1 h per pair of wards; cost = range of the sensible options
Quotation POST /shipping/quotations 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
Cart PUT /e-commerce/cart/destination, PUT /e-commerce/cart/shops/{shopId}/fulfillment defaults below
Agreement checkout session (commerce_logistics_changes.md §11c, §33) 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

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

The buyer has… The shop's parcel is
a destination and a shipper covers it Delivery with the pre-selected option
a destination, nobody covers it Pickup + notice "Delivery is not available to X yet"
no destination Pickup + notice "Add a delivery address to see delivery options"

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

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 & 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:

Route kind How leg 1 starts
STATION_COLLECTS the station business fetches it from the shop itself (it ticks where it collects + a flat fee, 0 = free)
DOOR_TO_STATION a door shipper takes it shop → origin station, then the station business carries it on

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

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".

1.10 Codes and the parcel number

Parcel number NX-4K7P-2Q 4-digit codes
Purpose identifies the parcel (on the box, QR) proves a handover
Secret no yes — hashed, never logged
How many one per parcel, for life (kept when switching pickup ↔ delivery) one per handover
Who sees it buyer, seller, every shipper on the route, station staff only the holder

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

Handover Holder (gets the SMS) Types it Endpoint
Pickup at the shop buyer (receiver) seller POST /shipping/orders/{id}/collect
Shop → shipper shipper (owner's phone) seller POST /shipping/orders/{id}/hand-over
Shipper → shipper / station the receiving rider / station counter the giver POST /shipping/jobs/{id}/hand-over-next
Door delivery receiver rider POST /shipping/jobs/{id}/deliver
Collect at a station buyer station staff (last leg) POST /shipping/jobs/{id}/deliver

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 (⭐ / 💰 / ⚡):

Found What happens
same price or cheaper, and not later takes over by itself; the difference is refunded; buyer notified (SHIPPER_CHANGED)
dearer, slower, nobody, or already 3 changes on this order the buyer decides (fulfillment.decision)

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

reason Means
NO_SHIPPER nobody can take it
COSTS_MORE / SLOWER the replacement is dearer / later
TOO_MANY_CHANGES 3 replacements already on this order
WAITING_TOO_LONG still no shipper 24 h after Ready
PARCEL_TOO_BIG a shipper found it bulky at the shop (§1.13)
choices Does
USE_NEW_SHIPPER pay the difference from the wallet (WALLET_INSUFFICIENT if short; negative = money back)
KEEP_WAITING only for WAITING_TOO_LONG; not asked again for 24 h
PICKUP delivery refunded, the order becomes a pickup order (READY, code by SMS)
END_AT_STATION station route whose last door leg failed: collect at that station, the leg refunded
CANCEL everything refunded

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

Action Allowed while Money
Cancel the whole order PLACED (before the seller accepts), or the delivery is stuck (no shipper / a decision waiting) everything refunded
Switch to pickup delivery, until a shipper accepts (PLACED / ACCEPTED / READY) delivery refunded in full
Switch to delivery pickup, until collected (PLACED / ACCEPTED / READY) delivery paid from the wallet
Change the delivery address until a shipper accepts; max 3 changes per order difference paid / refunded

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):

Reason Then
TOO_BIG 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
BADLY_PACKED back to ACCEPTED; the seller repacks and taps Ready again → the same shipper gets a fresh offer

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):

Signal ⚠ Warning ⏸ Paused (owner resumes) ⛔ Suspended (admin lifts)
Offers missed in a row 2 3 —
Automatic pauses — — 3rd within 7 days
Acceptance rate (last 20 offers) < 50% < 30% —
Broke an accepted job (admin finding) — 1st 2nd within 30 days
Found at fault in a problem (admin finding) 1st — 2 within 30 days
False "too big" claims — — 3
On time (last 20 jobs) < 60% — —

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

1.18 Timers (run by the backend)

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

1.19 Notifications

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

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

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

1.20 Admin

Role Can
STAFF_ADMIN 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
SUPER_ADMIN all of that + anything with money or settings: escrow release / refund, order cancel, commission changes, Bolt on/off, coverage, invoices, ride state (test modes)

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: POST {base_url}/shipping/estimations

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

Request JSON Sample:

{
  "dropoff": { "addressId": "9b1d0c2e-…" },
  "productIds": ["5f0e…", "77a1…"]
}
Parameter Type Required Description
dropoff object Yes the header "Deliver to" — a drop-off (location doc §1.6)
productIds array Yes products on screen (TOO_MANY_PRODUCTS above the limit)

Success Response JSON Sample:

{
  "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" }
    ]
  }
}
Field Description
status DELIVERY (cost + eta) · PICKUP_ONLY (no shipper; show pickupArea) · DIGITAL · UNAVAILABLE
cost what the buyer pays (after campaigns), cheapest → dearest of the sensible options
freeDelivery the cheapest shown option is free
campaign badge "Delivery from 7,000 3,500 · Shop + NexGate pay part" (absent without a campaign)

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: POST {base_url}/shipping/quotations

Access Level: 🔒 Protected (buyer) · Bearer token

Request JSON Sample (sheet):

{
  "items": [ { "productId": "5f0e…", "quantity": 2 } ],
  "includeCart": true,
  "dropoff": { "lat": -6.7735, "lng": 39.2187 },
  "preview": false
}
Parameter Type Required Description
items array one of items / shopId products of one shop (PRODUCTS_FROM_DIFFERENT_SHOPS), quantity 1–1000, max 50 lines
shopId UUID without items the cart page: quote what is in the cart from this shop
includeCart boolean No add what the buyer already has in the cart from this shop (needed so the quotation fits the cart)
dropoff object Yes where to (location doc §1.6)
preview boolean No product page: compute only, nothing saved, no quotationId

Success Response JSON Sample:

{
  "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:

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

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: GET {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: PUT {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: GET {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"):

[ { "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: POST {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: PUT {base_url}/e-commerce/cart/destination

Access Level: 🔒 Protected (buyer)

Request JSON Sample:

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

Success Response JSON Sample (the delivery change):

{
  "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: POST {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: PUT {base_url}/e-commerce/cart/shops/{shopId}/fulfillment

Access Level: 🔒 Protected (buyer)

Request JSON Sample:

{ "type": "DELIVERY", "quotationId": "3c1f…", "optionId": "o-2" }
Parameter Type Required Description
type enum Yes PICKUP or DELIVERY
quotationId / optionId UUID No the option picked in the list; DELIVERY alone = the default shipper

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):

{
  "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" } } } ]
}
Field Shown when
status always — Part 4
parcelNumber from the seller's accept
delivery delivery orders: the shipper, price breakdown, window, route, campaign offer
pickupTime pickup: the buyer's planned time
collectBy / acceptBy collection deadline / seller's accept deadline
needsShipperSince a shipper said no; "We're finding a new shipper"
decision the buyer must choose (§1.11)
refusal a shipper refused the parcel at the shop (§1.13)
code 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
rider Bolt: driver card (§1.9)
shippers name + phone per leg once its shipper accepted (not for Bolt)
headingAt, pickedUpAt, deliveredAt, collectedAt, completedAt, closedAt + closeReason, problemReportedAt each step's time

C1. Accept the order (seller)

Endpoint: POST {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 & ready (seller)

Endpoint: POST {base_url}/shipping/orders/{orderId}/ready

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

Request JSON Sample:

{ "packedWell": true, "labelOnPackage": true }
Parameter Type Required Description
packedWell boolean delivery: Yes "I have packed it well"
labelOnPackage boolean delivery: Yes "the parcel number / label is on the package"

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: PUT {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: POST {base_url}/shipping/orders/{orderId}/code

Access Level: 🔒 Protected (the buyer)

Success Response JSON Sample:

{
  "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: POST {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: POST {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: POST {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: POST {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: POST {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.

Order is Result Message
COMPLETED, within problemReportUntil Recorded for admins, no money moves "Problem reported; our team will review it"
DELIVERED (Bolt) Every part frozen; an admin settles it with escrow release / refund "Problem reported; payment is on hold"

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: POST {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: POST {base_url}/shipping/orders/{orderId}/switch-to-delivery

Access Level: 🔒 Protected (the buyer)

Request JSON Sample:

{
  "quotationId": "3c1f…", "optionId": "o-1",
  "dropoff": { "addressId": "9b1d…" },
  "receiver": { "name": "Mama Json", "phone": "0712345678" },
  "note": "Call when you arrive"
}
Parameter Type Required Description
quotationId / optionId UUID Yes from C10
dropoff object Yes the same drop-off as in C10
receiver object No omit = the buyer
note string No max 300

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: POST {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: POST {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: POST {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: POST {base_url}/shipping/orders/{orderId}/cancel

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

Request JSON Sample (seller):

{ "informedBuyer": true, "reason": "Out of stock in this size" }
Parameter Type Required Description
informedBuyer boolean seller: Yes the pop-up "I have already informed the buyer"
reason string No max 500

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: GET {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:

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


E. Shipper profile and reviews (anyone logged in)

E1. Public shipper profile

Endpoint: GET {base_url}/shipping/businesses/{businessId}/public

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

Success Response JSON Sample:

{
  "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

Endpoint Does
POST {base_url}/shipping/businesses/{businessId}/reviews write a review
PUT {base_url}/shipping/businesses/{businessId}/reviews edit my review
DELETE {base_url}/shipping/businesses/{businessId}/reviews delete my review
GET {base_url}/shipping/businesses/{businessId}/reviews reviews with text
GET {base_url}/shipping/businesses/{businessId}/reviews/paged?page=1&size=10 paged
GET {base_url}/shipping/businesses/{businessId}/reviews/my-review mine
GET {base_url}/shipping/businesses/{businessId}/reviews/summary average + 1..5 distribution
POST {base_url}/shipping/businesses/{businessId}/reviews/{reviewId}/reply owner reply { "replyText": "…" } (max 1000)

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

Review JSON Sample:

{ "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: POST {base_url}/shipping/businesses

Access Level: 🔒 Protected (any user)

Request JSON Sample:

{
  "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" }
}
Parameter Type Required Description Validation
name string Yes business name max 100
contactPhone string Yes the phone buyers and sellers call valid TZ phone
office object Yes the office pin (lat, lng, landmark ≤300, building ≤100) inside a ward
businessLicence object Yes fileId (File Thunder, business document), number (unique), expiresOn number ≤60
directorNida object Yes fileId, number 20 digits
latraLicence object Yes fileId, number, expiresOn

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: GET {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

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


F4. Get the business (owner / admin)

Endpoint: GET {base_url}/shipping/businesses/{businessId}

Success Response JSON Sample:

{
  "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

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: GET {base_url}/shipping/businesses/{businessId}/reliability

Success Response JSON Sample:

{
  "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: GET …/setup

{ "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

PUT …/setup/profile — { "logoFileId": "…", "description": "…" (≤500), "whatsapp": "…", "email": "…" } → the business. Errors: LOGO_INVALID, PHONE_INVALID.

G3. Service type

PUT …/setup/service-type — { "door": true, "station": false } → the business. Errors: SERVICE_TYPE_REQUIRED.

G4. Limits

PUT …/setup/limits

{ "maxParcelValue": 2000000, "acceptsBulky": true, "bulkyExtra": 3000,
  "responseWindowMinutes": 30, "headsUp": true, "stationReachKm": 30 }
Parameter Description Validation
maxParcelValue most valuable parcel it carries (null = no limit) ≥ 0
acceptsBulky / bulkyExtra carries bulky parcels, and the extra charged (0 = none) extra required when bulky (BULKY_EXTRA_REQUIRED)
responseWindowMinutes time to answer an offer 5–120, default 30
headsUp non-binding "order coming" notices default on
stationReachKm station businesses: how far buyers may be to collect 1–200, default 30

G5. Working hours

{
  "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

Request JSON Sample:

{
  "trips": "WITHIN_AND_ACROSS",
  "areas": [ { "level": "REGION", "regionCode": "07" },
             { "level": "DISTRICT", "regionCode": "05", "districtCode": "03" },
             { "level": "WARD", "wardId": 1146 } ]
}
Parameter Description
trips WITHIN_EACH — both ends in the same ticked area · WITHIN_AND_ACROSS — both ends in any ticked areas
areas up to 100, from the location area picker (location doc §1.3)

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

Request JSON Sample (bands + value ladder):

{
  "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 } ]
}
Parameter Description Validation
mode BANDS (by distance) or FLAT
bands each starts where the previous ends (first at 0 km); the last toKm = max distance ≤10, toKm 0.1–500, price ≥1, minutes 5–10080
flat { "price", "minMinutes", "maxMinutes" } — price 0 only with a value ladder (value-only pricing)
valueAddons insurance ladder by parcel value: a fixed amount per step, a percent allowed on the open top step ≤10

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/…

Endpoint Does
POST …/stations add a station
GET …/stations list
PUT …/stations/{stationId} edit
DELETE …/stations/{stationId} remove
PUT …/stations/{stationId}/hours the station's own hours (same body as G5)
PUT …/station-prices · GET …/station-prices the pair price table
PUT …/collection collection from shops

Station request:

{ "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):

{ "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:

{ "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:

{
  "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"]
}
Field Description
valueBand UP_TO_50K, UP_TO_500K, ABOVE_500K — never the exact value
from / to areas only, until accepted
details exact places, receiver and note — only after the shipper accepted
cost / commission / payout / payoutStatus its price, NexGate's cut, what it gets, and whether held / released / refunded
stage Upcoming only: WAITING_FOR_SELLER, SELLER_PACKING
signature its party state on the deal: PENDING, SIGNED, DECLINED, WITHDRAWN
rated parties it already rated privately

I1. Lists

Endpoint Shows
GET {base_url}/shipping/businesses/{businessId}/upcoming?page=1&size=20 paid parcels coming its way, before any offer
GET {base_url}/shipping/businesses/{businessId}/offers?page=1&size=20 open offers with a countdown
GET {base_url}/shipping/businesses/{businessId}/jobs?status=ACTIVE&page=1&size=20 ACTIVE (accepted, not done) or DONE
GET {base_url}/shipping/businesses/{businessId}/earnings?page=1&size=20 { held, released, refunded, jobs }
GET {base_url}/shipping/jobs/{jobId} one job

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: POST {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:

{
  "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: POST {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

Step Endpoint Body Who / when
Heading to the shop POST …/shipping/jobs/{jobId}/heading — the leg collecting at the shop, after accepting
Check the parcel POST …/shipping/jobs/{jobId}/check-parcel { "parcelNumber": "NX-4K7P-2Q" } at the shop or a handover, before the code; → { "yours": true, "message": "✓ this parcel is yours" }
Deliver POST …/shipping/jobs/{jobId}/deliver { "code": "4821" } last leg: the receiver's code at the door, or the buyer's code at the station (AT_STATION)
Hand to the next leg POST …/shipping/jobs/{jobId}/hand-over-next { "code": "…" } the giver types the next rider's / station counter's code
Arrived at the station POST …/shipping/jobs/{jobId}/arrived — station leg at its destination station → AT_STATION, sends the next code
New pickup code POST …/shipping/jobs/{jobId}/code — the leg collecting at the shop lost its code, before or after tapping heading → message "New pickup code sent"
My handover code POST …/shipping/jobs/{jobId}/handover-code — a receiving leg / station: show its handover code once (+SMS)

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: POST {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: POST {base_url}/shipping/jobs/{jobId}/rate

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

Field Values
party SELLER (after the hand-over), BUYER (after delivery)
score 1–5
issue buyer: WRONG_ADDRESS, NOT_REACHABLE, NO_SHOW · seller: LATE_HANDOVER, BADLY_PACKED · both: RUDE, OTHER (needs a note)

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


J. Bolt webhook (Bolt only)

POST {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.

Endpoint Role Does
GET …/businesses?status=&integrated=&regionCode=&districtCode=&wardId=&search=&from=&to=&page=1&size=20 staff shippers list (with adminStats { from, to, earned, held, deliveries, rating }, default last 30 days)
GET …/businesses/{businessId}/overview?from=&to= staff one shipper's page: business, coverage, stations, reliability, stats, jobs { active, delivered, missed }
GET …/businesses/{businessId}/reliability staff as F6, for admins
POST …/businesses/{businessId}/suspend · /lift staff stop / restart a shipper (the reason is shown to it)
GET …/businesses/{businessId}/commission staff { source: BUSINESS | PLATFORM, calculation, value, history }
PUT …/businesses/{businessId}/commission super { "percent": 5, "effectiveFrom": "…", "reason": "…" } — percent null = back to the platform rate; never in the past (COMMISSION_IN_PAST, COMMISSION_ORDER)
GET …/documents/expiring?days=30 staff KYC documents expired or expiring, soonest first (daysLeft < 0 = expired)
GET …/operations staff 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 }
GET …/notes?targetType=ORDER|BUSINESS&targetId= · POST …/notes staff internal notes { targetType, targetId, text } (≤1000), with the admin's name
GET …/reports?groupBy=REGION|DISTRICT|WARD&regionCode=&districtCode=&from=&to= staff by area only: total, areas[] { code, name, deliveries, pickups, onTimeRate, averageCost, boltSpend }, top 10 shippers
GET …/campaigns?creator=&status=&page=&size= staff every campaign + totals (campaigns doc)
GET …/accounts/{accountId}/party-ratings staff what shippers privately said about an account, as buyer and as seller
POST …/refusals/{refusalId}/false-claim staff a "too big" refusal was false → strike (NOT_A_BULKY_CLAIM)
PUT …/reviews/{reviewId}/status staff { "status": "HIDDEN", "reason": "…" }
POST …/orders/{orderId}/reassign staff take the job from the shipper (between Ready and pickup), find another (REASSIGN_NOT_ALLOWED, NOT_DELIVERY)
POST …/orders/{orderId}/cancel super cancel while the parcel is at the shop; everything refunded (a shipper heading keeps 50%) — after it left: ADMIN_USE_ESCROW_ACTIONS
POST …/escrows/{escrowId}/release · /refund super settle a stuck / reported order part by hand (ESCROW_STATE, ESCROW_NOT_ON_ORDER)

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/…

Endpoint Role Does
GET …/providers staff providers with status, connection, coverage, spent today vs daily limit
PUT …/providers/{businessId}/coverage super { "coverage": { "trips", "areas" }, "reason" } — where Bolt is offered
POST …/providers/{businessId}/on · /off super the kill-switch (COVERAGE_REQUIRED before on)
GET …/providers/bolt/rides?page=1&size=20 staff rides: states, times, held price vs Bolt's receipt (difference), rider
POST …/providers/bolt/rides/{rideId}/state super test modes only: move a ride { "state": "DRIVER_ON_ROUTE_TO_CLIENT" } (BOLT_LIVE)
GET …/providers/bolt/status staff mode, on/off, limit vs spent today, live / stuck / problem rides, owed, this month paid / receipts / kept, lastWebhookAt
GET …/providers/bolt/invoices staff recorded invoices
POST …/providers/bolt/invoices super { "invoiceNumber", "from", "to", "amount", "note" } → with our ledgerAmount and difference (INVOICE_ALREADY_RECORDED, INVOICE_PERIOD_INVALID)
POST …/providers/bolt/invoices/{invoiceId}/pay super { "reference": "<bank ref>", "reason" } — difference settled with revenue, then the bill paid out of PROVIDER-BOLT; paying twice changes nothing (INVOICE_CANNOT_BE_PAID)

K3. Audit log

GET {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)

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

4.2 Agreement status (backend; shown through the order)

DRAFT PENDING AGREED DONE CANCELLED
checkout, editable paid, waiting for seller / shippers to sign everyone signed buyer confirmed refunded

4.3 Other values

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

4.4 Fixed rules (backend settings)

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

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.

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

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.

Hints:


Standard Response Format

Success

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

Error (coded refusal)

{
  "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)" }
}
Field Type Description
success boolean true for success, false for errors
httpStatus string HTTP status name
message string Human-readable result, safe to show
action_time string When the response was made
data object/string Payload, or { code, reason, details? }

HTTP Method Badge Standards


Part 1 — How campaigns work

1.1 Who can run what

Creator Covers Kinds Money comes from Who manages it
SHIPPER its own deliveries, from any shop PERCENT, FIXED (no FREE; free delivery = PERCENT 100) nowhere — it simply charges less the business owner only (not admins)
SELLER deliveries of its own shop's orders FREE, PERCENT, FIXED the order's own items money, at payment the shop owner (or a super admin)
NEXGATE deliveries of any shop, or chosen shops FREE, PERCENT, FIXED a pot held in escrow, funded from SHIPPING-CAMPAIGNS super admins
Kind Means Applies to
FREE the whole delivery, up to a cap per order the cheapest qualifying option becomes free; a faster one costs the buyer the difference
PERCENT value% of the delivery, optional cap the option the buyer picks
FIXED value TZS off the option the buyer picks

1.2 Who qualifies

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

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.

Field Means Example Left out Who can use it
minOrder the buyer's items from this shop must add up to at least this; delivery is not counted 45,000 in the cart → no campaign; 60,000 → applies any order size qualifies everyone
perBuyerLimit how many orders one buyer can use this campaign on; a refunded order gives its use back 2 → the third order pays delivery as normal unlimited everyone
cap the most the campaign pays on one order delivery 4,000 → free; delivery 7,000 → buyer pays 2,000 no limit per order everyone; required for a seller's FREE / PERCENT
spendLimit the most the seller or shipper gives away across all orders; nothing is set aside, it only counts 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 not allowed — required (CAMPAIGN_LIMIT_REQUIRED) seller and shipper (NexGate uses budget)

What each is useful for

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.

Field left out Means
cap no limit per order (not allowed for a seller's FREE / PERCENT)
minOrder any order size qualifies
perBuyerLimit one buyer can use it on every order
startsAt starts now
areas every destination
fromAreas shipper: parcels starting anywhere
shopIds NexGate: every shop
productIds seller: every product of the shop
excludedProductIds seller: no product left out
audience EVERYONE

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.
Case Seller NexGate Buyer
6,000 · seller 50% · NexGate 30% 3,000 1,800 1,200
10,000 · seller 50% at most 3,000 · NexGate 30% 3,000 3,000 4,000
6,000 · seller 70% · NexGate 50% 4,200 1,800 (trimmed) 0 · Free
8,000, shipper 25% off → 6,000 · seller 50% · NexGate 30% 3,000 1,800 1,200 (the shipper earns 6,000)
6,000 · NexGate 50% but the pot holds 1,000 — 0 (full share or nothing) 6,000

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):

"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 }
  ]
}
Field Meaning
listPrice the shipper's table price (= cost.total)
price after the shipper's own discount — what the shipper is paid
shares who pays part of price; a SHIPPER share is the discount (not money)
buyerPays the rest

Product cards show a badge from the estimation's campaign field: { "listFrom": 7000, "paidBy": ["SELLER", "NEXGATE"] } → "Delivery from 7,000 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:

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 ──────┘

1.6 One order, start to finish

Stage What happens
Estimation (card) badge only — matching campaigns, nothing exact, nothing held
Quotation (sheet / cart / checkout) the rules run on every option; best campaign per creator; the quotation remembers which it used; nothing held
Payment 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
Recorded buyer · seller · NexGate amounts frozen on the delivery escrow — they drive every refund and report
Delivered + confirmed the shipper gets its full price; the seller gets items minus its share (commission on the full items price)

1.7 After payment

Change Campaign money
Address change (before a shipper accepts) 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
Cheaper shipper on reassignment the difference comes back in proportion (pot, seller's items part, buyer)
Dearer shipper shares stay; the buyer pays the extra
Switch to pickup / cancel / refund every share goes back where it came from; the buyer gets back all they paid
Pickup → delivery after payment campaigns apply like at checkout (CAMPAIGN_ENDED possible)
Admin cancel while the rider is heading the 50% wasted trip is paid pro rata by everyone in the delivery part

Where a NexGate share goes on a refund:

Campaign state at refund NexGate's share Seller's limit
Running / Paused back to the pot restored
Ran out back to the pot → Running again restored
Ended / Cancelled back to the pot, moved on to SHIPPING-CAMPAIGNS within a minute nothing to do

1.8 Installments and group purchase

1.9 States

status (stored) state (shown) Means
SCHEDULED SCHEDULED starts later (startsAt)
RUNNING RUNNING / RAN_OUT live; RAN_OUT = pot empty or spending limit used up
PAUSED PAUSED stopped by the creator; resume any time
ENDED ENDED the end date passed (timer, every minute)
CANCELLED CANCELLED stopped for good by the creator

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: POST {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):

{
  "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):

{
  "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):

{
  "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:

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

Success Response JSON Sample:

{
  "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:

Field Description
state §1.9
numbers orders and buyers that used it; givenAway (net of refunds), returned
pot NexGate only: funded, used, returned, left
limit seller and shipper: { limit, used }
endedAt when it ended / was stopped

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: GET {base_url}/shipping/campaigns?creator=SELLER&shopId=…

Access Level: 🔒 Protected (same as create)

Query Parameters:

Parameter Type Required Description
creator enum Yes SELLER, SHIPPER, NEXGATE
shopId UUID SELLER the shop
businessId UUID SHIPPER the business

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


3. Get / edit one campaign

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: GET {base_url}/shipping/campaigns/{campaignId}/uses?page=1&size=20

Access Level: 🔒 Protected (whoever runs it)

Success Response data (a page, newest first):

{ "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

Endpoint Does
POST {base_url}/shipping/campaigns/{campaignId}/pause stops for new orders; paid orders keep it; idempotent
POST {base_url}/shipping/campaigns/{campaignId}/resume back to RUNNING (or SCHEDULED); idempotent
POST {base_url}/shipping/campaigns/{campaignId}/stop CANCELLED for good; a NexGate pot's leftover goes back to SHIPPING-CAMPAIGNS at once

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


6. Top up a NexGate pot

Endpoint: POST {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: GET {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:

{
  "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.

Endpoint Does
GET …/system-accounts PLATFORM-REVENUE, SHIPPING-CAMPAIGNS, PROVIDER-BOLT, … with balances; revenue also shows putIn (owner top-ups) and transferredOut
GET …/system-accounts/{accountNumber}/entries?page=1&size=20 history: { entryNumber, type, direction: IN | OUT, amount, other, description, metadata, at }
POST …/system-accounts/top-up real money NexGate put in → PLATFORM-REVENUE: { "amount": 1000000, "reference": "<bank / M-Pesa id>", "reason": "…" } — record only when the money really arrived
POST …/system-accounts/transfer { "fromAccount": "PLATFORM-REVENUE", "toAccount": "SHIPPING-CAMPAIGNS", "amount": 500000, "reason": "…" } — the only allowed pair for now

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

Value Options
CampaignCreator SHIPPER, SELLER, NEXGATE (also the stacking order)
CampaignKind FREE, PERCENT, FIXED
CampaignAudience EVERYONE, FIRST_ORDER
CampaignStatus (filter) SCHEDULED, RUNNING, PAUSED, ENDED, CANCELLED
CampaignState (shown) the statuses + RAN_OUT
Code When
CAMPAIGN_KIND_NOT_ALLOWED a shipper asked for FREE
CAMPAIGN_VALUE_INVALID FREE with a value, a percent outside 1–100, FIXED without an amount
CAMPAIGN_CAP_REQUIRED a seller FREE / PERCENT without a cap
CAMPAIGN_CAP_ABOVE_MINIMUM a seller's cap (or fixed amount) is bigger than the minimum order after commission
CAMPAIGN_END_REQUIRED a campaign without an end date
CAMPAIGN_LIMIT_REQUIRED a seller or shipper campaign without a spendLimit
CAMPAIGN_DATES_INVALID end not after the start, or in the past
CAMPAIGN_FIELD_NOT_ALLOWED a field this creator cannot use (from areas, shops, products; a spending limit on NexGate)
CAMPAIGN_BUDGET_REQUIRED a NexGate campaign without a budget
CAMPAIGN_BUDGET_LOW SHIPPING-CAMPAIGNS holds less than the budget / top-up (message says how much)
CAMPAIGN_CLOSED editing, pausing, resuming or topping up an ended / cancelled campaign
CAMPAIGN_CREATOR_FIXED changing creator on edit
CAMPAIGN_HAS_NO_POT top-up on a seller / shipper campaign
CAMPAIGN_ENDED at payment: a campaign ended, ran out or no longer fits since checkout (details = { shopId, businessId, businessName, before, after })
SHOP_REQUIRED / BUSINESS_REQUIRED seller / shipper campaign without its shop / business
NOT_YOUR_SHOP / NOT_YOUR_BUSINESS / ADMIN_ONLY not allowed to run this creator's campaigns
AREA_NOT_FOUND · SHOP_NOT_FOUND · PRODUCT_NOT_IN_SHOP a bad area, shop or product id
REFERENCE_ALREADY_USED · TRANSFER_NOT_ALLOWED · INSUFFICIENT_BALANCE system accounts

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

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

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

Badge Means App must act?
NEW a new endpoint, field or notification only to use the new feature
CHANGED an existing endpoint gained fields or behaves differently; old calls still work should update
BREAKING old calls fail or give a different meaning — a field removed or renamed, a rule tightened must update before the deploy date
REMOVED the endpoint / field / notification is gone must stop using it
FIX a bug fixed; same shape, now correct values check screens that relied on the wrong value

HTTP methods

Rules this log follows


0. At a glance

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

0.1 Breaking changes — do these first

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

0.2 Removed

Service Endpoint / field / notification Use instead Section
Shops request + response fields city, region, streetAddress, landmark, latitude, longitude location (shop location) §1.2–§1.4
Checkout shippingAddressId, shippingMethodId (request) · shippingAddress, shippingMethod (response) fulfillment §4.2, §4.3
Orders deliveryAddress, trackingNumber, carrier (detail) · trackingNumber on /ship fulfillment §5.2
Installments shippingAddress on the agreement fulfillment §6.1

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

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

After

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

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

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


1.2 BREAKING Create / update shop — location fields removed

Endpoint: POST {base_url}/e-commerce/shops · PUT {base_url}/e-commerce/shops/{shopId}

Change BREAKING in meaning — old bodies are still accepted (the fields are ignored) but nothing is saved from them
Impact Must update
Reference commerce_logistics_changes.md §5

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

Request

Field Before After Note
city, region required on create removed
streetAddress, landmark, latitude, longitude optional removed landmark + pin now live in the shop location
phoneNumber, countryCode, the rest unchanged unchanged phoneNumber is also the shop location's phone
BeforeAfter
{
  "shopName": "Mama Yoyo Shop",
  "phoneNumber": "+255744742944",
  "city": "Dar es Salaam",
  "region": "Dar es Salaam",
  "landmark": "Opposite the clock tower"
}
{
  "shopName": "Mama Yoyo Shop",
  "phoneNumber": "+255744742944"
}

App to do


1.3 BREAKING 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.

Change BREAKING — fields removed; new blocks added
Impact Must update
Reference §6, §21

Response

Field Before After Note
streetAddress, city, region present removed
latitude, longitude, landmark present removed
hasLocation — added true / false
location — added same object as GET …/location (location doc §7), or null
availability — added open now / paused / taking orders
BeforeAfter
{
  "shopName": "Mama Yoyo Shop",
  "city": "Dar es Salaam",
  "region": "Dar es Salaam",
  "landmark": "Opposite the clock tower",
  "latitude": -6.819, "longitude": 39.2768
}
{
  "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 } }
}

Behaviour

App to do


1.4 BREAKING Shop search and global search

Endpoint: GET {base_url}/e-commerce/shops/search · GET {base_url}/e-commerce/search?query=…

Response Field Before After
shop search items city owner-typed text removed
shop search items location — added (location object or null)
global search, type: "SHOP" shop.location (string) owner-typed landmark the area name, e.g. "Ubungo, Ubungo, Dar es Salaam", or null

Reference: §7, §8


1.5 CHANGED Shop reviews — the owner's reply is returned

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

Change CHANGED (+ FIX on the rating)
Impact Should update
Reference §31

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

Field Before After
replyText, repliedAt — added (null when no reply)

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


1.6 NEW 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: PUT {base_url}/e-commerce/shops/{shopId}/hours · GET {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):

{
  "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:

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

Success Response JSON Sample (PUT and GET):

{ "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:

Field Description
weekly, specialDays as saved, weekly sorted by day then open time
timeZone always East Africa Time

Errors:

Code / message Status When
HOURS_INVALID 409 a special day listed twice, or not closed and with no hours
"Only the shop owner can change the shop's hours or pause it" 403 not the owner
"This shop has not set its opening hours yet" 404 GET before any hours were saved

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:


1.7 NEW Pause / reopen the shop

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

Endpoint: PUT {base_url}/e-commerce/shops/{shopId}/pause · DELETE {base_url}/e-commerce/shops/{shopId}/pause

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

Authentication: Bearer token

Request JSON Sample (PUT):

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

Request Body Parameters:

Parameter Type Required Description Validation
mode enum Yes STOP_ORDERS — checkout refused with SHOP_CLOSED; KEEP_SELLING — shows "paused" but orders still come in and wait
until datetime with offset No reopens by itself at that time (checked every 5 minutes); leave out = until reopened by hand must be in the future
reason string No shown to buyers ("Paused: Stock taking") max 255

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

{ "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:

Code / message Status When
SHOP_NOT_PAUSABLE 409 the shop is neither ACTIVE nor already paused (e.g. SUSPENDED, PENDING, closed)
"Only the shop owner can change the shop's hours or pause it" 403 not the owner

Rules:

App to do:


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

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

2.2 CHANGED Product responses — shop location

Response Field added
GET …/products/{productId}/detailed (owner) shopLocation
GET …/products/{productId}, by slug (public) shopLocation
shop product lists / filter / search (shop summary block) shop.location

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

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

App to do


2.3 CHANGED Products — bulky

Before After
Create (POST) — optional "bulky": true (default false)
Update (PUT / PATCH) — "bulky" changes it; leaving it out keeps it
Detailed, summary, public responses — "bulky": false | true (next to condition)

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


2.4 FIX Refused product saves / used installment plans

Before (wrong) After (correct)
update + publish with no image → refused "At least one product image is required", but the new name / price were saved a refused create / update / publish / delete / restore changes nothing
deleting an installment plan buyers used → raw database error "Buyers have already used this plan, so it can't be deleted. Deactivate it instead."

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

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

After

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

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

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 CHANGED Add to cart / change / remove an item

Endpoint: POST {base_url}/e-commerce/cart/add · PUT {base_url}/e-commerce/cart/items/{itemId} · DELETE {base_url}/e-commerce/cart/items/{itemId}

Change CHANGED — old bodies still work
Impact Should update
Reference §32

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)

Field Before After Note
productId, quantity required unchanged
fulfillment — added, optional: { type: PICKUP | DELIVERY, quotationId, optionId } the choice from the product sheet
dropoff — added, optional same shape as checkout; only when the buyer changed the address in the sheet — it becomes the cart's address
BeforeAfter
{
  "productId": "5f0e…",
  "quantity": 2
}
{
  "productId": "5f0e…",
  "quantity": 2,
  "fulfillment": { "type": "DELIVERY", "quotationId": "3c1f…", "optionId": "o-1" },
  "dropoff": { "addressId": "9b1d…" }
}

Response (add, change, remove)

Field Before After Note
data null the delivery change { deliveryBefore, deliveryAfter, switchedToPickup, canChangeBack, message, changes }
BeforeAfter
{ "success": true,
  "message": "Product added to cart successfully",
  "data": null }
{ "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": "…" } ] } }

Behaviour

App to do


3.3 CHANGED Get the cart

Endpoint: GET {base_url}/e-commerce/cart

Change CHANGED — fields added; cartItems and totalAmount unchanged (items only)
Impact Should update
Reference §32, §48, §49, §65, §68

Response

Field Before After Note
destination — added the cart's delivery place (pin, areaLabel, label) or null
shops[] — added one per shop with ticked physical items (below)
cartItems[].selected — added the tick
cartSummary.deliveryTotal — added delivery of ticked items, what the buyer pays
cartSummary.totalWithDelivery — added
cartSummary.selectedItems, selectedQuantity, selectedAmount — added ticked items only
cartSummary.selectedTotal — added ticked items + their delivery — the amount to pay

shops[]:

{ "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

App to do


3.4 NEW Tick / untick cart items

Purpose: choose which cart items the next checkout buys.

Endpoint: PUT {base_url}/e-commerce/cart/selection

Access Level: 🔒 Protected (cart owner)

Authentication: Bearer token

Request JSON Sample:

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

Request Body Parameters:

Parameter Type Required Description Validation
itemIds array of uuid Yes one item, a whole shop's items, or every item items of my cart
selected boolean Yes tick (true) or untick (false)

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:


4. Checkout & 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

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

After

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

Change Method Endpoint One line App
BREAKING POST /e-commerce/checkout-sessions fulfillment replaces shippingAddressId / shippingMethodId must update
BREAKING PATCH /e-commerce/checkout-sessions/{id} same must update
BREAKING GET checkout session response fulfillment replaces shippingAddress / shippingMethod; real delivery in pricing must update
CHANGED POST /e-commerce/checkout-sessions/{id}/process-payment, /retry-payment new refusals; deliveryAmount + parts should update
FIX POST same sellerAmount no longer includes the shipper's money check

4.2 BREAKING Create / update a checkout session — fulfillment

Endpoint: POST {base_url}/e-commerce/checkout-sessions · PATCH {base_url}/e-commerce/checkout-sessions/{id}

Change BREAKING — two fields removed; fulfillment required when the session has physical items
Impact Must update before the deploy
Reference §11c, §33, §55, §56

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

Request

Field Before After Note
shippingAddressId fake: any uuid gave "John Doe, 123 Main Street" removed
shippingMethodId fake: always "DHL, Standard Shipping, 0" removed
fulfillment.byShop — added shopId → PICKUP | DELIVERY, one per shop with physical items
fulfillment.deliveries — added shopId → { quotationId, optionId } — the option from the sheet / cart; missing → today's default shipper
fulfillment.dropoff — added required if any shop is DELIVERY — exactly one of addressId / recentId / lat+lng (+ saveAs, customLabel, directions)
fulfillment.receiver — added, optional { name, phone }; omit = me
fulfillment.note — added, optional this order only, max 300
BeforeAfter
{
  "sessionType": "REGULAR_DIRECTLY",
  "items": [ { "productId": "5f0e…", "quantity": 1 } ],
  "shippingAddressId": "1111…",
  "shippingMethodId": "2222…"
}
{
  "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"
  }
}

Behaviour

Errors

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

App to do


4.3 BREAKING Checkout session response — fulfillment and real delivery prices

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

Change BREAKING — two fake blocks removed
Impact Must update
Reference §1, §11c, §33, §53, §65

Response

Field Before After Note
shippingAddress fake John Doe block removed
shippingMethod fake DHL block removed
fulfillment — added shopId → that shop's fulfillment (below)
pricing.shippingByShop — added shopId → delivery, DELIVERY shops only, what the buyer pays
pricing.shippingCost, total shipping always 0 real sum of shippingByShop

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

{ "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": [ … ] } } }

4.4 CHANGED Process / retry payment

Endpoint: POST {base_url}/e-commerce/checkout-sessions/{id}/process-payment · /retry-payment

Change CHANGED + FIX
Impact Should update
Reference §33, §34, §47, §65, §67

Response

Field Before After Note
sellerAmount every held part added together (seller + shipper) the seller's share only FIX
deliveryAmount — added the delivery parts' full value
parts — added [{ escrowId, escrowNumber, part: ITEMS | LEG, orderId, amount }] — one per held part, every shop's order
escrowId, escrowNumber, orderId, amountPaid unchanged
Before (wrong)After (correct)
{ "escrowId": "e1…",
  "amountPaid": 16000.99,
  "sellerAmount": 16000.99 }
{ "escrowId": "e1…",
  "amountPaid": 16000.99,
  "sellerAmount": 1000.99,
  "deliveryAmount": 15000,
  "parts": [ { "part": "ITEMS", "amount": 1000.99, "orderId": "…", "…": "…" },
             { "part": "LEG",   "amount": 15000,   "orderId": "…", "…": "…" } ] }

Behaviour

Errors

Code Status When Before / After
DELIVERY_OPTION_GONE 409 the chosen shipper stopped taking jobs after the session was made — the session stays open: change the shipper with PATCH, pay NEW
CAMPAIGN_ENDED 409 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 NEW
DELIVERY_PRICE_CHANGED 409 now also when only the buyer's part changed CHANGED

App to do


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

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

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

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

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

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 BREAKING Order detail and lists — fulfillment

Endpoint: GET {base_url}/e-commerce/orders/{orderId} and the order lists

Change BREAKING — three fields removed
Impact Must update
Reference §11c, §24, §26, §37–§41, §45, §53, §59, §63

Response

Field Before After Note
deliveryAddress, trackingNumber, carrier text / fake removed
fulfillment — added (detail) the object from §4.3 plus status, steps and times (below)
fulfillmentType — added (lists) PICKUP / DELIVERY, null for digital
fulfillmentStatus — added (lists)
productOrderStatus kept still works; for pickup / shipper orders it follows the fulfillment steps
BeforeAfter
{ "orderNumber": "ORD-2026-94070",
  "productOrderStatus": "SHIPPED",
  "deliveryAddress": "123 Main Street",
  "trackingNumber": "TRACK-8F2A",
  "carrier": "DHL" }
{ "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, "…": "…" } }

fulfillment keys added beyond §4.3

Key Meaning
status 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
parcelNumber, pickupTime parcel number from Accept; buyer's planned pickup time
placedAt, acceptedAt, readyAt, collectedAt, headingAt, pickedUpAt, deliveredAt, completedAt, closedAt step times, absent until set
acceptBy, collectBy deadlines (24 opening hours to accept; 14 days to collect)
closeReason e.g. NOT_ACCEPTED_IN_TIME, NOT_COLLECTED_IN_TIME, ADMIN_REFUNDED, ADMIN_CANCELLED
code { status: ACTIVE | USED | LOCKED | EXPIRED | REPLACED, expiresAt } — detail only, never the code itself
packedConfirmedAt, labelConfirmedAt the seller's Ready ticks
needsShipperSince the shipper said no and a new one is being found
decision the buyer must choose (new shipper costs more, nobody found, …) — shipping doc §1.11
refusal the latest shipper refusal at the shop (TOO_BIG / BADLY_PACKED)
shippers one per leg whose shipper accepted: { leg, businessId, name, phone } (not for Bolt)
rider Bolt only: driverName, driverPhone, driverPicture, plate, vehicleModel, trackingUrl, etaToShopMinutes, state

Behaviour

App to do


5.3 CHANGED Cancel an order

Endpoint: POST {base_url}/e-commerce/orders/{orderId}/cancel

Change CHANGED — rules for pickup orders and orders a shipper delivers
Impact Should update
Reference §25, §34, §43, §69
Who Before After (pickup orders and shipper orders)
Buyer any time before shipped only before the seller accepts (PLACED), or while the delivery has no shipper (needsShipperSince / a decision waiting)
Seller any time before delivered pickup: until collected; delivery: only before Ready. Body { "informedBuyer": true, "reason"? }
Refund the order's single escrow every part (items + delivery), stock back

Old orders without a shipper keep the old rules.

Errors

Code Status When Before / After
CANCEL_NOT_ALLOWED 409 after those windows ("You can switch to pickup instead" / "Contact support to cancel") NEW (was FULFILLMENT_STATE)
INFORM_BUYER_FIRST 409 seller without informedBuyer: true NEW
INSTALLMENT_ORDER 409 an installment order — cancel the agreement instead NEW

App to do


5.4 BREAKING Old ship / confirm-delivery / regenerate-code

Endpoint: POST {base_url}/e-commerce/orders/{orderId}/ship · /confirm-delivery · /regenerate-code

Change BREAKING — refused for most new orders
Impact Must update
Reference §25, §40
Order Before After
Pickup order seller ships, buyer confirms with the code 409 USE_PICKUP_FLOW — use the shipping order actions
Order a shipper delivers — 409 SHIPPER_DELIVERS
Old order without a shipper unchanged (old flow)

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

App to do


5.5 BREAKING 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.

Change BREAKING
Impact Must update
Reference §20, §26
Before After
Length 6 digits 4 digits (confirmationCode must match ^[0-9]{4}$)
Lifetime 30 days 24 hours; a new code kills the old one; max 5 per order per 24 h
Delivery of the code inside the "Order shipped" email / SMS / push its own SMS to the receiver; the bell says "Your delivery code was sent by SMS", never the code
Wrong code HTTP 400 with prose 409 coded refusal, details.triesLeft
Old codes gone — a buyer with a SHIPPED order taps "I lost my code"

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

BeforeAfter
{ "orderId": "…",
  "orderNumber": "ORD-2026-94070",
  "codeSent": true,
  "destination": "email",
  "codeExpiresAt": null,
  "maxAttempts": 5 }
{ "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" }

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

Errors

Code Status When Before / After
CODE_WRONG 409 wrong code; details.triesLeft NEW (was 400)
CODE_LOCKED 409 after 5 wrong tries — even the right code, until a new one is asked for NEW
CODE_NOT_ACTIVE 409 no active code, or already used NEW
CODE_EXPIRED 409 older than 24 h NEW
CODE_LIMIT 409 more than 5 new codes in 24 h NEW

App to do


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.

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

6.1 CHANGED Agreement — fulfillment, layaway, cancel

Field / rule Before After
shippingAddress always empty removed
fulfillment — added (same object as orders)
Layaway (AFTER_PAYMENT) refuses delivery at checkout (LAYAWAY_DELIVERY_LATER); when paid off the order is pickup and the buyer may choose delivery from the order
INSTALLMENT_AGREEMENT_COMPLETED gains nextStep ("Collect it at the shop, or choose delivery in your order." for layaway)
Agreement cancel when the order exists it is cancelled too and everything refunded (down payment, delivery, instalments) — refused once the parcel left the shop
Order cancel on an installment order allowed (left the agreement ACTIVE) refused INSTALLMENT_ORDER everywhere

Reference: §17, §56, §69

6.2 FIX Installment money

Before (wrong) After (correct)
every instalment after the down payment failed to pay (database error) pays normally
confirming delivery released only the down payment + delivery; held instalments stayed held for good every instalment held so far is released; one paid after confirmation goes to the seller at once
early payoff on a 0 % plan crashed "/ by zero" works
a "ships now" plan sometimes never got its order always gets it

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

App to do


7. Group purchase

7.1 CHANGED Group checkout with delivery

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

Reference: §55

App to do


8. Wallet & transactions

8.1 CHANGED Transaction history titles

Where Before After
Buyer, split payment "N sellers" "N parts"
Shipper payout — "Delivery Earnings" ("Payment received for delivery"); type still SALE
Extra delivery payment after ordering — "Delivery Payment"
Money back (cheaper shipper, switch to pickup) — "Refund Received"

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.

Change Method Endpoint One line App
CHANGED PATCH /e-events/drafts/{draftId}/location pin outside Tanzania → OUTSIDE_COVERAGE should update
BREAKING PATCH /e-events/{eventId}/publish, /e-events/{eventId}/published/reveal-location in-person / hybrid needs a pin must update
CHANGED GET event responses venue gains ward, areaLabel, matchType should update
CHANGED POST / PUT / PATCH ticket create / draft update / published update optional donationTarget to use
CHANGED GET ticket details, ticket list, event tickets donation progress on donation tickets should update

9.1 CHANGED Venue — area from the pin

Endpoint: PATCH {base_url}/e-events/drafts/{draftId}/location · event responses

Field Before After
request venue unchanged; venue.coordinates outside Tanzania's wards → OUTSIDE_COVERAGE
response venue.ward, venue.areaLabel, venue.matchType — added (null without a pin)
locationSummary, share preview, ticket / booking location, event on a post or clip typed address the area when no address was typed
"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 BREAKING Publish / reveal location needs a pin

Endpoint: PATCH {base_url}/e-events/{eventId}/publish · {base_url}/e-events/{eventId}/published/reveal-location

Before After
an IN_PERSON / HYBRID event published with a venue name only refused 422 "Drop a pin on the map for the venue" (details.stage LOCATION_DETAILS) without coordinates

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

App to do

9.3 CHANGED Donation target and progress

Endpoint: POST {base_url}/e-events/tickets/{eventId} · PUT {base_url}/e-events/tickets/{ticketId} · PATCH {base_url}/e-events/tickets/{ticketId}/published

Change CHANGED — optional field in, optional block out
Impact To use (the progress bar)
Reference §79

Request

Field Before After Note
donationTarget — added, optional > 0, at most 10 digits + 2 decimals; donation tickets only

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

Field Before After Note
donation — added { target, raised, donations } on donation tickets; null on others; target null when not set
BeforeAfter
{ "name": "Support the choir",
  "ticketPricingType": "DONATION",
  "price": 0.00 }
{ "name": "Support the choir",
  "ticketPricingType": "DONATION",
  "price": 0.00,
  "donation": { "target": 500000.00,
                "raised": 210000.00,
                "donations": 11 } }

Errors

Message Status When
"A donation target can only be set on a donation ticket" 422 donationTarget on a paid / free ticket

App to do


10. Profile & account

10.1 CHANGED Profile cover photo

Endpoint: PUT {base_url}/profile/update · GET {base_url}/profile/me, /profile/id/{userId}, /profile/u/{username}

Change CHANGED — field in, field out
Impact To use
Reference §79
Where Field Before After
PUT /profile/update coverPhotoFileId — added, optional — a File Thunder upload with context COVER_PHOTO
profile responses coverMedia — added — same shape as profileMedia (fileId, status, variants, mimeType), null when not set
BeforeAfter
{ "userName": "joshuasakweli",
  "profileMedia": { "fileId": "…", "status": "READY",
                    "variants": { "thumb": "https://…/thumb.webp" } } }
{ "userName": "joshuasakweli",
  "profileMedia": { "fileId": "…", "status": "READY",
                    "variants": { "thumb": "https://…/thumb.webp" } },
  "coverMedia":   { "fileId": "…", "status": "READY",
                    "variants": { "medium": "https://…/medium.webp",
                                  "large": "https://…/large.webp" } } }

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

App to do

10.2 CHANGED 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:

Key Before After
device.name, device.platform, ipAddress yes unchanged
device.type — Phone / Tablet / Computer
device.browser — e.g. Chrome, Safari, NexGate app
device.os — Windows, macOS, iOS, Android, Linux, ChromeOS
device.location, location — e.g. "Dar es Salaam, TZ" ("Unknown location" when not found)
timestamp — e.g. "Oct 25, 2026 at 8:15 AM EAT"

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 CHANGED Category management is admin only

Endpoint Before After
POST /interests/categories, PUT /{categoryId}, DELETE /{categoryId}, PATCH /{categoryId}/toggle-active, GET /{categoryId}/usage any signed-in user SUPER_ADMIN / STAFF_ADMIN only (403 for others)
GET /interests/categories/all public unchanged

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 FIX Chat avatars and group icons are real links

Endpoint: GET {base_url}/chat/conversations (display.avatar) · group responses (iconMedia: create, get, PUT /chat/groups/{conversationId}/icon)

Before (wrong) After (correct)
variants held storage paths — "thumb": "messages/4a8c…/thumb.webp" — which no image can load "thumb": "https://…/thumb.webp" — full links; same object shape

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


13. Digital downloads

13.1 FIX Files keep their name and type

Endpoint: GET {base_url}/e-commerce/digital-files/my-downloads/{accessId}/url — then the app downloads the returned url

Before (wrong) After (correct)
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) the link answers Content-Disposition: attachment; filename="notes pedi.zip" and the real Content-Type (application/zip, video/mp4, …)

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

App to do


14. Admin dashboard (existing screens)

Change Method Endpoint One line
NEW PUT /admin/shops/reviews/{reviewId}/status moderate a shop review: { "status": "HIDDEN", "reason": "…" } (SUPER_ADMIN, reason required, audit-logged) → { reviewId, shopId, status }
CHANGED GET fees, current + history lists a new fee type DELIVERY_COMMISSION (PERCENTAGE)
CHANGED GET /api/admin/reconciliation/position gains owedToProviders, campaignMoney, ownerTopUps; expectedSelcomFloat includes them
CHANGED GET /api/admin/reconciliation/trial-balance new lines PROVIDER, CAMPAIGN_BUDGET, CAMPAIGN_POT
CHANGED — interest categories management is admin only (§11)

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.

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

16. Error codes index

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

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

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

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