Commission Ledger API

The HTTP API is a JSON API that powers the Commission Ledger portal. It is consumed by the bundled browser front end, but any client that can hold a cookie session works. Amounts are handled in the account currency (KES) and stored to two decimal places.

Conventions

AspectBehaviour
Base URLhttps://kountoo.co.ke/api — served through api.php
Content typeRequest and response bodies are JSON (application/json; charset=utf-8), except the CSV export
Body size limit1 MiB for POST/PUT/PATCH; larger bodies are rejected with 413
AuthenticationPHP session cookie issued by POST /api/auth/login. No bearer tokens
CSRFAll non-GET requests must either carry a same-origin Origin header or an X-CSRF-Token header with the token returned by login
Rolesadmin and client; every endpoint states its allowed roles
IDsPath IDs are UUIDs; malformed IDs are rejected with 400 Invalid ID.
ErrorsNon-success responses are {"error": "<message>"}
CORSSame-origin by default. Cross-origin requests must match an exact origin in CORS_ALLOWED_ORIGINS; wildcard origins are never accepted, and requests are credentialed

Common responses

  • 204 — CORS pre-flight (OPTIONS) acknowledgement, no body.
  • 401 — No session, or the session user is inactive: {"error": "Please sign in."}
  • 403 — Role check failed (Forbidden.), CSRF/CORS rejection, or the account still has mustChangePassword set and the path is not /api/me, /api/auth/password or /api/auth/logout.
  • 404 — Endpoint or record not found.
  • 409 — Conflicting state: duplicate record, cycle already calculated, open request, insufficient ledger balance, or a database constraint violation.
  • 413 — Request body over 1 MiB.
  • 500 — Unexpected server or database failure. Details are logged server-side only, never returned.

Authentication

Sign in

POST/api/auth/loginPublic

Body:

{
  "email": "jane@example.com",
  "password": "..."
}

On success the session starts, the cookie is set, and the session ID is regenerated.

  • 200 — {"user": {"id", "full_name", "email", "role", "mustChangePassword"}, "csrfToken": "64 hex chars"}
  • 401 — Invalid email or password.
Keep the returned csrfToken — it is required for non-GET requests from clients that do not send an Origin header.

Sign out

POST/api/auth/logoutAny authenticated role
  • 200 — {"ok": true}, destroys the session.

Request a password reset

POST/api/auth/password-reset-requestPublic (clients only)

Body: {"email": "jane@example.com"}. Creates a reset request for the administrator. The response is identical whether or not the email exists.

  • 200 — {"message": "If the account is eligible, a request has been sent to the administrator."}

At most one pending request per client, and at most one request per 24 hours.

Change password

PUT/api/auth/passwordAny authenticated role

Body: {"password": "…"} — minimum 12 characters. Also clears the mustChangePassword flag.

  • 200 — {"ok": true}

Current session

GET/api/meAny authenticated role
  • 200 — {"user": {…}, "csrfToken": "…"} (same shape as login)

Read profile

GET/api/profileAny authenticated role
  • 200 — {"user": {…}}

Update profile

PUT/api/profileAny authenticated role
{
  "name": "Jane Doe",
  "email": "jane@example.com",
  "avatarType": "male",
  "password": "optional, min 12 chars"
}
  • 200 — {"ok": true}
  • 400 — Enter a valid name and email. or Password must be at least 12 characters.

System

Health check

GET/api/healthPublic

Verifies database connectivity.

  • 200 — {"status": "ok", "database": "ok"}
  • 503 — {"status": "degraded", "database": "unavailable"}

Client portal (role: client)

Dashboard overview

GET/api/client/overview

Returns everything the client dashboard renders.

{
  "capital": 150000.0,
  "investments": [{ "amount", "invested_at", "eligible_on",
                    "expected_payout_on", "expected_commission" }],
  "payouts": [{ "amount", "cycle_number", "payout_on",
                "investment_amount", "invested_at" }],
  "paymentMethod": { "method", "account_name", "mpesa_number",
                     "bank_name", "bank_account" },
  "payoutRequest": { "id", "status", "requested_at" } | null
}

