Ziggo / Delivery-first commerce platform / Design package
Multi-vendor commerce · delivery as backbone

A delivery-first commerce & logistics platform

One operating system connecting vendors, customers, and fleets — last-mile bikes to long-haul trucks — across any industry. Medicine, agriculture, hospitality, imported cargo and general retail are seed examples; new industries onboard by configuration, not code. This package is the discovery and design record; no code has been written.

Documents  23 Delivery modes  Last-mile + Long-haul Verticals  Any — 5 seeded, data-driven Build status  Not started As of  2026-07-05

What Ziggo is

Ziggo is a two-sided marketplace welded to a logistics operating system. On one side, many independent vendors list and sell physical goods; on the other, customers order them. What sets Ziggo apart is that delivery is not a bolt-on — it is the core of the product. Most commerce platforms treat "getting the goods there" as someone else's problem. Here, the platform owns the whole chain: it validates the order, prices the delivery, creates delivery jobs, assigns a driver and vehicle, plans the route, tracks every checkpoint, captures proof of delivery, and settles the money — for every order, across every industry.

Because it serves regulated and perishable goods (medicine, fresh produce, hot food, cross-border cargo), the platform is industry-aware by configuration, not by code. A "compliance engine" reads per-industry rules — cold-chain, prescription checks, customs documents, age verification — as data. Onboarding a brand-new industry is an admin data entry task, not a software release. That single design choice is what lets one codebase serve pharmacies, farms, restaurants, and freight forwarders at the same time.

Who uses it

BuyerCustomerBrowses catalogs, orders goods, tracks the shipment live, receives it with proof of handover.
SellerVendor / merchantOnboards their business, publishes catalog & stock, watches orders through to delivery, gets paid out.
FleetDriver / riderReceives assigned jobs, navigates the route, updates status, captures proof of delivery.
ControlDispatcherAssigns jobs to the right fleet, monitors live progress, reroutes on exceptions.
OpsOperations managerRuns the platform day-to-day — vendors, jobs, exceptions, service levels, reporting.
MoneyFinanceOversees payments, commission, vendor & driver payouts, settlement reconciliation.
ConfigAdminManages roles and the industry / compliance rules that drive the whole platform.
CareSupport agentHandles tickets, claims, refunds and replacement workflows.

Two ways goods move

The same platform prices, dispatches, tracks and proves delivery for both movement modes — the difference is in vehicle class, routing, and pricing.

Last-mile
Bikes & small vehicles

Direct, fast, usually one drop. Priced per job on distance + surcharges (cold-chain, off-hours, signature). Assigned to a single rider, typically same-day or scheduled-window.

Long-haul
Trucks & fleet assets

Multi-stop, consolidated. Several orders share one optimized truck route. Priced on distance, weight/volume and stops; refrigerated / hazmat-capable vehicles carry a premium.

How an order flows

Every order travels the same pipeline — from commerce, through dispatch and physical delivery, to settlement. The dispatch stage is where an order becomes a last-mile or a long-haul job.

1 · Commerce
  1. Browse & place order
  2. Validate stock & price
  3. Compliance check
  4. Capture payment
2 · Dispatch
  1. Create delivery job(s)
  2. Match capability
    (cold-chain / hazmat)
  3. Assign driver + vehicle
  4. Plan route
    (last-mile / long-haul)
3 · Delivery
  1. Pickup
  2. In transit
  3. Arrive at stop
  4. Proof of delivery
4 · Settlement
  1. Finalize payment
  2. Commission & fees
  3. Vendor & driver payout
  4. Invoice / receipt

Order to settlement — sequence

The same journey at message level, showing which service talks to which. Solid lines are direct calls; dashed lines are asynchronous events or return updates; amber highlights the two moments the customer feels — handover and being charged/paid.

Customer Order Compliance Payments Dispatch Driver 1 place order 2 checkOrder → flags 3 capture payment 4 order.confirmed → create job 5 match capable driver + vehicle 6 assign job 7 pickup + status 8 proof of delivery 9 job.delivered → post ledger 10 receipt · vendor & driver paid
direct call - - async event / return customer-felt moment
Phase 0
Discovery & design
✓ Complete
Phase 1
Planning & spec
✓ Complete
Phase 2
Design & architecture
● At gate — review
Phase 3–5
Build · Test · Deploy
○ Not started
Decisions locked · stakeholder · 2026-07-05 Scope: build all at once — every vertical and both delivery modes in a single go-live (no phased-vertical launch); risk R-02 accepted.  Industry model: stored dynamically in the database as IndustryType + ComplianceProfile config records — no per-vertical code.
01

Product Vision

01-product-vision.md

Build a delivery-first commerce platform that lets multiple vendors sell and fulfill goods across industries while operating a flexible delivery network for both last-mile and long-haul movement.

Problem statement

Existing commerce systems treat delivery as an afterthought. This platform positions delivery as the core operating model — vendors sell goods while the platform manages fulfillment, route planning, dispatch, tracking, and proof of delivery.

Core value propositions

  • Unified commerce platform for multiple vendors
  • Delivery orchestration across last-mile and long-haul flows
  • Industry-aware workflows for medicine, agriculture, hospitality, imported cargo
  • Visibility for customers, vendors, drivers, dispatchers, administrators
  • Scalable from small local fleets to large regional transport networks

Strategic goals

  1. Support multi-vendor commerce with centralized operations
  2. Offer reliable delivery execution for urgent and scheduled shipments
  3. Support regulated sectors such as medicine and temperature-sensitive cargo
  4. Enable onboarding of new vendors and industries with configurable workflows
  5. Evolve into a marketplace plus logistics operating system

