import { useCallback, useEffect, useState, type FormEvent } from "react"; import { api, apiObjectUrl } from "../lib/api"; type Driver = { id: number; first_name: string; last_name: string; profile_image_url: string | null; car_image_url: string | null; car_seats: number; rating: string; service: string; online: boolean; car_model: string | null; total_rides: number; revenue: number; approval_status: string; rejection_reason: string | null; submitted_at: string | null; // What the driver typed at onboarding, usually read off the scans below. license_number: string | null; license_expiry: string | null; national_id: string | null; plate_number: string | null; // Stored scan names, served through /driver/documents/:name. license_image_url: string | null; id_image_url: string | null; vehicle_reg_image_url: string | null; }; // What each driver still owes the company, and what the company still owes // them. Loaded alongside the driver list so an operator can reconcile a shift // without leaving the page. type Balance = { driver_id: number; name: string; owes_company_cents: number; owed_to_driver_cents: number; unsettled_rides: number; }; const money = (cents: number) => (cents / 100).toFixed(2); const EMPTY = { first_name: "", last_name: "", profile_image_url: "", car_image_url: "", car_seats: 4, rating: 4.5, }; export default function Drivers() { const [drivers, setDrivers] = useState([]); const [error, setError] = useState(null); const [editing, setEditing] = useState(null); const [balances, setBalances] = useState>({}); // Vetting a driver against their scans. Separate from the edit form: this is // a decision about whether someone may carry passengers, not a field update. const [reviewing, setReviewing] = useState(null); // Opening the picker rather than settling outright. A driver handing over // part of what they owe is normal, and settling the whole balance because // the button only offered all-or-nothing would put the ledger out of step // with the cash actually received. const [settleFor, setSettleFor] = useState<{ driver: Driver; side: "platform_fee" | "driver_payout"; } | null>(null); const load = useCallback(async () => { try { const [res, ledger] = await Promise.all([ api<{ data: Driver[] }>("/admin/drivers"), api<{ data: Balance[] }>("/admin/settle"), ]); setDrivers(res.data); setBalances( Object.fromEntries(ledger.data.map((b) => [b.driver_id, b])), ); setError(null); } catch (e) { setError((e as Error).message); } }, []); useEffect(() => { load(); }, [load]); const remove = async (id: number) => { if (!confirm("Delete this driver?")) return; try { await api(`/admin/drivers/${id}`, { method: "DELETE" }); await load(); } catch (e) { setError((e as Error).message); } }; return ( <>

Drivers & fleet

{error &&
{error}
} {drivers.map((d) => ( ))}
ID Name Service Seats Rating Vetting Online Rides Revenue Owes company Owed to driver
{d.id} {d.first_name} {d.last_name} {d.service} {d.car_seats} {d.rating} {d.approval_status} {d.online ? "● online" : "○ off"} {d.total_rides} {d.revenue.toLocaleString()} {balances[d.id]?.owes_company_cents ? ( {money(balances[d.id].owes_company_cents)} ) : ( )} {balances[d.id]?.owed_to_driver_cents ? ( {money(balances[d.id].owed_to_driver_cents)} ) : ( )}
{balances[d.id]?.owes_company_cents ? ( ) : null} {balances[d.id]?.owed_to_driver_cents ? ( ) : null}
{settleFor && ( setSettleFor(null)} onSettled={() => { setSettleFor(null); load(); }} /> )} {reviewing && ( setReviewing(null)} onDecided={() => { setReviewing(null); load(); }} /> )} {editing && ( setEditing(null)} onSaved={() => { setEditing(null); load(); }} /> )} ); } // One document scan, fetched with the operator's token and rendered from a // blob URL — the route is authenticated, so a bare would 401. function DocumentScan({ name, label }: { name: string; label: string }) { const [src, setSrc] = useState(null); const [error, setError] = useState(null); useEffect(() => { let url: string | null = null; let cancelled = false; apiObjectUrl(`/driver/documents?name=${encodeURIComponent(name)}`) .then((objectUrl) => { url = objectUrl; // The panel may have closed while the fetch was in flight; revoke // rather than setting state on an unmounted component. if (cancelled) URL.revokeObjectURL(objectUrl); else setSrc(objectUrl); }) .catch((e) => { if (!cancelled) setError((e as Error).message); }); return () => { cancelled = true; if (url) URL.revokeObjectURL(url); }; }, [name]); return (
{label}
{error ? (
{error}
) : src ? ( // Opens full size in a tab: small print on a licence is unreadable at // thumbnail size, and reading it is the whole point of this panel. {label} ) : (
Loading…
)}
); } // The driver's profile photo. Unlike a document scan this route is public, so // the browser can load it straight from a — a stored name is resolved // through the API, while an external URL an owner typed in is used as-is. function DriverPhoto({ name }: { name: string }) { const src = /^https?:/i.test(name) ? name : `${import.meta.env.VITE_API_URL ?? ""}/driver/photo?name=${encodeURIComponent(name)}`; return ( Driver profile photo ); } /** * Check what a driver typed against the documents they photographed, then * approve or reject. * * The scans exist precisely because the typed numbers arrive from OCR and OCR * is fallible — so the two are shown side by side and the decision rests on * the document, not on the field. Rejecting requires a reason, which is what * the driver sees in the app and corrects against. */ function VettingPanel({ driver, onClose, onDecided, }: { driver: Driver; onClose: () => void; onDecided: () => void; }) { const [reason, setReason] = useState(driver.rejection_reason ?? ""); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const decide = async ( approval_status: "approved" | "rejected" | "suspended", ) => { if (approval_status !== "approved" && !reason.trim()) { setError("Give the driver a reason they can act on."); return; } setBusy(true); setError(null); try { await api(`/admin/drivers/${driver.id}`, { method: "PATCH", body: JSON.stringify({ approval_status, rejection_reason: approval_status === "approved" ? undefined : reason.trim(), }), }); onDecided(); } catch (e) { setError((e as Error).message); } finally { setBusy(false); } }; const scans: [string | null, string][] = [ [driver.license_image_url, "Driving licence"], [driver.id_image_url, "ID card"], [driver.vehicle_reg_image_url, "Vehicle registration"], ]; const present = scans.filter(([name]) => name); return (
e.stopPropagation()}>