Open a payout request

POST/api/client/payout-request
  • 201 — {"ok": true}
  • 409 — You already have an open payout request. or There are no eligible investments awaiting payout.

Update payment method

PUT/api/client/payment-method

Body: {"method": "M-Pesa" | "Bank Account", "accountName": "…"} plus, for M-Pesa, mpesaNumber; for a bank account, bankName and bankAccount. Legacy snake_case keys (account_name, mpesa_number, bank_name, bank_account) are also accepted. Upserts the client's single payment method.

  • 200 — {"ok": true}
  • 400 — Invalid payment details. / Complete the selected payment details.

Client management (role: admin)

List clients

GET/api/clients

Only active client accounts are returned, ordered by full name.

{
  "clients": [{
    "id", "full_name", "email", "active", "avatar_type", "capital",
    "method", "mpesa_number", "bank_account",
    "investments": [{ "amount", "invested_at" }]
  }]
}

Create a client

POST/api/clients

Body: {"name": "…", "email": "…"}. Creates a client with a one-time temporary password, or re-activates a previously deleted (inactive) client with the same email.

  • 201 — {"client": {"id", "full_name", "email"}, "temporaryPassword": "12 hex chars"}
  • 200 — same shape plus "restored": true when an inactive client was restored
  • 400 — Enter a valid name and email.
  • 409 — A client with this email already exists.
The temporary password is shown once; the client must change it at first sign-in.

Record capital

POST/api/clients/{clientId}/capital

Body: {"amount": 25000, "investmentMode": "single" | "separate"}. single adds the amount to the client's most recent confirmed investment (creating one if none exists); the default separate creates a new confirmed investment dated today.

  • 201 — {"ok": true}
  • 400 — Amount must be greater than zero. / Invalid ID.
  • 404 — Client not found.

Deactivate a client

DELETE/api/clients/{clientId}
  • 200 — {"ok": true}
  • 404 — Client not found.

Issue a temporary password

POST/api/admin/clients/{clientId}/temporary-password

Issues a new temporary password and clears the client's pending password-reset requests.

  • 200 — {"temporaryPassword": "12 hex chars"}
  • 404 — Client not found.

List password reset requests

GET/api/admin/password-reset-requests
  • 200 — {"requests": [{"id", "requested_at", "user_id", "full_name", "email"}]}

Ledger & dashboard (role: admin)

List transactions

GET/api/transactions
  • 200 — {"transactions": [{…, "created_by_name", "reversal_id"}]}, newest first.

Record a transaction

POST/api/transactions

Body: {"type": "Capital In" | "Dividend In" | "Payout Out", "party": "…", "amount": 5000, "reference"?: "…", "notes"?: "…"}

  • 201 — {"ok": true}
  • 400 — Invalid transaction.

Reverse a transaction

POST/api/transactions/{transactionId}/reverse

Creates the offsetting entry (Payout Out → Capital In, otherwise Payout Out) and links it via reversal_of. Atomic; each transaction can be reversed once.

  • 201 — {"ok": true}
  • 404 — Transaction not found. / Transaction has already been reversed.

Ledger balance

GET/api/ledger/balance
  • 200 — {"balance": 0.0} — sum of Capital In/Dividend In minus Payout Out.

Dashboard totals

GET/api/dashboard
  • 200 — {"clients": int, "capital": 0.0, "pendingPayouts": 0.0, "cycle": {"payout_on"} | null}

Analytics

GET/api/analytics
{
  "paidOutThisMonth": 0.0,
  "pendingLiability": 0.0,
  "feesCollectedThisMonth": 0.0,
  "topClients": [{ "full_name", "email", "total_paid" }]
}

Fee rules (role: admin)

List fee rules

GET/api/fee-rules
  • 200 — {"feeRules": [{"id", "name", "type": "flat" | "tiered", "flat_rate", "tiers", "active", …}]}, newest first.

Create a fee rule

POST/api/fee-rules