Non-goals for phase 1

  • Full autonomous fleet management
  • Advanced AI routing optimization
  • Multi-country regulatory compliance beyond the initial target geography
  • Full ERP integration in the first release
02

Business Requirements

02-business-requirements.md

Benchmarked against the operating models of Amazon (marketplace + fulfilment + advertising), Jumia (African marketplace + own logistics + wallet + agent network), Jiji (classifieds/C2C supply + promoted listings), and Uber Direct/Connect (delivery-as-a-service + peer parcel send). Ziggo combines all four on a delivery-first backbone.

Objectives

Delivery-first commerce where fulfilment is the core competence · one system for last-mile + long-haul across any industry · first-class support for low-trust, cash-heavy markets · a two-sided marketplace · multiple revenue streams · logistics that can be sold as a service.

Marketplace models supported

ModelDescriptionBenchmark
B2C managed marketplaceVerified vendors sell to consumers; commission + fulfilmentAmazon, Jumia
C2C peer marketplaceIndividuals list; monetise via promoted listings & delivery, not commissionJiji
B2B / wholesaleBulk/trade orders, long-haul freight, negotiated pricingJumia B2B
Delivery-as-a-ServiceExternal merchants use Ziggo's fleet/API, white-labelledUber Direct
Peer parcel sendA customer sends a package to another person on demandUber Connect

Fulfilment models supported

ModelStockDeliveryBenchmark
Vendor-fulfilledVendorZiggo fleet or vendorAmazon FBM, Jumia
Platform-fulfilled ("Ziggo Fulfilment")Ziggo warehouseZiggo fleetAmazon FBA
On-demand courierOriginNearest driver, real-time matchUber Direct
Dropship / cross-dockSupplierZiggo consolidates
Long-haul consolidatedMixedOne truck, many ordersFreight forwarders

Business capabilities

Discovery & merchandising: search/filter/recommendations · featured-offer / "Buy Box" selection when vendors compete on the same item · promoted / sponsored listings (Jiji TOP/Boost, Amazon Sponsored) · vendor storefronts. Ordering & payments: multi-vendor cart · cash-on-delivery as a first-class flow · card/transfer/platform wallet · escrow (funds released only on POD) · BNPL/financing (future) · promos/referrals/loyalty. Fulfilment & logistics: all models above · own fleet + third-party + on-demand matching · platform fulfilment centres · Delivery-as-a-Service API for external merchants. Trust & safety: vendor/seller verification & moderation · ratings & reviews · buyer-protection guarantee (Amazon A-to-z style) · seller protection · escrow-backed settlement · fraud/abuse controls · buyer-seller chat. Growth & monetisation: membership/loyalty (Prime-style) · advertising · referrals · agent-assisted commerce (JForce-style) for offline/low-trust buyers · vendor subscription tiers. Seller tools: seller centre with catalog, multi-location inventory, pricing, promotions, payouts, analytics & account health.

Competitive benchmark — what Ziggo adopts

CapabilityAmazonJumiaJijiUberZiggo
Multi-vendor marketplace✓ C2C✓ B2C+C2C+B2B
Platform fulfilment (FBA-style)
Own last-mile fleetpartial✓ core
Long-haul freightpartial✓ differentiator
Delivery-as-a-Service API✓ (later)
Cash-on-deliverylimitedoffline✓ first-class
Platform wallet
Escrow / buyer protectionpartial
Promoted / sponsored listings
Featured offer / Buy Box
Agent-assisted commerce✓ JForce
Membership / loyaltypartial✓ (later)

Success metrics (KPIs)

Marketplace: GMV, take-rate, active vendors & retention, repeat rate, conversion. Logistics: on-time & first-attempt success rate, delivery time by mode, cost per order, fleet utilisation, exception rate. Trust: NPS/CSAT, dispute & return rate, resolution time. Financial: revenue per merchant, ad/promoted revenue, COD share & reconciliation accuracy, payout timeliness.

Launch scope — locked 2026-07-08 In the first launch: all three marketplace models (B2C + C2C + B2B) · all fulfilment models incl. platform fulfilment (FBA-style warehouses) · COD + payment gateway (buyer protection via refund-from-settlement) · all growth levers — promoted listings, subscriptions, agent network (JForce-style), membership/loyalty. Deferred: wallet & escrow, external DaaS API, peer parcel send, BNPL. Implemented as backlog epics E11–E17.
Honest consequence (risk R-16, Critical) This launch spans marketplace + platform-fulfilment warehousing + an agent field-workforce + advertising + loyalty — major operational & capital undertakings, not just software. Recommend piloting platform fulfilment and the agent network per-region behind feature flags rather than full rollout at once. Remaining blocker: launch jurisdiction (R-01).
03

Functional Requirements

03-functional-requirements.md
FR-1
User management — register all roles, assign permissions, verify identity
FR-2
Vendor management — onboarding, verification, catalog & inventory, commission/pricing
FR-3
Customer experience — browse, order, select delivery, track, rate
FR-4
Order & fulfillment — create, validate, convert to jobs, same-day/scheduled, multi-stop/bulk
FR-5
Delivery operations — assign vehicles/drivers, route last-mile & long-haul, dispatch, checkpoints, POD
FR-6
Industry handling — a generic configurable engine; any industry onboards as config. Seed examples: medicine expiry/temp/signature · agriculture grade/cold-chain/farm pickup · hospitality time windows · cargo customs stages
FR-7
Payments & settlement — multiple methods, fees/commissions, vendor payouts, invoices
FR-8
Support & operations — tickets, exceptions/claims, refund/replacement, audit logs
FR-9
Reporting & analytics — sales, delivery performance, fleet utilization, vendor metrics
04

