Backend API for the AutoParts Marketplace buyer flow, Seller Flow Milestones S-A through S-E, Admin Milestones A-A through A-F, and Logistics Milestones L-A through L-E. This repository currently implements the buyer flow, seller flow, the full admin operations slice, and the full logistics slice: buyer authentication, catalogue browsing, cart management, checkout order creation with calculated delivery fees, Paystack-backed payment initialization and verification, buyer order tracking/history, seller registration plus CAC verification onboarding, seller-owned listing management, seller-side order management, the seller inventory dashboard, seller sales plus payout request workflows, dedicated admin auth with dashboard overview, seller verification, catalogue management, user and order oversight, payout review, platform configuration RBAC, disputes review, audit-log access, plus logistics company registration, delivery zones, company-managed riders, rider authentication, nearest-rider delivery-job auto-assignment, admin manual assignment fallback, rider-driven delivery progression, failed-delivery recovery, delivery-fee settlement, logistics-company payout reuse, company dashboard summaries, and admin logistics delivery metrics.
- Buyer registration with email or Nigerian phone number and password
- Buyer login with JWT access token
- Forgot-password, reset-password, and authenticated change-password flows
- Auth-protected
GET /api/v1/me - Product catalogue schema and seed data for categories, products, images, compatibility, and vehicle taxonomy
- Public catalogue browsing with filtering, pagination, and single-product detail
- Authenticated buyer cart management with quantity updates and removal
- Buyer checkout order creation with saved-or-inline delivery address support plus calculated delivery fees
- Paystack payment initialization for paystack, bank transfer, and USSD checkout methods
- Paystack payment verification with webhook-first confirmation, authenticated redirect fallback verification, and duplicate-safe order confirmation
- Buyer order history listing, single-order detail, current status/history, and receipt responses
- Order status-history persistence for
pending_paymentandconfirmed, with buyer-readable lifecycle tracking - Seller registration with shared auth credentials plus seller business profile fields
- Seller document upload for CAC and proof of address with
multerlocal storage - Seller registration-time CAC lookup through Dojah with the provider response stored for later admin review
- Seller-triggered CAC verification retry to refresh stored Dojah metadata after fixing provider credentials or transient errors
- Seller document upload for CAC and proof of address with pending admin review after upload
- Seller-protected
GET /api/v1/seller/meprofile and verification-status response - Seller CRUD for owned product listings with multipart photo upload and compatibility records
- Seller-scoped incoming order views with pagination and order-item ownership enforcement
- Seller order-item updates to
ready_for_pickuporcancelled, with automatic delivery-job creation when the seller hands an item over for dispatch - Seller inventory dashboard with seller-scoped stock levels, low-stock flags, and summary counts
- Automatic stock decrement when a buyer payment confirms an order for the first time
- Seller CSV bulk upload for creating multiple listings in one request
- Seller sales and revenue summary by date range with platform commission deduction
- Seller pending payout calculation plus payout request history
- Dedicated admin authentication via
adminsplus/api/v1/admin/login - Admin RBAC with
roles,permissions,role_permissions, andadmin_roles - Seeded
super_adminaccess plus a scopedverification_adminrole - Permission-gated
GET /api/v1/admin/me - Admin-protected super admin dashboard overview with KPI cards, alerts, queue previews, leaderboard widgets, and recent activity behind
dashboard.read - Admin-protected seller verification review queue, seller detail view, and approve or reject actions behind
sellers.verify - Admin-protected category tree create/update plus archive-and-restore management behind
categories.manage - Admin-protected vehicle taxonomy CRUD behind
categories.manage - Admin-protected buyer and seller oversight listing with search, pagination, and seller-profile summaries behind
users.manage - Admin-controlled buyer/seller account statuses (
active,suspended,banned) enforced at login and on protected routes - Admin-protected platform-wide order oversight list with search, payment filters, and controlled order-status intervention behind
orders.manage - Admin-triggered reconciliation for stale pending Paystack payments behind
orders.manage - Admin-protected payout review queue with seller or logistics-company detail plus approve, reject, and mark-paid transitions behind
payouts.approve - Admin-owned platform config reads and updates for default commission, category overrides, seller-tier overrides, and platform settings behind
config.manage - Admin-protected disputes queue with buyer/order/seller context plus resolve-or-reject actions behind
disputes.resolve - Admin-protected audit-log list endpoint behind
audit_logs.read - Audit-log writes for seller verification, user status changes, order interventions, payout decisions, dispute decisions, and platform config changes
- Logistics company registration and login with dedicated company-scoped JWT access
- Delivery-zone records for rider onboarding and later assignment/fee matching
- Company-owned rider creation, listing, update, and ownership enforcement
- Rider login, rider profile access, and availability updates
- Company and rider delivery-job views with explicit
pending -> assigned -> picked_up -> in_transit -> deliveredprogression plus rider-sidefailedhandling that advances buyer-visible order tracking - Failed delivery jobs now capture a required reason, release the rider back to
available, return the item toready_for_pickup, and stay visible for manual reassignment - Delivery-fee calculation now uses a shared base-plus-distance-plus-weight calculator that persists per-order and per-job fees in kobo
- Delivered jobs now record the platform logistics margin and the logistics-company share for settlement
- Logistics companies now have earnings summaries plus payout-request creation through the shared payouts workflow
- Logistics company job views now include dashboard-ready job-status totals plus rider performance summaries
- Admin logistics company approval or suspension plus rider oversight behind
logistics.manage - Admin delivery-job queue review plus manual rider assignment behind
logistics.manage - Admin logistics oversight now includes cross-company company or rider summary counts, unassigned-job visibility, filterable delivery-job reviews, and delivery metrics
- Seller payout eligibility now unlocks only after delivered logistics jobs, not just paid orders
- Seller compatibility payloads now validate against admin-managed vehicle taxonomy entries
- Seller commission reads now resolve from admin-owned platform config with
PLATFORM_COMMISSION_RATE_PERCENTretained as a bootstrap fallback in development and test - Buyer order detail now includes per-item
itemStatusalongside the existing order-level status history - Buyer catalogue, cart, and order reads now project seller business metadata from real seller profiles instead of the old product-level seller stub
- Joi request validation, auth rate limiting, central error handling
- MySQL migration and seed scaffolding for buyer-flow tables plus seller onboarding, payout, admin-role, logistics company or rider tables, and delivery settlement fields
- Unit and integration test suites for auth, catalogue browsing, cart, checkout, payments, buyer order history, seller onboarding, seller listing management, seller order management, seller inventory, seller finance, logistics company and rider delivery flows, admin seller verification, admin catalogue management, admin user or order oversight, admin logistics oversight, delivery-fee settlement, and the super admin dashboard
src/
config/
controllers/
db/
migrations/
seeds/
middleware/
repositories/
routes/
services/
utils/
validators/
app.js
server.js
tests/
integration/
setup/
unit/
scripts/
Copy .env.example to .env and fill in the required values.
Seller onboarding uses:
UPLOAD_DIRfor Apache-served seller documents and product images (for example,./public_html/uploads)BASE_URLfor the public API origin used when serializing stored product image pathsCORS_ALLOWED_ORIGINSas an optional comma-separated frontend allowlist for browser requests; leave it blank to allow any origin during local developmentPAYSTACK_SECRET_KEY,PAYSTACK_PUBLIC_KEY,PAYSTACK_BASE_URL, andAPP_URLfor checkout initialization, transaction verification, and webhook-safe redirect fallbacksDOJAH_BASE_URL,DOJAH_APP_ID, andDOJAH_API_KEYfor CAC lookups during seller registrationPLATFORM_COMMISSION_RATE_PERCENTas the bootstrap fallback commission rate before admin-managed config is changed in development and testDELIVERY_BASE_FEE_KOBO,DELIVERY_PER_KM_KOBO, andLOGISTICS_PLATFORM_MARGIN_PCTfor shared delivery-fee and settlement calculations
Product image note:
- New product image uploads persist to
UPLOAD_DIR/products; Apache serves them at/uploads/products. - Run
node scripts/report-legacy-product-images.jsto identify existing remote image URLs before deciding how to migrate them.
Local admin review uses:
SUPER_ADMIN_EMAILandSUPER_ADMIN_PASSWORDfornpm run seednpm run seedto provision the seededsuper_adminplus the scopedverification_adminrole definitions
Paystack deployment notes:
- Configure the Paystack dashboard webhook URL separately in both test mode and live mode as
https://<railway-domain>/webhooks/paystack. localhostcannot receive Paystack webhooks directly; use the deployed Railway URL or a tunnel such as ngrok during local testing.PAYSTACK_BASE_URLdefaults tohttps://api.paystack.coand is mainly useful when switching between provider environments or test doubles.APP_URLis used for Paystack redirect UX and absolute partner product image URLs. Set it to the public origin that serves/uploads, for examplehttps://autoparts.zubitechnologies.com. If this is a separate frontend origin, proxy/uploadsto the API upload directory.- Railway deployments already set
app.set('trust proxy', 1)in the Express app for proxy-aware request metadata.
npm run dev
npm start
npm run migrate
npm run seed
npm test
npm run test:unit
npm run test:integration
npm run lintPOST /api/v1/auth/registerPOST /api/v1/auth/loginPOST /api/v1/auth/forgot-passwordPOST /api/v1/auth/reset-passwordPATCH /api/v1/auth/passwordGET /api/v1/me
GET /api/v1/productsGET /api/v1/products/:id
GET /api/v1/cartPOST /api/v1/cart/itemsPATCH /api/v1/cart/items/:idDELETE /api/v1/cart/items/:id
POST /api/v1/ordersGET /api/v1/ordersGET /api/v1/orders/:idGET /api/v1/orders/:id/statusGET /api/v1/orders/:id/receipt
POST /api/v1/payments/initializeGET /api/v1/payments/verify/:referenceGET /api/v1/payments/callback
POST /webhooks/paystack
POST /api/v1/seller/registerPOST /api/v1/seller/documentsPOST /api/v1/seller/cac-verification/retryGET /api/v1/seller/mePOST /api/v1/seller/productsGET /api/v1/seller/productsPATCH /api/v1/seller/products/:idDELETE /api/v1/seller/products/:idGET /api/v1/seller/inventoryPOST /api/v1/seller/inventory/bulkGET /api/v1/seller/ordersPATCH /api/v1/seller/orders/:id/statusGET /api/v1/seller/dashboardGET /api/v1/seller/salesPOST /api/v1/seller/payoutsGET /api/v1/seller/payouts
POST /api/v1/logistics/registerPOST /api/v1/logistics/loginGET /api/v1/logistics/meGET /api/v1/logistics/zonesPOST /api/v1/logistics/ridersGET /api/v1/logistics/ridersGET /api/v1/logistics/riders/:idPATCH /api/v1/logistics/riders/:idPATCH /api/v1/logistics/riders/:id/suspendPATCH /api/v1/logistics/riders/:id/reactivateGET /api/v1/logistics/jobsGET /api/v1/logistics/earningsPOST /api/v1/logistics/payouts
POST /api/v1/rider/loginGET /api/v1/rider/mePATCH /api/v1/rider/availabilityGET /api/v1/rider/jobsGET /api/v1/rider/jobs/:idPATCH /api/v1/rider/jobs/:id/status
POST /api/v1/admin/loginGET /api/v1/admin/dashboardGET /api/v1/admin/meGET /api/v1/admin/sellersGET /api/v1/admin/sellers/:idPATCH /api/v1/admin/sellers/:id/verificationGET /api/v1/admin/usersPATCH /api/v1/admin/users/:id/statusGET /api/v1/admin/logistics/companiesPATCH /api/v1/admin/logistics/companies/:id/statusGET /api/v1/admin/logistics/ridersGET /api/v1/admin/delivery-jobsPATCH /api/v1/admin/delivery-jobs/:id/assignGET /api/v1/admin/categoriesPOST /api/v1/admin/categoriesGET /api/v1/admin/categories/:idPATCH /api/v1/admin/categories/:idDELETE /api/v1/admin/categories/:idGET /api/v1/admin/ordersPATCH /api/v1/admin/orders/:id/statusGET /api/v1/admin/payoutsPATCH /api/v1/admin/payouts/:idGET /api/v1/admin/configPATCH /api/v1/admin/configGET /api/v1/admin/disputesPATCH /api/v1/admin/disputes/:idGET /api/v1/admin/audit-logsGET /api/v1/admin/vehicle-taxonomyPOST /api/v1/admin/vehicle-taxonomyGET /api/v1/admin/vehicle-taxonomy/:idPATCH /api/v1/admin/vehicle-taxonomy/:idDELETE /api/v1/admin/vehicle-taxonomy/:id
Register with email:
{
"fullName": "Amaka Nwosu",
"email": "amaka@example.com",
"password": "Password123!"
}Register with Nigerian phone number:
{
"fullName": "Tunde Adebayo",
"phone": "08012345678",
"password": "Password123!"
}Login:
{
"identifier": "amaka@example.com",
"password": "Password123!"
}Login as the seeded dev admin:
{
"email": "superadmin@autoparts.local",
"password": "Password123"
}Suspend a seller or buyer account:
{
"status": "suspended"
}Move an order forward from the admin panel:
{
"status": "picked_up",
"note": "Collected from seller by operations team."
}Forgot password:
{
"identifier": "amaka@example.com"
}Reset password:
{
"token": "64-char-reset-token",
"newPassword": "NewPassword123!"
}Browse products:
GET /api/v1/products?partName=brake%20pad&vehicleMake=Toyota&vehicleModel=Camry&vehicleYear=2010&category=brake-system&condition=new&minPriceKobo=1000000&maxPriceKobo=3000000&location=Lagos&sellerRating=4.5&sellerBusinessName=Prime&page=1&limit=10
Fetch a single product:
GET /api/v1/products/4001
Add a cart item:
{
"productId": 4001,
"quantity": 2
}Update a cart item:
{
"quantity": 3
}Create an order with a new delivery address:
{
"paymentMethod": "paystack",
"deliveryAddress": {
"label": "Workshop",
"street": "12 Adeola Odeku Street",
"city": "Ikeja",
"state": "Lagos",
"phone": "08012345678"
}
}Create an order with an existing saved address:
{
"paymentMethod": "bank_transfer",
"deliveryAddressId": 3
}Initialize a payment:
{
"orderId": 1,
"callbackUrl": "https://example.com/payments/callback"
}Initialize a payment for a phone-only buyer:
{
"orderId": 1,
"email": "buyer@example.com"
}Register a seller:
{
"fullName": "Uche Okafor",
"email": "uche@example.com",
"phone": "08012345678",
"password": "Password123!",
"businessName": "Prime Auto Hub",
"contactEmail": "sales@primeautohub.ng",
"contactPhone": "08012345678",
"address": "12 Sapara Williams Close, Victoria Island, Lagos",
"cacNumber": "RC-123456"
}Upload seller documents as multipart form-data:
POST /api/v1/seller/documents
Authorization: Bearer <token>
cacDocument=<pdf/jpg/png file>
proofOfAddressDocument=<pdf/jpg/png file>
Create a seller product as multipart form-data:
POST /api/v1/seller/products
Authorization: Bearer <token>
title=Front Brake Disc
description=Premium brake disc for Toyota Camry sedans.
categoryId=1002
partNumber=DISC-001
condition=new
priceKobo=4500000
stockQty=12
location=Lagos
compatibility=[{"make":"Toyota","model":"Camry","yearFrom":2007,"yearTo":2011}]
photos=<jpg/png file>
photos=<jpg/png file>
Update a seller product:
PATCH /api/v1/seller/products/:id
Authorization: Bearer <token>
priceKobo=5200000
stockQty=9
compatibility=[{"make":"Toyota","model":"Camry","yearFrom":2008,"yearTo":2012}]
photos=<jpg/png file>
List seller orders:
GET /api/v1/seller/orders?itemStatus=pending&page=1&limit=10
Authorization: Bearer <token>
List seller inventory:
GET /api/v1/seller/inventory?status=all&lowStockOnly=false&page=1&limit=10
Authorization: Bearer <token>
Get seller dashboard summary:
GET /api/v1/seller/dashboard?dateFrom=2026-07-01&dateTo=2026-07-07
Authorization: Bearer <token>
Bulk upload seller inventory as multipart form-data:
POST /api/v1/seller/inventory/bulk
Authorization: Bearer <token>
file=<inventory.csv>
List seller sales for a period:
GET /api/v1/seller/sales?dateFrom=2026-07-01&dateTo=2026-07-07
Authorization: Bearer <token>
Create a seller payout request:
POST /api/v1/seller/payouts
Authorization: Bearer <token>
{"bankAccountRef":"BANK-0012345678"}
List seller payout history:
GET /api/v1/seller/payouts?status=requested&page=1&limit=10
Authorization: Bearer <token>
List the admin seller verification queue:
GET /api/v1/admin/sellers?status=pending&page=1&limit=10
Authorization: Bearer <admin-token>
Fetch one seller verification profile, including documents and the stored Dojah response:
GET /api/v1/admin/sellers/:id
Authorization: Bearer <admin-token>
Approve a seller verification:
PATCH /api/v1/admin/sellers/:id/verification
Authorization: Bearer <admin-token>
{"verificationStatus":"verified"}
Create an admin category:
{
"name": "Cooling System",
"slug": "cooling-system"
}Create an admin vehicle taxonomy entry:
{
"make": "Mazda",
"model": "CX-5",
"trim": "Signature",
"yearFrom": 2018,
"yearTo": 2021
}Archive a category without permanently deleting it:
DELETE /api/v1/admin/categories/:id
Authorization: Bearer <admin-token>
Restore an archived category:
{
"status": "active"
}Reject a seller verification:
PATCH /api/v1/admin/sellers/:id/verification
Authorization: Bearer <admin-token>
{"verificationStatus":"rejected","rejectionReason":"CAC document details could not be matched."}
Inventory CSV header:
title,description,categoryId,partNumber,condition,priceKobo,stockQty,location,status,compatibleMake,compatibleModel,compatibleYearFrom,compatibleYearTo,imageUrls
Inventory CSV sample row:
Front Brake Disc,"Premium brake disc for Toyota Camry sedans.",1002,BULK-DISC-001,new,4500000,12,Lagos,active,Toyota,Camry,2007,2011,https://example.com/disc-1.png|https://example.com/disc-2.png
Mark a seller order item as ready for pickup:
PATCH /api/v1/seller/orders/:id/status
Authorization: Bearer <token>
{"itemStatus":"ready_for_pickup"}
Cancel a seller order item:
PATCH /api/v1/seller/orders/:id/status
Authorization: Bearer <token>
{"itemStatus":"cancelled"}
Verify a payment callback:
GET /api/v1/payments/verify/APT-1-1234567890-ABCDEF12
Authorization: Bearer <token>
List buyer orders:
GET /api/v1/orders?status=confirmed&page=1&limit=10
Fetch a single buyer order:
GET /api/v1/orders/1
Fetch current order status and history:
GET /api/v1/orders/1/status
Fetch a receipt as JSON:
GET /api/v1/orders/1/receipt
Fetch a receipt as HTML:
GET /api/v1/orders/1/receipt?format=html
- Login accepts
identifierandpassword.identifiermay be an email address or a Nigerian phone number. - Registration accepts either
email,phone, or both. - In
developmentandtest, forgot-password returns the reset token in the response until email/SMS delivery is added. - Protected routes require
Authorization: Bearer <token>. - Admin users are provisioned outside the public registration flow; local development gets a seeded admin account after
npm run seed. - Catalogue list responses return
{ products, pagination }. - Product price fields and price filters use kobo integers, for example
minPriceKobo=1000000. - The
sellerRatingcatalogue filter is treated as a minimum public seller rating threshold. - Cart responses return
{ id, items, summary }. - Checkout currently supports
paystack,bank_transfer, andussdas payment-method selections. - Delivery fees are now calculated in kobo from the shared base-fee, inferred-distance, and shipment-weight rules used by the logistics settlement flow.
POST /api/v1/ordersaccepts either a saveddeliveryAddressIdor an inlinedeliveryAddressobject, stores an address snapshot on the order, and persists the computed delivery fee on both the order and each order item.GET /api/v1/ordersreturns{ orders, pagination }and supports optional filtering by buyer orderstatus.GET /api/v1/orders/:idreturns the order detail, item lines with per-itemitemStatus, the delivery snapshot, and status history for the authenticated buyer.GET /api/v1/orders/:id/statusreturns the current buyer-visible order status plus the status history timeline.GET /api/v1/orders/:id/receiptreturns JSON by default and supports?format=htmlfor a printable HTML receipt.POST /api/v1/payments/initializeuses the authenticated buyer email by default. If the buyer registered without an email, the request can include anemailfield for Paystack initialization.POST /api/v1/payments/initializesends the Paystack amount in kobo, persists the generated reference on the order, and includesorder_idplususer_idmetadata for later verification.POST /webhooks/paystackis the payment source of truth. The callback redirect is UX-only and the buyer-facing fallback should callGET /api/v1/payments/verify/:referenceafter the user lands back in the app.- Successful Paystack verification moves the order from
pending_paymenttoconfirmed. - The first successful payment confirmation decrements product stock for the matching order items.
- Order creation records an initial
pending_paymentstatus-history entry, and successful payment verification recordsconfirmed. - Webhook signatures are verified against the raw request body with
x-paystack-signatureandPAYSTACK_SECRET_KEY; duplicate webhook deliveries are deduplicated inpayment_webhook_events. - Verification never trusts webhook amounts directly: the backend re-checks the reference against Paystack and flags mismatched
amountorcurrencyresponses instead of fulfilling the order. POST /api/v1/admin/payments/reconcile-pendinglets an admin re-check stale pending payments older than a chosen threshold and settle or expire them through the same Paystack verification path.GET /api/v1/seller/inventoryreturns{ inventory, summary, pagination }and supportsstatuspluslowStockOnlyfiltering.- Low-stock alerts use a fixed threshold of
5units for Milestone S-D. POST /api/v1/seller/inventory/bulkcurrently treats each csv row as one listing with one compatibility entry;imageUrlsshould be pipe-separated when multiple image URLs are provided.GET /api/v1/seller/ordersreturns only the authenticated seller's slice of each order and supports optional filtering by selleritemStatus.PATCH /api/v1/seller/orders/:id/statusoperates on the seller-ownedorder_items.id; moving an item toready_for_pickupnow creates a delivery job and immediately tries nearest-rider auto-assignment.GET /api/v1/seller/dashboardreturns seller profile basics plus UI-ready overview cards, monthly revenue chart data, product-status counts, featured products, customer leaderboard entries, and the existing seller-scoped inventory, order, sales, and payout summaries. It accepts the same optionaldateFromplusdateToquery pair as the seller sales endpoint.GET /api/v1/seller/salesreturns{ period, commissionRatePercent, sales, payouts }and supports optionaldateFromplusdateTofiltering inYYYY-MM-DDformat.POST /api/v1/seller/payoutscurrently creates one payout request for all eligible delivered seller order items that are not already tied to an open payout record.GET /api/v1/seller/payoutsreturns{ payouts, pagination }and supports optional payoutstatusfiltering.POST /api/v1/logistics/registerprovisions a new logistics company and returns the company profile plus a company-scoped access token.POST /api/v1/logistics/loginauthenticates a logistics company with the registered email and password.GET /api/v1/logistics/zonesreturns the delivery zones available for rider onboarding.POST /api/v1/logistics/riderscreates a rider for the authenticated company;zoneIdmust reference an existing delivery zone.GET /api/v1/logistics/ridersreturns{ riders, pagination, filters }and supportsstatus,search,page, andlimit.PATCH /api/v1/logistics/riders/:idlets a company update only its own rider records.PATCH /api/v1/logistics/riders/:id/suspendsuspends one company-owned rider, reassigns not-yet-picked-up jobs, and flags in-progress jobs for manual handling.PATCH /api/v1/logistics/riders/:id/reactivaterestores one company-owned rider account after a suspension.GET /api/v1/logistics/jobsreturns{ jobs, pagination, filters, summary }for the authenticated company and supportsstatus,search,page, andlimit;summary.jobsByStatusexposes company-wide job counts, andsummary.riderPerformanceexposes rider availability plus per-rider delivery outcomes.GET /api/v1/logistics/earningsreturns delivered-job earnings, current payout balances, and settlement totals for the authenticated company.POST /api/v1/logistics/payoutscreates one payout request for all eligible delivered jobs that are not already attached to an open logistics-company payout.POST /api/v1/rider/loginreturns a rider-scoped token for the delivery execution routes.PATCH /api/v1/rider/availabilityacceptsavailable,unavailable, oron_delivery.GET /api/v1/rider/jobsreturns only the authenticated rider's own jobs and supportsstatus,search,page, andlimit.GET /api/v1/rider/jobs/:idreturns the job detail with seller, buyer, order, item, assignee, and delivery-job status history only when the job belongs to the authenticated rider.PATCH /api/v1/rider/jobs/:id/statusenforcesassigned -> picked_up -> in_transit -> deliveredand also allowsassigned|picked_up|in_transit -> failed; only the assigned rider can update the job, andfailureReasonis required forfailed.- Seller payout eligibility now depends on delivered logistics jobs instead of raw payment confirmation alone.
GET /api/v1/admin/logistics/companiesreturns{ companies, pagination, filters, summary }and supportsstatus,search,page, andlimit.PATCH /api/v1/admin/logistics/companies/:id/statusacceptsapprovedorsuspendedfor admin review decisions.GET /api/v1/admin/logistics/ridersreturns{ riders, pagination, filters, summary }and supportscompanyId,status,search,page, andlimit.GET /api/v1/admin/delivery-jobsreturns{ jobs, pagination, filters, summary }and supportsstatus,companyId,riderId,search,page, andlimit;summary.jobsByStatusexposes the queue mix, andsummary.deliveryMetricsexposes unassigned volume, completion rate, and delivered-fee totals.PATCH /api/v1/admin/delivery-jobs/:id/assignassigns a pending job, or reassigns a failed one, to a rider and records an audit-log entry for the manual intervention.GET /api/v1/admin/sellersreturns{ sellers, pagination, filters }and supportsstatus=all|pending|verified|rejected, defaulting topending.GET /api/v1/admin/dashboardreturns UI-ready summary data for the admin home screen, including alerts, overview cards, operational cards, seller verification and payout queue previews, dispute and order previews, top sellers, recent audit activity, and platform-health metrics.GET /api/v1/admin/sellers/:idreturns the seller account, uploaded documents, and the stored CAC lookup response from Dojah.PATCH /api/v1/admin/sellers/:id/verificationacceptsverifiedorrejected;rejectionReasonis required when rejecting.GET /api/v1/admin/payoutsreturns{ payouts, pagination, filters }and supportsstatus,payeeType,sellerId,companyId,search,page, andlimit.PATCH /api/v1/admin/payouts/:idacceptsapproved,rejected, orpaid;rejectionReasonis required when rejecting, and onlyrequested -> approved|rejectedplusapproved -> paidare allowed for both seller and logistics-company payout requests.GET /api/v1/admin/configreturns the current admin-owned platform config for commissions and other operational settings.PATCH /api/v1/admin/configaccepts any combination ofcommissionRateDefault,commissionRatesByCategory,commissionRatesBySellerTier, andplatformSettings.GET /api/v1/admin/disputesreturns{ disputes, pagination, filters }and supportsstatus,raisedBy,search,page, andlimit.PATCH /api/v1/admin/disputes/:idacceptsresolvedorrejected;resolutionNoteis required, refund metadata is optional for resolved disputes, and only open disputes can be reviewed.GET /api/v1/admin/audit-logsreturns{ auditLogs, pagination, filters }and supportsadminId,action,targetType,targetId,page, andlimit.- The webhook endpoint expects the
x-paystack-signatureheader, stores only sanitized Paystack references/status metadata, and never stores card data.
- Money values are stored in kobo.
- Run
npm run migrateto apply SQL files insrc/db/migrations. - Run
npm run seedto load the sample catalogue data, delivery zones, and the dev admin user for local review flows. - The current migration set creates the auth, catalogue, cart, buyer address, order, payment, order-status-history, seller onboarding, seller payout, admin RBAC,
platform_config,audit_logs,disputes,logistics_companies,riders,delivery_zones, delivery-job lifecycle data, and payout-settlement fields needed through Logistics MilestoneL-E.
Partners authenticate with x-api-key, independently of buyer/seller JWTs. Keep keys on your server. Keys have the format ap_live_ followed by 64 random hexadecimal characters. Only SHA-256 hashes are stored; the full key is returned once on creation. The eight-character display prefix is not unique and is not a credential.
All three routes require catalog:read and share a limit of 120 requests per minute per API-key ID. The limiter uses process-local memory: multiple PM2 workers each maintain their own counter, and restarts reset counters.
| Method | Endpoint | Query parameters |
|---|---|---|
| GET | /api/v1/partner/products |
page, limit, search, category, sellerId, minPrice, maxPrice, sort |
| GET | /api/v1/partner/sellers |
page, limit |
| GET | /api/v1/partner/sellers/:id/products |
Product filters; the path ID always determines the seller |
Pagination defaults to page 1 and limit 10, with a maximum limit of 100. category accepts an ID, slug or name. search matches product titles, descriptions and part numbers. minPrice and maxPrice are integers in kobo. sort=newest is the default; sort=price sorts ascending, with stable ID tie-breaking.
Only active products from verified sellers whose user accounts are active and have role seller are included. There is no separate product approval field. Seller product counts include only active products. An unavailable or ineligible seller returns 404 on the seller-products route. City and state are currently null because the schema has no structured seller city/state columns. Responses never include seller addresses, contact details, account identifiers, bank information, KYC data, passwords or verification-provider payloads.
curl 'https://api.example.com/api/v1/partner/products?page=1&limit=10&search=brake&sort=price' \
-H "x-api-key: $PARTNER_API_KEY"
curl 'https://api.example.com/api/v1/partner/sellers' -H "x-api-key: $PARTNER_API_KEY"
curl 'https://api.example.com/api/v1/partner/sellers/12/products' -H "x-api-key: $PARTNER_API_KEY"Partner product responses include images: [{url, isPrimary, position}] ordered by stored position, and thumbnailUrl containing the first image URL. The first eligible image is primary; there is no primary-image database flag. Products without eligible images return images: [] and thumbnailUrl: null. Images for all products on a page are loaded in one additional query; empty pages perform no image query.
URLs use the APP_URL origin, never BASE_URL or a request Host header. Set APP_URL=https://autoparts.zubitechnologies.com before deployment. If it is missing or invalid and a product has a local image, the endpoint returns a configuration error rather than an unusable relative URL. Only stored /uploads/products/<image filename> paths are exposed; legacy remote URLs, disk paths and invalid paths are omitted. No schema migration is needed.
Multer saves files under UPLOAD_DIR/products and stores their public relative path in product_images.url. Express already mounts UPLOAD_DIR at /uploads; it permits only the products/ and product-images/ directories with jpg, jpeg, png, webp and gif extensions, denies dotfiles and directory access, and sends Cache-Control: public, max-age=604800 plus X-Content-Type-Options: nosniff on served images. All other upload directories, including seller-documents/, blog/ and dispute evidence, are blocked from static access. No authenticated admin seller-document streaming endpoint currently exists; admin verification returns metadata only. If Apache serves uploads directly, configure the same restrictions and headers there.
uploads/, public_html/uploads/ and uploads-test/ are ignored by Git. Keep uploads persistent across releases and exclude them from deployment cleanup or synchronization deletion; .gitignore alone cannot prevent deployment tools from deleting files.
Example products response (seller-products uses the same shape):
{
"success": true,
"data": {
"products": [{
"id": 42, "title": "Brake pad", "description": "Front brake pad set",
"partNumber": "BP-42", "priceKobo": 250000, "stockQty": 8,
"images": [
{"url": "https://autoparts.zubitechnologies.com/uploads/products/brake-front.jpg", "isPrimary": true, "position": 1},
{"url": "https://autoparts.zubitechnologies.com/uploads/products/brake-back.jpg", "isPrimary": false, "position": 2}
],
"thumbnailUrl": "https://autoparts.zubitechnologies.com/uploads/products/brake-front.jpg",
"location": "Lagos", "condition": "new", "createdAt": "2026-10-19T10:00:00.000Z",
"category": {"id": 3, "name": "Brakes", "slug": "brakes"},
"seller": {"id": 12, "businessName": "Martins Tech", "city": null, "state": null,
"verificationStatus": "verified", "rating": 4.5, "createdAt": "2026-01-01T10:00:00.000Z"}
}],
"pagination": {"page": 1, "limit": 10, "total": 1, "totalPages": 1}
},
"message": "Request completed successfully."
}Example sellers response:
{"success":true,"data":{"sellers":[{"id":12,"businessName":"Martins Tech","city":null,"state":null,"verificationStatus":"verified","rating":4.5,"createdAt":"2026-01-01T10:00:00.000Z","productCount":1}],"pagination":{"page":1,"limit":10,"total":1,"totalPages":1}},"message":"Request completed successfully."}Missing keys return 401 AUTH_REQUIRED; malformed, unknown, expired or revoked keys return 401 UNAUTHORIZED; insufficient scopes return 403 FORBIDDEN; invalid inputs return 422 VALIDATION_ERROR. Rate limits return 429 RATE_LIMIT_EXCEEDED. Errors follow the existing envelope:
{"success":false,"error":{"code":"UNAUTHORIZED","message":"Invalid or inactive API key."}}Use an active admin JWT with the super_admin role for all management routes:
POST /api/v1/admin/api-keys: body{"name":"Martins Tech","scopes":["catalog:read"],"expiresAt":null}. Scopes default to["catalog:read"]; expiration defaults to null or accepts a future ISO timestamp. Returns 201 with metadata and a one-timedata.key.GET /api/v1/admin/api-keys: returnsdata.apiKeyswithid,name,keyPrefix,scopes,lastUsedAt,expiresAt,revokedAt,createdAt. Never returns hashes or full keys.PATCH /api/v1/admin/api-keys/:id/revoke: revokes a key immediately; repeated revocations preserve the original timestamp. Unknown IDs return 404.
curl -X POST 'https://api.example.com/api/v1/admin/api-keys' \
-H "Authorization: Bearer $ADMIN_TOKEN" -H 'Content-Type: application/json' \
-d '{"name":"Martins Tech","scopes":["catalog:read"]}'
npm run apikey:create -- --name "Martins Tech"The CLI uses the configured database and prints the generated key once. Treat terminal output as a secret; do not redirect it to application logs. The CLI is a trusted operator tool and requires host/database access.
The Partner catalogue and Partner API-key management folders in postman/admin-platform.postman_collection.json contain these requests and examples. Set partnerApiKey locally; no script automatically saves the returned key.
Deploy the code, configure the existing database environment, then apply 042_create_api_keys_table.sql through the migration runner before restarting the API:
export PATH=/opt/cpanel/ea-nodejs20/bin:$PATH
npm ci
npm run migrate
pm2 restart autopart-api --update-envEnsure Apache forwards x-api-key and does not log that header. Create the partner key after migration, deliver it securely, and verify the partner endpoints. No new dependencies are required.