Flat rule: {"type": "flat", "name": "…", "flatRate": 5, "activate"?: true} — rate 0–100.

Tiered rule: {"type": "tiered", "name": "…", "tiers": [{"min": 0, "max"?: 50000, "rate": 5}], "activate"?: true} — tiers must have increasing, non-overlapping ranges and rates 0–100. Rates are percentages.

  • 201 — {"ok": true}
  • 400 — Invalid fee rule. / Rate must be between 0 and 100. / Tiered rules require tiers. / Tiers must have increasing non-overlapping ranges and rates from 0 to 100.

When activate is true, the previously active rule is deactivated in the same transaction.

Activate a fee rule

PUT/api/fee-rules/{ruleId}/activate
  • 200 — {"ok": true}
  • 404 — Fee rule not found. (only one rule can be active at a time)

Delete a fee rule

DELETE/api/fee-rules/{ruleId}

Deletes an inactive rule; active rules are silently not deleted.

  • 200 — {"ok": true}

Payout cycles (role: admin)

List payout cycles

GET/api/payout-cycles
  • 200 — {"cycles": [{"id", "cycle_number", "starts_on", "payout_on", …}]}, newest payout date first.

Create a payout cycle

POST/api/payout-cycles

Body: {"startsOn": "2026-11-01", "payoutOn": "2026-11-30"} — payoutOn must be after startsOn. The cycle number is assigned under a PostgreSQL advisory lock to prevent duplicates.

  • 201 — {"ok": true}
  • 400 — Enter a valid start date and a payout date after it.

Calculate payouts

POST/api/payout-cycles/{cycleId}/calculate-payouts

Calculates a payout for every confirmed investment of active clients whose 45-day eligibility date falls on or before the cycle's payout date. The active fee rule's fee plus 16% VAT on the fee are deducted. Atomic — all payouts or none.

  • 200 — {"payouts": [{"id", "amount": "12.00"}]}
  • 404 — Cycle or active fee rule not found.
  • 409 — Payouts have already been calculated for this cycle.

Settlement & payout requests (role: admin)

List payouts

GET/api/payouts?status=pending|paid

Query parameter status defaults to pending; anything else is rejected. Sorted by cycle payout date.

  • 200 — {"payouts": [{…, "full_name", "payout_on", "investment_amount", "invested_at"}]}
  • 400 — Invalid payout status.

Mark a payout as paid

PUT/api/payouts/{payoutId}/mark-paid

Marks a pending payout as paid under an advisory lock, verifies the ledger balance covers the amount, and records a Payout Out transaction. Atomic.

  • 200 — {"ok": true}
  • 409 — Pending payout not found. / Insufficient ledger balance.

List payout requests

GET/api/payout-requests
  • 200 — {"requests": [{"id", "client_id", "status", "requested_at", "full_name", "email"}]}

Resolve a payout request

PUT/api/payout-requests/{requestId}/resolve
  • 200 — {"ok": true}

Export (role: admin)

GET/api/export/ledger

Returns the full transaction ledger as a CSV download. Formula-like cell values are prefixed with ' to protect against CSV injection.

  • 200 — text/csv; charset=utf-8 with Content-Disposition: attachment; filename="commission-ledger.csv", columns: Date,Type,Party,Amount,Reference,Notes

Example session

# 1. Sign in and capture the session cookie and CSRF token
curl -c cookies.txt -H 'Content-Type: application/json' \
  -d '{"email":"admin@example.com","password":"..."}' \
  https://kountoo.co.ke/api/auth/login

# 2. Use the session for GETs (CSRF token not required)
curl -b cookies.txt https://kountoo.co.ke/api/dashboard

# 3. Use the session plus CSRF header for state-changing calls
TOKEN=...  # csrfToken from the login response
curl -b cookies.txt -X POST \
  -H 'Content-Type: application/json' \
  -H "X-CSRF-Token: $TOKEN" \
  -d '{"name":"Jane Doe","email":"jane@example.com"}' \
  https://kountoo.co.ke/api/clients