User Stories & Use Cases

04-user-stories-use-cases.md

Eleven core use cases, each specified with actors, pre/postconditions, and main / alternate / exception flows. Index below; two representative full specs follow.

IDUse casePrimary actor
UC-01Vendor onboardingVendor, Admin
UC-02Customer order placementCustomer
UC-03Order validation & acceptanceSystem, Vendor
UC-04Delivery job creationSystem
UC-05Driver assignmentDispatcher, System
UC-06Real-time dispatch & route managementDispatcher
UC-07Delivery status updatesDriver
UC-08Proof of delivery captureDriver
UC-09Exception handlingDriver, Dispatcher, Support
UC-10Payment & settlementSystem
UC-11Reporting & analyticsVendor, Admin, Ops
UC-02Customer order placement
ActorsCustomer, System
PreCustomer has an account and a valid delivery address; vendor catalog is published.
MainBrowse & add to cart → select address & service level → system prices incl. delivery fee & surcharges → confirm & pay → Order created as pending → proceeds to UC-03.
AltRestricted item requires prescription/ID before checkout; cash-on-delivery defers capture to handover.
ExceptionAddress outside serviceable zone → checkout blocked with reason; payment fails → order not created.
PostA pending order exists, or checkout was blocked with a clear reason.
UC-08Proof of delivery capture
ActorsDriver, Recipient, System
PreDriver has arrived at the final delivery stop.
MainCapture signature/photo per service level → verify recipient ID for restricted items → record temperature for cold-chain → create ProofOfDelivery, set job delivered → trigger settlement (UC-10).
ExceptionID/age verification fails → handover refused → UC-09; recipient unavailable → attempt recorded, retry policy applies.
PostProofOfDelivery exists and job is delivered, or an exception case is opened.

Full flows for all 11 use cases are in the source document.

05

Domain Model & Class Diagram

05-domain-model-and-class-diagram.md
Decision · 2026-07-05 IndustryType is stored dynamically as database records, not a closed compile-time enum. Values below are a seed list; each industry carries a ComplianceProfile (required product fields, mandatory handling capabilities, license type, commission rate, service levels). Adding an industry is a data operation.

Shared enumerations

Role              = customer | vendor | driver | dispatcher | operationsManager
                    | financeUser | supportAgent | admin
IndustryType      = medicine | agriculture | hospitality | importedCargo
                    | generalRetail   (seed records, extensible via DB)
DeliveryMode      = lastMile | longHaul
OrderStatus       = pending | pendingCompliance | confirmed | inFulfillment
                    | completed | cancelled | disputed
DeliveryJobStatus = created | unassignable | assigned | pickedUp | inTransit
                    | delivered | failed | returned
VehicleType       = bike | van | truck | refrigeratedTruck
HazardClass       = none | flammable | biohazard | controlledSubstance | fragile
VerificationStatus= pending | verified | expiring | expired | rejected

Relationship overview

  • A Vendor manages many Products; a Customer places many Orders
  • An Order contains many OrderItems and is fulfilled by one or more DeliveryJobs via one FulfillmentRequest
  • A DeliveryJob is assigned one Driver + one Vehicle, concludes with one ProofOfDelivery, may raise ExceptionCases
  • One RoutePlan may serve multiple DeliveryJobs — the structural key to long-haul consolidation
  • Each PaymentTransaction produces one or more SettlementLedger entries

Class diagram (textual)

User <|-- CustomerProfile / VendorProfile / DriverProfile / DispatcherProfile

VendorProfile   "1" -- "0..*" Product
CustomerProfile "1" -- "0..*" Order
Order           "1" -- "0..*" OrderItem
Order           "1" -- "1"    FulfillmentRequest
FulfillmentRequest "1" -- "0..*" DeliveryJob
DeliveryJob     "0..*" -- "1"  RoutePlan
RoutePlan       "1" -- "0..*"  RouteStop
DeliveryJob     "1" -- "0..1"  ProofOfDelivery
DeliveryJob     "0..1" -- "1"  DriverProfile / Vehicle
Order           "1" -- "0..*"  PaymentTransaction
PaymentTransaction "1" -- "0..*" SettlementLedger
Phase 2 update Detailed design added ComplianceProfile, IndustryType (as a table), PayoutAccount, IdempotencyKey, and DomainEvent (outbox); Product moved to typed columns + a validated JSONB attribute bag. See docs 18 & 19.
06

Data Flow & Architecture

06-dataflow-and-architecture.md

High-level layers

Client applications → API layer → domain services → workflow/orchestration → data & integrations.

Order flow

submit order → validate address/stock/pricing → accept & route to fulfillment
→ dispatch creates delivery job → driver app receives assignment
→ delivery events published → proof of delivery stored → settlement + notifications

Architectural principles

  • Event-driven for operational workflows · API-first for integrations
  • Role-based access control · configurable rules for sector-specific operations
  • Observability from day one

Security considerations

Authentication & MFA for operational accounts · secure document storage · audit logging for changes and approvals · role-based permissions across finance, dispatch, and vendor operations.

10

Business & Revenue Model

10-business-and-revenue-model.md

Revenue streams

Marketplace commission · delivery fee · freight/long-haul charges · optional vendor subscription tiers · priority/express surcharge · value-added services (cold-chain, signature, insurance, customs brokerage) · settlement-float interest.

