Waseel: driver capture, chat/calls, dispatch, and session fixes
Driver onboarding now photographs the licence, ID card and vehicle
registration and reads the credential fields off them, plus a camera-only
profile selfie riders check the arriving driver against. Adds in-app chat
and WebRTC calls, push-backed ride offers, ratings, cancellation and
payment sheets, settlement, and the owner dashboard endpoints behind them.
Camera permission on Android:
- Declare CAMERA and READ_MEDIA_IMAGES in the manifest. expo-image-picker's
own plugin never declares CAMERA, and Android denies a request for an
undeclared permission instantly and silently — no dialog is ever shown,
which is indistinguishable from the app not asking at all.
- Handle canAskAgain: once Android stops showing the dialog, repeating why
we need it is a dead end, so offer Open Settings instead (lib/capture-
permission.ts), matching what the location flow already did.
Session: a 401 on a request that carried a token now ends the session
instead of being reinterpreted per-screen — driver-home had been reading it
as "this user has no driver profile" and showing an onboarding form to an
already-onboarded driver. Requests without a token are exempt so a failed
sign-in doesn't sign you out, and the notification is latched per token so
concurrent polls tear the session down once. (root) gains the auth guard
that turns that into the sign-in screen; app/index.tsx only guarded the way
in, leaving a session that ended mid-screen with nowhere to go.
Also ignore .uploads/ — it holds driver licence, ID and vehicle scans plus
profile photos, which are personal data and must not be committed.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
1d84003e0a
commit
8807ff41c5
@@ -0,0 +1,80 @@
|
||||
import { requireAuth } from "@/lib/jwt";
|
||||
import { sql } from "@/lib/db";
|
||||
import { SERVICES } from "@/constants/services";
|
||||
import { boundingBox, haversine } from "@/lib/utils";
|
||||
import { DRIVER_STALE_SECONDS } from "@/constants/dispatch";
|
||||
|
||||
// GET — how many drivers of each service are within reach of a point.
|
||||
//
|
||||
// The rider map filters by the selected service, so an empty map is ambiguous:
|
||||
// it means "nobody at all" and "nobody driving a moto, though three cars are a
|
||||
// street away" identically. That's the state riders were getting stuck in —
|
||||
// staring at an empty map with no way to know that switching service would
|
||||
// fill it. This answers the question the map can't.
|
||||
//
|
||||
// Query: ?lat=33.89&lng=35.50&radius=20000
|
||||
//
|
||||
// Returns every known service, zeros included, so the client can render the
|
||||
// full picker without inventing missing keys.
|
||||
const DEFAULT_RADIUS_M = 20000;
|
||||
const MAX_RADIUS_M = 20000;
|
||||
|
||||
export async function GET(req: Request) {
|
||||
const auth = requireAuth(req);
|
||||
if ("error" in auth) return auth.error;
|
||||
|
||||
try {
|
||||
const url = new URL(req.url);
|
||||
const lat = Number(url.searchParams.get("lat"));
|
||||
const lng = Number(url.searchParams.get("lng"));
|
||||
|
||||
if (Number.isNaN(lat) || Number.isNaN(lng)) {
|
||||
return Response.json(
|
||||
{ error: "lat and lng query params are required numbers." },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const requested = Number(url.searchParams.get("radius"));
|
||||
const radius =
|
||||
Number.isFinite(requested) && requested > 0
|
||||
? Math.min(requested, MAX_RADIUS_M)
|
||||
: DEFAULT_RADIUS_M;
|
||||
|
||||
const box = boundingBox(lat, lng, radius);
|
||||
|
||||
// Same visibility rules as /driver/nearby — vetted, online, fresh, real
|
||||
// account, positioned. A driver riders can't be matched to must not be
|
||||
// counted here either, or the hint sends them to an empty service.
|
||||
const rows = await sql<{
|
||||
service: string;
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
}>`
|
||||
SELECT service, latitude, longitude
|
||||
FROM drivers
|
||||
WHERE online = TRUE
|
||||
AND approval_status = 'approved'
|
||||
AND user_id IS NOT NULL
|
||||
AND last_seen > CURRENT_TIMESTAMP - make_interval(secs => ${DRIVER_STALE_SECONDS})
|
||||
AND latitude IS NOT NULL
|
||||
AND longitude IS NOT NULL
|
||||
AND latitude BETWEEN ${box.minLat} AND ${box.maxLat}
|
||||
AND longitude BETWEEN ${box.minLng} AND ${box.maxLng}
|
||||
`;
|
||||
|
||||
const counts: Record<string, number> = {};
|
||||
for (const service of SERVICES) counts[service.id] = 0;
|
||||
|
||||
for (const row of rows) {
|
||||
if (haversine(lat, lng, row.latitude, row.longitude) > radius) continue;
|
||||
if (counts[row.service] === undefined) continue;
|
||||
counts[row.service] += 1;
|
||||
}
|
||||
|
||||
return Response.json({ data: { radius, counts } });
|
||||
} catch (error) {
|
||||
console.error("[DRIVER_AVAILABILITY]: ", error);
|
||||
return Response.json({ error: "Internal Server Error" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { preflight, withCors } from "@/lib/admin";
|
||||
import { sql } from "@/lib/db";
|
||||
import { requireAuth } from "@/lib/jwt";
|
||||
import { isStoredUploadName, readUpload, uploadMimeType } from "@/lib/uploads";
|
||||
|
||||
// GET /(api)/driver/documents?name=… — serve one stored document scan.
|
||||
//
|
||||
// These are identity documents, so they are not static files: every read is
|
||||
// authenticated and authorised here. Exactly two principals may fetch a scan —
|
||||
// the driver it belongs to, and an owner reviewing that driver. Knowing the
|
||||
// (unguessable) file name is not itself permission.
|
||||
//
|
||||
// The name travels as a query parameter rather than a path segment because it
|
||||
// ends in .jpg/.png/.webp, and a dotted final segment is exactly what static
|
||||
// asset middleware tends to claim before the router ever sees it. A query
|
||||
// parameter cannot be mistaken for a file on disk.
|
||||
//
|
||||
// CORS is applied because the admin dashboard is a separate origin; it fetches
|
||||
// the bytes with its bearer token and renders them from a blob URL, since an
|
||||
// <img src> cannot carry an Authorization header.
|
||||
|
||||
export async function OPTIONS(request: Request) {
|
||||
return preflight(request);
|
||||
}
|
||||
|
||||
const notFound = (request: Request) =>
|
||||
withCors(request, Response.json({ error: "Not found." }, { status: 404 }));
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const auth = requireAuth(request);
|
||||
if ("error" in auth) return withCors(request, auth.error);
|
||||
|
||||
const name = new URL(request.url).searchParams.get("name");
|
||||
|
||||
// Rejecting the name before it reaches the filesystem is what keeps a
|
||||
// crafted "../../.env" from ever being joined onto the upload directory.
|
||||
if (!isStoredUploadName(name)) return notFound(request);
|
||||
|
||||
try {
|
||||
const rows = await sql<{ role: string | null; owns: boolean }>`
|
||||
SELECT
|
||||
(SELECT role FROM users WHERE id = ${auth.userId}) AS role,
|
||||
EXISTS (
|
||||
SELECT 1 FROM drivers
|
||||
WHERE user_id = ${auth.userId}
|
||||
AND ${name} IN (
|
||||
license_image_url, id_image_url, vehicle_reg_image_url
|
||||
)
|
||||
) AS owns
|
||||
`;
|
||||
|
||||
const allowed = rows[0]?.role === "owner" || rows[0]?.owns === true;
|
||||
|
||||
// A 404 rather than a 403: a caller who is not entitled to the document
|
||||
// shouldn't learn whether it exists.
|
||||
if (!allowed) return notFound(request);
|
||||
|
||||
const bytes = await readUpload(name, "document");
|
||||
if (!bytes) return notFound(request);
|
||||
|
||||
return withCors(
|
||||
request,
|
||||
new Response(new Uint8Array(bytes), {
|
||||
headers: {
|
||||
"Content-Type": uploadMimeType(name),
|
||||
"Content-Length": String(bytes.length),
|
||||
// Never let a shared cache hold somebody's ID card.
|
||||
"Cache-Control": "private, no-store",
|
||||
"Content-Disposition": `inline; filename="${name}"`,
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("[DRIVER_DOCUMENT_GET]: ", error);
|
||||
return withCors(
|
||||
request,
|
||||
Response.json({ error: "Internal Server Error" }, { status: 500 }),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
import { requireDriverProfile } from "@/lib/driver";
|
||||
import { sql } from "@/lib/db";
|
||||
import { DRIVER_BUSY_ARRAY } from "@/lib/ride-lifecycle";
|
||||
import { boundingBox, haversine } from "@/lib/utils";
|
||||
import { BROADCAST_RADIUS_M, REQUEST_TTL_SECONDS } from "@/constants/dispatch";
|
||||
|
||||
// POST — driver location heartbeat. Each ping updates lat/lng/last_seen and
|
||||
// keeps the driver marked online. The client (use-driver-location) fires this
|
||||
@@ -11,7 +14,7 @@ export async function POST(req: Request) {
|
||||
|
||||
try {
|
||||
const body = await req.json();
|
||||
const { latitude, longitude } = body;
|
||||
const { latitude, longitude, heading, speed_kph } = body;
|
||||
|
||||
if (
|
||||
typeof latitude !== "number" ||
|
||||
@@ -25,20 +28,112 @@ export async function POST(req: Request) {
|
||||
);
|
||||
}
|
||||
|
||||
// Heading and speed are optional and frequently unavailable — a phone
|
||||
// sitting still reports heading -1, and a cached fix may carry neither.
|
||||
// Anything unusable is stored as NULL rather than as a wrong direction,
|
||||
// because a confidently wrong arrow on a rider's map is worse than none.
|
||||
const bearing =
|
||||
typeof heading === "number" && heading >= 0 && heading <= 360
|
||||
? Math.round(heading) % 360
|
||||
: null;
|
||||
|
||||
const speed =
|
||||
typeof speed_kph === "number" && speed_kph >= 0 && speed_kph < 300
|
||||
? Math.round(speed_kph)
|
||||
: null;
|
||||
|
||||
// A ping refreshes position and liveness only. It deliberately does NOT
|
||||
// set online = TRUE: a ping already in flight when the driver toggles off
|
||||
// would land afterwards and put them back in the match pool, so they'd
|
||||
// keep getting requests they thought they'd opted out of. Going online is
|
||||
// an explicit PATCH to /driver/profile and nothing else.
|
||||
const { driverId } = result;
|
||||
const rows = await sql`
|
||||
UPDATE drivers
|
||||
SET latitude = ${latitude},
|
||||
longitude = ${longitude},
|
||||
last_seen = CURRENT_TIMESTAMP,
|
||||
online = TRUE
|
||||
-- COALESCE, not overwrite: a fix without a usable heading (typical
|
||||
-- at a standstill) shouldn't erase the direction the car was last
|
||||
-- known to be facing, which is still the best guess for how it's
|
||||
-- parked. Speed does overwrite, because "not moving" is real
|
||||
-- information and must be able to reach zero.
|
||||
heading = COALESCE(${bearing}, heading),
|
||||
speed_kph = ${speed},
|
||||
last_seen = CURRENT_TIMESTAMP
|
||||
WHERE id = ${driverId}
|
||||
RETURNING id, latitude, longitude, last_seen, online
|
||||
RETURNING id, latitude, longitude, heading, speed_kph, last_seen, online
|
||||
`;
|
||||
|
||||
return Response.json({ data: rows[0] });
|
||||
// The nearest open request this driver could take, returned with the
|
||||
// heartbeat.
|
||||
//
|
||||
// While a driver is online this endpoint is hit every few seconds by a
|
||||
// foreground-service location task that keeps running with the screen
|
||||
// off — so it is the one request we know is still happening when the
|
||||
// dashboard poll has stopped. Piggybacking the nearest job here lets the
|
||||
// app raise a local notification for it without a second round trip, and
|
||||
// without needing remote push credentials.
|
||||
//
|
||||
// Filtered to requests this driver hasn't already offered on, so a driver
|
||||
// who volunteered and is waiting on the rider isn't buzzed about the same
|
||||
// job every five seconds.
|
||||
const box = boundingBox(latitude, longitude, BROADCAST_RADIUS_M);
|
||||
const driver = rows[0] as { online?: boolean } | undefined;
|
||||
|
||||
const nearby = driver?.online
|
||||
? await sql<{
|
||||
ride_id: number;
|
||||
origin_address: string;
|
||||
fare_price: number;
|
||||
origin_latitude: number;
|
||||
origin_longitude: number;
|
||||
}>`
|
||||
SELECT r.ride_id, r.origin_address, r.fare_price,
|
||||
r.origin_latitude, r.origin_longitude
|
||||
FROM rides r
|
||||
WHERE r.status = 'requested'
|
||||
AND r.service = (SELECT service FROM drivers WHERE id = ${driverId})
|
||||
AND r.created_at > CURRENT_TIMESTAMP - make_interval(secs => ${REQUEST_TTL_SECONDS})
|
||||
AND r.origin_latitude BETWEEN ${box.minLat} AND ${box.maxLat}
|
||||
AND r.origin_longitude BETWEEN ${box.minLng} AND ${box.maxLng}
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM ride_offers ro
|
||||
WHERE ro.ride_id = r.ride_id
|
||||
AND ro.driver_id = ${driverId}
|
||||
AND ro.status = 'offered'
|
||||
)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM rides busy
|
||||
WHERE busy.driver_id = ${driverId}
|
||||
AND busy.status = ANY(${DRIVER_BUSY_ARRAY}::text[])
|
||||
)
|
||||
ORDER BY r.created_at DESC
|
||||
LIMIT 5
|
||||
`
|
||||
: [];
|
||||
|
||||
// Same great-circle trim the dashboard applies, so the notification and
|
||||
// the list the driver opens agree on what counts as nearby.
|
||||
const pending = nearby
|
||||
.map((r) => ({
|
||||
ride_id: r.ride_id,
|
||||
origin_address: r.origin_address,
|
||||
fare_price: Number(r.fare_price),
|
||||
distance: haversine(
|
||||
latitude,
|
||||
longitude,
|
||||
Number(r.origin_latitude),
|
||||
Number(r.origin_longitude),
|
||||
),
|
||||
}))
|
||||
.filter((r) => r.distance <= BROADCAST_RADIUS_M)
|
||||
.sort((a, b) => a.distance - b.distance)[0];
|
||||
|
||||
return Response.json({
|
||||
data: { ...rows[0], pending_request: pending ?? null },
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[DRIVER_LOCATION]: ", error);
|
||||
return Response.json({ error: "Internal Server Error" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,30 @@
|
||||
import { requireAuth } from "@/lib/jwt";
|
||||
import { sql } from "@/lib/db";
|
||||
import { boundingBox, haversine } from "@/lib/utils";
|
||||
import { DRIVER_STALE_SECONDS } from "@/constants/dispatch";
|
||||
|
||||
// GET — online drivers of `service` near (lat,lng), for the rider map and the
|
||||
// "nearest driver ETA" estimate on confirm-ride. Only real, logged-in drivers
|
||||
// (user_id IS NOT NULL) with a fresh location ping are returned; legacy seed
|
||||
// rows have no position and are never shown to riders.
|
||||
// "drivers near you" count on the request screen. Only vetted, logged-in
|
||||
// drivers (approved + user_id IS NOT NULL) with a fresh location ping are
|
||||
// returned; legacy seed rows have no position and are never shown to riders.
|
||||
//
|
||||
// Query: ?service=car&lat=33.89&lng=35.50&radius=8000
|
||||
//
|
||||
// The radius is enforced, not decorative. Returning every online driver in the
|
||||
// country to any signed-in account turns this endpoint into a live tracker for
|
||||
// the whole fleet; bounding it means a caller only ever learns about cars they
|
||||
// could plausibly hail. A coarse bounding box does the work in the index, then
|
||||
// a great-circle pass trims the corners.
|
||||
const DEFAULT_RADIUS_M = 8000;
|
||||
const MAX_RADIUS_M = 20000;
|
||||
// Drivers are returned at ~11m precision (4 decimal places). That is well
|
||||
// inside "which street is the car on" for a map pin, and stops the endpoint
|
||||
// from being a metre-accurate trace of someone's working day.
|
||||
const COORD_PRECISION = 1e4;
|
||||
|
||||
const snap = (value: number): number =>
|
||||
Math.round(value * COORD_PRECISION) / COORD_PRECISION;
|
||||
|
||||
export async function GET(req: Request) {
|
||||
const auth = requireAuth(req);
|
||||
if ("error" in auth) return auth.error;
|
||||
@@ -24,22 +42,47 @@ export async function GET(req: Request) {
|
||||
);
|
||||
}
|
||||
|
||||
const rows = await sql`
|
||||
const requested = Number(url.searchParams.get("radius"));
|
||||
const radius =
|
||||
Number.isFinite(requested) && requested > 0
|
||||
? Math.min(requested, MAX_RADIUS_M)
|
||||
: DEFAULT_RADIUS_M;
|
||||
|
||||
const box = boundingBox(lat, lng, radius);
|
||||
|
||||
const rows = await sql<{
|
||||
id: number;
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
heading: number | null;
|
||||
speed_kph: number | null;
|
||||
}>`
|
||||
SELECT id, first_name, last_name, profile_image_url, car_image_url,
|
||||
car_seats, rating, service, car_model, latitude, longitude,
|
||||
last_seen
|
||||
heading, speed_kph, last_seen
|
||||
FROM drivers
|
||||
WHERE service = ${service}
|
||||
AND online = TRUE
|
||||
AND approval_status = 'approved'
|
||||
AND user_id IS NOT NULL
|
||||
AND last_seen > CURRENT_TIMESTAMP - INTERVAL '60 seconds'
|
||||
AND last_seen > CURRENT_TIMESTAMP - make_interval(secs => ${DRIVER_STALE_SECONDS})
|
||||
AND latitude IS NOT NULL
|
||||
AND longitude IS NOT NULL
|
||||
AND latitude BETWEEN ${box.minLat} AND ${box.maxLat}
|
||||
AND longitude BETWEEN ${box.minLng} AND ${box.maxLng}
|
||||
`;
|
||||
|
||||
return Response.json({ data: rows });
|
||||
const nearby = rows
|
||||
.filter((d) => haversine(lat, lng, d.latitude, d.longitude) <= radius)
|
||||
.map((d) => ({
|
||||
...d,
|
||||
latitude: snap(d.latitude),
|
||||
longitude: snap(d.longitude),
|
||||
}));
|
||||
|
||||
return Response.json({ data: nearby });
|
||||
} catch (error) {
|
||||
console.error("[DRIVER_NEARBY]: ", error);
|
||||
return Response.json({ error: "Internal Server Error" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
import { preflight, withCors } from "@/lib/admin";
|
||||
import { sql } from "@/lib/db";
|
||||
import { requireAuth } from "@/lib/jwt";
|
||||
import {
|
||||
deleteUpload,
|
||||
isStoredUploadName,
|
||||
MAX_UPLOAD_BYTES,
|
||||
pruneOrphanUploads,
|
||||
readUpload,
|
||||
sniffImageType,
|
||||
storeUpload,
|
||||
uploadMimeType,
|
||||
} from "@/lib/uploads";
|
||||
|
||||
// The driver's profile photo — the face a rider sees beside a driver's name
|
||||
// when picking between offers, and what they check the arriving car's driver
|
||||
// against.
|
||||
//
|
||||
// POST uploads it (authenticated, driver-role only). GET serves it, and unlike
|
||||
// the document route it does NOT require a token: this image is rendered by
|
||||
// plain <Image>/<img> tags across the rider app, the driver map and the admin
|
||||
// dashboard, none of which can attach an Authorization header without turning
|
||||
// every avatar into a bespoke fetch-and-blob dance. What protects it instead
|
||||
// is that the name is 128 bits of randomness and the route refuses any name no
|
||||
// driver row actually points at — so it cannot be enumerated, and it cannot be
|
||||
// used as a general-purpose anonymous image host for whatever somebody
|
||||
// uploaded and abandoned.
|
||||
//
|
||||
// This is the opposite trade to /(api)/driver/documents, which is why the two
|
||||
// live in separate directories on disk: a name that addresses a licence scan
|
||||
// resolves to nothing here.
|
||||
|
||||
export async function OPTIONS(request: Request) {
|
||||
return preflight(request);
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const name = new URL(request.url).searchParams.get("name");
|
||||
|
||||
const notFound = () =>
|
||||
withCors(request, Response.json({ error: "Not found." }, { status: 404 }));
|
||||
|
||||
// Rejecting the name before it reaches the filesystem is what keeps a
|
||||
// crafted "../../.env" from ever being joined onto the upload directory.
|
||||
if (!isStoredUploadName(name)) return notFound();
|
||||
|
||||
try {
|
||||
// Only photos a driver profile actually points at are served. Without
|
||||
// this, any signed-in driver could upload an arbitrary image and walk away
|
||||
// with a permanent public URL for it.
|
||||
const rows = await sql<{ used: boolean }>`
|
||||
SELECT EXISTS (
|
||||
SELECT 1 FROM drivers WHERE profile_image_url = ${name}
|
||||
) AS used
|
||||
`;
|
||||
|
||||
if (!rows[0]?.used) return notFound();
|
||||
|
||||
const bytes = await readUpload(name, "photo");
|
||||
if (!bytes) return notFound();
|
||||
|
||||
return withCors(
|
||||
request,
|
||||
new Response(new Uint8Array(bytes), {
|
||||
headers: {
|
||||
"Content-Type": uploadMimeType(name),
|
||||
"Content-Length": String(bytes.length),
|
||||
// The name changes whenever the photo does, so the bytes behind a
|
||||
// given URL are immutable and can be cached hard. That matters: the
|
||||
// rider's nearby-drivers view re-renders these constantly.
|
||||
"Cache-Control": "public, max-age=604800, immutable",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("[DRIVER_PHOTO_GET]: ", error);
|
||||
return withCors(
|
||||
request,
|
||||
Response.json({ error: "Internal Server Error" }, { status: 500 }),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Photos are cheap compared with a scan (no Vision call), but still a disk
|
||||
* write, so keep a lid on how fast one account can retake theirs.
|
||||
*/
|
||||
const PHOTO_LIMIT = 15;
|
||||
const PHOTO_WINDOW_MS = 60 * 60 * 1000;
|
||||
const recentUploads = new Map<string, number[]>();
|
||||
|
||||
const overPhotoLimit = (userId: string): boolean => {
|
||||
const now = Date.now();
|
||||
const cutoff = now - PHOTO_WINDOW_MS;
|
||||
const history = (recentUploads.get(userId) ?? []).filter((at) => at > cutoff);
|
||||
|
||||
if (history.length >= PHOTO_LIMIT) {
|
||||
recentUploads.set(userId, history);
|
||||
return true;
|
||||
}
|
||||
|
||||
history.push(now);
|
||||
recentUploads.set(userId, history);
|
||||
|
||||
if (recentUploads.size > 500) {
|
||||
for (const [key, times] of recentUploads) {
|
||||
if (times.every((at) => at <= cutoff)) recentUploads.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
const PRUNE_INTERVAL_MS = 60 * 60 * 1000;
|
||||
let lastPruneAt = 0;
|
||||
|
||||
/**
|
||||
* A driver who takes a photo and then abandons onboarding leaves a file
|
||||
* nothing points at. Same sweep as the scan route, over the photo directory.
|
||||
*/
|
||||
const pruneOrphansOccasionally = async (): Promise<void> => {
|
||||
if (Date.now() - lastPruneAt < PRUNE_INTERVAL_MS) return;
|
||||
lastPruneAt = Date.now();
|
||||
|
||||
try {
|
||||
const rows = await sql<{ profile_image_url: string | null }>`
|
||||
SELECT profile_image_url FROM drivers
|
||||
WHERE profile_image_url IS NOT NULL
|
||||
`;
|
||||
|
||||
const referenced = new Set(
|
||||
rows.map((row) => row.profile_image_url).filter(Boolean) as string[],
|
||||
);
|
||||
|
||||
await pruneOrphanUploads(referenced, "photo");
|
||||
} catch (error) {
|
||||
console.error("[DRIVER_PHOTO_PRUNE]: ", error);
|
||||
}
|
||||
};
|
||||
|
||||
// POST — upload or replace the driver's profile photo.
|
||||
//
|
||||
// A driver who already has a profile row gets it attached straight away, so
|
||||
// retaking a bad photo is one step. During onboarding there is no row yet, so
|
||||
// the name is just returned and travels up with the profile submission.
|
||||
export async function POST(req: Request) {
|
||||
const auth = requireAuth(req);
|
||||
if ("error" in auth) return auth.error;
|
||||
|
||||
try {
|
||||
const users = await sql<{ role: string | null }>`
|
||||
SELECT role FROM users WHERE id = ${auth.userId}
|
||||
`;
|
||||
if (users[0]?.role !== "driver") {
|
||||
return Response.json(
|
||||
{ error: "Only driver accounts can upload a driver photo." },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
if (overPhotoLimit(auth.userId)) {
|
||||
return Response.json(
|
||||
{
|
||||
error: "Too many uploads. Wait a few minutes and try again.",
|
||||
code: "PHOTO_RATE_LIMIT",
|
||||
},
|
||||
{ status: 429 },
|
||||
);
|
||||
}
|
||||
|
||||
const body = await req.json();
|
||||
const raw = body.image_base64;
|
||||
|
||||
if (typeof raw !== "string" || raw.length === 0) {
|
||||
return Response.json(
|
||||
{ error: "image_base64 is required." },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const encoded = raw.includes(",") ? raw.slice(raw.indexOf(",") + 1) : raw;
|
||||
|
||||
// Base64 inflates by 4/3, so reject on the encoded length before
|
||||
// allocating — otherwise an oversized upload is buffered just to be
|
||||
// refused.
|
||||
if (encoded.length > MAX_UPLOAD_BYTES * 1.4) {
|
||||
return Response.json(
|
||||
{ error: "That image is too large.", code: "IMAGE_TOO_LARGE" },
|
||||
{ status: 413 },
|
||||
);
|
||||
}
|
||||
|
||||
const image = Buffer.from(encoded, "base64");
|
||||
|
||||
if (image.length > MAX_UPLOAD_BYTES) {
|
||||
return Response.json(
|
||||
{ error: "That image is too large.", code: "IMAGE_TOO_LARGE" },
|
||||
{ status: 413 },
|
||||
);
|
||||
}
|
||||
|
||||
const mimeType = sniffImageType(image);
|
||||
if (!mimeType) {
|
||||
return Response.json(
|
||||
{
|
||||
error: "Upload a JPEG, PNG or WebP photo.",
|
||||
code: "UNSUPPORTED_IMAGE",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const photo = await storeUpload(image, mimeType, "photo");
|
||||
|
||||
// Attach it now if the driver already has a profile, so retaking a bad
|
||||
// photo is a single step. Mid-onboarding there is no row yet and the name
|
||||
// simply travels up with the profile submission instead.
|
||||
//
|
||||
// This deliberately does not touch approval_status: a driver swapping a
|
||||
// blurry photo for a clear one shouldn't be knocked out of service, and
|
||||
// the reviewer sees whatever the current photo is when they next open the
|
||||
// profile.
|
||||
const existing = await sql<{ profile_image_url: string | null }>`
|
||||
SELECT profile_image_url FROM drivers WHERE user_id = ${auth.userId}
|
||||
`;
|
||||
|
||||
const attached = existing.length > 0;
|
||||
|
||||
if (attached) {
|
||||
await sql`
|
||||
UPDATE drivers SET profile_image_url = ${photo}
|
||||
WHERE user_id = ${auth.userId}
|
||||
`;
|
||||
|
||||
// Only a name we stored is safe to unlink — an owner may have set an
|
||||
// external URL from the dashboard, and that is not ours to delete.
|
||||
const previous = existing[0].profile_image_url;
|
||||
if (previous && previous !== photo && isStoredUploadName(previous)) {
|
||||
await deleteUpload(previous, "photo");
|
||||
}
|
||||
}
|
||||
|
||||
void pruneOrphansOccasionally();
|
||||
|
||||
return Response.json({
|
||||
data: {
|
||||
/** Opaque stored name; send it with the profile if onboarding. */
|
||||
photo,
|
||||
attached,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[DRIVER_PHOTO_POST]: ", error);
|
||||
return Response.json({ error: "Internal Server Error" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
+247
-16
@@ -1,6 +1,8 @@
|
||||
import { requireAuth } from "@/lib/jwt";
|
||||
import { sql, query } from "@/lib/db";
|
||||
import { isServiceId, requireDriverProfile } from "@/lib/driver";
|
||||
import { DRIVER_BUSY_ARRAY } from "@/lib/ride-lifecycle";
|
||||
import { deleteUpload, isStoredUploadName } from "@/lib/uploads";
|
||||
import { SERVICES, type ServiceId } from "@/constants/services";
|
||||
|
||||
// GET — the signed-in user's own driver profile, or 403 (code: ONBOARD) when
|
||||
@@ -12,23 +14,54 @@ export async function GET(req: Request) {
|
||||
const { auth, driverId } = result;
|
||||
const rows = await sql`
|
||||
SELECT id, first_name, last_name, profile_image_url, car_image_url,
|
||||
car_seats, rating, service, online, car_model, user_id
|
||||
car_seats, rating, rating_count, service, online, car_model, user_id,
|
||||
approval_status, rejection_reason, submitted_at, reviewed_at,
|
||||
license_number, license_expiry, plate_number,
|
||||
license_image_url, id_image_url, vehicle_reg_image_url
|
||||
FROM drivers WHERE id = ${driverId}
|
||||
`;
|
||||
return Response.json({ data: rows[0], userId: auth.userId });
|
||||
}
|
||||
|
||||
// Credentials collected at onboarding. The numbers are typed by the driver —
|
||||
// usually prefilled from a scan by /(api)/driver/scan, but a scan is only ever
|
||||
// a suggestion, so they are validated here exactly as if they had been typed
|
||||
// from scratch. The scans themselves are stored alongside so the reviewer
|
||||
// checks the numbers against the document rather than taking them on trust.
|
||||
const trimmed = (v: unknown, max: number): string | null => {
|
||||
if (typeof v !== "string") return null;
|
||||
const value = v.trim();
|
||||
return value.length > 0 && value.length <= max ? value : null;
|
||||
};
|
||||
|
||||
// Expiry is a plain YYYY-MM-DD date and has to still be in the future — an
|
||||
// expired licence is exactly what vetting exists to catch.
|
||||
const futureDate = (v: unknown): string | null => {
|
||||
if (typeof v !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(v)) return null;
|
||||
const date = new Date(`${v}T00:00:00Z`);
|
||||
if (Number.isNaN(date.getTime()) || date.getTime() <= Date.now()) return null;
|
||||
return v;
|
||||
};
|
||||
|
||||
// Scans and profile photos are both referenced by the opaque name their
|
||||
// upload route handed back, and only names in that shape are accepted. A client
|
||||
// cannot invent one, so it cannot point its profile row at a file it never
|
||||
// uploaded — and since the name is all that is stored, there is no path here
|
||||
// for the filesystem to interpret.
|
||||
const storedName = (v: unknown): string | null =>
|
||||
isStoredUploadName(v) ? v : null;
|
||||
|
||||
// POST — onboarding. A driver-role user creates their one linked drivers row.
|
||||
// The user must carry role='driver' (set on sign-up / role.tsx) so a rider
|
||||
// can't silently become a driver by hitting this endpoint.
|
||||
// The user must carry role='driver' (set on sign-up / role.tsx), and the row is
|
||||
// created 'pending': it is not matched, not shown to riders, and cannot go
|
||||
// online until an owner approves it. Role alone has never been a credential.
|
||||
export async function POST(req: Request) {
|
||||
const auth = requireAuth(req);
|
||||
if ("error" in auth) return auth.error;
|
||||
|
||||
try {
|
||||
const body = await req.json();
|
||||
const { car_model, car_seats, service, profile_image_url, car_image_url } =
|
||||
body;
|
||||
const { car_model, car_seats, service, car_image_url } = body;
|
||||
|
||||
// The user must be flagged a driver to onboard a driver profile.
|
||||
const users = await sql<{ role: string | null; name: string | null }>`
|
||||
@@ -43,7 +76,9 @@ export async function POST(req: Request) {
|
||||
|
||||
if (!isServiceId(service)) {
|
||||
return Response.json(
|
||||
{ error: `service must be one of: ${SERVICES.map((s) => s.id).join(", ")}.` },
|
||||
{
|
||||
error: `service must be one of: ${SERVICES.map((s) => s.id).join(", ")}.`,
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
@@ -56,6 +91,66 @@ export async function POST(req: Request) {
|
||||
);
|
||||
}
|
||||
|
||||
const licenseNumber = trimmed(body.license_number, 60);
|
||||
const nationalId = trimmed(body.national_id, 60);
|
||||
const plateNumber = trimmed(body.plate_number, 20);
|
||||
const licenseExpiry = futureDate(body.license_expiry);
|
||||
|
||||
if (!licenseNumber || !nationalId || !plateNumber) {
|
||||
return Response.json(
|
||||
{
|
||||
error:
|
||||
"Driving licence number, national ID and plate number are required.",
|
||||
code: "CREDENTIALS_REQUIRED",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
if (!licenseExpiry) {
|
||||
return Response.json(
|
||||
{
|
||||
error: "Licence expiry must be a future date (YYYY-MM-DD).",
|
||||
code: "LICENSE_EXPIRED",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const licenseDocument = storedName(body.license_document);
|
||||
const idDocument = storedName(body.id_document);
|
||||
const vehicleRegDocument = storedName(body.vehicle_reg_document);
|
||||
const profilePhoto = storedName(body.profile_photo);
|
||||
|
||||
// The licence scan is the one document review cannot do without: it is
|
||||
// what the reviewer checks the typed licence number and expiry against.
|
||||
// The ID card and vehicle registration help but are not required, so a
|
||||
// driver whose registration is with the car's owner can still onboard.
|
||||
if (!licenseDocument) {
|
||||
return Response.json(
|
||||
{
|
||||
error: "Scan your driving licence before submitting.",
|
||||
code: "LICENSE_SCAN_REQUIRED",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
// The profile photo is what a rider sees next to a driver's name when
|
||||
// choosing between offers, and it is how they check that the person who
|
||||
// pulls up is the person the app sent. A driver with no photo would be an
|
||||
// anonymous row in that list, so it is collected up front rather than left
|
||||
// as a profile nicety somebody gets round to.
|
||||
if (!profilePhoto) {
|
||||
return Response.json(
|
||||
{
|
||||
error: "Add a profile photo before submitting.",
|
||||
code: "PHOTO_REQUIRED",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const [firstName, ...rest] = (users[0].name ?? "").split(" ");
|
||||
|
||||
// One profile per driver user. The partial unique index on user_id
|
||||
@@ -64,20 +159,32 @@ export async function POST(req: Request) {
|
||||
const rows = await sql`
|
||||
INSERT INTO drivers (
|
||||
user_id, first_name, last_name, profile_image_url, car_image_url,
|
||||
car_seats, rating, service, car_model, online
|
||||
car_seats, rating, service, car_model, online,
|
||||
approval_status, license_number, license_expiry, national_id,
|
||||
plate_number, submitted_at,
|
||||
license_image_url, id_image_url, vehicle_reg_image_url
|
||||
) VALUES (
|
||||
${auth.userId},
|
||||
${firstName || "Driver"},
|
||||
${rest.join(" ") || ""},
|
||||
${profile_image_url ?? null},
|
||||
${profilePhoto},
|
||||
${car_image_url ?? null},
|
||||
${seats},
|
||||
5.0,
|
||||
${service as ServiceId},
|
||||
${car_model ?? null},
|
||||
FALSE
|
||||
FALSE,
|
||||
'pending',
|
||||
${licenseNumber},
|
||||
${licenseExpiry},
|
||||
${nationalId},
|
||||
${plateNumber},
|
||||
CURRENT_TIMESTAMP,
|
||||
${licenseDocument},
|
||||
${idDocument},
|
||||
${vehicleRegDocument}
|
||||
)
|
||||
RETURNING id, service, online
|
||||
RETURNING id, service, online, approval_status
|
||||
`;
|
||||
return Response.json({ data: rows[0] }, { status: 201 });
|
||||
} catch (error) {
|
||||
@@ -112,8 +219,130 @@ export async function PATCH(req: Request) {
|
||||
values.push(value);
|
||||
};
|
||||
|
||||
// A profile that hasn't been cleared cannot go online, and therefore can
|
||||
// never be matched. This is the gate the whole vetting flow rests on —
|
||||
// everything else (dispatch filters, the rider map) is defence in depth.
|
||||
if (online === true && result.approvalStatus !== "approved") {
|
||||
return Response.json(
|
||||
{
|
||||
error: "Your driver account is not approved yet.",
|
||||
code: "NOT_APPROVED",
|
||||
approval_status: result.approvalStatus,
|
||||
},
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
// A rejected driver may fix their details and resubmit, which puts them
|
||||
// back in the review queue rather than silently leaving them stuck. A
|
||||
// rejection is often about the scan rather than the numbers ("the photo is
|
||||
// unreadable"), so a fresh scan on its own counts as a resubmission.
|
||||
const resubmitted =
|
||||
result.approvalStatus === "rejected" &&
|
||||
(body.license_number !== undefined ||
|
||||
body.national_id !== undefined ||
|
||||
body.plate_number !== undefined ||
|
||||
body.license_expiry !== undefined ||
|
||||
body.license_document !== undefined ||
|
||||
body.id_document !== undefined ||
|
||||
body.vehicle_reg_document !== undefined);
|
||||
|
||||
// Scans replaced by this resubmission, deleted once the row actually
|
||||
// points at the new ones — an orphaned file is tidier than a row pointing
|
||||
// at a document that is no longer on disk.
|
||||
const superseded: string[] = [];
|
||||
|
||||
if (resubmitted) {
|
||||
const licenseNumber = trimmed(body.license_number, 60);
|
||||
const nationalId = trimmed(body.national_id, 60);
|
||||
const plateNumber = trimmed(body.plate_number, 20);
|
||||
const licenseExpiry = futureDate(body.license_expiry);
|
||||
|
||||
if (!licenseNumber || !nationalId || !plateNumber || !licenseExpiry) {
|
||||
return Response.json(
|
||||
{
|
||||
error:
|
||||
"Licence number, expiry (future date), national ID and plate number are all required to resubmit.",
|
||||
code: "CREDENTIALS_REQUIRED",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
// Only documents the driver re-scanned are sent; anything omitted keeps
|
||||
// the scan already on file.
|
||||
const replacements: Record<string, string | null> = {
|
||||
license_image_url: storedName(body.license_document),
|
||||
id_image_url: storedName(body.id_document),
|
||||
vehicle_reg_image_url: storedName(body.vehicle_reg_document),
|
||||
};
|
||||
|
||||
const existing = await sql<{
|
||||
license_image_url: string | null;
|
||||
id_image_url: string | null;
|
||||
vehicle_reg_image_url: string | null;
|
||||
}>`
|
||||
SELECT license_image_url, id_image_url, vehicle_reg_image_url
|
||||
FROM drivers WHERE id = ${result.driverId}
|
||||
`;
|
||||
|
||||
// Same rule as onboarding, applied to the state the row will be left in:
|
||||
// a driver may resubmit without re-scanning, but not end up with no
|
||||
// licence scan at all.
|
||||
if (!(replacements.license_image_url ?? existing[0]?.license_image_url)) {
|
||||
return Response.json(
|
||||
{
|
||||
error: "Scan your driving licence before resubmitting.",
|
||||
code: "LICENSE_SCAN_REQUIRED",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
for (const [column, name] of Object.entries(replacements)) {
|
||||
if (!name) continue;
|
||||
|
||||
const previous = existing[0]?.[column as keyof (typeof existing)[0]];
|
||||
if (previous && previous !== name) superseded.push(previous);
|
||||
|
||||
push(column, name);
|
||||
}
|
||||
|
||||
push("license_number", licenseNumber);
|
||||
push("license_expiry", licenseExpiry);
|
||||
push("national_id", nationalId);
|
||||
push("plate_number", plateNumber);
|
||||
push("approval_status", "pending");
|
||||
push("rejection_reason", null);
|
||||
updates.push(`submitted_at = CURRENT_TIMESTAMP`);
|
||||
}
|
||||
|
||||
// Going offline mid-ride would strand the rider: dispatch stops seeing the
|
||||
// driver, the location heartbeat stops, and the rider's map freezes on a
|
||||
// car that never arrives — with no way to re-dispatch, since the ride is
|
||||
// already assigned. Finish or cancel the ride first.
|
||||
if (online === false) {
|
||||
const active = await sql<{ ride_id: number }>`
|
||||
SELECT ride_id FROM rides
|
||||
WHERE driver_id = ${result.driverId}
|
||||
AND status = ANY(${DRIVER_BUSY_ARRAY}::text[])
|
||||
LIMIT 1
|
||||
`;
|
||||
if (active[0]) {
|
||||
return Response.json(
|
||||
{
|
||||
error: "Finish or cancel your current ride before going offline.",
|
||||
code: "RIDE_IN_PROGRESS",
|
||||
ride_id: active[0].ride_id,
|
||||
},
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof online === "boolean") push("online", online);
|
||||
if (typeof car_model === "string" || car_model === null) push("car_model", car_model);
|
||||
if (typeof car_model === "string" || car_model === null)
|
||||
push("car_model", car_model);
|
||||
if (car_seats !== undefined) {
|
||||
const seats = Number(car_seats);
|
||||
if (!Number.isInteger(seats) || seats < 1 || seats > 8) {
|
||||
@@ -126,10 +355,7 @@ export async function PATCH(req: Request) {
|
||||
}
|
||||
if (service !== undefined) {
|
||||
if (!isServiceId(service)) {
|
||||
return Response.json(
|
||||
{ error: "Invalid service." },
|
||||
{ status: 400 },
|
||||
);
|
||||
return Response.json({ error: "Invalid service." }, { status: 400 });
|
||||
}
|
||||
push("service", service as string);
|
||||
}
|
||||
@@ -143,9 +369,14 @@ export async function PATCH(req: Request) {
|
||||
`UPDATE drivers SET ${updates.join(", ")} WHERE id = $${idx} RETURNING *`,
|
||||
values,
|
||||
);
|
||||
|
||||
// Nothing references the old scans now, and they are identity documents —
|
||||
// don't keep them around a moment longer than the row does.
|
||||
await Promise.all(superseded.map((name) => deleteUpload(name, "document")));
|
||||
|
||||
return Response.json({ data: rows[0] });
|
||||
} catch (error) {
|
||||
console.error("[DRIVER_PROFILE_PATCH]: ", error);
|
||||
return Response.json({ error: "Internal Server Error" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+218
-32
@@ -1,11 +1,21 @@
|
||||
import { requireDriverProfile } from "@/lib/driver";
|
||||
import { sql } from "@/lib/db";
|
||||
import { DRIVER_BUSY_ARRAY, expireStaleRequests } from "@/lib/ride-lifecycle";
|
||||
import { boundingBox, haversine } from "@/lib/utils";
|
||||
import { BROADCAST_RADIUS_M, REQUEST_TTL_SECONDS } from "@/constants/dispatch";
|
||||
import { splitFare } from "@/lib/pricing";
|
||||
|
||||
// GET — the driver's world in one poll:
|
||||
// offers : incoming ride_offers awaiting this driver's accept/decline,
|
||||
// each joined to its ride so the card can show pickup/dest/fare.
|
||||
// active : the ride this driver is currently on (accepted or en_route).
|
||||
// requests: open ride requests broadcast near this driver, each carrying
|
||||
// how far the pickup is, what the driver would earn, and whether
|
||||
// they have already offered on it.
|
||||
// active : the ride this driver is currently on (accepted -> en_route).
|
||||
// recent : rides completed today, for the earnings summary.
|
||||
//
|
||||
// Requests are found by distance from the driver's own last position, using
|
||||
// the same radius lib/dispatch broadcasts over — the two questions ("who
|
||||
// should be told about this request?" and "what is open near me?") have to
|
||||
// agree, or a driver gets pushed a job their dashboard then hides.
|
||||
export async function GET(req: Request) {
|
||||
const result = await requireDriverProfile(req);
|
||||
if ("error" in result) return result.error;
|
||||
@@ -13,53 +23,211 @@ export async function GET(req: Request) {
|
||||
try {
|
||||
const { driverId } = result;
|
||||
|
||||
const offers = await sql`
|
||||
SELECT
|
||||
ro.id AS offer_id, ro.offered_at,
|
||||
r.ride_id, r.origin_address, r.destination_address,
|
||||
r.origin_latitude, r.origin_longitude,
|
||||
r.destination_latitude, r.destination_longitude,
|
||||
r.ride_time, r.fare_price, r.payment_status, r.service, r.user_id
|
||||
FROM ride_offers ro
|
||||
JOIN rides r ON r.ride_id = ro.ride_id
|
||||
WHERE ro.driver_id = ${driverId} AND ro.status = 'offered'
|
||||
ORDER BY ro.offered_at DESC
|
||||
// This poll is one of the lazy paths that stands in for a background
|
||||
// worker, so it also buries requests nobody was picked for. Awaited: the
|
||||
// list read below should not include a request that just died.
|
||||
await expireStaleRequests();
|
||||
|
||||
// The driver's own position and state. A driver with no fix yet can't be
|
||||
// told what's near them, and one who is offline shouldn't be shown work.
|
||||
const [me] = await sql<{
|
||||
latitude: number | null;
|
||||
longitude: number | null;
|
||||
service: string;
|
||||
online: boolean;
|
||||
}>`
|
||||
SELECT latitude, longitude, service, online
|
||||
FROM drivers WHERE id = ${driverId}
|
||||
`;
|
||||
|
||||
const canSeeRequests =
|
||||
me?.online === true && me.latitude !== null && me.longitude !== null;
|
||||
|
||||
// Coarse box in the index, great-circle pass afterwards — the same
|
||||
// two-step every other proximity query in this codebase uses.
|
||||
const box = canSeeRequests
|
||||
? boundingBox(me.latitude!, me.longitude!, BROADCAST_RADIUS_M)
|
||||
: null;
|
||||
|
||||
const openRequests = box
|
||||
? await sql<OpenRequestRow>`
|
||||
SELECT
|
||||
r.ride_id, r.origin_address, r.destination_address,
|
||||
r.origin_latitude, r.origin_longitude,
|
||||
r.destination_latitude, r.destination_longitude,
|
||||
r.ride_time, r.fare_price, r.service, r.created_at,
|
||||
u.name AS rider_name, u.rating AS rider_rating,
|
||||
mine.id AS my_offer_id,
|
||||
(SELECT COUNT(*)::int FROM ride_offers ro
|
||||
WHERE ro.ride_id = r.ride_id AND ro.status = 'offered')
|
||||
AS offer_count
|
||||
FROM rides r
|
||||
LEFT JOIN users u ON u.id = r.user_id
|
||||
LEFT JOIN ride_offers mine
|
||||
ON mine.ride_id = r.ride_id
|
||||
AND mine.driver_id = ${driverId}
|
||||
AND mine.status = 'offered'
|
||||
WHERE r.status = 'requested'
|
||||
AND r.service = ${me.service}
|
||||
AND r.created_at > CURRENT_TIMESTAMP - make_interval(secs => ${REQUEST_TTL_SECONDS})
|
||||
AND r.origin_latitude BETWEEN ${box.minLat} AND ${box.maxLat}
|
||||
AND r.origin_longitude BETWEEN ${box.minLng} AND ${box.maxLng}
|
||||
ORDER BY r.created_at DESC
|
||||
`
|
||||
: [];
|
||||
|
||||
// Distance is computed here rather than in SQL so the filter and the
|
||||
// number the driver reads on the card are the same calculation.
|
||||
const requests = (openRequests as unknown as OpenRequestRow[])
|
||||
.map((row) => ({
|
||||
...row,
|
||||
pickup_distance_m: Math.round(
|
||||
haversine(
|
||||
me.latitude!,
|
||||
me.longitude!,
|
||||
Number(row.origin_latitude),
|
||||
Number(row.origin_longitude),
|
||||
),
|
||||
),
|
||||
}))
|
||||
.filter((row) => row.pickup_distance_m <= BROADCAST_RADIUS_M)
|
||||
.sort((a, b) => a.pickup_distance_m - b.pickup_distance_m);
|
||||
|
||||
// Note: pickup_code is deliberately NOT selected here. The whole point of
|
||||
// the code is that the driver has to get it from the rider at the car.
|
||||
//
|
||||
// The rider's phone number isn't selected either. It used to be shipped to
|
||||
// the driver client and never rendered — personal data in transit for
|
||||
// nothing. Driver↔rider contact goes through the in-app chat and WebRTC
|
||||
// call, which is this app's equivalent of a masked number.
|
||||
const active = await sql`
|
||||
SELECT
|
||||
r.ride_id, r.status, r.service, r.payment_status,
|
||||
r.origin_address, r.destination_address,
|
||||
r.origin_latitude, r.origin_longitude,
|
||||
r.destination_latitude, r.destination_longitude,
|
||||
r.ride_time, r.fare_price, r.created_at,
|
||||
u.name AS rider_name, u.phone AS rider_phone
|
||||
r.ride_time, r.fare_price, r.created_at, r.arrived_at,
|
||||
u.name AS rider_name, u.rating AS rider_rating
|
||||
FROM rides r
|
||||
LEFT JOIN users u ON u.id = r.user_id
|
||||
WHERE r.driver_id = ${driverId} AND r.status IN ('accepted', 'en_route')
|
||||
WHERE r.driver_id = ${driverId}
|
||||
AND r.status = ANY(${DRIVER_BUSY_ARRAY}::text[])
|
||||
ORDER BY r.created_at DESC
|
||||
LIMIT 1
|
||||
`;
|
||||
|
||||
const recent = await sql`
|
||||
SELECT ride_id, fare_price, service, completed_at
|
||||
// driver_payout_cents is what the driver actually keeps; fare_price is
|
||||
// what the rider paid. Everything the driver sees is the payout — COALESCE
|
||||
// covers rides completed before the split existed.
|
||||
const recent = await sql<RecentRow>`
|
||||
SELECT ride_id, fare_price, service, payment_status, completed_at,
|
||||
COALESCE(driver_payout_cents, fare_price) AS payout_cents,
|
||||
COALESCE(platform_fee_cents, 0) AS fee_cents
|
||||
FROM rides
|
||||
WHERE driver_id = ${driverId} AND status = 'completed'
|
||||
AND completed_at >= CURRENT_DATE
|
||||
ORDER BY completed_at DESC
|
||||
`;
|
||||
|
||||
const earnings = recent.reduce(
|
||||
(sum, r) => sum + Number(r.fare_price),
|
||||
0,
|
||||
// The driver's running balance with the company, across all time rather
|
||||
// than just today — an unremitted commission doesn't stop mattering at
|
||||
// midnight. Two directions: cash commission they're holding for us, and
|
||||
// card payouts we still owe them.
|
||||
const [balance] = await sql<{
|
||||
owes_company_cents: number;
|
||||
owed_to_driver_cents: number;
|
||||
}>`
|
||||
SELECT
|
||||
COALESCE(SUM(platform_fee_cents)
|
||||
FILTER (WHERE platform_fee_settled_at IS NULL), 0)::int
|
||||
AS owes_company_cents,
|
||||
COALESCE(SUM(driver_payout_cents)
|
||||
FILTER (WHERE driver_payout_settled_at IS NULL), 0)::int
|
||||
AS owed_to_driver_cents
|
||||
FROM rides
|
||||
WHERE driver_id = ${driverId}
|
||||
AND status = 'completed'
|
||||
AND payment_status IN ('paid','cash_collected')
|
||||
`;
|
||||
|
||||
// A ride the driver finished recently and hasn't rated. Surfaced as a
|
||||
// prompt on the dashboard so the rating survives the driver immediately
|
||||
// accepting their next trip.
|
||||
const pendingRating = await sql`
|
||||
SELECT r.ride_id, u.name AS rider_name
|
||||
FROM rides r
|
||||
LEFT JOIN users u ON u.id = r.user_id
|
||||
WHERE r.driver_id = ${driverId}
|
||||
AND r.status = 'completed'
|
||||
AND r.completed_at > CURRENT_TIMESTAMP - INTERVAL '1 day'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM ride_ratings rr
|
||||
WHERE rr.ride_id = r.ride_id AND rr.rater_type = 'driver'
|
||||
)
|
||||
ORDER BY r.completed_at DESC
|
||||
LIMIT 1
|
||||
`;
|
||||
|
||||
const settled = (r: RecentRow) =>
|
||||
r.payment_status === "paid" || r.payment_status === "cash_collected";
|
||||
|
||||
const sumPayout = (rows: typeof recent) =>
|
||||
rows.reduce((sum, r) => sum + Number(r.payout_cents), 0);
|
||||
const sumFares = (rows: typeof recent) =>
|
||||
rows.reduce((sum, r) => sum + Number(r.fare_price), 0);
|
||||
|
||||
// Earnings count settled money only, and count the driver's share of it.
|
||||
// A cash ride the driver marked "not collected" is still an unpaid trip
|
||||
// and used to land in this headline anyway, so the figure a driver saw and
|
||||
// the figure they'd be paid against disagreed from day one.
|
||||
const earnings = sumPayout(recent.filter(settled));
|
||||
|
||||
// The platform's cut of the same rides, so the number above is explainable
|
||||
// rather than mysteriously smaller than the fares they remember charging.
|
||||
const platformFees = recent
|
||||
.filter(settled)
|
||||
.reduce((sum, r) => sum + Number(r.fee_cents), 0);
|
||||
|
||||
// Cash the driver has taken in hand today — the full fare, because that's
|
||||
// the physical money in their pocket, not their share of it. This is the
|
||||
// figure they'll be reconciled against, and the platform's cut of it is
|
||||
// owed back.
|
||||
const cashCollected = sumFares(
|
||||
recent.filter((r) => r.payment_status === "cash_collected"),
|
||||
);
|
||||
|
||||
// Fares that were never collected. Surfaced rather than hidden so an
|
||||
// unpaid trip is visible to the driver on the day it happened.
|
||||
const cashOwed = sumFares(recent.filter((r) => r.payment_status === "cash"));
|
||||
|
||||
// A driver deciding whether to take a ride cares what they'll be paid, not
|
||||
// what the rider is charged. The split isn't stored until completion, so
|
||||
// it's computed here from the same helper that stamps it later — the two
|
||||
// can't disagree, and the driver is never shown a number they won't get.
|
||||
const withPayout = <T extends { fare_price: number }>(row: T) => ({
|
||||
...row,
|
||||
payout_cents: splitFare(Number(row.fare_price)).driverPayoutCents,
|
||||
});
|
||||
|
||||
return Response.json({
|
||||
data: {
|
||||
offers: offers as unknown as OfferRow[],
|
||||
active: (active[0] as unknown as ActiveRide | undefined) ?? null,
|
||||
recent: recent as unknown as RecentRow[],
|
||||
// The server's clock, so the client can draw a request countdown that
|
||||
// matches the TTL dispatch actually enforces. Without it a phone whose
|
||||
// clock is a few seconds out shows a timer that expires early or late.
|
||||
now: new Date().toISOString(),
|
||||
requests: requests.map(withPayout),
|
||||
active: active[0]
|
||||
? withPayout(active[0] as unknown as ActiveRide)
|
||||
: null,
|
||||
recent,
|
||||
earnings,
|
||||
platform_fees: platformFees,
|
||||
cash_collected: cashCollected,
|
||||
cash_owed: cashOwed,
|
||||
owes_company: Number(balance?.owes_company_cents ?? 0),
|
||||
owed_to_driver: Number(balance?.owed_to_driver_cents ?? 0),
|
||||
pending_rating:
|
||||
(pendingRating[0] as unknown as PendingRatingRow | undefined) ?? null,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
@@ -68,9 +236,7 @@ export async function GET(req: Request) {
|
||||
}
|
||||
}
|
||||
|
||||
type OfferRow = {
|
||||
offer_id: number;
|
||||
offered_at: string;
|
||||
type OpenRequestRow = {
|
||||
ride_id: number;
|
||||
origin_address: string;
|
||||
destination_address: string;
|
||||
@@ -80,12 +246,23 @@ type OfferRow = {
|
||||
destination_longitude: number;
|
||||
ride_time: number;
|
||||
fare_price: number;
|
||||
payment_status: string;
|
||||
service: string;
|
||||
user_id: string;
|
||||
created_at: string;
|
||||
rider_name: string | null;
|
||||
rider_rating: number | null;
|
||||
/** The id of this driver's live offer on the request, or null. */
|
||||
my_offer_id: number | null;
|
||||
/** How many drivers are competing for it, this one included. */
|
||||
offer_count: number;
|
||||
/** Metres from the driver's last position to the pickup. */
|
||||
pickup_distance_m?: number;
|
||||
/** The driver's share of the fare, computed per request. */
|
||||
payout_cents?: number;
|
||||
};
|
||||
|
||||
type ActiveRide = {
|
||||
/** The driver's share of the fare, computed per request. */
|
||||
payout_cents?: number;
|
||||
ride_id: number;
|
||||
status: string;
|
||||
service: string;
|
||||
@@ -99,13 +276,22 @@ type ActiveRide = {
|
||||
ride_time: number;
|
||||
fare_price: number;
|
||||
created_at: string;
|
||||
arrived_at: string | null;
|
||||
rider_name: string | null;
|
||||
rider_phone: string | null;
|
||||
rider_rating: number | null;
|
||||
};
|
||||
|
||||
type RecentRow = {
|
||||
ride_id: number;
|
||||
fare_price: number;
|
||||
payout_cents: number;
|
||||
fee_cents: number;
|
||||
service: string;
|
||||
payment_status: string;
|
||||
completed_at: string;
|
||||
};
|
||||
};
|
||||
|
||||
type PendingRatingRow = {
|
||||
ride_id: number;
|
||||
rider_name: string | null;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
import { sql } from "@/lib/db";
|
||||
import {
|
||||
isDocumentType,
|
||||
OcrUnavailableError,
|
||||
parseDocumentText,
|
||||
recogniseDocument,
|
||||
} from "@/lib/document-ocr";
|
||||
import { requireAuth } from "@/lib/jwt";
|
||||
import {
|
||||
MAX_UPLOAD_BYTES,
|
||||
pruneOrphanUploads,
|
||||
sniffImageType,
|
||||
storeUpload,
|
||||
} from "@/lib/uploads";
|
||||
|
||||
// POST — a driver photographs one of their documents; we keep the scan and
|
||||
// read what we can off it to prefill the onboarding form.
|
||||
//
|
||||
// The scan is stored whether or not OCR succeeds: the reviewer wants to see the
|
||||
// actual licence next to the numbers the driver submitted, and that value does
|
||||
// not depend on Vision having had a good day. When OCR fails the route still
|
||||
// answers 200 with an empty field set and a code the client uses to say "type
|
||||
// these in yourself" — an unreadable photo is a normal outcome, not an error.
|
||||
|
||||
/**
|
||||
* Scans are the most expensive call in the app (a paid Vision request plus a
|
||||
* disk write), so cap how fast one account can make them. In-process and
|
||||
* therefore per-server — enough to stop a stuck retry loop or a bored driver
|
||||
* burning the Vision quota, not a defence against a distributed attacker.
|
||||
*/
|
||||
const SCAN_LIMIT = 20;
|
||||
const SCAN_WINDOW_MS = 60 * 60 * 1000;
|
||||
const recentScans = new Map<string, number[]>();
|
||||
|
||||
const overScanLimit = (userId: string): boolean => {
|
||||
const now = Date.now();
|
||||
const cutoff = now - SCAN_WINDOW_MS;
|
||||
const history = (recentScans.get(userId) ?? []).filter((at) => at > cutoff);
|
||||
|
||||
if (history.length >= SCAN_LIMIT) {
|
||||
recentScans.set(userId, history);
|
||||
return true;
|
||||
}
|
||||
|
||||
history.push(now);
|
||||
recentScans.set(userId, history);
|
||||
|
||||
// Without this the map grows one entry per driver forever. Anything whose
|
||||
// whole history has aged out is a driver who isn't scanning any more.
|
||||
if (recentScans.size > 500) {
|
||||
for (const [key, times] of recentScans) {
|
||||
if (times.every((at) => at <= cutoff)) recentScans.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Abandoned onboarding leaves identity documents on disk that nothing points
|
||||
* at. Sweeping them here rather than on a cron keeps the deployment to one
|
||||
* process; once an hour is often enough for files that get a day's grace.
|
||||
*/
|
||||
const PRUNE_INTERVAL_MS = 60 * 60 * 1000;
|
||||
let lastPruneAt = 0;
|
||||
|
||||
const pruneOrphansOccasionally = async (): Promise<void> => {
|
||||
if (Date.now() - lastPruneAt < PRUNE_INTERVAL_MS) return;
|
||||
lastPruneAt = Date.now();
|
||||
|
||||
try {
|
||||
const rows = await sql<{
|
||||
license_image_url: string | null;
|
||||
id_image_url: string | null;
|
||||
vehicle_reg_image_url: string | null;
|
||||
}>`
|
||||
SELECT license_image_url, id_image_url, vehicle_reg_image_url
|
||||
FROM drivers
|
||||
WHERE license_image_url IS NOT NULL
|
||||
OR id_image_url IS NOT NULL
|
||||
OR vehicle_reg_image_url IS NOT NULL
|
||||
`;
|
||||
|
||||
const referenced = new Set<string>();
|
||||
for (const row of rows) {
|
||||
for (const name of Object.values(row)) {
|
||||
if (name) referenced.add(name);
|
||||
}
|
||||
}
|
||||
|
||||
await pruneOrphanUploads(referenced, "document");
|
||||
} catch (error) {
|
||||
// A failed sweep must never fail the driver's scan.
|
||||
console.error("[DRIVER_SCAN_PRUNE]: ", error);
|
||||
}
|
||||
};
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const auth = requireAuth(req);
|
||||
if ("error" in auth) return auth.error;
|
||||
|
||||
try {
|
||||
const body = await req.json();
|
||||
const { doc_type: docType } = body;
|
||||
|
||||
if (!isDocumentType(docType)) {
|
||||
return Response.json(
|
||||
{ error: "doc_type must be license, id or vehicle_reg." },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
// Same gate as onboarding itself: only a driver-role account has any
|
||||
// business uploading driver documents.
|
||||
const users = await sql<{ role: string | null }>`
|
||||
SELECT role FROM users WHERE id = ${auth.userId}
|
||||
`;
|
||||
if (users[0]?.role !== "driver") {
|
||||
return Response.json(
|
||||
{ error: "Only driver accounts can scan documents." },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
if (overScanLimit(auth.userId)) {
|
||||
return Response.json(
|
||||
{
|
||||
error: "Too many scans. Wait a few minutes and try again.",
|
||||
code: "SCAN_RATE_LIMIT",
|
||||
},
|
||||
{ status: 429 },
|
||||
);
|
||||
}
|
||||
|
||||
const raw = body.image_base64;
|
||||
if (typeof raw !== "string" || raw.length === 0) {
|
||||
return Response.json(
|
||||
{ error: "image_base64 is required." },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
// Some clients send a full data URI. Take the payload either way.
|
||||
const encoded = raw.includes(",") ? raw.slice(raw.indexOf(",") + 1) : raw;
|
||||
|
||||
// Base64 inflates by 4/3, so reject on the encoded length before
|
||||
// allocating — otherwise an oversized upload is buffered just to be
|
||||
// refused.
|
||||
if (encoded.length > MAX_UPLOAD_BYTES * 1.4) {
|
||||
return Response.json(
|
||||
{ error: "That image is too large.", code: "IMAGE_TOO_LARGE" },
|
||||
{ status: 413 },
|
||||
);
|
||||
}
|
||||
|
||||
const image = Buffer.from(encoded, "base64");
|
||||
|
||||
if (image.length > MAX_UPLOAD_BYTES) {
|
||||
return Response.json(
|
||||
{ error: "That image is too large.", code: "IMAGE_TOO_LARGE" },
|
||||
{ status: 413 },
|
||||
);
|
||||
}
|
||||
|
||||
// The magic bytes decide the type, not whatever the client claimed, so a
|
||||
// non-image can't be parked on the disk under a .jpg name.
|
||||
const mimeType = sniffImageType(image);
|
||||
if (!mimeType) {
|
||||
return Response.json(
|
||||
{
|
||||
error: "Upload a JPEG, PNG or WebP photo.",
|
||||
code: "UNSUPPORTED_IMAGE",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const document = await storeUpload(image, mimeType, "document");
|
||||
|
||||
void pruneOrphansOccasionally();
|
||||
|
||||
let fields = {};
|
||||
let ocrFailed = false;
|
||||
|
||||
try {
|
||||
const text = await recogniseDocument(image);
|
||||
fields = parseDocumentText(text, docType);
|
||||
} catch (error) {
|
||||
if (!(error instanceof OcrUnavailableError)) throw error;
|
||||
// Logged, not surfaced: the message can name the API key's failure mode
|
||||
// and the driver can do nothing with it but type the fields manually.
|
||||
console.error("[DRIVER_SCAN_OCR]: ", error.message);
|
||||
ocrFailed = true;
|
||||
}
|
||||
|
||||
return Response.json({
|
||||
data: {
|
||||
doc_type: docType,
|
||||
/** Opaque stored name; submit it with the profile to attach the scan. */
|
||||
document,
|
||||
fields,
|
||||
...(ocrFailed ? { code: "OCR_UNAVAILABLE" } : {}),
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[DRIVER_SCAN_POST]: ", error);
|
||||
return Response.json({ error: "Internal Server Error" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user