MajlinkE
Enterprise operations

MaaZGSI REST API v1

Complete API for building a React Native mobile application. Covers auth, retailer operations, supplier management, and field agent workflows.

React Native Sanctum Bearer JSON v1.0
Overview Authentication Error Codes Pagination React Native Setup Nov 2026 client feedbackNew Mobile app changes (by screen)New ↳ Log Sale & markup23 Nov ↳ Sales History23 Nov ↳ Stock23 Nov ↳ Supplier sale & payment23 Nov ↳ Agent clients & notes23 Nov ↳ Supplier "What we supply"25 Nov ↳ Retailer suppliers directory25 Nov Payment Integration GuideNew Steps 1–3 · Signup payment Steps 4–9 · Renewal payment Errors to handle Testing checklist Signup, Expiry & RenewalNew GET /subscription/statusNew POST /subscription/renewNew POST /auth/login GET /auth/me POST /auth/logout POST /auth/change-password PUT /auth/profile GET /retailer/dashboard GET /retailer/inventory POST /retailer/inventory/{product}/priceNew GET /retailer/closing-stockNew POST /retailer/sales GET /retailer/sales GET /retailer/sales/{id}/receiptNew GET /retailer/orders POST /retailer/orders GET /retailer/orders/{id} GET /retailer/alerts GET /retailer/reports/top-products GET /retailer/reports/high-margin GET /retailer/reports/sales-overviewNew ExpensesNew TeamNew GET /supplier/dashboard GET /supplier/retailers GET /supplier/retailers/{id} GET /supplier/orders GET /supplier/orders/{id} POST /supplier/orders/{id}/approve POST /supplier/orders/{id}/reject GET /supplier/inventory GET /supplier/alerts GET /supplier/mismatches POST /supplier/mismatches/{id}/resolve GET /supplier/credit Analytics Endpoints GET /agent/retailers GET /agent/retailers/{id} GET /agent/visits POST /agent/visits Axios Service Auth Flow Screen → Endpoint Map

Overview

Base URL: https://dev.majlinkenterprise.com/api/v1
  • All requests and responses use JSON. Always include Accept: application/json.
  • Authenticated endpoints require Authorization: Bearer {token} in the header.
  • All successful responses follow the shape {"success": true, "message": "...", "data": {...}}.
  • Paginated responses include a meta key with current_page, last_page, per_page, total.

Authentication

MaaZGSI uses Laravel Sanctum token authentication. After login, store the token in AsyncStorage and include it on every request.

// React Native — add to every authenticated request
headers: {
  "Authorization": `Bearer ${token}`,
  "Accept": "application/json",
  "Content-Type": "application/json",
}
💡 Tokens do not expire automatically. They are revoked on logout or password change. Store the token securely using expo-secure-store or react-native-keychain.

Error Codes

HTTP CodeMeaningResponse body
200Success{"success": true, ...}
201CreatedResource created successfully
401UnauthenticatedInvalid or missing token
403ForbiddenValid token but insufficient permissions
404Not FoundResource does not exist
422Validation Error{"success": false, "errors": {"field": ["message"]}}
500Server ErrorUnexpected error — check logs

React Native Project Setup

1. Install dependencies

npx create-expo-app MaaZGSIMobile --template blank-typescript
cd MaaZGSIMobile
npx expo install axios @react-native-async-storage/async-storage
npx expo install expo-secure-store
npx expo install @react-navigation/native @react-navigation/stack
npx expo install react-native-screens react-native-safe-area-context

2. Environment config (config.ts)

export const API_BASE = 'https://dev.majlinkenterprise.com/api/v1';

3. Axios instance with interceptor (services/api.ts)

import axios from 'axios';
import * as SecureStore from 'expo-secure-store';
import { API_BASE } from '../config';

const api = axios.create({
  baseURL: API_BASE,
  headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
  timeout: 15000,
});

// Attach token automatically to every request
api.interceptors.request.use(async (config) => {
  const token = await SecureStore.getItemAsync('auth_token');
  if (token) config.headers.Authorization = `Bearer ${token}`;
  return config;
});

// Handle 401 → redirect to Login
api.interceptors.response.use(
  (res) => res,
  async (err) => {
    if (err.response?.status === 401) {
      await SecureStore.deleteItemAsync('auth_token');
      // navigate to Login screen (use navigation ref)
    }
    return Promise.reject(err);
  }
);

export default api;

4. Auth context (context/AuthContext.tsx)

import React, { createContext, useContext, useState } from 'react';
import * as SecureStore from 'expo-secure-store';
import api from '../services/api';

const AuthContext = createContext({} as any);