Commission by vertical

Configurable per vendor and per industryType. Starting defaults — require market validation before Phase 1 sign-off.

VerticalSuggested rangeRationale
General retail10–20%Standard marketplace benchmark
Hospitality (F&B)15–30%High frequency, low AOV, time-critical delivery cost
Agriculture5–12%Thin margins, price-sensitive, bulk orders
Medicine3–8%Regulated margins, compliance overhead
Imported cargoflat / per-shipmentPriced on logistics cost, not goods value

Delivery pricing

Last-mile: base fee + per-km within zone, with multipliers for cold-chain, signature/ID, off-hours, surge. Long-haul: base + (distance × rate) + (weight/volume × rate) + stop_surcharge × stops, with route consolidation reducing per-order cost.

Worked example — medicine, ₦10,000 goods, last-mile, cold-chain

LineAmount
Commission (5%)₦500
Delivery fee (base + cold-chain), to customer₦1,200
Vendor payout₦9,500
Driver payout (fee − 20% margin)₦960
Platform net revenue₦740

Illustrative only — currency, tax, and rate cards need finance confirmation.

11

Industry Compliance

11-industry-compliance.md
Jurisdiction not yet confirmed Rules below are common global regulatory patterns expressed as platform capabilities. Each must be validated against the actual launch country before Phase 2.

Medicine / pharmaceutical

Verified pharmacy license before listing · controlledSubstanceSchedule flag with order-time prescription/ID checks · cold-chain enforcement (refrigerated vehicles only, temperature at delivery) · batch/lot + expiry tracking for recalls · signature & recipient-ID at handover · extended audit retention.

Agriculture / produce

Produce grade & harvest date · farm-origin traceability · time-to-delivery SLAs for perishables · farm pickup as an origin stop type · optional inspection/phytosanitary certificates.

Hospitality (food & beverage)

Tight delivery-window SLA with at-risk flagging · kitchen prep-time input feeding dispatch timing · age verification for alcohol · heat-retention flag · allergen/ingredient metadata.

Imported cargo / freight

Shipment documents (bill of lading, commercial invoice, packing list, certificate of origin) · HS codes · customs stages as explicit statuses · hazmat class matched to vehicle/driver certification · bonded warehouse as a stop type · multi-order route consolidation.

Cross-cutting

Stricter access control & retention for PII and health-adjacent data · immutable audit trail for flagged orders · one configurable identity-verification capability reused across verticals · license verification at vendor onboarding varying by industryType.

12

Non-Functional Requirements

12-non-functional-requirements.md

Numeric targets are Phase-1 proposals for validation, not committed SLAs.

Performance

OperationTarget
Catalog browse / search< 300ms p95
Order placement (checkout confirm)< 1.5s p95
Dispatch auto-assignment decision< 5s
Status update → customer< 10s
Last-mile route (single job)< 2s
Long-haul route (consolidated)< 30s async

Availability

PathTargetRationale
Order & payment capture99.9%Direct revenue impact
Dispatch & driver app99.9%Failure blocks deliveries in progress
Tracking / notifications99.5%Degrades UX, doesn't block fulfillment
Reporting / analytics99%Internal, downtime-tolerant

Other targets

  • Security: TLS everywhere, encryption at rest, separate key management for sensitive fields, RBAC + field-level checks, MFA for operational roles, no raw card storage (tokenized gateway)
  • Retention: by sensitivity — extended for controlled-substance / customs records; tracking-ping geo data short-lived (~90 days) then aggregated
  • Observability: correlation ID spanning order → settlement; business metrics; alerts on dispatch backlog, stale jobs, payment failures, cold-chain breaches
  • DR: near-zero RPO for transactional data; RTO in minutes for the dispatch path
  • Localization: multi-currency assumed; flexible address formats · Accessibility: WCAG 2.1 AA
13

Technology Stack Recommendation

13-technology-stack-recommendation.md

A recommendation to react to, not a final decision — confirm against team expertise, cloud relationships, and launch jurisdiction.

Guiding call Modular monolith first, not microservices-from-day-one. One deployable service with strict internal module boundaries (Catalog · Order · Dispatch · Payments · Notifications). Extract a service later — most likely Dispatch — only when traffic proves the need. Managed queue, not Kafka, at this scale.
LayerRecommendation
Portal — web version (every portal)React + Next.js (TypeScript)
Portal — mobile app (every portal)Kotlin + Jetpack Compose + Material 3 (Android)
BackendTypeScript + NestJS (Python/FastAPI viable alternative)
API styleREST + webhooks, URL-versioned
Primary DBPostgreSQL + PostGIS (geo)
CacheRedis
EventingManaged queue (SQS/SNS or Pub/Sub); Kafka only if proven
SearchPostgres FTS first → OpenSearch if outgrown
Object storageS3-compatible (POD photos, compliance docs)
Maps / routingGoogle/Mapbox; OSRM/VROOM fallback
PaymentsGateway behind an internal interface (jurisdiction-dependent provider)
InfraContainers on managed platform · Terraform · GitHub Actions
07

SDLC Plan & Approval Gates

07-sdlc-plan-and-gates.md
Current position · 2026-07-05 Phase 0 complete · Phase 1 complete (verified) · Phase 2 deliverables complete, awaiting architecture-review gate · no code written.
PhaseObjectiveGate
0 doneDiscovery & product designStakeholder sign-off before implementation
1 donePlanning & specificationProduct / ops / engineering alignment
2 gateDesign & architectureArchitecture review & approval
3ImplementationQuality & release-readiness review
4Testing & validationRelease sign-off
5Deployment & operationsProduction-readiness review