Vetting — {driver.first_name} {driver.last_name} (#{driver.id})

{/* The photo riders will actually see. It is checked here rather than left to chance because it is the one part of the profile shown to every passenger before they get into the car. */} {driver.profile_image_url && (
Shown to riders choosing a driver
)}

Status: {driver.approval_status} {driver.submitted_at ? ` · submitted ${new Date(driver.submitted_at).toLocaleString()}` : ""}

Licence number {driver.license_number ?? }
Licence expiry {driver.license_expiry ? ( driver.license_expiry.slice(0, 10) ) : ( )}
National ID {driver.national_id ?? }
Plate {driver.plate_number ?? }
Car {driver.car_model ?? }
{present.length > 0 ? (
{present.map(([name, label]) => ( ))}
) : (
No scans on file — this profile predates document capture.
)} setReason(e.target.value)} /> {error &&
{error}
}
{driver.approval_status === "approved" && ( )}
); } function DriverForm({ initial, onClose, onSaved, }: { initial: Driver | null; onClose: () => void; onSaved: () => void; }) { const [form, setForm] = useState( initial ? { first_name: initial.first_name, last_name: initial.last_name, profile_image_url: initial.profile_image_url ?? "", car_image_url: initial.car_image_url ?? "", car_seats: initial.car_seats, rating: Number(initial.rating), } : { ...EMPTY }, ); const [error, setError] = useState(null); const [busy, setBusy] = useState(false); const set = (key: keyof typeof form) => (e: { target: { value: string } }) => setForm((f) => ({ ...f, [key]: key === "car_seats" || key === "rating" ? Number(e.target.value) : e.target.value, })); const submit = async (e: FormEvent) => { e.preventDefault(); setBusy(true); try { await api(initial ? `/admin/drivers/${initial.id}` : "/admin/drivers", { method: initial ? "PATCH" : "POST", body: JSON.stringify(form), }); onSaved(); } catch (err) { setError((err as Error).message); } finally { setBusy(false); } }; return (
e.stopPropagation()} onSubmit={submit}>

{initial ? `Edit driver #${initial.id}` : "New driver"}

{error &&
{error}
}
); } // Pick exactly which rides a payment covers. // // Settling is an assertion about the real world — that cash was handed over, // or a transfer was made — so the operator has to be able to say precisely // which trips it accounts for. Everything is selected by default, because // settling the whole balance is still the common case; unticking is the // exception, not the workflow. type UnsettledRide = { ride_id: number; amount_cents: number; fare_price: number; origin_address: string; destination_address: string; completed_at: string; }; function SettlePicker({ driver, side, onClose, onSettled, }: { driver: Driver; side: "platform_fee" | "driver_payout"; onClose: () => void; onSettled: () => void; }) { const [rides, setRides] = useState([]); const [picked, setPicked] = useState>(new Set()); const [note, setNote] = useState(""); const [loading, setLoading] = useState(true); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const collecting = side === "platform_fee"; useEffect(() => { let cancelled = false; (async () => { try { const res = await api<{ data: { rides: UnsettledRide[] } }>( `/admin/settle?driver_id=${driver.id}&side=${side}`, ); if (cancelled) return; setRides(res.data.rides); setPicked(new Set(res.data.rides.map((r) => r.ride_id))); } catch (e) { if (!cancelled) setError((e as Error).message); } finally { if (!cancelled) setLoading(false); } })(); return () => { cancelled = true; }; }, [driver.id, side]); const toggle = (rideId: number) => setPicked((prev) => { const next = new Set(prev); if (next.has(rideId)) next.delete(rideId); else next.add(rideId); return next; }); const allPicked = rides.length > 0 && picked.size === rides.length; const total = rides .filter((r) => picked.has(r.ride_id)) .reduce((sum, r) => sum + r.amount_cents, 0); const submit = async () => { if (picked.size === 0) return; setBusy(true); try { await api("/admin/settle", { method: "POST", body: JSON.stringify({ side, // Ride ids, not driver_id: the server settles exactly these and // leaves the rest of the balance outstanding. ride_ids: [...picked], note: note.trim() || undefined, }), }); onSettled(); } catch (e) { setError((e as Error).message); setBusy(false); } }; return (
e.stopPropagation()}>

{collecting ? "Collect commission from" : "Pay out"}{" "} {driver.first_name} {driver.last_name}

{collecting ? "Cash rides where this driver still owes the platform fee." : "Card rides where the platform still owes this driver."}

{error ?

{error}

: null} {loading ? (

Loading rides…

) : rides.length === 0 ? (

Nothing outstanding.

) : ( <>
{rides.map((r) => ( ))}
Ride Route Fare {collecting ? "Commission" : "Payout"}
toggle(r.ride_id)} /> #{r.ride_id} {r.origin_address} → {r.destination_address}
{new Date(r.completed_at).toLocaleDateString()}
{money(r.fare_price)} {money(r.amount_cents)}
setNote(e.target.value)} />

{picked.size} of {rides.length} ride {rides.length === 1 ? "" : "s"} · {money(total)}

)}
); }