export function AuthProvider({ children }: any) {
  const [user, setUser] = useState(null);

  const login = async (email: string, password: string) => {
    const { data } = await api.post('/auth/login', { email, password });
    await SecureStore.setItemAsync('auth_token', data.data.token);
    setUser(data.data.user);
    return data.data.user;
  };

  const logout = async () => {
    await api.post('/auth/logout');
    await SecureStore.deleteItemAsync('auth_token');
    setUser(null);
  };

  return (
    <AuthContext.Provider value={{ user, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
}

export const useAuth = () => useContext(AuthContext);

November 2026 update — client feedback New

Change log

25 Nov · latest

  • Supplier "What we supply" — organization.description on login and /auth/me; supplier admins send description to PUT /auth/profile (16).
  • Retailer suppliers directory — GET /retailer/suppliers, /retailer/suppliers/categories, /retailer/suppliers/{id}, POST /retailer/suppliers/{id}/connect; dashboard adds my_suppliers and supplier_categories (17).
  • Supplier description in pickers — Log Sale and Place Order show the chosen supplier's "What we supply". For the app's supplier picker use GET /retailer/suppliers?mine=1 (has description and phone); GET /retailer/products rows now also carry supplier_description (2, 8).

23 Nov

  • Client feedback round 1: retailer sales, markup, printing, history search, overview periods, expenses, stock, orders, team; supplier retailers, stock, sales & payments; field agent clients and visits (1–15).

Nothing was removed or renamed in either update — existing calls keep working.

Everything below is live on the dev server. Existing calls keep working; the right-hand column is what the app needs to change to match the web. For the step-by-step version with request/response samples, see Mobile App Changes — screen by screen.

AddedMethodEndpointWhat changedMobile app to-do
23 NovGET/retailer/dashboardNow also returns kpis.today_items_sold, kpis.today_sales_count and kpis.items_sold (units in the selected period).Show today_items_sold on the "No. of items sold" card — it was never populated before.
23 NovGET/retailer/products?organization_id=&search=New. Supplier catalogue for Log Sale / Place Order: product_id, name, product_name, code, supplier_name, cost, supplier_price, sell_price, markup_percent, current_stock.Use this for the product search on Log Sale and Place Order (search previously returned nothing because the app searched the retailer's own stock).
23 NovGET/retailer/sellersNew. Owner + active team members: id, name, role.Fill a "Sold by" picker on Log Sale.
23 NovPOST/retailer/salesPer item send markup_percent (on cost) or price; neither = saved selling price. Optional items.*.save_markup (remember as default) and sold_by. Response adds total_items and print_url.Bring back the markup % field per line (price = cost × (1 + markup/100)); add the Sold by picker.
23 NovGET/retailer/sales?date=&from=&to=&search=&sold_by=Each row now has product_names, product_count, total_items, total_amount, sold_by_name. search matches product name or receipt ref. Response includes summary {sales, items, amount}.Add date + name search on Sales History; show product names, total items, total and seller on each row.
23 NovGET/retailer/sales/{id}/receiptItems include product_name; sale.sold_by_name, sale.total_items; store (shop name/address); print_url.Tapping a sale opens this. For printing, open print_url (signed, valid 2 h) in the in-app browser or pass it to expo-print — it auto-opens the print dialog.
23 NovGET/retailer/reports/sales-overview?range=range = 7d | 30d | 3m | 6m | 9m | 1y, or custom from/to. Response adds range and ranges.Add 3 / 6 / 9 months / 1 year chips plus a custom date picker.
23 NovGET/retailer/reports/top-productsRows now include product_id, product_name and rank.Show product_name (the app was showing "Product #1, #2").
23 NovGET/retailer/expense-categoriesNew. id, title, name.Category picker on Add Expense — without it the app could never save an expense.
23 NovPOST / PUT/retailer/expenses · /retailer/expenses/{id}Category is optional: send expense_category_id, or category_name (created if new). date defaults to today. PUT is new (edit).Add Edit on each expense.
23 NovPOST/retailer/inventory/{product}/adjustNew. type=add|remove|set, quantity, optional reason (received, returned, damaged, lost, count, other), notes, reorder_level.Add / remove / set stock and the low-stock alert level from the Stock screen. Price & markup stay on POST /retailer/inventory/{product}/price.
23 NovGET/retailer/inventory?filter=Rows add product_name and stock_status. New filter=attention = low + out of stock.Low-stock list must show the product name; relabel "Total SKUs" to "Products stocked" / "Units in stock".
23 NovPUT / DELETE/retailer/orders/{id}New. Edit (replace items) or delete a pending order. Orders are always priced at the supplier's current price.Edit + Delete on pending orders.
23 NovPOST/retailer/teampassword is now optional — if missing, one is generated, emailed to the member and returned once as data.password. sub_user_role defaults to cashier.Fixes the Add Team Member button; show the returned password if present.
23 NovGET / POST / DELETE/supplier/retailers?search= · /supplier/retailers · /supplier/retailers/{id}Search, add (new shop or link existing by email; returns a one-time password) and remove (status removed, history kept; POST …/{id}/restore undoes).Search bar + Add / Remove retailer.
23 NovGET / POST/supplier/stock · /supplier/stock/{product}/adjustNew. The supplier's own warehouse stock (stock_on_hand) and add / remove / set."My Stock" screen. Low-stock alerts remain the retailers' shelves.
23 NovPOST/supplier/salesNew. Sell / deliver to a retailer: retailer_id, items[{product_id, quantity, unit_price?}], amount_paid?, payment_reference?. Unpaid part goes onto the retailer's outstanding balance."Record Sale" for suppliers.
23 NovPOST/supplier/credit/{retailer_id}/paymentNew. amount, reference?, notes? — reduces the outstanding balance."Record payment" on the credit screen.
23 NovGET / POST / DELETE/agent/clients?search= · /agent/clients · /agent/clients/{id}Clients = retailers (same data, agent wording). Search; add a client (email optional); remove. /agent/retailers still works.Rename "Retailers" to "Clients"; add search bar, Add client and Remove.
23 NovGET/agent/clients/{id}Adds last_note (latest note, when, by whom) and recent_visits.Show the last note at the top of the outlet screen.
25 Nov · latestPUT/auth/profile · /auth/meSupplier admins can send description (what they supply). Login and /auth/me return it as organization.description.Show "What we supply" on the Profile screen; add the field to Edit Profile for supplier admins.
23 NovGET / POST/agent/visits?search=&date=&retailer_id= · /agent/visitsFixed — both were failing with a server error before this update. List supports search (notes or client) and date.Visits now save and list; add search.
25 Nov · latestGET / POST/retailer/suppliers · /retailer/suppliers/categories · /retailer/suppliers/{id} · /retailer/suppliers/{id}/connectNew. Supplier directory: every active supplier with products, by product category, with contact details and the retailer's relationship. Prices only once connected. Dashboard adds my_suppliers and supplier_categories.New Suppliers screen + "Find a supplier" card on Home with Call / Email.
💡 Markup is always on the product's cost: price = cost × (1 + markup_percent / 100). If the user edits the price instead, send price and the server works out the markup.

Mobile App Changes — screen by screen New

Latest (25 Nov 2026): items 16 and 17, highlighted in green. Items 1–15 were added on 23 Nov 2026. Full list in the change log.

What the app has to change so it matches the website after the November 2026 client feedback. The server side is already live on dev, so every call below works today. Work through it one screen at a time. The change table above is the short version.

⚠️ Two rules for every screen: never hardcode prices or product lists (always load them from the server), and show the server's message on any 4xx error. Every error has a readable message the user can act on.

Checklist

#AddedScreenRoleSizeWorks today without an app change?
123 NovDashboard: items soldRetailerSmallNo — card reads a field that didn't exist
223 NovLog Sale: search, markup, sold byRetailerLargeNo
323 NovPrinting receiptsRetailerSmallNo
423 NovSales History: search + full rowsRetailerMediumPartly — rows already carry the new fields
523 NovSales Overview: 3/6/9/12 monthsRetailerSmallNo
623 NovExpenses: categories + editRetailerMediumNo — saving was impossible without categories
723 NovStock: names, adjust, add productRetailerMediumNo
823 NovOrders: product search, edit, deleteRetailerMediumNo
923 NovTop Products: namesRetailerTinyProbably yes
1023 NovTeam: add memberRetailer ownerTinyYes — password now optional
1123 NovRetailers: search, add, removeSupplierMediumNo
1223 NovMy Stock (warehouse)SupplierMediumNo — new screen
1323 NovRecord Sale + Record PaymentSupplierMediumNo — new screens
1423 NovClients: rename, search, add, removeField agentMediumNo
1523 NovVisits + last noteField agentSmallSaving/listing visits: yes (was a server bug). Last note: no
1625 Nov · latestProfile: "What we supply"Supplier adminSmallNo
1725 Nov · latestSuppliers directory (by category)RetailerMediumNo — new screen

1 · Dashboard — "No. of items sold" 23 Nov

GET /retailer/dashboard?period=today|week|month|custom now returns these extra KPIs:

"kpis": {
  "today_items_sold": 65,   // units sold today — use this for "No. of items sold"
  "today_sales_count": 3,   // number of sales today
  "items_sold": 410,        // units sold in the selected period
  ...
}

Bind the card to today_items_sold (or items_sold if the card follows the period selector). Refetch the dashboard after a sale is logged.

2 · Log Sale — product search, markup %, sold by 23 Nov

a. Load the product list for the chosen supplier (debounce the search box about 300 ms):

GET /retailer/products?organization_id=8&search=holl&limit=50

// each item
{ "product_id": 194, "name": "Hollandia Evaporated Milk", "code": "CHI-HEM-400",
  "supplier_name": "Chi Limited", "cost": 310, "supplier_price": 420,
  "sell_price": 465, "markup_percent": 50, "current_stock": 27 }

Supplier picker 25 Nov · latest: fill it from GET /retailer/suppliers?mine=1, which returns the retailer's suppliers with name, description ("What we supply") and phone. Under the picker, show the chosen supplier's description (or "This supplier hasn't described what they supply yet.") with a link to the supplier screen (17). Each product row also carries supplier_description.

b. Each line in the cart shows: product name, quantity, cost (read-only), Markup %, Selling price and line total. Prefill markup and price from markup_percent / sell_price. The two fields drive each other:

// user edits markup
price  = round2(cost * (1 + markup / 100));
// user edits price
markup = cost > 0 ? round2((price - cost) / cost * 100) : 0;

c. Sold by — a picker filled from GET /retailer/sellers ([{ id, name, role }], owner first). Default to the logged-in user. Hide it if the list has only one entry.

d. Save — send price per line (not markup; this avoids rounding drift). Add save_markup: true so the server remembers the price as the default next time (a "Remember these prices" switch, on by default):

POST /retailer/sales
{
  "organization_id": 8,
  "sold_by": 65,
  "items": [
    { "product_id": 194, "quantity": 3, "price": 465, "save_markup": true }
  ],
  "notes": "optional", "latitude": 6.43, "longitude": 3.42
}

// 201
{ "sale_id": 24322, "reference": "SC-MOB-…", "grand_total": 1395, "total_items": 3,
  "sold_by": 65, "date": "2026-11-23 13:16:40", "print_url": "https://dev.majlinkenterprise.com/receipt/24322?…" }
💡 You can also send markup_percent instead of price, and the server works out the price from cost. Send neither and the saved selling price is used. A 422 means a product isn't from that supplier, or the shop isn't an active retailer of it.

e. After saving, show a success sheet with total, items, a Print receipt button (see 3) and New sale.

3 · Printing receipts 23 Nov

POST /retailer/sales and GET /retailer/sales/{id}/receipt both return print_url: a signed link (valid 2 hours, no login needed) to a printable receipt page that opens the print dialog by itself. Open it in the in-app browser:

import * as WebBrowser from 'expo-web-browser';

async function printReceipt(printUrl: string) {
  await WebBrowser.openBrowserAsync(printUrl);  // page calls window.print() on load
}
💡 The link expires, so don't store it. Fetch the receipt again when printing an old sale. A Bluetooth thermal printer would need its own integration later; this covers system printing and Save as PDF.

4 · Sales History — search by name / date, full rows 23 Nov

Query paramMeaning
searchProduct name or receipt reference (partial match)
dateA single day, Y-m-d
from / toDate range, Y-m-d
sold_byUser id from /retailer/sellers
page, per_pagePagination (default 15)
GET /retailer/sales?search=hollandia&date=2026-11-23

{ "data": [ {
    "id": 24322, "reference": "SC-MOB-…", "date": "2026-11-23 13:16:40",
    "product_names": "Chivita Active 1L, Hollandia Evaporated Milk",
    "product_count": 2, "total_items": 13, "total_amount": 7195,
    "sold_by_id": 65, "sold_by_name": "Amaka (cashier)", "payment_statut": "paid"
  } ],
  "meta": { ... },
  "summary": { "sales": 4, "items": 78, "amount": 60195 }   // totals for the whole search
}

UI: a search box, a date chip (Today / pick a date / range) and a "Sold by" filter. Each row shows product names (2 lines max), items, total and seller. Show the summary as a bar above the list. Tapping a row opens GET /retailer/sales/{id}/receipt:

{ "sale":  { ...same fields as the row..., "notes": "…" },
  "items": [ { "product_name": "Hollandia Evaporated Milk", "code": "…", "quantity": 3, "price": 465, "total": 1395 } ],
  "store": { "business_name": "Ebeano Supermarket", "business_address": "…", "city": "Lekki" },
  "print_url": "https://…" }

5 · Sales Overview — period chips 23 Nov

GET /retailer/reports/sales-overview?range=6m          // 7d | 30d | 3m | 6m | 9m | 1y
GET /retailer/reports/sales-overview?from=2026-01-01&to=2026-06-30   // custom

// response adds
"range": "6m", "group": "month",
"ranges": { "7d": "7 days", "30d": "30 days", "3m": "3 months", "6m": "6 months", "9m": "9 months", "1y": "1 year" }

Draw the chips from ranges, plus a "Custom" chip that opens two date pickers. Longer ranges come back grouped by week or month (group), so chart labels look like 2026-07. Format them as "Jul 2026".

6 · Expenses — categories, add, edit 23 Nov

GET  /retailer/expense-categories        // [{ id, title, name }] — fill the picker
POST /retailer/expenses                  // add
PUT  /retailer/expenses/{id}             // edit (new)
DELETE /retailer/expenses/{id}           // unchanged

// body for POST / PUT
{ "amount": 6500, "date": "2026-11-23", "description": "Diesel",
  "expense_category_id": 12 }          // or "category_name": "Generator fuel" for a new one

The category is optional (none = "Other"), and date defaults to today. Add an "Other… type a category" option that sends category_name. The expense list rows now include expense_category_id, so the edit form can preselect the category. Add an edit (pencil) action on each row.

7 · Stock — labels, low stock by name, adjust, add product 23 Nov

  • Labels: replace "Total SKUs" with Products stocked (stock.product_count) and Units in stock (stock.total_qty).
  • Low-stock list: GET /retailer/inventory?filter=attention returns low and out-of-stock products, each with product_name, current_stock, reorder_level and stock_status (ok | low_stock | out_of_stock). Show the name and "4 left" or "Out", never only a number. filter=low_stock and filter=out_of_stock still work for tabs.
  • Adjust (a button on each product): a sheet with Add / Remove / Set exact, quantity, reason and the low-stock alert level.
POST /retailer/inventory/{product_id}/adjust
{ "type": "add", "quantity": 24, "reason": "received", "notes": "optional", "reorder_level": 5 }
// type: add | remove | set      reason: received | returned | damaged | lost | count | other
// to change only the alert level: { "type": "add", "quantity": 0, "reorder_level": 5 }

// 200
{ "product_id": 194, "name": "Hollandia Evaporated Milk", "current_stock": 51, "reorder_level": 5, "change": 24 }
  • Price & margin in the same sheet uses the existing POST /retailer/inventory/{product}/price with margin_percent or selling_price.
  • Add product to stock (for a product the shop doesn't have yet): pick it from GET /retailer/products, then call …/adjust with type: "add".

8 · Orders — product search, edit and delete pending 23 Nov

  • Supplier picker 25 Nov · latest: same as Log Sale. Use GET /retailer/suppliers?mine=1 and show the chosen supplier's description under it.
  • Search when adding to an order: use GET /retailer/products?organization_id=&search= (the same call as Log Sale) and show supplier_price. The old screen searched the shop's own stock, which is why nothing came up.
  • Prices: the server now prices orders at the supplier's current price. unit_price is ignored and can be left out.
PUT    /retailer/orders/{id}   { "items": [ { "product_id": 194, "quantity": 5 } ], "notes": "…" }
       // replaces all items; returns the same shape as GET /retailer/orders/{id}
DELETE /retailer/orders/{id}
       // 404 "Only your pending orders can be edited/deleted." once the supplier has acted

Show Edit and Delete only when status === "pending". Edit reopens the order form prefilled with the current items. Ask for confirmation before deleting.

9 · Top Products — names 23 Nov

GET /retailer/reports/top-products rows now have product_id, product_name (same as name) and rank. Render item.product_name ?? item.name and never fall back to "Product #n". It also accepts from/to as well as days.

10 · Team — add member 23 Nov

POST /retailer/team: password and sub_user_role are now optional (the role defaults to cashier). If the password is left out, the server generates one, emails it to the member and returns it once:

{ "id": 65, "username": "Amaka", "email": "amaka@shop.ng", "sub_user_role": "cashier",
  "password": "x7Kp2mQa9z", "emailed": true }

If password is present in the response, show it in a "Share these login details" sheet with a copy button. Only shop owners can call this (team members get 403), so hide the Add button for them.

11 · Supplier · Retailers — search, add, remove 23 Nov

GET    /supplier/retailers?search=ebeano&status=active   // status: active | pending | suspended | removed | all
POST   /supplier/retailers                              // add
DELETE /supplier/retailers/{id}                         // remove (history kept)
POST   /supplier/retailers/{id}/restore                 // undo a removal

// POST body — only name is required
{ "name": "Musa Ali", "business_name": "Musa Provisions", "email": "optional", "phone": "0803…",
  "address": "…", "city": "Kano", "state": "Kano", "business_type": "Supermarket", "credit_limit": 500000 }
// 201 { "id": 68, "name": "Musa Ali", "created": true, "email": "…", "password": "…" }

List rows now include display_name (shop name, or the person's name if there's no shop name). Use it as the title. If the email already belongs to a shop on MajlinkE, it is linked instead (created: false, no password). Show password once when present. Add a search bar at the top, an "Add retailer" button, a Remove action (with confirmation), and a "Removed" tab with Restore.

12 · Supplier · My Stock (new screen) 23 Nov

The supplier's own warehouse stock, separate from the existing Inventory screen (which shows the retailers' shelves — label that screen "Retailers' stock", and explain that low-stock alerts are about retailers running low).

GET  /supplier/stock?search=&page=
// rows: { product_id, name, code, cost, price, stock_on_hand, is_active }

POST /supplier/stock/{product_id}/adjust
{ "type": "add", "quantity": 200, "reason": "received", "notes": "Invoice 4471" }
// 200 { "product_id": 194, "name": "…", "stock_on_hand": 200, "change": 200 }

Recording a sale to a retailer (13) takes stock out of here automatically. stock_on_hand can go negative if the supplier delivers more than was recorded, so show negatives in red.

13 · Supplier · Record Sale and Record Payment (new screens) 23 Nov

Record Sale: pick a retailer and products (from /supplier/stock, using price as the default unit price), show the running total, then ask for Amount paid now with a "Paid in full" shortcut. Show "₦X goes on credit" live.

POST /supplier/sales
{ "retailer_id": 59, "amount_paid": 1000, "payment_reference": "optional", "notes": "optional",
  "items": [ { "product_id": 194, "quantity": 10, "unit_price": 400 } ] }   // unit_price optional = product price

// 201
{ "delivery_id": 310, "reference": "DEL-…", "total": 4000, "amount_paid": 1000,
  "on_credit": 3000, "outstanding_balance": 303000 }

The sale also adds the goods to the retailer's shelf stock and takes them out of My Stock. Record Payment goes on the retailer's credit screen:

POST /supplier/credit/{retailer_id}/payment   { "amount": 50000, "reference": "TRF-8812", "notes": "optional" }
// 200 { "outstanding_balance": 253000 }

Refresh GET /supplier/credit/{retailer_id} afterwards. The history now shows "Goods delivered (DEL-…)" and "Paid on delivery" entries.

14 · Field agent · Clients — rename, search, add, remove 23 Nov

  • Rename every "Retailer" label in the agent screens to Client (tab, titles, empty states, pickers). Suppliers keep "Retailers".
  • Use the new paths: /agent/clients and /agent/clients/{id}. The old /agent/retailers… paths still work and return the same data.
GET    /agent/clients?search=nkechi      // name, shop name, phone or city; rows include display_name, last_visit, last_note
POST   /agent/clients                    // { name, business_name?, phone?, email?, address?, city?, state?, business_type? }
DELETE /agent/clients/{id}

// POST 201
{ "id": 69, "name": "Mama Nkechi", "email": null, "created": true, "password": null }

Email is optional. Many outlets won't use the app, and they can still be tracked and visited (password is only returned when an email was given). Put the search bar at the top of the list, an "Add client" button, and "Remove client" on the client screen.

15 · Field agent · Visits and the last note 23 Nov

💡 GET /agent/visits, POST /agent/visits and GET /agent/retailers were returning a 500 server error before this update. They work now with no app change, so test them first.
GET /agent/visits?search=cartons&date=2026-11-23&retailer_id=59   // search matches notes or client name

GET /agent/clients/{id}
{ ...,
  "last_note": { "notes": "Needs 2 cartons of Hollandia next week", "status": "visited",
                 "visited_at": "2026-11-23 13:16:41", "agent_name": "Tunde Field Agent" },
  "recent_visits": [ { "id": 1, "status": "visited", "notes": "…", "visited_at": "…" } ] }
  • Show last_note as a highlighted "Last note" card at the top of the client screen (or "No notes yet").
  • On each card in the client list, show the first line of last_note (the list rows include it as a string).
  • On Log Visit, after a client is picked, show their last note above the notes box. After saving, go back to the client screen so the new note appears at the top.

16 · Supplier · Profile — "What we supply" 25 Nov · latest

Suppliers now describe what they supply when they sign up (on the web /subscribe page). It is stored on the organisation and returned by POST /auth/login and GET /auth/me as organization.description (may be null).

  • Profile screen (supplier admin and field agent): add an about card under contact titled "What we supply" that shows organization.description, or "Not added yet" when it's empty.
  • Edit profile (supplier admin only): add a multi-line "What do you supply?" field (max 1,000 characters) and send it with the existing call:
PUT /auth/profile
{ "username": "Chi Limited Admin", "phone": "0803…",
  "description": "Beverages and dairy (Chivita, Hollandia, Capri-Sun), delivering across Lagos and Ogun" }

// 200 { "id": 49, "username": "…", "email": "…", "phone": "…", "description": "…" }
// 403 if a non-supplier-admin sends description — leave the field out for other roles

Re-fetch /auth/me after saving so the profile card updates. On the website, suppliers edit it under Business Profile.

17 · Retailer · Suppliers directory — browse by category, reach a supplier 25 Nov · latest

A new Suppliers screen (and a "Find a supplier" block on the Home/dashboard) so a retailer can find any supplier by product category and call or email them. It lists every active supplier on MajlinkE plus any the retailer already works with, with the retailer's own suppliers first.

GET /retailer/suppliers/categories          // chips: [{ id, name, supplier_count }]
GET /retailer/suppliers?category_id=12&search=dairy&mine=1
// each supplier
{ "id": 8, "name": "Chi Limited", "description": "Beverages and dairy…",
  "phone": "+234 1 764 0000", "email": "info@chifoods.com", "address": "…",
  "categories": [ { "id": 12, "name": "Dairy & Chilled" }, { "id": 3, "name": "Food & Beverages" } ],
  "product_count": 8,
  "relationship": "active",        // active | pending | suspended | removed | null (not connected)
  "is_my_supplier": true, "accepting_orders": true }

GET  /retailer/suppliers/{id}               // same fields + products: [{ product_id, name, code, category, price }]
                                            // price is null until the retailer is connected
POST /retailer/suppliers/{id}/connect       // shop owner only; → { "relationship": "pending" }
  • Home/dashboard: GET /retailer/dashboard now also returns my_suppliers (id, name, phone, email, categories) and supplier_categories. Show a "Find a supplier" card with a search box, the first category chips (tap → Suppliers screen filtered by that category) and the retailer's suppliers with Call / Email buttons.
  • Suppliers screen: a search bar, a horizontal row of category chips ("All" first), an "Only my suppliers" toggle, then supplier cards: name, a "Your supplier" or "Request sent" badge, a 2-line description, category tags, and Call / Email buttons.
  • Call / Email: Linking.openURL('tel:' + phone.replace(/[^0-9+]/g, '')) and Linking.openURL('mailto:' + email).
  • Supplier screen: contact details, "What we supply", products grouped by category. If is_my_supplier, show Place an order (opens Place Order with this supplier preselected). If relationship is null or removed and accepting_orders is true, show Request to work with this supplier (shop owners only). The request appears in the supplier's Retailers → Pending Approval.

Testing on dev

  • Retailer: Ebeano Supermarket (Lekki), supplied by Chi Limited (org 8). Field agent: Emeka (Dangote, org 7). Ask the admin for passwords.
  • Chi Limited's subscription has lapsed on dev, so its supplier and agent logins get the "subscription has lapsed" 403. Use Dangote, or ask the admin to renew Chi Limited.
  • Sales and stock changes on dev are real data on the test server, so use small quantities.

Payment Integration — Step by Step New

This is the build order for adding payments to the mobile app. Follow the steps in order. The endpoint details live in Signup, Expiry & Renewal; this section is the how-to.

How payment works in this app

  • Paystack is the only payment gateway. Always send payment_gateway: "paystack".
  • The server starts every payment and confirms every payment. The app never talks to Paystack's API, never holds a Paystack key, and never decides on its own that a payment succeeded.
  • The app's only jobs are: open the checkout page Paystack gives us, then ask the server what happened.
FlowWhoHow the app does itAfter payment
New signupSomeone with no account yetWebView on /subscribeWaits for admin approval, login details sent by email
RenewalLogged-in supplier_adminPOST /subscription/renew → in-app browserActivated automatically, no approval
⚠️ Never put a Paystack key (pk_… or sk_…) in the app, and don't use the Paystack mobile SDK. Payments the server didn't start have no matching reference, so they are never credited to the organisation.

Step 0 — Install packages

npx expo install react-native-webview expo-web-browser

Step 1 — Add a "Subscribe" WebView screen

Signup must stay a web page (there's no token yet, and approval is manual). Load it in a WebView. If you have a Growth Partner referral code, add ?ref=CODE.

// screens/SubscribeScreen.tsx
import React, { useState } from 'react';
import { Linking } from 'react-native';
import { WebView } from 'react-native-webview';

const SUBSCRIBE_URL = 'https://dev.majlinkenterprise.com/subscribe';
const CALLBACK_PATH = '/subscribe/callback/';

export default function SubscribeScreen({ navigation, route }: any) {
  const ref = route.params?.ref;
  const uri = ref ? `${SUBSCRIBE_URL}?ref=${encodeURIComponent(ref)}` : SUBSCRIBE_URL;
  const [done, setDone] = useState(false);

  return (
    <WebView
      source={{ uri }}
      onShouldStartLoadWithRequest={(req) => {
        // Step 2: bank-app / USSD links (not http/https) must open outside the WebView
        if (!/^https?:/i.test(req.url)) { Linking.openURL(req.url).catch(() => {}); return false; }
        return true;
      }}
      onNavigationStateChange={(nav) => {
        // Step 3: the callback page means the payment step is over
        if (!done && nav.url.includes(CALLBACK_PATH)) {
          setDone(true);
          setTimeout(() => navigation.replace('SignupSubmitted'), 2500); // let them read the status page first
        }
      }}
    />
  );
}

Step 2 — Let bank apps open outside the WebView

On Paystack's checkout, "Pay with bank" or USSD can try to open another app with a non-web link. The onShouldStartLoadWithRequest handler above sends those to the phone instead of showing a blank page. Leave it in.

Step 3 — Show a "Submitted" screen

When the WebView reaches /subscribe/callback/paystack, the server has already checked the payment with Paystack. The page shows paid, processing, or error. Replace the WebView with a plain native screen:

💡 Suggested copy: "Thanks — your application has been submitted. Once our team approves it, we'll email your login details to the admin email you entered. Then come back and log in." Don't try to log in at this point, because the account doesn't exist until a super admin approves it.

Step 4 — Know when to send the user to Renewal

Only supplier_admin users can pay. There are two triggers:

  1. Before it lapses: POST /auth/login and GET /auth/me return data.user.organization.subscription_days_left. Show a banner at 7 days or fewer, and a "Renew now" button.
  2. After it lapses: every /supplier/* and /agent/* call returns 403 with data.subscription_status. Catch that once in the Axios interceptor:
// services/api.ts — add to the existing response interceptor
if (err.response?.status === 403 && err.response?.data?.data?.subscription_status !== undefined) {
  // supplier_admin → Renew screen; field_agent → "Ask your admin to renew" screen
  navigationRef.navigate(user.role_type === 'supplier_admin' ? 'Renew' : 'SubscriptionLapsed');
}
💡 A plain 403 (no subscription_status in data) is an ordinary permissions error. Don't send those users to Renewal.

Step 5 — Build the Renew screen from GET /subscription/status

This endpoint still works while the organisation is suspended. Take prices from it every time. Plans are edited by admins, so never hardcode prices.

const { data } = await api.get('/subscription/status');
const s = data.data;
// Show: s.plan_label, s.subscription_expires_at, s.subscription_days_left
// Toggle: Monthly ₦{s.monthly_price}  /  Annual ₦{s.annual_price}
// If s.extra_users > 0: "+ {s.extra_users} extra users × ₦{s.additional_user_price}" (server adds this; just display it)
// Optional coupon text field

Step 6 — Start the payment with POST /subscription/renew

Save subscription_expires_at before paying. In Step 8 you compare against it to know whether the payment went through.

const before = s.subscription_expires_at;

const res = await api.post('/subscription/renew', {
  payment_gateway: 'paystack',
  billing_cycle: cycle,                  // 'monthly' | 'annual'
  ...(coupon ? { coupon_code: coupon } : {}),
});
const { checkout_url, payment_reference } = res.data.data;
💡 Disable the Pay button while this request is running. Each tap creates a new payment reference.

Step 7 — Open checkout in an in-app browser (not a WebView)

import * as WebBrowser from 'expo-web-browser';

await WebBrowser.openBrowserAsync(checkout_url);
// Resolves when the user closes the browser — paid, cancelled, or just closed.
// After paying, Paystack redirects to our /subscribe/callback/paystack page,
// which confirms the payment on the server. The user then closes the browser.

The in-app browser (SFSafariViewController / Chrome Custom Tabs) handles bank-app links and 3-D Secure pages properly. This call uses a bearer token, so a WebView adds nothing.

Step 8 — Ask the server what happened (poll briefly)

How the browser closed tells you nothing. The server is the only source of truth. It confirms through the callback page or Paystack's webhook, whichever arrives first, and that can take a few seconds. Poll /subscription/status until the expiry date moves forward:

// services/payments.ts
export async function waitForRenewal(before: string | null, tries = 10, everyMs = 3000) {
  for (let i = 0; i < tries; i++) {
    const { data } = await api.get('/subscription/status');
    const s = data.data;
    if (s.subscription_status === 'active' && s.subscription_expires_at !== before) {
      return { paid: true, status: s };
    }
    await new Promise((r) => setTimeout(r, everyMs));
  }
  return { paid: false }; // not confirmed yet — NOT necessarily failed
}

Step 9 — Show the result

  • paid: true: show "Subscription renewed until {date}", refresh /auth/me so the expiry banner goes away, and return the user to where they were.
  • paid: false: show "We haven't confirmed your payment yet. If you were charged, it will show up shortly." Add a "Check again" button that runs Step 8 again. Don't say the payment failed, and don't start a new payment on your own.

Putting Steps 6–9 together:

async function renew(cycle: 'monthly' | 'annual', coupon?: string) {
  setLoading(true);
  try {
    const before = (await api.get('/subscription/status')).data.data.subscription_expires_at;
    const res = await api.post('/subscription/renew', {
      payment_gateway: 'paystack', billing_cycle: cycle, ...(coupon ? { coupon_code: coupon } : {}),
    });
    await WebBrowser.openBrowserAsync(res.data.data.checkout_url);
    const result = await waitForRenewal(before);
    result.paid ? showSuccess(result.status) : showPending();
  } catch (e: any) {
    showError(e.response?.data?.message ?? 'Network error — please try again.');
  } finally {
    setLoading(false);
  }
}

Errors to handle

Every error has a readable message, so show it as it is.

StatusWhenWhat the app should do
422Bad coupon (invalid, expired, used up, or wrong plan), or a missing or invalid fieldShow the message next to the coupon field and let them fix it or remove it
403The user isn't a supplier_adminHide the Pay button for other roles and show "Ask your admin to renew"
404The organisation's plan can't be foundShow the message and a way to contact support
502The server couldn't start a Paystack checkoutShow "Could not start payment, please try again." Retrying is safe
401Token revokedAlready handled: the interceptor sends them to Login

Testing checklist

⚠️ The dev server uses live Paystack keys, so every test payment is a real charge. Use the Test plan (₦200 monthly or annual). Ask the platform owner to refund test payments from the Paystack dashboard.
  1. Signup: open the Subscribe screen, choose the Test plan, and pay ₦200. You should see the callback status page and then your "Submitted" screen. A super admin should then see the application at /admin/platform/subscriptions.
  2. Renewal: renewal charges the organisation's current plan. Ask a super admin to move your test organisation to the Test plan first (Admin → Organisations → Change plan). Then renew from the app and check that the expiry date moves forward by 30 days (monthly) or 365 days (annual).
  3. Cancel: start a renewal and close the browser without paying. You should get the "not confirmed yet" message and no change to the expiry date.
  4. Bad coupon: enter NOTREAL. You should get a 422 with the message shown in the app.
  5. Lapsed account: with a suspended test organisation, any supplier screen should send a supplier_admin to Renew and a field_agent to the "ask your admin" screen.
  6. Bank transfer / USSD: pay at least once with a non-card method on a real phone, to check that Step 2's external-link handling works.

Subscription Signup, Expiry & Renewal New

New supplier organisations sign up and pay through /subscribe — a hosted web page, not a JSON endpoint. It has to stay a web flow because payment happens on Paystack's own hosted checkout page (required for PCI compliance — the app never touches card details), and because approval is a manual step, not something that returns from a single API call.

💡 The right way to offer this in the mobile app is a WebView screen, not a native form. Point it at https://dev.majlinkenterprise.com/subscribe and let the user complete the whole flow — form, plan choice, gateway checkout — inside that WebView. If the app has its own referral/deep-link flow for MAJLINK Growth Partners, append ?ref={code} to the URL — an invalid or missing code never blocks signup, it just fails to attribute the new business to a partner.

Flow the WebView will show

  1. Company + admin account form (including a state selector — seeded with Nigeria's states), plan picker (admin-configurable at /admin/platform/plans — not a fixed list), monthly/annual billing toggle, an optional coupon code, and payment through Paystack.
  2. Redirect to the gateway's own hosted checkout page to pay the (possibly discounted) total — card, bank transfer, or USSD.
  3. Redirect back to /subscribe/callback/{gateway}, which renders a status page: paid (awaiting admin approval), processing, or error.

Detecting completion in React Native

Watch the WebView's navigation events for the callback URL to know the payment step is done, then swap it for a native "check your email" screen — there is no token or account to log in with yet at this point, since a super admin still has to approve.

import { WebView } from 'react-native-webview';

<WebView
  source={{ uri: 'https://dev.majlinkenterprise.com/subscribe' }}
  onNavigationStateChange={{(navState) => {
    if (navState.url.includes('/subscribe/callback/')) {
      // Payment step is done — application is now awaiting admin approval.
      // Swap the WebView for a native "Application submitted — check your
      // email" screen. Do NOT attempt to log in yet; there is no account
      // until a super admin approves it.
      setShowWebView(false);
    }
  }}}
/>

What happens next (outside the app)

  • A super admin reviews the paid application and clicks Approve.
  • Approval creates the organisation + admin user, generates a password, and emails it to the applicant.
  • The applicant returns to the app and logs in normally via POST /auth/login with the emailed credentials.
⚠️ There is no polling endpoint for application status yet — the applicant finds out purely by email once approved. If you need in-app status polling, that would be a new authenticated endpoint (not built yet) since the applicant has no token before approval.

Subscriptions expire — enforcement is API-native

Every org has a subscription_expires_at (roughly a 30-day billing cycle). Reminder emails go out at 7, 3, and 1 day before expiry; after expiry there's a 3-day grace period (still usable, just warned) before the org's subscription_status flips to suspended. At that point, every /supplier/* and /agent/* API call returns 403 (not just web routes) with the shape below — check subscription_days_left proactively from POST /auth/login or GET /auth/me so you can warn the user before they hit a hard 403.

// 403 response body on any /supplier/* or /agent/* call once suspended
{
  "success": false,
  "message": "Your organisation's subscription has lapsed. Please renew to continue.",
  "data": {
    "subscription_status": "suspended",
    "subscription_expires_at": "2026-08-10T00:00:00+00:00",
    "subscription_days_left": -3
  }
}
💡 /retailer/* routes are deliberately exempt — retailers aren't the billing owner, so a supplier's lapsed subscription never blocks their own retailer accounts. Only supplier_admin and field_agent users of the lapsed org are affected.

Renewal — fully native, no WebView

Unlike /subscribe (which has to stay a web page — there's no account/token yet), renewal is a normal bearer-token API call. Same auto-activate-on-payment behavior as before: no admin approval, and it extends from whichever is later — right now, or the org's current expiry — so renewing early never loses paid time.

GET /subscription/status Auth required Plan, price, expiry — reachable even while suspended

Supplier admin only. Deliberately not gated by the suspension check above — this is exactly the endpoint a blocked app needs to render the renewal screen. Plans are admin-configurable (/admin/platform/plans) — always read pricing from this response rather than hardcoding tier prices in the app.

{
  "success": true,
  "data": {
    "plan": "enterprise", "plan_label": "Enterprise",
    "billing_cycle": "monthly",
    "monthly_price": 120000, "annual_price": 1200000,
    "included_users": null, "additional_user_price": 0, "extra_users": 0,
    "is_on_trial": false, "trial_ends_at": null,
    "subscription_status": "suspended",
    "subscription_expires_at": "2026-08-10T00:00:00+00:00",
    "subscription_days_left": -3
  }
}
💡 included_users/additional_user_price are null/0 for a plan with unlimited seats. When included_users is set, extra_users is how many staff/team users the org has beyond that limit — POST /subscription/renew's price already factors this overage in automatically, you don't compute it client-side.
POST /subscription/renew Auth required Start a renewal payment — returns a checkout URL

Also reachable while suspended, for the same reason as /subscription/status.

FieldTypeRequiredNotes
payment_gatewaystringRequiredpaystack
billing_cyclestringRequiredmonthly or annual — can differ from the org's current cycle, e.g. switching to annual at renewal
coupon_codestringOptionalValidated server-side; a 422 with a human-readable message is returned if invalid/expired/exhausted/wrong-plan

Success response (200):

{
  "success": true,
  "message": "Open checkout_url in an in-app browser to complete payment.",
  "data": {
    "checkout_url": "https://checkout.paystack.com/abc123",
    "payment_reference": "REN-XXXXXXXXXX-1755043200"
  }
}

React Native usage — open checkout_url in an in-app browser (expo-web-browser or Chrome Custom Tabs/SFSafariViewController), not a WebView — this is a bearer-token flow, no session cookie involved:

import * as WebBrowser from 'expo-web-browser';

const { data } = await api.post('/subscription/renew', {{
  payment_gateway: 'paystack',
  billing_cycle: 'monthly',
  coupon_code: 'LAUNCH20', // omit if none
}});

const result = await WebBrowser.openBrowserAsync(data.data.checkout_url);
// When the browser closes (user completed or cancelled), the payment has already
// been recorded server-side via webhook regardless of what the browser did —
// just re-fetch status to pick up the outcome:
const refreshed = await api.get('/subscription/status');
💡 Payment confirmation happens server-side (gateway webhook + redirect callback, whichever lands first) — closing the in-app browser doesn't mean payment failed or succeeded. Always re-fetch /subscription/status (or /auth/me) after the browser closes rather than assuming from how it closed.

Invoices — web-only, no JSON endpoint yet

Every confirmed payment (signup approval or renewal) generates a downloadable PDF invoice. There's no /api/v1/... equivalent — the same session-cookie caveat as /renew applies: /invoices (list) and /invoices/{id} (PDF download) are regular web routes requiring a web session, not a bearer token. Link out to them in a WebView/in-app browser signed into the web session if you need to surface invoices in the app; a JSON list endpoint would be a small, separate addition if you need native rendering instead of a PDF viewer.

Auth Endpoints

POST /auth/login Public Authenticate and receive a bearer token

Request body:

FieldTypeRequiredNotes
emailstringRequiredUser's email address
passwordstringRequiredAccount password
device_namestringOptionalIdentifies the device. Revokes existing token with same name. Default: mobile-app

Success response (200):

{
  "success": true,
  "message": "Login successful.",
  "data": {
    "token": "1|abc123...",
    "token_type": "Bearer",
    "user": {
      "id": 20, "username": "Emzor Admin",
      "email": "admin@emzorpharma.com",
      "role_type": "supplier_admin",
      "organization": {
        "id": 1, "name": "Emzor Pharmaceuticals Ltd",
        "subscription_plan": "enterprise",
        "subscription_status": "active",
        "subscription_expires_at": "2026-09-12T01:47:30+00:00",
        "subscription_days_left": 30
      }
    }
  }
}
💡 subscription_days_left is negative once overdue (e.g. -2 = expired 2 days ago), null if no expiry is set. subscription_status is active or suspended — a suspended org has been locked out server-side after a 3-day grace period past expiry. Use these two fields to render your own in-app renewal banner (e.g. warn at subscription_days_left <= 7) — this is returned on both /auth/login and /auth/me, present on every screen that reads the cached user/org, no extra request needed.

React Native usage:

const { data } = await api.post('/auth/login', {
  email: 'admin@emzorpharma.com',
  password: 'Supplier@123',
  device_name: `MaaZGSI-${Platform.OS}`,
});
await SecureStore.setItemAsync('auth_token', data.data.token);
GET /auth/me Auth required Get current user profile and organisation

Returns the authenticated user, their organisation (including subscription_status/subscription_days_left — see the note under POST /auth/login), and retailer profile if applicable.

const { data } = await api.get('/auth/me');
const { username, role_type, organization } = data.data;
POST /auth/logout Auth required Revoke current token

Revokes the current access token. The token is immediately invalid after this call.

await api.post('/auth/logout');
await SecureStore.deleteItemAsync('auth_token');
POST /auth/change-password Auth required Change password and revoke all tokens
FieldTypeRequiredNotes
current_passwordstringRequiredMust match existing password
new_passwordstringRequiredMin 8 characters
new_password_confirmationstringRequiredMust match new_password
⚠️ All tokens are revoked after a password change. User must log in again on all devices.
PUT /auth/profile Auth required Update username and phone number
FieldTypeRequired
usernamestringOptional
phonestringOptional

Retailer Endpoints

All retailer endpoints require a user with role_type = retailer authenticated via bearer token.
GET /retailer/dashboard Auth required New fields KPI cards, gross/net profit, cash flow, closing stock summary, 30-day revenue-vs-expenses chart, 7-day sales trend
Query ParamValuesDefault
periodtoday | week | month | custommonth
from / todate (Y-m-d) — used when period=custom—
{
  "period": "month", "from": "2026-07-01", "to": "2026-07-21",
  "kpis": {
    "today_sales": 0,       "monthly_sales": 609120,
    "total_sales_count": 146, "pending_orders": 1,
    "out_of_stock": 0,      "low_stock": 3,
    "unread_alerts": 4,    "suppliers_count": 2,
    "gross_profit": 184320,  "total_expenses": 42000,
    "net_profit": 142320,   "cash_flow": 567120
  },
  "stock": {
    "product_count": 32, "total_qty": 1840,
    "cost_value": 920000, "sell_value": 1310000,
    "out_of_stock": 0, "low_stock": 3
  },
  "chart": {
    "labels": ["22 Jun", "23 Jun", ...],
    "revenue": [18000, 0, ...],
    "expenses": [2000, 0, ...]
  },
  "sales_trend": [
    { "day": "2026-07-15", "total": 233600, "count": 3 }, ...
  ]
}
GET /retailer/inventory Auth required New fields Stock qty, cost, sell price and % margin per item across all suppliers
Query ParamValuesDefault
filterall | low_stock | out_of_stockall
org_idinteger— (all suppliers)
searchstring — matches product name/code—
per_pageinteger20
// Each item in data[]
{
  "product_id": 15, "name": "Emzor ORS Sachets", "code": "EMZ-015",
  "cost": 1200, "sell_price": 1950, "margin_pct": 62.5,
  "current_stock": "200.00", "reorder_level": "20.00",
  "stock_cost_value": 240000, "stock_sell_value": 390000,
  "organization_id": 1, "organization_name": "Emzor Pharmaceuticals Ltd"
}
💡 sell_price/margin_pct reflect this retailer's custom price if one was set via the margin editor below, otherwise the supplier's default product price.
POST /retailer/inventory/{product}/price Auth required New Inline margin editor — set a custom selling price by margin % or fixed price
FieldTypeRequiredNotes
margin_percentnumberOne of these twoComputes selling_price = cost × (1 + margin/100)
selling_pricenumberOne of these twoComputes margin_percent from cost
await api.post(`/retailer/inventory/${productId}/price`, { margin_percent: 45 });
// Response: { "product_id": 15, "selling_price": 1740, "margin_percent": 45 }
GET /retailer/closing-stock Auth required New Daily closing stock — qty, cost, sell price, margin, stock value per item
Query ParamValuesDefault
statuslow_stock | out_of_stock— (all)
per_pageinteger25
// Each item in data[]
{ "product_id": 15, "name": "Emzor ORS Sachets", "cost": 1200,
  "sell_price": 1950, "margin_pct": 62.5,
  "current_stock": 200, "stock_value": 240000, "last_sale_at": "2026-07-20 16:40:00" }
POST /retailer/sales Auth required Log a sale — auto deducts inventory, fires alerts
FieldTypeRequiredNotes
organization_idintegerRequiredSupplier org this stock belongs to
itemsarrayRequiredMin 1 item
items[].product_idintegerRequired
items[].quantitynumberRequiredUnits sold
items[].pricenumberRequiredSelling price per unit
latitudenumberOptionalGPS latitude
longitudenumberOptionalGPS longitude
notesstringOptionalFree text note
// Request
const { data } = await api.post('/retailer/sales', {
  organization_id: 1,
  items: [
    { product_id: 3, quantity: 10, price: 2100 },
    { product_id: 7, quantity: 25, price: 1300 },
  ],
  latitude:  12.0022,
  longitude: 8.5920,
});
// Response (201)
{ "sale_id": 18942, "reference": "SC-MOB-ABC123", "grand_total": 53500 }
⚠️ If sold quantity exceeds supplied quantity, a mismatch log is automatically created and a critical alert fires to the supplier.
GET /retailer/sales Auth required Paginated sales history
Query ParamTypeNotes
org_idintegerFilter by supplier
fromdate (Y-m-d)Start date
todate (Y-m-d)End date
per_pageintegerDefault 15
GET /retailer/sales/{id}/receipt Auth required New Print-ready receipt data for a sale
{
  "sale": { "id": 18942, "Ref": "SC-MOB-ABC123", "date": "2026-07-20 16:40:00", "GrandTotal": 53500, ... },
  "items": [
    { "name": "Emzor ORS Sachets", "code": "EMZ-015", "quantity": 10, "price": 2100, "total": 21000 }, ...
  ]
}
💡 Render this into a receipt layout client-side (or via react-native-print / expo-print) for on-device printing/sharing.
POST /retailer/orders Auth required Place a restock order with a supplier
FieldTypeRequired
organization_idintegerRequired
items[].product_idintegerRequired
items[].quantitynumberRequired
items[].unit_pricenumberRequired
notesstringOptional
{ "order_id": 128, "reference": "ORD-MOB-XYZ", "total_amount": 185000, "status": "pending" }
GET /retailer/orders Auth required List retailer's supply orders

Query params: status (pending|approved|delivered|rejected), per_page

GET /retailer/orders/{id} Auth required Single order with full line items

Returns {"order": {...}, "items": [...]} with product names on each item.

GET /retailer/alerts Auth required Alerts for this retailer

Query params: type (out_of_stock|low_stock|new_order|...), unread=1

GET /retailer/reports/top-products Auth required Top 10 products by units sold

Query param: days (default 30). Returns product name, code, price, cost, total_qty, total_revenue.

GET /retailer/reports/high-margin Auth required This retailer's own stocked products, ranked by margin

Returns products currently in this retailer's own inventory (not a supplier-set flag), using their custom selling price when one is set via POST /retailer/inventory/{product}/price — falling back to the product's default price otherwise. margin_pct is markup over cost: (sell_price − cost) / cost × 100. Paginated, ordered by margin descending. Identical data source and formula to the web /retailer/reports/high-margin page.

{
  "success": true,
  "data": [
    { "id": 14, "name": "Emzor Cough Syrup 100ml", "code": "EMZ-014",
      "cost": 350, "sell_price": 600, "margin_percent": 71.4,
      "current_stock": "656.00" }
  ],
  "meta": { "current_page": 1, "last_page": 1, "per_page": 20, "total": 6 }
}
GET /retailer/reports/sales-overview Auth required New Products/qty/amount sold + gross & net profit, grouped by day/week/month
Query ParamValuesDefault
from / todate (Y-m-d)Last 30 days
groupday | week | monthday
{
  "from": "2026-06-22", "to": "2026-07-21", "group": "week",
  "sales_by_period": [
    { "period": "2026-29", "count": 12, "revenue": 184000,
      "gross_profit": 61200, "expenses": 9000, "net_profit": 52200 }, ...
  ],
  "products_sold": [
    { "name": "Emzor ORS Sachets", "total_qty": 140, "total_revenue": 273000,
      "margin_pct": 62.5, "gross_profit": 105000 }, ...
  ],
  "totals": { "revenue": 184000, "gross_profit": 61200, "expenses": 9000, "net_profit": 52200, "count": 12 },
  "chart": { "labels": [...], "revenue": [...], "profit": [...], "expenses": [...] }
}
GET /retailer/expenses Auth required New Paginated expense list with category breakdown and period total
Query ParamValuesDefault
from / todate (Y-m-d)Current month
per_pageinteger20

meta.sum_amount holds the total for the selected date range.

POST /retailer/expenses Auth required New Record a new expense
FieldTypeRequiredNotes
expense_category_idintegerRequiredSee /categories or an expense-categories lookup
amountnumberRequired
datedate (Y-m-d)Required
descriptionstringOptionalMax 500 chars
DELETE /retailer/expenses/{id} Auth required New Soft-delete an expense
GET /retailer/team Auth required New List sub-accounts (cashier/manager/viewer) — owner only
⚠️ Only the main retailer account can manage the team. Sub-users calling any /retailer/team* endpoint receive 403.

Every other /retailer/* endpoint is shared: a cashier/manager/viewer sub-user authenticates with their own token but reads and writes against the owner's data.

POST /retailer/team Auth required New Add a sub-user (cashier, manager, or viewer)
FieldTypeRequiredNotes
usernamestringRequired
emailstringRequiredMust be unique
passwordstringRequiredMin 6 characters
sub_user_rolestringRequiredcashier | manager | viewer
phonestringOptional
POST /retailer/team/{id}/revoke Auth required New Deactivate a sub-user (status → 0), blocking their login
POST /retailer/team/{id}/restore Auth required New Re-activate a previously revoked sub-user
DELETE /retailer/team/{id} Auth required New Permanently remove a sub-user

Supplier Endpoints

All supplier endpoints require a user with role_type = supplier_admin and an organization_id assigned.
🔒 Data boundary: suppliers never see a retailer's sale price or customer revenue. Every KPI, trend, and analytics endpoint below is sourced from supply_orders / supply_order_items — the supplier's own stock quantity supplied and the supply cost the retailer paid them, not what the retailer resold it for.
GET /supplier/dashboard Auth required Full dashboard KPIs + 7-day delivery trend
{
  "organisation": { "id": 1, "name": "Emzor Pharmaceuticals Ltd", "plan": "enterprise" },
  "kpis": {
    "total_retailers": 8,   "active_retailers": 5,
    "pending_orders": 3,   "unread_alerts": 4,
    "month_revenue": 0,    "total_outstanding": 0,
    "low_stock": 0,        "out_of_stock": 0,
    "open_mismatches": 2
  },
  "sales_trend": [ { "day": "2026-05-29", "total": 777800, "count": 5 }, ... ]
}

month_revenue and sales_trend[].total are the supplier's own delivered supply amount (from supply_orders.total_amount) — never the retailer's retail sale total.

GET /supplier/retailers Auth required Paginated retailer list — query: status (active|pending|suspended|all), per_page
GET /supplier/retailers/{id} Auth required Retailer detail with inventory, recent orders, 30-day supply-delivery trend, open mismatch count
GET /supplier/orders Auth required All supply orders — query: status (pending|approved|delivered|rejected), per_page
GET /supplier/orders/{id} Auth required Single order with full line items and retailer name
POST /supplier/orders/{id}/approve Auth required Approve a pending order — sends info alert to retailer

No request body needed. Returns {"order_id": 10, "status": "approved"}.

await api.post(`/supplier/orders/${orderId}/approve`);
POST /supplier/orders/{id}/reject Auth required Reject a pending order with a reason
FieldTypeRequired
reasonstringRequired
GET /supplier/inventory Auth required All inventory snapshots — query: filter (all|low_stock|out_of_stock), per_page
GET /supplier/alerts Auth required Org alerts — query: type, severity, unread=1, per_page. Returns retailer & product names.
GET /supplier/mismatches Auth required Mismatch logs — query: status (open|investigating|resolved), severity (critical|warning)
GET /supplier/credit Auth required Credit summary: outstanding balance and available credit per active retailer
POST /supplier/mismatches/{id}/resolve Auth required Mark a mismatch as resolved
FieldTypeRequired
notesstringOptional
GET /supplier/analytics/* Auth required Four analytics endpoints — all accept ?days= (default 30)
EndpointReturns
/supplier/analytics/top-productsTop 10 products by qty supplied — name, code, price, cost, total_qty, total_supplied
/supplier/analytics/top-retailersTop 10 retailers by supply amount received — username, order_count, total_supplied
/supplier/analytics/sales-trendDaily delivered supply amount + order count for the period (from supply_orders)
/supplier/analytics/geoRetailer sale locations: latitude, longitude, date, retailer_id, retailer_name, product_name — no sale amount included
💡 All four are computed from supply_orders/supply_order_items (delivered orders only), i.e. what the supplier shipped and was paid by the retailer — never the retailer's downstream sale price to their own customers.

Field Agent Endpoints

Requires role_type = field_agent with organization_id assigned.
GET /agent/retailers Auth required All org retailers with last sale date and last visit date

Each retailer includes: username, city, latitude, longitude, last_sale, last_visit, plan.

const { data } = await api.get('/agent/retailers');
// Use data.data for the array, data.meta for pagination
GET /agent/retailers/{id} Auth required Full retailer detail — inventory, stock summary, last visit, recent sales

Returns stock_summary: {"out_of_stock": N, "low_stock": N, "total_products": N} — useful for pre-visit briefing.

GET /agent/visits Auth required Agent's own visit history — query: retailer_id, per_page
POST /agent/visits Auth required Log a retailer visit with GPS and checklist
FieldTypeRequiredNotes
retailer_idintegerRequired
statusstringRequiredvisited | missed | postponed — matches the web visit-logging form exactly, same table (field_agent_visits)
notesstringOptionalFree-text field observation notes
latitudenumberOptionalGPS latitude at time of visit
longitudenumberOptionalGPS longitude at time of visit
checklistarrayOptionalArray of checklist items [{"item": "...", "passed": true}]
const { data } = await api.post('/agent/visits', {
  retailer_id: 22,
  status: 'visited',
  latitude: 12.0022, longitude: 8.5920,
  notes: 'Stock count matches. Ordered 200 units Paracetamol.',
  checklist: [
    { item: 'NAFDAC certificate displayed', passed: true },
    { item: 'Cold chain maintained', passed: false },
  ],
});
// Response (201): { "visit_id": 12, "status": "visited" }

React Native Implementation Guide

Auth Flow

// App.tsx — check for stored token on launch
useEffect(() => {
  (async () => {
    const token = await SecureStore.getItemAsync('auth_token');
    if (token) {
      try {
        const { data } = await api.get('/auth/me');
        setUser(data.data);
        navigation.replace('Main');
      } catch {
        navigation.replace('Login');
      }
    } else {
      navigation.replace('Login');
    }
  })();
}, []);

Role-based navigation after login

const { role_type } = user;
if (role_type === 'retailer')      navigation.replace('RetailerStack');
if (role_type === 'supplier_admin') navigation.replace('SupplierStack');
if (role_type === 'field_agent')   navigation.replace('AgentStack');
if (role_type === 'super_admin')   navigation.replace('AdminStack');

Screen → API Endpoint Map

ScreenRoleEndpoint
LoginScreenAllPOST /auth/login
ProfileScreenAllGET /auth/me, PUT /auth/profile
RetailerHomeRetailerGET /retailer/dashboard
StockScreenRetailerGET /retailer/inventory
LogSaleScreenRetailerPOST /retailer/sales
SalesHistoryScreenRetailerGET /retailer/sales
RetailerOrdersScreenRetailerGET /retailer/orders, POST /retailer/orders
RetailerAlertsScreenRetailerGET /retailer/alerts
TopProductsScreenRetailerGET /retailer/reports/top-products
SupplierHomeSupplierGET /supplier/dashboard
RetailersScreenSupplierGET /supplier/retailers
RetailerDetailScreenSupplierGET /supplier/retailers/{id}
OrdersScreenSupplierGET /supplier/orders
OrderDetailScreenSupplierGET /supplier/orders/{id}
InventoryScreenSupplierGET /supplier/inventory
AlertsScreenSupplierGET /supplier/alerts
MismatchesScreenSupplierGET /supplier/mismatches
CreditScreenSupplierGET /supplier/credit
AnalyticsScreenSupplierGET /supplier/analytics/top-products + sales-trend + top-retailers
AgentHomeScreenField AgentGET /agent/retailers
RetailerBriefScreenField AgentGET /agent/retailers/{id}
LogVisitScreenField AgentPOST /agent/visits
VisitHistoryScreenField AgentGET /agent/visits

Suggested React Native file structure

MaaZGSIMobile/
├── src/
│   ├── config.ts                  # API_BASE URL
│   ├── services/
│   │   └── api.ts                 # Axios instance with interceptors
│   ├── context/
│   │   └── AuthContext.tsx        # Login, logout, user state
│   ├── navigation/
│   │   ├── AppNavigator.tsx       # Root navigator (auth check)
│   │   ├── RetailerStack.tsx      # Retailer tab + stack
│   │   ├── SupplierStack.tsx      # Supplier tab + stack
│   │   └── AgentStack.tsx         # Field agent stack
│   ├── screens/
│   │   ├── auth/
│   │   │   ├── LoginScreen.tsx
│   │   │   └── ChangePasswordScreen.tsx
│   │   ├── retailer/
│   │   │   ├── DashboardScreen.tsx
│   │   │   ├── InventoryScreen.tsx
│   │   │   ├── LogSaleScreen.tsx
│   │   │   ├── OrdersScreen.tsx
│   │   │   └── AlertsScreen.tsx
│   │   ├── supplier/
│   │   │   ├── DashboardScreen.tsx
│   │   │   ├── RetailersScreen.tsx
│   │   │   ├── OrdersScreen.tsx
│   │   │   ├── InventoryScreen.tsx
│   │   │   ├── AlertsScreen.tsx
│   │   │   ├── MismatchesScreen.tsx
│   │   │   ├── CreditScreen.tsx
│   │   │   └── AnalyticsScreen.tsx
│   │   └── agent/
│   │       ├── RetailersScreen.tsx
│   │       ├── RetailerDetailScreen.tsx
│   │       └── LogVisitScreen.tsx
│   └── hooks/
│       ├── useRetailerDashboard.ts  # useSWR or React Query wrappers
│       └── useSupplierOrders.ts
└── App.tsx