Every phase produces documented evidence: requirement documents, design artifacts, backlog items, test evidence, deployment evidence.

08

Implementation Roadmap

08-implementation-roadmap.md

Recommended execution order — superseded in sequencing by the single-go-live decision (see Milestone Plan), retained as the capability roadmap.

  1. Core commerce foundation
  2. Delivery orchestration engine
  3. Driver & dispatcher operations
  4. Finance & settlement
  5. Industry-specific modules (now data-driven configuration)
  6. Optimization & scale
14

Risk Register

14-risk-register.md

Scored on likelihood × impact → severity. Owners are role-based (team not yet staffed).

IDRiskSeverityMitigationOwner
R-01Launch jurisdiction unconfirmed; compliance rules are placeholders. Escalated — regulated capabilities now launch-blocking.CriticalConfirm before M5; keep rules data-drivenProduct / Legal
R-02Build-all-at-once → large first build, delayed first revenue.AcceptedData-driven engine ⇒ verticals are config not code; hard items flagged on critical pathProduct
R-03Controlled-substance / prescription handling carries legal liability.HighLaunch OTC-only first; specialist ID vendor; legal reviewLegal / Product
R-04Settlement/payout errors lose money and trust.HighAppend-only ledger, reconciliation, high-rigor testsEng / Finance
R-05Dispatch failures physically stall deliveries in progress.High99.9% target, manual-dispatch fallback, stale-job alertsEng / Ops
R-06Routing/consolidation is hard; naive build won't scale.MediumThird-party routing API; isolate behind interfaceEngineering
R-07Two-sided cold-start: no vendors ⇄ no customers.HighSeed anchor vendors across verticals before opening demandProduct / Business
R-09Health-adjacent / PII mishandling → legal & reputational exposure.HighField-level access control, encryption, retention rules, auditEng / Legal
R-14Broad multi-role attack surface.HighRBAC, MFA, security review at each release gateEng / Security

Register shows the highest-severity risks; medium risks R-08, R-10–R-13 are in the source document.

Resolve before Phase 2 gate R-01 confirm jurisdiction (now on critical path) · R-07 anchor-vendor seeding across verticals · R-05 / R-04 dispatch reliability & settlement integrity, both in scope from first launch.
15

Product Backlog

15-product-backlog.md
Build all at once The R1–R4 tags are internal build stages (B1–B4) that all complete before one go-live. No vertical or delivery mode is deferred post-launch. Priority legend: Must Should Could.

10 epics · ~60 stories. Representative epics shown with full acceptance material in the source.

E4 — Order & fulfillment

IDStoryPrioritySizeStage
S4.1Order creation & lifecycleMustLB1
S4.2Order validation (stock/address/pricing)MustMB1
S4.3Vendor accept/reject + auto-acceptMustMB1
S4.4Fulfillment request & job creationMustLB1
S4.5Split & partial fulfillmentShouldLB2

E5 — Delivery orchestration

IDStoryPrioritySizeStage
S5.2Driver assignment — manualMustMB1
S5.3Driver assignment — auto-dispatchShouldLB2
S5.4Last-mile route (single job)MustMB1
S5.5Long-haul multi-stop + consolidationShouldXLB4
S5.7Proof of delivery captureMustMB1
S5.8Capability-matched assignment (cold/hazmat)MustMB2
S5.9ID/age verification at handoverMustMB3

E7 — Payments & settlement

IDStoryPrioritySizeStage
S7.1Payment gateway interface + providerMustLB1
S7.3Commission & delivery-fee calculationMustMB1
S7.4Settlement ledger (append-only)MustLB1
S7.5Vendor & driver payoutsMustLB1
Trade-off of build-all-at-once Larger, later first release — first revenue now depends on B1–B4. Long-haul routing (S5.5, XL) and regulated capabilities become launch-blocking, so jurisdiction must be confirmed before launch. Mitigating factor: the data-driven industry engine means "all verticals" multiplies configuration, not code.
16

Milestone Plan

16-milestone-plan.md
Single go-live All verticals and both delivery modes ship together. M1–M6 are build stages that all precede one launch — long-haul (M6) and regulated verticals (M5) are no longer post-launch. Durations are relative effort, not calendar dates.
MThemeEffortExit gate
M0Foundations & setup3–4 wksPipeline deploys through CI/CD
M1Commerce core6–8 wksCustomer places order end-to-end (no delivery)
M2Last-mile delivery6–8 wksOrder → delivered with POD & tracking
M3Payments & settlement5–6 wksMoney moves; ledger reconciles (build gate, not launch)
M4Operational depth8–10 wksRuns at scale, less manual intervention
M5Regulated capabilities6–8 wksRegulated industries transact compliantly (legal + jurisdiction)
M6Long-haul & cargo10–12 wksMulti-stop shipment w/ customs docs completes
Single go-liveProduction-readiness review across M1–M6 → GO-LIVE

Critical path

M0 → M1 → M2 → M3 → (M4, M5, M6 overlap) → readiness review → SINGLE GO-LIVE

longest tail: M6 (long-haul consolidation, S5.5 XL)
              M5 (gated on confirmed jurisdiction + legal sign-off)

M4/M5/M6 can overlap once M2/M3 dependencies exist, but all three must complete before go-live — the main cost of building all at once is that long-haul and regulated capabilities now sit on the critical path to first revenue.

17

Technical Specification

