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:
Krikorios
2026-08-26 02:17:55 +03:00
co-authored by Claude Opus 5
parent 1d84003e0a
commit 8807ff41c5
111 changed files with 14568 additions and 1411 deletions
+243
View File
@@ -0,0 +1,243 @@
import { sql } from "@/lib/db";
import { requireRideParticipant, rideIsActive } from "@/lib/ride-participants";
// In-app WebRTC audio call signaling, carried over the same DB-backed polling
// pattern as chat (no WebSocket). Non-trickle ICE: each side gathers all
// candidates locally and bundles them into a single SDP offer/answer stored as
// text, so the whole handshake is a few polled round-trips.
//
// POST { sdp_offer } -> caller starts a call (status=ringing)
// GET -> poll: callee reads the offer, both read
// the answer + status; lazily sweeps stale
// ringing calls to 'missed'.
// PATCH { action, sdp_answer? } -> answer / decline / end
// A ringing call older than this with no answer is treated as missed. Swept
// lazily inside GET, the way the broadcast advances on the ride-status poll.
const RINGING_TTL_SECONDS = 30;
type CallRow = {
id: number;
ride_id: number;
caller_type: "rider" | "driver";
status: "ringing" | "answered" | "ended" | "declined" | "missed";
sdp_offer: string | null;
sdp_answer: string | null;
started_at: string | null;
ended_at: string | null;
created_at: string;
};
// POST — initiate a call. Rejects if the ride isn't active or a call is already
// in flight for it, so two calls can't stack on one ride.
export async function POST(req: Request, { id }: { id: string }) {
const rideId = Number(id);
if (!Number.isInteger(rideId)) {
return Response.json({ error: "Invalid ride id." }, { status: 400 });
}
const participant = await requireRideParticipant(req, rideId);
if ("error" in participant) return participant.error;
let body: { sdp_offer?: string };
try {
body = await req.json();
} catch {
return Response.json({ error: "Invalid JSON body." }, { status: 400 });
}
const sdpOffer = body.sdp_offer;
if (!sdpOffer || typeof sdpOffer !== "string") {
return Response.json({ error: "Missing sdp_offer." }, { status: 400 });
}
try {
if (!(await rideIsActive(rideId))) {
return Response.json(
{ error: "This ride is no longer active." },
{ status: 409 },
);
}
// Snapshot both parties onto the call row so authorization is one
// equality check on poll and the call survives a driver reassignment.
const ride = await sql<{ user_id: string; driver_id: number }>`
SELECT user_id, driver_id FROM rides
WHERE ride_id = ${rideId} AND driver_id IS NOT NULL
`;
if (!ride[0]) {
return Response.json(
{ error: "This ride has no driver assigned." },
{ status: 409 },
);
}
// Only one non-terminal call per ride at a time.
const inFlight = await sql<{ n: number }>`
SELECT COUNT(*)::int AS n FROM calls
WHERE ride_id = ${rideId} AND status IN ('ringing','answered')
`;
if ((inFlight[0]?.n ?? 0) > 0) {
return Response.json(
{ error: "A call is already in progress for this ride." },
{ status: 409 },
);
}
const inserted = await sql<{ id: number }>`
INSERT INTO calls (ride_id, user_id, driver_id, caller_type, status, sdp_offer)
VALUES (
${rideId},
${ride[0].user_id},
${ride[0].driver_id},
${participant.role},
'ringing',
${sdpOffer}
)
RETURNING id
`;
return Response.json({ data: { callId: inserted[0].id } }, { status: 201 });
} catch (error) {
console.error("[POST_CALL]: ", error);
return Response.json({ error: "Internal Server Error." }, { status: 500 });
}
}
// GET — poll the call for this ride. Returns the latest non-terminal call (or
// the most recent terminal one so the caller sees ended/declined/missed), with
// `is_caller` so each side knows whether it placed the call.
export async function GET(req: Request, { id }: { id: string }) {
const rideId = Number(id);
if (!Number.isInteger(rideId)) {
return Response.json({ error: "Invalid ride id." }, { status: 400 });
}
const participant = await requireRideParticipant(req, rideId);
if ("error" in participant) return participant.error;
try {
// Lazy missed-call sweep: a ringing call nobody answered in time is
// marked missed so the caller's screen can stop ringing.
await sql`
UPDATE calls
SET status = 'missed', ended_at = CURRENT_TIMESTAMP
WHERE ride_id = ${rideId}
AND status = 'ringing'
AND created_at < CURRENT_TIMESTAMP - make_interval(secs => ${RINGING_TTL_SECONDS})
`;
const rows = await sql<CallRow>`
SELECT id, ride_id, caller_type, status, sdp_offer, sdp_answer,
started_at, ended_at, created_at
FROM calls
WHERE ride_id = ${rideId}
ORDER BY created_at DESC
LIMIT 1
`;
const call = rows[0] ?? null;
return Response.json({
data: call
? { ...call, is_caller: call.caller_type === participant.role }
: null,
});
} catch (error) {
console.error("[GET_CALL]: ", error);
return Response.json({ error: "Internal Server Error." }, { status: 500 });
}
}
// PATCH — answer (callee only), decline (callee only), or end (either).
export async function PATCH(req: Request, { id }: { id: string }) {
const rideId = Number(id);
if (!Number.isInteger(rideId)) {
return Response.json({ error: "Invalid ride id." }, { status: 400 });
}
const participant = await requireRideParticipant(req, rideId);
if ("error" in participant) return participant.error;
let body: { action?: string; sdp_answer?: string };
try {
body = await req.json();
} catch {
return Response.json({ error: "Invalid JSON body." }, { status: 400 });
}
const action = body.action;
if (action !== "answer" && action !== "decline" && action !== "end") {
return Response.json(
{ error: "action must be 'answer', 'decline', or 'end'." },
{ status: 400 },
);
}
try {
// Answer/decline are the callee's moves; end is either party's.
const isCaller = (callerType: string) => callerType === participant.role;
const rows = await sql<{ caller_type: string; status: string }>`
SELECT caller_type, status FROM calls
WHERE ride_id = ${rideId} AND status IN ('ringing','answered')
ORDER BY created_at DESC LIMIT 1
`;
const call = rows[0];
if (!call) {
return Response.json(
{ error: "No active call for this ride." },
{ status: 409 },
);
}
if (action === "answer") {
if (isCaller(call.caller_type)) {
return Response.json(
{ error: "Caller cannot answer their own call." },
{ status: 403 },
);
}
if (call.status !== "ringing") {
return Response.json(
{ error: "Call is no longer ringing." },
{ status: 409 },
);
}
const sdpAnswer = body.sdp_answer;
if (!sdpAnswer || typeof sdpAnswer !== "string") {
return Response.json({ error: "Missing sdp_answer." }, { status: 400 });
}
await sql`
UPDATE calls
SET status = 'answered', sdp_answer = ${sdpAnswer}, started_at = CURRENT_TIMESTAMP
WHERE ride_id = ${rideId} AND status = 'ringing'
`;
return Response.json({ data: { action: "answered" } });
}
if (action === "decline") {
if (isCaller(call.caller_type)) {
return Response.json(
{ error: "Caller cannot decline their own call." },
{ status: 403 },
);
}
await sql`
UPDATE calls
SET status = 'declined', ended_at = CURRENT_TIMESTAMP
WHERE ride_id = ${rideId} AND status = 'ringing'
`;
return Response.json({ data: { action: "declined" } });
}
// end — either party, while ringing or answered.
await sql`
UPDATE calls
SET status = 'ended', ended_at = CURRENT_TIMESTAMP
WHERE ride_id = ${rideId} AND status IN ('ringing','answered')
`;
return Response.json({ data: { action: "ended" } });
} catch (error) {
console.error("[PATCH_CALL]: ", error);
return Response.json({ error: "Internal Server Error." }, { status: 500 });
}
}
+154
View File
@@ -0,0 +1,154 @@
import { sql } from "@/lib/db";
import { requireRideParticipant, rideIsActive } from "@/lib/ride-participants";
// In-app chat for a ride. Both the rider and the assigned driver can read and
// post, but only while the ride is active (accepted / en_route); a terminal
// ride is read-only so the conversation is frozen once the trip ends.
type MessageRow = {
id: number;
ride_id: number;
sender_type: "rider" | "driver";
sender_id: string;
body: string;
created_at: string;
sender_name: string;
sender_avatar: string | null;
};
// GET — messages for the ride. `?since=<id>` returns only rows with id > since
// (the polling cursor), oldest-first so the client can append directly. With
// no cursor the full history is returned for the initial load.
export async function GET(req: Request, { id }: { id: string }) {
const rideId = Number(id);
if (!Number.isInteger(rideId)) {
return Response.json({ error: "Invalid ride id." }, { status: 400 });
}
const participant = await requireRideParticipant(req, rideId);
if ("error" in participant) return participant.error;
const sinceParam = new URL(req.url).searchParams.get("since");
const since = Number(sinceParam);
const hasCursor = Number.isInteger(since) && since > 0;
try {
// The optional `since` cursor can't be a nested sql fragment (sql executes
// immediately), so branch into two queries that each take no extra params.
const rows = hasCursor
? await sql<MessageRow>`
SELECT
m.id,
m.ride_id,
m.sender_type,
COALESCE(m.sender_user_id::text, m.sender_driver_id::text) AS sender_id,
m.body,
m.created_at,
COALESCE(u.name, CONCAT_WS(' ', d.first_name, d.last_name)) AS sender_name,
d.profile_image_url AS sender_avatar
FROM messages m
LEFT JOIN users u ON u.id = m.sender_user_id
LEFT JOIN drivers d ON d.id = m.sender_driver_id
WHERE m.ride_id = ${rideId} AND m.id > ${since}
ORDER BY m.id ASC
`
: await sql<MessageRow>`
SELECT
m.id,
m.ride_id,
m.sender_type,
COALESCE(m.sender_user_id::text, m.sender_driver_id::text) AS sender_id,
m.body,
m.created_at,
COALESCE(u.name, CONCAT_WS(' ', d.first_name, d.last_name)) AS sender_name,
d.profile_image_url AS sender_avatar
FROM messages m
LEFT JOIN users u ON u.id = m.sender_user_id
LEFT JOIN drivers d ON d.id = m.sender_driver_id
WHERE m.ride_id = ${rideId}
ORDER BY m.id ASC
`;
return Response.json({ data: rows });
} catch (error) {
console.error("[GET_MESSAGES]: ", error);
return Response.json({ error: "Internal Server Error." }, { status: 500 });
}
}
// POST — send a message. Rejected (409) if the ride is no longer active, so a
// completed/cancelled trip can't receive new messages.
export async function POST(req: Request, { id }: { id: string }) {
const rideId = Number(id);
if (!Number.isInteger(rideId)) {
return Response.json({ error: "Invalid ride id." }, { status: 400 });
}
const participant = await requireRideParticipant(req, rideId);
if ("error" in participant) return participant.error;
let body: { body?: string };
try {
body = await req.json();
} catch {
return Response.json({ error: "Invalid JSON body." }, { status: 400 });
}
const text = (body.body ?? "").trim();
if (!text) {
return Response.json({ error: "Message body is empty." }, { status: 400 });
}
if (text.length > 4000) {
return Response.json({ error: "Message is too long." }, { status: 400 });
}
try {
if (!(await rideIsActive(rideId))) {
return Response.json(
{ error: "This ride is no longer active." },
{ status: 409 },
);
}
const inserted = await sql<MessageRow>`
INSERT INTO messages (ride_id, sender_type, sender_user_id, sender_driver_id, body)
VALUES (
${rideId},
${participant.role},
${participant.role === "rider" ? participant.userId : null},
${participant.role === "driver" ? participant.driverId : null},
${text}
)
RETURNING
id,
ride_id,
sender_type,
COALESCE(sender_user_id::text, sender_driver_id::text) AS sender_id,
body,
created_at
`;
// Join the sender's name/avatar for the returned row so the client can
// render the optimistic bubble identically to polled ones.
const message = inserted[0];
if (participant.role === "driver") {
const driver = await sql<{ name: string; avatar: string | null }>`
SELECT CONCAT_WS(' ', first_name, last_name) AS name, profile_image_url AS avatar
FROM drivers WHERE id = ${participant.driverId}
`;
message.sender_name = driver[0]?.name ?? "";
message.sender_avatar = driver[0]?.avatar ?? null;
} else {
const rider = await sql<{ name: string }>`
SELECT name FROM users WHERE id = ${participant.userId}
`;
message.sender_name = rider[0]?.name ?? "";
message.sender_avatar = null;
}
return Response.json({ data: message }, { status: 201 });
} catch (error) {
console.error("[POST_MESSAGE]: ", error);
return Response.json({ error: "Internal Server Error." }, { status: 500 });
}
}
+171
View File
@@ -0,0 +1,171 @@
import { requireApprovedDriver } from "@/lib/driver";
import { sql, transaction } from "@/lib/db";
import { sendPushToUser } from "@/lib/push";
import { DRIVER_BUSY_ARRAY } from "@/lib/ride-lifecycle";
import { haversine } from "@/lib/utils";
// POST — a driver's answer to a broadcast request.
//
// { action: 'offer' } — volunteer for it. The rider sees this driver
// appear in their list of offers and may pick them.
// { action: 'withdraw' } — take the offer back, before the rider picks.
//
// Offering is not an assignment: several drivers can be offered on the same
// request at once and none of them is committed until the rider chooses. That
// is why offering doesn't take a driver off the board, and why withdrawing is
// free — the cost of a driver changing their mind lands here rather than on a
// rider whose ride was already promised away.
export async function POST(req: Request, { id }: { id: string }) {
const rideId = Number(id);
if (!Number.isInteger(rideId)) {
return Response.json({ error: "Invalid ride id." }, { status: 400 });
}
// Approval is re-checked here, not just at broadcast time: a driver
// suspended between seeing a request and tapping Offer must not be able to
// put themselves in front of a rider. (Rides already under way stay under
// requireDriverProfile — a suspension must never strand a rider who is
// sitting in the car.)
const result = await requireApprovedDriver(req);
if ("error" in result) return result.error;
const { driverId } = result;
let body: { action?: string };
try {
body = await req.json();
} catch {
return Response.json({ error: "Invalid JSON body." }, { status: 400 });
}
const action = body.action;
if (action !== "offer" && action !== "withdraw") {
return Response.json(
{ error: "action must be 'offer' or 'withdraw'." },
{ status: 400 },
);
}
try {
if (action === "withdraw") {
const withdrawn = await sql<{ id: number }>`
UPDATE ride_offers
SET status = 'withdrawn', responded_at = CURRENT_TIMESTAMP
WHERE ride_id = ${rideId}
AND driver_id = ${driverId}
AND status = 'offered'
RETURNING id
`;
if (!withdrawn[0]) {
return Response.json(
{ error: "There is no live offer to withdraw." },
{ status: 409 },
);
}
return Response.json({ data: { status: "withdrawn" } });
}
const offered = await transaction<{
userId: string;
alreadyOffered: boolean;
} | null>(async (tx) => {
// Lock the request so a rider picking someone else at this exact moment
// and this driver offering can't both believe they won.
const rides = await tx<{
status: string;
user_id: string;
service: string;
lat: number;
lng: number;
}>`
SELECT status, user_id, service,
origin_latitude AS lat, origin_longitude AS lng
FROM rides WHERE ride_id = ${rideId} FOR UPDATE
`;
const ride = rides[0];
if (!ride || ride.status !== "requested") return null;
// The driver's own state has to be re-read here rather than trusted from
// the dashboard that drew the button: service, liveness and — above all
// — whether they picked up another ride in the meantime.
const drivers = await tx<{
service: string;
online: boolean;
latitude: number | null;
longitude: number | null;
}>`
SELECT service, online, latitude, longitude
FROM drivers WHERE id = ${driverId}
`;
const driver = drivers[0];
if (!driver || !driver.online || driver.service !== ride.service) {
return null;
}
const busy = await tx<{ n: number }>`
SELECT COUNT(*)::int AS n FROM rides
WHERE driver_id = ${driverId}
AND status = ANY(${DRIVER_BUSY_ARRAY}::text[])
`;
if ((busy[0]?.n ?? 0) > 0) return null;
const distance =
driver.latitude === null || driver.longitude === null
? null
: Math.round(
haversine(ride.lat, ride.lng, driver.latitude, driver.longitude),
);
// ON CONFLICT rather than an existence check: the unique index is the
// real guard, and a driver who taps Offer twice (or re-offers after
// withdrawing) should end up with one live offer either way.
const rows = await tx<{ inserted: boolean }>`
INSERT INTO ride_offers (ride_id, driver_id, status, pickup_distance_m)
VALUES (${rideId}, ${driverId}, 'offered', ${distance})
ON CONFLICT (ride_id, driver_id) DO UPDATE
SET status = 'offered',
offered_at = CURRENT_TIMESTAMP,
responded_at = NULL,
pickup_distance_m = EXCLUDED.pickup_distance_m
WHERE ride_offers.status IN ('withdrawn', 'offered')
RETURNING (xmax = 0) AS inserted
`;
// No row means the conflict target existed in a state we refuse to
// revive — the rider already picked someone, or this offer was closed
// with the request.
if (!rows[0]) return null;
return { userId: ride.user_id, alreadyOffered: !rows[0].inserted };
});
if (!offered) {
return Response.json(
{ error: "This request is no longer open." },
{ status: 409 },
);
}
// Nudge the rider — they are sitting on a screen watching for exactly
// this. Only for the first offer on the request: the rest arrive on the
// list they are already looking at, and a buzz per driver would turn a
// busy street into a nuisance.
if (!offered.alreadyOffered) {
const [count] = await sql<{ n: number }>`
SELECT COUNT(*)::int AS n FROM ride_offers
WHERE ride_id = ${rideId} AND status = 'offered'
`;
if ((count?.n ?? 0) === 1) {
void sendPushToUser(offered.userId, {
title: "A driver is available",
body: "Open your ride to see who can pick you up.",
data: { type: "ride_offer_received", rideId },
});
}
}
return Response.json({ data: { status: "offered" } });
} catch (error) {
console.error("[RIDE_OFFER]: ", error);
return Response.json({ error: "Internal Server Error" }, { status: 500 });
}
}
+117
View File
@@ -0,0 +1,117 @@
import { sql } from "@/lib/db";
import { requireRideParticipant } from "@/lib/ride-participants";
import { refreshDriverRating, refreshRiderRating } from "@/lib/ride-lifecycle";
// Two-way rating on a finished ride: the rider rates the driver, the driver
// rates the rider. Either party may only rate once (the UNIQUE (ride_id,
// rater_type) constraint makes the write an idempotent upsert, so a re-submit
// corrects a mis-tap instead of double-counting), and only after the ride is
// completed — a cancelled ride has nothing to rate.
// GET — both sides' ratings for this ride, so a client can show "you rated
// this ride 5" and (once the other party has rated) what they said.
export async function GET(req: Request, { id }: { id: string }) {
const rideId = Number(id);
if (!Number.isInteger(rideId)) {
return Response.json({ error: "Invalid ride id." }, { status: 400 });
}
const participant = await requireRideParticipant(req, rideId);
if ("error" in participant) return participant.error;
try {
const rows = await sql<{
rater_type: "rider" | "driver";
rating: number;
comment: string | null;
created_at: string;
}>`
SELECT rater_type, rating, comment, created_at
FROM ride_ratings WHERE ride_id = ${rideId}
`;
const mine = rows.find((r) => r.rater_type === participant.role) ?? null;
const theirs = rows.find((r) => r.rater_type !== participant.role) ?? null;
return Response.json({ data: { mine, theirs } });
} catch (error) {
console.error("[GET_RIDE_RATING]: ", error);
return Response.json({ error: "Internal Server Error" }, { status: 500 });
}
}
// POST — submit (or correct) this party's rating. Body: { rating: 1..5,
// comment?: string }.
export async function POST(req: Request, { id }: { id: string }) {
const rideId = Number(id);
if (!Number.isInteger(rideId)) {
return Response.json({ error: "Invalid ride id." }, { status: 400 });
}
const participant = await requireRideParticipant(req, rideId);
if ("error" in participant) return participant.error;
let body: { rating?: unknown; comment?: unknown };
try {
body = await req.json();
} catch {
return Response.json({ error: "Invalid JSON body." }, { status: 400 });
}
const rating = Number(body.rating);
if (!Number.isInteger(rating) || rating < 1 || rating > 5) {
return Response.json(
{ error: "rating must be a whole number from 1 to 5." },
{ status: 400 },
);
}
// Comments are optional and capped — they're shown verbatim in the admin
// portal's ride detail, so an unbounded field is a liability.
const rawComment =
typeof body.comment === "string" ? body.comment.trim() : "";
const comment = rawComment ? rawComment.slice(0, 500) : null;
try {
const rides = await sql<{
status: string;
driver_id: number | null;
user_id: string;
}>`
SELECT status, driver_id, user_id FROM rides WHERE ride_id = ${rideId}
`;
const ride = rides[0];
if (!ride) {
return Response.json({ error: "Ride not found." }, { status: 404 });
}
if (ride.status !== "completed") {
return Response.json(
{ error: "Only a completed ride can be rated." },
{ status: 409 },
);
}
const rows = await sql<{ rating: number; comment: string | null }>`
INSERT INTO ride_ratings (ride_id, rater_type, rating, comment)
VALUES (${rideId}, ${participant.role}, ${rating}, ${comment})
ON CONFLICT (ride_id, rater_type) DO UPDATE
SET rating = EXCLUDED.rating,
comment = EXCLUDED.comment,
updated_at = CURRENT_TIMESTAMP
RETURNING rating, comment
`;
// Fold the new score into the rated party's headline average. Awaited
// rather than fire-and-forget so the client's next read sees it.
if (participant.role === "rider" && ride.driver_id !== null) {
await refreshDriverRating(ride.driver_id);
} else if (participant.role === "driver") {
await refreshRiderRating(ride.user_id);
}
return Response.json({ data: rows[0] }, { status: 201 });
} catch (error) {
console.error("[RATE_RIDE]: ", error);
return Response.json({ error: "Internal Server Error" }, { status: 500 });
}
}
-102
View File
@@ -1,102 +0,0 @@
import { requireDriverProfile } from "@/lib/driver";
import { transaction } from "@/lib/db";
import { matchNextDriver } from "@/lib/dispatch";
// POST — a driver responds to a ride offer.
// { action: 'accept' } — claim the ride: offer -> accepted, ride -> accepted,
// ride.driver_id set to this driver. Guarded so only
// the offered driver can accept, and only while the
// offer is still 'offered' (not expired/timed out).
// { action: 'decline' } — release the ride: offer -> declined, then offer
// it to the next-nearest driver via matchNextDriver.
export async function POST(req: Request, { id }: { id: string }) {
const rideId = Number(id);
if (!Number.isInteger(rideId)) {
return Response.json({ error: "Invalid ride id." }, { status: 400 });
}
const result = await requireDriverProfile(req);
if ("error" in result) return result.error;
const { driverId } = result;
let body: { action?: string };
try {
body = await req.json();
} catch {
return Response.json({ error: "Invalid JSON body." }, { status: 400 });
}
const action = body.action;
if (action !== "accept" && action !== "decline") {
return Response.json(
{ error: "action must be 'accept' or 'decline'." },
{ status: 400 },
);
}
try {
if (action === "accept") {
const claimed = await transaction(async (tx) => {
// Atomically flip the offer to accepted only if it's still offered to
// this driver. This is the race guard: two drivers can't both accept,
// and an expired offer can't be revived.
const offer = await tx<{ id: number }>`
UPDATE ride_offers
SET status = 'accepted', responded_at = CURRENT_TIMESTAMP
WHERE ride_id = ${rideId}
AND driver_id = ${driverId}
AND status = 'offered'
RETURNING id
`;
if (!offer[0]) return null;
// Assign the ride to this driver. The status='requested' guard means
// we never overwrite a ride another driver already accepted.
const ride = await tx`
UPDATE rides
SET status = 'accepted', driver_id = ${driverId}
WHERE ride_id = ${rideId} AND status = 'requested'
RETURNING ride_id
`;
if (!ride[0]) return null;
return offer[0].id;
});
if (claimed === null) {
return Response.json(
{ error: "This offer is no longer available." },
{ status: 409 },
);
}
return Response.json({ data: { action: "accepted" } });
}
// Decline: mark the offer declined and offer the ride to the next driver.
const declined = await transaction(async (tx) => {
const offer = await tx`
UPDATE ride_offers
SET status = 'declined', responded_at = CURRENT_TIMESTAMP
WHERE ride_id = ${rideId}
AND driver_id = ${driverId}
AND status = 'offered'
RETURNING id
`;
return offer[0]?.id ?? null;
});
if (declined === null) {
return Response.json(
{ error: "This offer is no longer available." },
{ status: 409 },
);
}
void matchNextDriver(rideId);
return Response.json({ data: { action: "declined" } });
} catch (error) {
console.error("[RIDE_RESPOND]: ", error);
return Response.json({ error: "Internal Server Error" }, { status: 500 });
}
}
+202
View File
@@ -0,0 +1,202 @@
import { requireAuth } from "@/lib/jwt";
import { transaction } from "@/lib/db";
import { getOrder, consumeOrderForRide } from "@/lib/payment-orders";
import { sendPushToDriver } from "@/lib/push";
import { DRIVER_BUSY_ARRAY, generatePickupCode } from "@/lib/ride-lifecycle";
// POST — the rider picks one of the drivers who offered, and pays.
//
// { offer_id, payment_method: 'cash' }
// { offer_id, payment_method: 'card', payment_order_id }
//
// This is the single moment a ride is assigned. Everything that has to be true
// at once — the request is still open, this offer is still live, the driver is
// still free, and (for card) a paid order of the right amount exists and has
// not been spent — is checked inside one transaction, so a rider and a
// disappearing driver can't half-complete it.
//
// The card order is consumed here rather than earlier for the same reason: if
// the pick fails because the driver just took another job, the transaction
// rolls back with the order still 'paid', and the rider can pick a different
// driver with the money they already put down instead of paying twice.
export async function POST(req: Request, { id }: { id: string }) {
const rideId = Number(id);
if (!Number.isInteger(rideId)) {
return Response.json({ error: "Invalid ride id." }, { status: 400 });
}
const auth = requireAuth(req);
if ("error" in auth) return auth.error;
let body: {
offer_id?: number;
payment_method?: string;
payment_order_id?: string;
};
try {
body = await req.json();
} catch {
return Response.json({ error: "Invalid JSON body." }, { status: 400 });
}
const offerId = Number(body.offer_id);
if (!Number.isInteger(offerId)) {
return Response.json({ error: "offer_id is required." }, { status: 400 });
}
const method = body.payment_method;
if (method !== "cash" && method !== "card") {
return Response.json({ error: "Invalid payment method." }, { status: 400 });
}
try {
// Card: everything about the order is verified before the transaction
// opens, so the only thing left to do inside it is spend it.
if (method === "card") {
if (!body.payment_order_id) {
return Response.json(
{ error: "Missing payment order id." },
{ status: 400 },
);
}
const order = await getOrder(body.payment_order_id);
if (!order)
return Response.json(
{ error: "Payment order not found." },
{ status: 404 },
);
if (order.user_id !== auth.userId)
return Response.json({ error: "Unauthorized." }, { status: 403 });
if (order.status !== "paid")
return Response.json(
{ error: "Payment not verified." },
{ status: 400 },
);
}
const picked = await transaction<
| { driverId: number; fare: number }
| "gone"
| "amount_mismatch"
| "order_spent"
>(async (tx) => {
// Lock the request. A second tap on a second driver serialises behind
// this and finds the ride already assigned.
const rides = await tx<{
status: string;
fare_price: number;
origin_address: string;
}>`
SELECT status, fare_price, origin_address
FROM rides
WHERE ride_id = ${rideId} AND user_id = ${auth.userId}
FOR UPDATE
`;
const ride = rides[0];
if (!ride || ride.status !== "requested") return "gone";
const offers = await tx<{ driver_id: number }>`
SELECT driver_id FROM ride_offers
WHERE id = ${offerId} AND ride_id = ${rideId} AND status = 'offered'
`;
const offer = offers[0];
if (!offer) return "gone";
// The driver may have been picked by somebody else in the seconds the
// rider spent deciding. Their other ride is the authority, not the offer.
const busy = await tx<{ n: number }>`
SELECT COUNT(*)::int AS n FROM rides
WHERE driver_id = ${offer.driver_id}
AND status = ANY(${DRIVER_BUSY_ARRAY}::text[])
`;
if ((busy[0]?.n ?? 0) > 0) return "gone";
let paymentStatus = "cash";
let orderId: string | null = null;
if (method === "card") {
const order = await getOrder(body.payment_order_id!);
if (!order) return "gone";
// Re-checked against the row we just locked: the fare is authoritative
// here, not the number the client did its arithmetic with.
if (order.amount_cents !== Number(ride.fare_price))
return "amount_mismatch";
const consumed = await consumeOrderForRide(
body.payment_order_id!,
auth.userId,
tx,
);
if (!consumed) return "order_spent";
paymentStatus = "paid";
orderId = body.payment_order_id!;
}
// Assign. The status='requested' guard is what stops a double-submit
// from reassigning a ride that already has a driver.
const assigned = await tx<{ ride_id: number }>`
UPDATE rides
SET status = 'accepted',
driver_id = ${offer.driver_id},
accepted_at = CURRENT_TIMESTAMP,
payment_status = ${paymentStatus},
payment_order_id = COALESCE(${orderId}, payment_order_id),
pickup_code = COALESCE(pickup_code, ${generatePickupCode()})
WHERE ride_id = ${rideId} AND status = 'requested'
RETURNING ride_id
`;
if (!assigned[0]) return "gone";
await tx`
UPDATE ride_offers
SET status = 'accepted', responded_at = CURRENT_TIMESTAMP
WHERE id = ${offerId}
`;
// Everyone else who volunteered is released in the same breath, so no
// driver is left with a card for a job that is already someone else's.
await tx`
UPDATE ride_offers
SET status = 'passed', responded_at = CURRENT_TIMESTAMP
WHERE ride_id = ${rideId} AND id <> ${offerId} AND status = 'offered'
`;
return { driverId: offer.driver_id, fare: Number(ride.fare_price) };
});
if (picked === "amount_mismatch") {
return Response.json(
{ error: "Payment does not match this ride." },
{ status: 400 },
);
}
if (picked === "order_spent") {
return Response.json(
{ error: "That payment has already been used." },
{ status: 409 },
);
}
if (picked === "gone") {
return Response.json(
{
error: "That driver is no longer available.",
code: "OFFER_UNAVAILABLE",
},
{ status: 409 },
);
}
void sendPushToDriver(picked.driverId, {
title: "You got the ride",
body: "The rider picked you. Head to the pickup point.",
data: { type: "ride_assigned", rideId },
});
return Response.json({ data: { status: "accepted" } });
} catch (error) {
console.error("[RIDE_SELECT]: ", error);
return Response.json({ error: "Internal Server Error" }, { status: 500 });
}
}