MaaZGSI REST API v1
Complete API for building a React Native mobile application. Covers auth, retailer operations, supplier management, and field agent workflows.
Overview
- 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
metakey withcurrent_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",
}
expo-secure-store or react-native-keychain.Error Codes
| HTTP Code | Meaning | Response body |
|---|---|---|
200 | Success | {"success": true, ...} |
201 | Created | Resource created successfully |
401 | Unauthenticated | Invalid or missing token |
403 | Forbidden | Valid token but insufficient permissions |
404 | Not Found | Resource does not exist |
422 | Validation Error | {"success": false, "errors": {"field": ["message"]}} |
500 | Server Error | Unexpected error — check logs |
Pagination
Any list endpoint accepts ?per_page=N (default 20) and ?page=N. Response includes a meta object:
{
"success": true,
"data": [ ... ],
"meta": {
"current_page": 1,
"last_page": 4,
"per_page": 20,
"total": 72
}
}
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.descriptionon login and/auth/me; supplier admins senddescriptiontoPUT /auth/profile(16). - Retailer suppliers directory —
GET /retailer/suppliers,/retailer/suppliers/categories,/retailer/suppliers/{id},POST /retailer/suppliers/{id}/connect; dashboard addsmy_suppliersandsupplier_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(hasdescriptionandphone);GET /retailer/productsrows now also carrysupplier_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.
| Added | Method | Endpoint | What changed | Mobile app to-do |
|---|---|---|---|---|
| 23 Nov | GET | /retailer/dashboard | Now 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 Nov | GET | /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 Nov | GET | /retailer/sellers | New. Owner + active team members: id, name, role. | Fill a "Sold by" picker on Log Sale. |
| 23 Nov | POST | /retailer/sales | Per 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 Nov | GET | /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 Nov | GET | /retailer/sales/{id}/receipt | Items 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 Nov | GET | /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 Nov | GET | /retailer/reports/top-products | Rows now include product_id, product_name and rank. | Show product_name (the app was showing "Product #1, #2"). |
| 23 Nov | GET | /retailer/expense-categories | New. id, title, name. | Category picker on Add Expense — without it the app could never save an expense. |
| 23 Nov | POST / 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 Nov | POST | /retailer/inventory/{product}/adjust | New. 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 Nov | GET | /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 Nov | PUT / 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 Nov | POST | /retailer/team | password 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 Nov | GET / 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 Nov | GET / POST | /supplier/stock · /supplier/stock/{product}/adjust | New. The supplier's own warehouse stock (stock_on_hand) and add / remove / set. | "My Stock" screen. Low-stock alerts remain the retailers' shelves. |
| 23 Nov | POST | /supplier/sales | New. 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 Nov | POST | /supplier/credit/{retailer_id}/payment | New. amount, reference?, notes? — reduces the outstanding balance. | "Record payment" on the credit screen. |
| 23 Nov | GET / 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 Nov | GET | /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 · latest | PUT | /auth/profile · /auth/me | Supplier 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 Nov | GET / POST | /agent/visits?search=&date=&retailer_id= · /agent/visits | Fixed — 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 · latest | GET / POST | /retailer/suppliers · /retailer/suppliers/categories · /retailer/suppliers/{id} · /retailer/suppliers/{id}/connect | New. 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. |
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.
message on any 4xx error. Every error has a readable message the user can act on.Checklist
| # | Added | Screen | Role | Size | Works today without an app change? |
|---|---|---|---|---|---|
| 1 | 23 Nov | Dashboard: items sold | Retailer | Small | No — card reads a field that didn't exist |
| 2 | 23 Nov | Log Sale: search, markup, sold by | Retailer | Large | No |
| 3 | 23 Nov | Printing receipts | Retailer | Small | No |
| 4 | 23 Nov | Sales History: search + full rows | Retailer | Medium | Partly — rows already carry the new fields |
| 5 | 23 Nov | Sales Overview: 3/6/9/12 months | Retailer | Small | No |
| 6 | 23 Nov | Expenses: categories + edit | Retailer | Medium | No — saving was impossible without categories |
| 7 | 23 Nov | Stock: names, adjust, add product | Retailer | Medium | No |
| 8 | 23 Nov | Orders: product search, edit, delete | Retailer | Medium | No |
| 9 | 23 Nov | Top Products: names | Retailer | Tiny | Probably yes |
| 10 | 23 Nov | Team: add member | Retailer owner | Tiny | Yes — password now optional |
| 11 | 23 Nov | Retailers: search, add, remove | Supplier | Medium | No |
| 12 | 23 Nov | My Stock (warehouse) | Supplier | Medium | No — new screen |
| 13 | 23 Nov | Record Sale + Record Payment | Supplier | Medium | No — new screens |
| 14 | 23 Nov | Clients: rename, search, add, remove | Field agent | Medium | No |
| 15 | 23 Nov | Visits + last note | Field agent | Small | Saving/listing visits: yes (was a server bug). Last note: no |
| 16 | 25 Nov · latest | Profile: "What we supply" | Supplier admin | Small | No |
| 17 | 25 Nov · latest | Suppliers directory (by category) | Retailer | Medium | No — 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?…" }
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 }
4 · Sales History — search by name / date, full rows 23 Nov
| Query param | Meaning |
|---|---|
search | Product name or receipt reference (partial match) |
date | A single day, Y-m-d |
from / to | Date range, Y-m-d |
sold_by | User id from /retailer/sellers |
page, per_page | Pagination (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=attentionreturns low and out-of-stock products, each withproduct_name,current_stock,reorder_levelandstock_status(ok | low_stock | out_of_stock). Show the name and "4 left" or "Out", never only a number.filter=low_stockandfilter=out_of_stockstill 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}/pricewithmargin_percentorselling_price. - Add product to stock (for a product the shop doesn't have yet): pick it from
GET /retailer/products, then call…/adjustwithtype: "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=1and show the chosen supplier'sdescriptionunder it. - Search when adding to an order: use
GET /retailer/products?organization_id=&search=(the same call as Log Sale) and showsupplier_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_priceis 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/clientsand/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_noteas 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/dashboardnow also returnsmy_suppliers(id, name, phone, email, categories) andsupplier_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, ''))andLinking.openURL('mailto:' + email). - Supplier screen: contact details, "What we supply", products grouped by
category. Ifis_my_supplier, show Place an order (opens Place Order with this supplier preselected). Ifrelationshipisnullorremovedandaccepting_ordersis 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.
| Flow | Who | How the app does it | After payment |
|---|---|---|---|
| New signup | Someone with no account yet | WebView on /subscribe | Waits for admin approval, login details sent by email |
| Renewal | Logged-in supplier_admin | POST /subscription/renew → in-app browser | Activated automatically, no approval |
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:
Step 4 — Know when to send the user to Renewal
Only supplier_admin users can pay. There are two triggers:
- Before it lapses:
POST /auth/loginandGET /auth/mereturndata.user.organization.subscription_days_left. Show a banner at 7 days or fewer, and a "Renew now" button. - After it lapses: every
/supplier/*and/agent/*call returns 403 withdata.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'); }
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;
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/meso 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.
| Status | When | What the app should do |
|---|---|---|
422 | Bad coupon (invalid, expired, used up, or wrong plan), or a missing or invalid field | Show the message next to the coupon field and let them fix it or remove it |
403 | The user isn't a supplier_admin | Hide the Pay button for other roles and show "Ask your admin to renew" |
404 | The organisation's plan can't be found | Show the message and a way to contact support |
502 | The server couldn't start a Paystack checkout | Show "Could not start payment, please try again." Retrying is safe |
401 | Token revoked | Already handled: the interceptor sends them to Login |
Testing checklist
- 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.
- 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).
- 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.
- Bad coupon: enter
NOTREAL. You should get a 422 with the message shown in the app. - Lapsed account: with a suspended test organisation, any supplier screen should send a
supplier_adminto Renew and afield_agentto the "ask your admin" screen. - 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.
?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
- 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.
- Redirect to the gateway's own hosted checkout page to pay the (possibly discounted) total — card, bank transfer, or USSD.
- Redirect back to /subscribe/callback/{gateway}, which renders a status page:
paid(awaiting admin approval),processing, orerror.
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/loginwith the emailed credentials.
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.
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.Also reachable while suspended, for the same reason as /subscription/status.
| Field | Type | Required | Notes |
|---|---|---|---|
payment_gateway | string | Required | paystack |
billing_cycle | string | Required | monthly or annual — can differ from the org's current cycle, e.g. switching to annual at renewal |
coupon_code | string | Optional | Validated 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');
/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
Request body:
| Field | Type | Required | Notes |
|---|---|---|---|
email | string | Required | User's email address |
password | string | Required | Account password |
device_name | string | Optional | Identifies 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
}
}
}
}
-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);
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;
Revokes the current access token. The token is immediately invalid after this call.
await api.post('/auth/logout'); await SecureStore.deleteItemAsync('auth_token');
| Field | Type | Required | Notes |
|---|---|---|---|
current_password | string | Required | Must match existing password |
new_password | string | Required | Min 8 characters |
new_password_confirmation | string | Required | Must match new_password |
| Field | Type | Required |
|---|---|---|
username | string | Optional |
phone | string | Optional |
Retailer Endpoints
role_type = retailer authenticated via bearer token.| Query Param | Values | Default |
|---|---|---|
period | today | week | month | custom | month |
from / to | date (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 }, ...
]
}
| Query Param | Values | Default |
|---|---|---|
filter | all | low_stock | out_of_stock | all |
org_id | integer | — (all suppliers) |
search | string — matches product name/code | — |
per_page | integer | 20 |
// 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.| Field | Type | Required | Notes |
|---|---|---|---|
margin_percent | number | One of these two | Computes selling_price = cost × (1 + margin/100) |
selling_price | number | One of these two | Computes margin_percent from cost |
await api.post(`/retailer/inventory/${productId}/price`, { margin_percent: 45 }); // Response: { "product_id": 15, "selling_price": 1740, "margin_percent": 45 }
| Query Param | Values | Default |
|---|---|---|
status | low_stock | out_of_stock | — (all) |
per_page | integer | 25 |
// 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" }
| Field | Type | Required | Notes |
|---|---|---|---|
organization_id | integer | Required | Supplier org this stock belongs to |
items | array | Required | Min 1 item |
items[].product_id | integer | Required | |
items[].quantity | number | Required | Units sold |
items[].price | number | Required | Selling price per unit |
latitude | number | Optional | GPS latitude |
longitude | number | Optional | GPS longitude |
notes | string | Optional | Free 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 }
| Query Param | Type | Notes |
|---|---|---|
org_id | integer | Filter by supplier |
from | date (Y-m-d) | Start date |
to | date (Y-m-d) | End date |
per_page | integer | Default 15 |
{
"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 }, ...
]
}
react-native-print / expo-print) for on-device printing/sharing.| Field | Type | Required |
|---|---|---|
organization_id | integer | Required |
items[].product_id | integer | Required |
items[].quantity | number | Required |
items[].unit_price | number | Required |
notes | string | Optional |
{ "order_id": 128, "reference": "ORD-MOB-XYZ", "total_amount": 185000, "status": "pending" }
Query params: status (pending|approved|delivered|rejected), per_page
Returns {"order": {...}, "items": [...]} with product names on each item.
Query params: type (out_of_stock|low_stock|new_order|...), unread=1
Query param: days (default 30). Returns product name, code, price, cost, total_qty, total_revenue.
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 }
}
| Query Param | Values | Default |
|---|---|---|
from / to | date (Y-m-d) | Last 30 days |
group | day | week | month | day |
{
"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": [...] }
}
| Query Param | Values | Default |
|---|---|---|
from / to | date (Y-m-d) | Current month |
per_page | integer | 20 |
meta.sum_amount holds the total for the selected date range.
| Field | Type | Required | Notes |
|---|---|---|---|
expense_category_id | integer | Required | See /categories or an expense-categories lookup |
amount | number | Required | |
date | date (Y-m-d) | Required | |
description | string | Optional | Max 500 chars |
/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.
| Field | Type | Required | Notes |
|---|---|---|---|
username | string | Required | |
email | string | Required | Must be unique |
password | string | Required | Min 6 characters |
sub_user_role | string | Required | cashier | manager | viewer |
phone | string | Optional |
Supplier Endpoints
role_type = supplier_admin and an organization_id assigned.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.{
"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.
No request body needed. Returns {"order_id": 10, "status": "approved"}.
await api.post(`/supplier/orders/${orderId}/approve`);
| Field | Type | Required |
|---|---|---|
reason | string | Required |
| Field | Type | Required |
|---|---|---|
notes | string | Optional |
| Endpoint | Returns |
|---|---|
/supplier/analytics/top-products | Top 10 products by qty supplied — name, code, price, cost, total_qty, total_supplied |
/supplier/analytics/top-retailers | Top 10 retailers by supply amount received — username, order_count, total_supplied |
/supplier/analytics/sales-trend | Daily delivered supply amount + order count for the period (from supply_orders) |
/supplier/analytics/geo | Retailer sale locations: latitude, longitude, date, retailer_id, retailer_name, product_name — no sale amount included |
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
role_type = field_agent with organization_id assigned.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
Returns stock_summary: {"out_of_stock": N, "low_stock": N, "total_products": N} — useful for pre-visit briefing.
| Field | Type | Required | Notes |
|---|---|---|---|
retailer_id | integer | Required | |
status | string | Required | visited | missed | postponed — matches the web visit-logging form exactly, same table (field_agent_visits) |
notes | string | Optional | Free-text field observation notes |
latitude | number | Optional | GPS latitude at time of visit |
longitude | number | Optional | GPS longitude at time of visit |
checklist | array | Optional | Array 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
| Screen | Role | Endpoint |
|---|---|---|
| LoginScreen | All | POST /auth/login |
| ProfileScreen | All | GET /auth/me, PUT /auth/profile |
| RetailerHome | Retailer | GET /retailer/dashboard |
| StockScreen | Retailer | GET /retailer/inventory |
| LogSaleScreen | Retailer | POST /retailer/sales |
| SalesHistoryScreen | Retailer | GET /retailer/sales |
| RetailerOrdersScreen | Retailer | GET /retailer/orders, POST /retailer/orders |
| RetailerAlertsScreen | Retailer | GET /retailer/alerts |
| TopProductsScreen | Retailer | GET /retailer/reports/top-products |
| SupplierHome | Supplier | GET /supplier/dashboard |
| RetailersScreen | Supplier | GET /supplier/retailers |
| RetailerDetailScreen | Supplier | GET /supplier/retailers/{id} |
| OrdersScreen | Supplier | GET /supplier/orders |
| OrderDetailScreen | Supplier | GET /supplier/orders/{id} |
| InventoryScreen | Supplier | GET /supplier/inventory |
| AlertsScreen | Supplier | GET /supplier/alerts |
| MismatchesScreen | Supplier | GET /supplier/mismatches |
| CreditScreen | Supplier | GET /supplier/credit |
| AnalyticsScreen | Supplier | GET /supplier/analytics/top-products + sales-trend + top-retailers |
| AgentHomeScreen | Field Agent | GET /agent/retailers |
| RetailerBriefScreen | Field Agent | GET /agent/retailers/{id} |
| LogVisitScreen | Field Agent | POST /agent/visits |
| VisitHistoryScreen | Field Agent | GET /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