17-technical-specification.md
Key decision · data-driven industry engine No per-vertical code path. IndustryType is a DB record; each references a ComplianceProfile declaring required product fields, mandatory handling capabilities, license type, commission rate, and service levels. Order/Dispatch/Catalog enforce these generically at runtime — onboarding an industry is configuration, not a release.

Module boundaries

ModuleOwns
IdentityUsers, roles, auth, permissions
CatalogProducts, categories, inventory, pricing rules
OrderOrder lifecycle, validation, fulfillment requests
Dispatch/DeliveryJobs, routing, vehicles/drivers, tracking, POD, exceptions
Payments/SettlementPayments, commission, ledger, payouts, invoices, refunds
NotificationsMulti-channel messaging, templates
PlatformAudit logging, observability, config

Conventions

  • API: REST/JSON, URL-versioned; Bearer JWT with role/permission claims; consistent error envelope; cursor pagination
  • Idempotency: keys on order placement, payment capture, driver status updates — critical on flaky mobile networks
  • Data: UUID keys; money as integer minor units + currency; forward-only migrations; append-only ledger & sensitive records
  • Eventing: at-least-once with idempotent consumers; per-entity ordering where sequence matters
  • Third parties: PaymentGateway, RoutingProvider, NotificationChannel, IdentityVerification — internal interfaces with swappable adapters

Testing strategy

Unit (pricing/commission, status transitions) · integration per module against real Postgres · contract tests for provider adapters · E2E on the critical path (order → dispatch → deliver → settle) · high-rigor coverage for Payments/Settlement and capability-matched dispatch · security review + load test before go-live.

18

System Design

18-system-design.md

Detailed runtime design realizing the Phase 1 conventions — architecture, the dynamic industry/compliance engine, sequence flows, and state machines. (The end-to-end sequence is drawn at the top of this page.)

The dynamic compliance engine

Industry behavior is data, resolved at runtime — there is no per-vertical code:

Product create ─► requiredFields(industry)  → validate product has all required keys
Order placed   ─► checkOrder(order)         → {handlingFlags, blockers}
Dispatch       ─► requiredCapabilities(job) → filter vehicles/drivers whose
                                              capabilitySet ⊇ required set

Capability matching is one generic set-superset test reused across cold-chain, hazmat, signature, and age-verification — not per-vertical branches. Adding an industry is inserting two rows.

Order state machine

pending ─validate─► confirmed ─fulfil─► inFulfillment ─complete─► completed
   │                    │                     │
   ├─hold─► pendingCompliance ─resolve─────────┤
   └─reject/fail─► cancelled                   └─dispute─► disputed

DeliveryJob state machine

created ─assign─► assigned ─pickup─► pickedUp ─depart─► inTransit ─deliver─► delivered
   │                                                        │
   ├─no capacity─► unassignable                             ├─fail─► failed ─retry─► assigned
   └────────────────────────────────────────────────────────┴─return─► returned
19

Data Model Specification

19-data-model-specification.md

Concrete PostgreSQL 15+ schema (with PostGIS). UUID keys; money as bigint minor units + currency; timestamptz UTC; append-only financial/audit tables.

Keystone: the dynamic industry & compliance tables

industry_type ── compliance_profile_id ─► compliance_profile
                                            ├ required_product_fields text[]
                                            ├ requires_cold_chain / hazmat /
                                            │ signature / age_verification / customs
                                            ├ required_license_type
                                            ├ default_commission_bps
                                            └ sensitive_data_class · retention_days

Both are tables, not enums — seed data editable by admins at runtime. Adding an industry is an INSERT, not a deploy.

Product: typed columns + validated JSONB

product( ... unit_price bigint, currency char(3), hazard_class hazard_class_t,
         requires_cold_chain bool,
         attributes jsonb )   -- industry-specific: hs_code, produce_grade,
                              -- controlled_substance_schedule, allergen_info ...
CREATE INDEX ... USING GIN (attributes);

The ComplianceEngine validates attributes contains every key the industry's required_product_fields demands — no per-vertical column explosion.

Integrity highlights

  • settlement_ledger & audit_log are append-only (UPDATE/DELETE revoked at the DB role level)
  • idempotency_key + domain_event (transactional outbox) back the eventing design
  • Balances are derived by summing ledger entries; a reconciliation worker asserts they tie out per period
  • PostGIS geography columns on address and delivery_zone for nearest-driver & zone lookups
20

API Contracts

20-api-contracts.md

REST over HTTPS, JSON, snake_case, base path /api/v1. Bearer JWT with role/permission claims. Idempotency keys on money-or-physical-world POSTs. Consistent error envelope with a correlation ID.

Representative endpoints

MethodPathPurpose
POST/ordersPlace order (idempotent) → 201 confirmed / 202 pending_compliance
POST/delivery-jobs/{id}/assignManual assign — 409 on capability mismatch
POST/delivery-jobs/{id}/podCapture proof of delivery → job delivered
GET/settlementsLedger view (read-only; posted internally on events)
POST/admin/industriesCreate industry type + compliance profile (runtime)
The dynamic-industry surface POST /admin/industries and PATCH /admin/compliance-profiles/{id} are how a new vertical is onboarded — two API calls, no deployment.
POST /api/v1/delivery-jobs/{id}/assign
{ "driver_id":"...", "vehicle_id":"..." }
409 → { "code":"dispatch.capability_mismatch",
        "details":{ "required":["cold_chain"], "vehicle_has":[] } }
21

Infrastructure Plan

21-infrastructure-plan.md

Topology

Internet → CDN/WAF → Load balancer
   ├─► API pods (stateless, autoscale on latency)
   └─► Worker pods (dispatch, routing, notifications, settlement, outbox)
        │
   Postgres(+PostGIS) primary+replica · Redis · Managed queue · S3 · Secrets mgr
        │
   Adapters → PaymentGateway · RoutingProvider · SMS/Push · IDVerify

Key decisions

  • Two workload classes scaled independently — API pods (bursty customer traffic) vs worker pods (continuous dispatch); a lunch-hour order spike can't starve deliveries in progress
  • Managed containers (Fargate/Cloud Run), not Kubernetes yet; Terraform for all three environments (local · staging · production)
  • Routing/consolidation isolated on its own worker pool; Dispatch is the likely future service extraction
  • Append-only enforced at the DB grant level; separate KMS key for compliance-sensitive fields; card data tokenized at the gateway
  • CI/CD gates migrations before rollout; feature flags let incomplete capabilities ship dark under build-all-at-once
  • DR: near-zero RPO, minutes RTO on the order/dispatch path, with restore drills
22

Portal Spec & Feature Catalog

22-portal-and-client-specification.md

Six portals, each with two parallel clients over the same REST API — a Next.js web version and a Kotlin (Android, Compose + Material 3) mobile app. Below is the full feature catalog per portal. Tags: (new) = needs a new entity/endpoint; B1–B4 = build stage.

PortalWebMobile (Kotlin/M3)Primary roles
CustomerNext.js (SSR/SEO)Android appcustomer
VendorNext.jsAndroid appvendor
Driver— (mobile-only)Android appdriver
DispatcherNext.jsAndroid appdispatcher, operations
Admin & operationsNext.jsAndroid appadmin, operations, finance, support
Agent (new)Next.jsAndroid app (primary)agent
Consolidation decision Finance and Support are role-gated areas inside the Admin & operations console, not separate apps.

1 · Customer portal

Account: register/login (OTP/social) · saved addresses & payment methods · notification prefs. Discovery: browse by category/industry/vendor · search + filters · product detail · vendor storefronts · wishlists (new) · recommendations. Ordering: multi-vendor cart · service level & window · itemized price + surcharges · serviceability check · promo codes · restricted-item prescription/ID flow · COD · scheduled/recurring orders (new). Tracking: live status timeline · driver ETA/map · notifications · reschedule. Post-delivery: POD/receipt · ratings & reviews · reorder · refund/return/replacement · support tickets.

2 · Vendor portal

Onboarding & account: business registration & KYC · industry selection (drives required fields) · license upload (regulated) · verification status · team members & roles (new) · payout account · storefront branding.

Catalog & merchandising: product CRUD with media/attributes · compliance-required fields enforced · categories & collections · product variants (size/color/pack) (new) · bundles/kits (new) · publish/schedule · featured/merchandising order · SEO fields · bulk CSV import/export (new).

Inventory & merchandise management — expanded core Stock levels — on-hand / reserved / available per product/variant (B1) · multi-location inventory across warehouses (new: StockLocation, B2) · stock adjustments with reason codes (received/damaged/lost/correction/wastage) + immutable audit (new: StockAdjustment, B2) · reservations auto-held on order, released on cancel — prevents oversell (B1) · low-stock / reorder alerts (B2) · reorder/restock workflow (new, B3) · stock transfers between locations (new: StockTransfer, B3) · batch/lot & expiry with FEFO picking (B2) · near-expiry & wastage management (new, B3) · backorder / out-of-stock handling (B2) · stocktake / cycle count reconciliation (new, B3) · barcode/SKU management + scan lookup (B2) · inventory audit trail (B2) · inventory reports — valuation, movement, ageing, low-stock (B2/B3).

Orders & fulfillment: order queue accept/reject/auto-accept · order detail (masked customer info) · fulfillment & delivery monitoring · split/partial fulfillment · picking/packing slips · returns & replacements. Pricing & promotions: per-product pricing · bulk price update · promotions/discounts (coupons, %/flat, time-boxed) (new: Promotion) · tiered/quantity pricing. Finance: earnings dashboard (sales, commission, net) · settlement & payout status · invoices/statements. Subscriptions & licenses (doc 23): compare/subscribe/upgrade plans · billing history · license records & renewals. Insights: sales & delivery-performance dashboards · support tickets.

3 · Driver app (mobile)

Account & shift: login + MFA · go online/offline · shift schedule · vehicle & capability profile. Jobs & nav: assigned jobs & accept · job/stop detail · turn-by-turn + ordered stops · long-haul multi-stop (B4) · barcode/QR scan (new). Execution & POD: milestone status (offline-queued, idempotent) · signature & photo · recipient ID/age verification · cold-chain temperature · COD collection. Exceptions: failed attempt/damage/refused/address · contact dispatcher. Earnings: per-job & daily summary · payout status.

4 · Dispatcher portal

Queue & assignment: live queue by zone · manual assign with capability-match enforcement · auto-dispatch oversight & override · bulk assign. Live ops: live map of drivers/jobs/routes · driver status & location · ETA/SLA-at-risk · reroute/reassign. Routing: last-mile single-job · long-haul multi-stop planning & consolidation (B4) · manual route editing. Exceptions & alerts: triage & resolution · stale-job/SLA-breach alerts · customs-hold (cargo). Oversight: fleet/driver availability · dispatch performance reporting.

5 · Admin & operations console

Users & access: users/roles/permissions · MFA policy · support impersonation (audited) (new). Industry & compliance config: create/edit industry types & compliance profiles · restricted/controlled-substance rules. Vendor operations: verification queue · license lifecycle oversight (expiring/expired) · suspend/reinstate. Catalog governance: global categories/taxonomy · listing moderation · attribute schemas per industry. Service config: delivery zones · service levels/SLAs · pricing rules/surcharges · vehicle types & fleet registry. Subscriptions/billing (doc 23): plans & entitlements · subscription revenue. Finance (role-gated): settlement & reconciliation · payout runs · invoices · refunds · financial reports. Support (role-gated): tickets · claims · refund/replacement · customer/vendor lookup. Reporting: sales, delivery, fleet, vendor, exception rates · scheduled exports. Governance: immutable audit-log viewer · platform config & feature flags.

6 · Agent portal (new, 2026-07-08)

JForce-style agents place & manage orders on behalf of offline/low-trust customers and earn commission. Account: onboarding & approval · KYC · territory. Assisted ordering: place an order for a named customer · attribution to the agent. Tracking & payments: track their orders · collect (often cash) & reconcile. Earnings: agent commission, statements, payout status. Customer book: manage served customers. (Epic E16.)

Launch-scope portals & epics (2026-07-08) The broad launch adds C2C peer marketplace (E12), B2B/wholesale (E13), platform fulfilment (E14), promoted listings & ads (E15), the agent network + this Agent portal (E16), and membership/loyalty (E17). These enlarge the build and several are operational undertakings (warehouses, agent workforce) — see risk R-16.
New entities from the launch-scope expansion Inventory: StockLocation, ProductVariant, StockAdjustment, StockTransfer, Promotion (+ Inventory.location_id/quantity_reserved). Marketplace/growth: Listing+ChatThread (C2C), BusinessBuyer/PriceAgreement/QuoteRequest (B2B), FulfilmentCenter/FulfilmentInbound, AdCampaign/PromotedListing, AgentAccount/AgentOrder, MembershipPlan/Membership. To be folded into the data model (doc 19) as each epic is scheduled.
23

Licensing & Subscription Module

23-licensing-and-subscription-module.md

One module for two related per-vendor lifecycles the earlier docs only hinted at: subscriptions (paid vendor plans + entitlements + recurring billing) and licensing (regulatory-permit lifecycle — renewal reminders, auto-suspend on expiry). A Should/build-stage-B2 revenue-enhancement module — not launch-blocking.

Subscriptions: plans & entitlements

Plans are data-driven (like the industry engine). Each plan grants typed entitlements — commission_bps_override, max_active_listings, priority_placement, advanced_analytics. Other modules ask entitlementsFor(vendorId) rather than branching on plan names.

Commission precedence (resolves a real ambiguity) plan entitlement override > vendor_profile.commission_bps > compliance_profile.default_commission_bps. A paid plan's reduced commission must beat both the per-vendor and industry defaults.

Subscription billing lifecycle

subscribe/trial → active ─(renewal ok)→ active (next period)
                     │
                     ├─(charge fails)→ past_due ─(dunning)─┬─ok→ active
                     │                                     └─exhausted→ suspended
                     └─(cancel_at_period_end)→ active till period end → cancelled

Proration on upgrade/downgrade via the PaymentGateway; subscription revenue recorded in the SettlementLedger alongside commission.

Licensing: permit lifecycle

pending →(admin verifies)→ verified →(near expiry)→ expiring ─(renewed)→ verified
                                 │                          └─(lapses)→ expired → auto-suspend listings
                                 └─(revoked)→ suspended

Turns the compliance engine's point-in-time license check into a managed lifecycle: a scheduled worker fires renewal reminders and auto-suspends listings on expiry. The compliance profile still owns which license an industry requires; this module owns the record and its transitions.

New epic E11 (non-launch-blocking)

IDStoryPriorityStage
S11.1Plans & entitlements config (admin)ShouldB2
S11.2Subscribe / upgrade / downgrade + prorationShouldB2
S11.3Recurring billing worker + dunningShouldB2
S11.4Entitlement enforcement (commission/limits/features)ShouldB2
S11.5License lifecycle + renewal remindersShouldB2
S11.6Auto-suspend on license expiryShouldB3
Open questions On billing suspension — free-tier fallback or listings pause? · plans global or per-region? · free/default tier or commission-only baseline? · monthly-only or annual too at launch?
09

Proof-of-Work Log

09-proof-of-work-log.md

Phase 0 — Discovery (complete)

Vision, business & functional requirements, user stories/use cases, domain model, data flow & architecture, SDLC plan, roadmap, business/revenue model, industry compliance, NFRs, technology stack.

Phase 1 — Planning (complete, verified)

Risk register (14 risks) · product backlog (10 epics, ~60 stories) · milestone plan (M0–M6) · technical specification.

Phase 2 — Design & architecture (complete, at gate)

  • System design — architecture, compliance engine, sequence & state diagrams
  • Data model specification — full PostgreSQL DDL incl. dynamic industry/compliance tables
  • API contracts — REST endpoints per module
  • Infrastructure plan — topology, environments, scaling, CI/CD, DR

Stakeholder decisions recorded (2026-07-05)

  • Build all at once — single go-live; R-02 accepted
  • Industry stored dynamically in the DB — data-driven compliance engine
  • Phase 1 verified; proceeded to Phase 2 with reconciliation back into Phase 1 docs (5 new entities, Product JSONB attributes)
Status Phases 0–2 complete · Phase 2 at architecture-review gate · Phase 3 (implementation) not started · no development work started.