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
+272
-38
@@ -1,11 +1,22 @@
|
||||
import { requireAuth } from "@/lib/jwt";
|
||||
import { sql, query } from "@/lib/db";
|
||||
import { matchNextDriver } from "@/lib/dispatch";
|
||||
import { sql } from "@/lib/db";
|
||||
import { broadcastRequest } from "@/lib/dispatch";
|
||||
import { requireDriverProfile } from "@/lib/driver";
|
||||
import {
|
||||
isCancellationReason,
|
||||
DRIVER_CANCELLABLE_ARRAY,
|
||||
RIDER_CANCELLABLE_ARRAY,
|
||||
} from "@/lib/ride-lifecycle";
|
||||
import { REQUEST_TTL_SECONDS } from "@/constants/dispatch";
|
||||
import { COMMISSION_RATE } from "@/lib/pricing";
|
||||
|
||||
// GET — single ride by id, the rider's status-poll endpoint. If the ride is
|
||||
// still 'requested' with no offer in flight, kick auto-match before reading
|
||||
// so the rider's poll itself drives matching forward (no background worker).
|
||||
// GET — single ride by id, the rider's status-poll endpoint.
|
||||
//
|
||||
// While the ride is still open this also returns the drivers who have offered
|
||||
// on it, which is what the rider chooses from. The poll re-drives the
|
||||
// broadcast too (a no-op once announced), so a request whose announcement lost
|
||||
// its race with the push service still reaches drivers on the next tick —
|
||||
// there is no background worker to do it.
|
||||
export async function GET(request: Request, { id }: { id: string }) {
|
||||
const auth = requireAuth(request);
|
||||
if ("error" in auth) return auth.error;
|
||||
@@ -23,9 +34,13 @@ export async function GET(request: Request, { id }: { id: string }) {
|
||||
return Response.json({ error: "Ride not found." }, { status: 404 });
|
||||
}
|
||||
|
||||
// Lazy match: try to offer the ride to a driver if it's still requested.
|
||||
// Lazy dispatch: announce the request if that hasn't happened yet, and
|
||||
// give up on it if it has run past its window. Awaited, because the row
|
||||
// this request is about to read is the one the sweep may rewrite — a
|
||||
// rider whose request just expired should be told, not shown a list of
|
||||
// drivers they can no longer pick.
|
||||
if (ride[0].status === "requested") {
|
||||
void matchNextDriver(rideId);
|
||||
await broadcastRequest(rideId);
|
||||
}
|
||||
|
||||
const rows = await sql`
|
||||
@@ -43,8 +58,22 @@ export async function GET(request: Request, { id }: { id: string }) {
|
||||
r.status,
|
||||
r.service,
|
||||
r.created_at,
|
||||
r.accepted_at,
|
||||
r.arrived_at,
|
||||
r.started_at,
|
||||
r.completed_at,
|
||||
r.cancelled_at,
|
||||
r.cancelled_by,
|
||||
r.cancellation_reason,
|
||||
r.cash_collected_at,
|
||||
-- The rider's copy of the pickup code. Only ever sent to the ride's
|
||||
-- own rider (this route is rider-scoped), and only while it still
|
||||
-- matters: once the trip has started the code is spent.
|
||||
CASE WHEN r.status IN ('accepted', 'arrived') THEN r.pickup_code END
|
||||
AS pickup_code,
|
||||
-- Has this rider already rated the ride? Drives the rating card.
|
||||
(SELECT rr.rating FROM ride_ratings rr
|
||||
WHERE rr.ride_id = r.ride_id AND rr.rater_type = 'rider') AS my_rating,
|
||||
json_build_object(
|
||||
'id', d.id,
|
||||
'first_name', d.first_name,
|
||||
@@ -53,6 +82,7 @@ export async function GET(request: Request, { id }: { id: string }) {
|
||||
'profile_image_url', d.profile_image_url,
|
||||
'car_image_url', d.car_image_url,
|
||||
'rating', d.rating,
|
||||
'rating_count', d.rating_count,
|
||||
'service', d.service,
|
||||
'car_model', d.car_model,
|
||||
'latitude', d.latitude,
|
||||
@@ -63,7 +93,38 @@ export async function GET(request: Request, { id }: { id: string }) {
|
||||
WHERE r.ride_id = ${rideId}
|
||||
`;
|
||||
|
||||
return Response.json({ data: rows[0] });
|
||||
// The drivers who have volunteered, newest first. Only while the request
|
||||
// is open: once it is assigned, the losing offers are nobody's business
|
||||
// and the winning one is just "your driver". Coordinates are deliberately
|
||||
// not included — a rider comparing offers needs how far away each driver
|
||||
// is, not where they are, and only the chosen driver's position is theirs
|
||||
// to watch.
|
||||
const offers =
|
||||
rows[0]?.status === "requested"
|
||||
? await sql`
|
||||
SELECT
|
||||
ro.id AS offer_id, ro.offered_at, ro.pickup_distance_m,
|
||||
d.id AS driver_id, d.first_name, d.last_name,
|
||||
d.profile_image_url, d.car_image_url, d.car_model, d.car_seats,
|
||||
d.rating, d.rating_count, d.service
|
||||
FROM ride_offers ro
|
||||
JOIN drivers d ON d.id = ro.driver_id
|
||||
WHERE ro.ride_id = ${rideId} AND ro.status = 'offered'
|
||||
ORDER BY ro.pickup_distance_m NULLS LAST, ro.offered_at
|
||||
`
|
||||
: [];
|
||||
|
||||
return Response.json({
|
||||
data: {
|
||||
...rows[0],
|
||||
offers,
|
||||
// The server's clock and the request window, so the "still looking"
|
||||
// countdown the rider watches is the one the server actually enforces
|
||||
// rather than whatever their phone thinks the time is.
|
||||
now: new Date().toISOString(),
|
||||
request_ttl_seconds: REQUEST_TTL_SECONDS,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[GET_RIDE]: ", error);
|
||||
return Response.json({ error: "Internal Server Error" }, { status: 500 });
|
||||
@@ -71,17 +132,27 @@ export async function GET(request: Request, { id }: { id: string }) {
|
||||
}
|
||||
|
||||
// PATCH — ride lifecycle transitions.
|
||||
// Rider: { status: 'cancelled' } — only from 'requested' or 'accepted', and
|
||||
// only on their own ride.
|
||||
// Driver: { status: 'en_route' | 'completed' } — only on the ride they own
|
||||
// (driver_id = their profile), from the right prior state.
|
||||
// Rider: { status: 'cancelled', reason? } — before the trip starts, on
|
||||
// their own ride.
|
||||
// Driver: { status: 'arrived' } accepted -> arrived
|
||||
// { status: 'en_route', pickup_code } arrived -> en_route
|
||||
// { status: 'completed', cash_collected? } en_route -> completed
|
||||
// { status: 'cancelled', reason? } before the trip starts
|
||||
// Every transition is a single guarded UPDATE: the prior state is part of the
|
||||
// WHERE clause, so a double-tap or a stale client can't skip a step or
|
||||
// resurrect a finished ride, and two racing writers can't both win.
|
||||
export async function PATCH(request: Request, { id }: { id: string }) {
|
||||
const rideId = Number(id);
|
||||
if (!Number.isInteger(rideId)) {
|
||||
return Response.json({ error: "Invalid ride id." }, { status: 400 });
|
||||
}
|
||||
|
||||
let body: { status?: string };
|
||||
let body: {
|
||||
status?: string;
|
||||
reason?: string;
|
||||
pickup_code?: string;
|
||||
cash_collected?: boolean;
|
||||
};
|
||||
try {
|
||||
body = await request.json();
|
||||
} catch {
|
||||
@@ -89,60 +160,223 @@ export async function PATCH(request: Request, { id }: { id: string }) {
|
||||
}
|
||||
|
||||
const next = body.status;
|
||||
// A reason is optional, but if one is sent it has to be a known code — the
|
||||
// admin portal counts these, and free text would make them uncountable.
|
||||
const reason = body.reason;
|
||||
if (reason !== undefined && !isCancellationReason(reason)) {
|
||||
return Response.json(
|
||||
{ error: "Unknown cancellation reason." },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
// Rider cancel — authenticate by ownership of the ride.
|
||||
// Cancel — either the rider (any time before the trip starts) or the
|
||||
// assigned driver (same window). Rider path is tried first: a user who is
|
||||
// also a driver should cancel their own ride as a rider, not be misrouted
|
||||
// to the driver branch.
|
||||
if (next === "cancelled") {
|
||||
const auth = requireAuth(request);
|
||||
if ("error" in auth) return auth.error;
|
||||
|
||||
const rows = await sql<{ status: string }>`
|
||||
const riderCancel = await sql<{ status: string }>`
|
||||
UPDATE rides
|
||||
SET status = 'cancelled', cancelled_at = CURRENT_TIMESTAMP
|
||||
SET status = 'cancelled',
|
||||
cancelled_at = CURRENT_TIMESTAMP,
|
||||
cancelled_by = 'rider',
|
||||
cancellation_reason = ${reason ?? null}
|
||||
WHERE ride_id = ${rideId}
|
||||
AND user_id = ${auth.userId}
|
||||
AND status IN ('requested', 'accepted')
|
||||
AND status = ANY(${RIDER_CANCELLABLE_ARRAY}::text[])
|
||||
RETURNING status
|
||||
`;
|
||||
if (!rows[0]) {
|
||||
return Response.json(
|
||||
{ error: "Ride cannot be cancelled." },
|
||||
{ status: 409 },
|
||||
);
|
||||
if (riderCancel[0]) {
|
||||
// Free the driver's offer so dispatch doesn't keep a phantom offer in
|
||||
// flight for a ride that no longer exists.
|
||||
await sql`
|
||||
UPDATE ride_offers
|
||||
SET status = 'cancelled', responded_at = CURRENT_TIMESTAMP
|
||||
WHERE ride_id = ${rideId} AND status = 'offered'
|
||||
`;
|
||||
return Response.json({ data: { status: riderCancel[0].status } });
|
||||
}
|
||||
return Response.json({ data: { status: rows[0].status } });
|
||||
|
||||
const driver = await requireDriverProfile(request);
|
||||
if (!("error" in driver)) {
|
||||
const driverCancel = await sql<{ status: string }>`
|
||||
UPDATE rides
|
||||
SET status = 'cancelled',
|
||||
cancelled_at = CURRENT_TIMESTAMP,
|
||||
cancelled_by = 'driver',
|
||||
cancellation_reason = ${reason ?? null}
|
||||
WHERE ride_id = ${rideId}
|
||||
AND driver_id = ${driver.driverId}
|
||||
AND status = ANY(${DRIVER_CANCELLABLE_ARRAY}::text[])
|
||||
RETURNING status
|
||||
`;
|
||||
if (driverCancel[0]) {
|
||||
return Response.json({ data: { status: driverCancel[0].status } });
|
||||
}
|
||||
}
|
||||
|
||||
return Response.json(
|
||||
{ error: "Ride cannot be cancelled." },
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
|
||||
// Driver transitions — must be the driver assigned to the ride.
|
||||
if (next === "en_route" || next === "completed") {
|
||||
if (next === "arrived" || next === "en_route" || next === "completed") {
|
||||
const result = await requireDriverProfile(request);
|
||||
if ("error" in result) return result.error;
|
||||
|
||||
const { driverId } = result;
|
||||
const priorStatus = next === "en_route" ? "accepted" : "en_route";
|
||||
const setClause =
|
||||
next === "completed"
|
||||
? "status = $1, completed_at = CURRENT_TIMESTAMP, driver_id = $2"
|
||||
: "status = $1, driver_id = $2";
|
||||
|
||||
const rows = await query<{ status: string }>(
|
||||
`UPDATE rides SET ${setClause}
|
||||
WHERE ride_id = $3 AND driver_id = $2 AND status = $4
|
||||
RETURNING status`,
|
||||
[next, driverId, rideId, priorStatus],
|
||||
);
|
||||
// Driver is at the pickup point. Purely informational for the rider,
|
||||
// but it's the signal that turns "on the way" into "your car is here".
|
||||
if (next === "arrived") {
|
||||
const rows = await sql<{ status: string }>`
|
||||
UPDATE rides
|
||||
SET status = 'arrived', arrived_at = CURRENT_TIMESTAMP
|
||||
WHERE ride_id = ${rideId}
|
||||
AND driver_id = ${driverId}
|
||||
AND status = 'accepted'
|
||||
RETURNING status
|
||||
`;
|
||||
if (!rows[0]) {
|
||||
return Response.json(
|
||||
{ error: "Ride cannot transition to that state." },
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
return Response.json({ data: { status: rows[0].status } });
|
||||
}
|
||||
|
||||
// Start the trip. The pickup code is the handshake that proves the
|
||||
// person in the car is the rider who ordered it — checked inside the
|
||||
// UPDATE so a wrong code can't start the trip even under a race.
|
||||
if (next === "en_route") {
|
||||
const code = String(body.pickup_code ?? "").trim();
|
||||
if (!code) {
|
||||
return Response.json(
|
||||
{ error: "Pickup code required.", code: "PICKUP_CODE_REQUIRED" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const rows = await sql<{ status: string }>`
|
||||
UPDATE rides
|
||||
SET status = 'en_route', started_at = CURRENT_TIMESTAMP
|
||||
WHERE ride_id = ${rideId}
|
||||
AND driver_id = ${driverId}
|
||||
AND status IN ('accepted', 'arrived')
|
||||
AND pickup_code = ${code}
|
||||
RETURNING status
|
||||
`;
|
||||
if (!rows[0]) {
|
||||
// Distinguish "wrong code" from "wrong state" — the driver needs to
|
||||
// know whether to re-ask the rider or reload the screen.
|
||||
const current = await sql<{
|
||||
status: string;
|
||||
pickup_code: string | null;
|
||||
}>`
|
||||
SELECT status, pickup_code FROM rides
|
||||
WHERE ride_id = ${rideId} AND driver_id = ${driverId}
|
||||
`;
|
||||
if (
|
||||
current[0] &&
|
||||
["accepted", "arrived"].includes(current[0].status) &&
|
||||
current[0].pickup_code !== code
|
||||
) {
|
||||
return Response.json(
|
||||
{
|
||||
error: "That code doesn't match.",
|
||||
code: "PICKUP_CODE_INVALID",
|
||||
},
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
return Response.json(
|
||||
{ error: "Ride cannot transition to that state." },
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
return Response.json({ data: { status: rows[0].status } });
|
||||
}
|
||||
|
||||
// Complete. For a cash ride the driver also confirms they collected the
|
||||
// fare, which is what moves the money from "owed" to "settled" — a cash
|
||||
// ride left at payment_status='cash' is an unreconciled debt, and the
|
||||
// admin portal reports on exactly that gap.
|
||||
const settleCash = body.cash_collected === true;
|
||||
|
||||
// Stamp the fare split at completion. Computed from the row's own
|
||||
// fare_price inside the UPDATE so it can't disagree with what was
|
||||
// charged, and recorded with the rate used so a later rate change never
|
||||
// rewrites what this driver was owed today.
|
||||
//
|
||||
// The ::numeric casts are load-bearing. Parameters are sent untyped, so
|
||||
// Postgres infers each one from context — and next to an integer column
|
||||
// it infers `fare_price * $n` as integer multiplication, then refuses to
|
||||
// parse "0.2" as an integer. Every completion failed on that, which is
|
||||
// what left drivers unable to end a trip at all.
|
||||
const rows = await sql<{ status: string; payment_status: string }>`
|
||||
UPDATE rides
|
||||
SET status = 'completed',
|
||||
completed_at = CURRENT_TIMESTAMP,
|
||||
commission_rate = ${COMMISSION_RATE}::numeric,
|
||||
platform_fee_cents = ROUND(fare_price * ${COMMISSION_RATE}::numeric),
|
||||
driver_payout_cents =
|
||||
fare_price - ROUND(fare_price * ${COMMISSION_RATE}::numeric),
|
||||
payment_status = CASE
|
||||
WHEN payment_status = 'cash' AND ${settleCash}::boolean
|
||||
THEN 'cash_collected'
|
||||
ELSE payment_status
|
||||
END,
|
||||
cash_collected_at = CASE
|
||||
WHEN payment_status = 'cash' AND ${settleCash}::boolean
|
||||
THEN CURRENT_TIMESTAMP
|
||||
ELSE cash_collected_at
|
||||
END,
|
||||
-- Whoever physically holds their own share is settled immediately;
|
||||
-- only the other side is left owed. A card ride means the company
|
||||
-- has its fee and owes the driver; a collected cash fare means the
|
||||
-- driver has their payout and owes the company. See
|
||||
-- lib/settlement.ts, which is where this rule is defined.
|
||||
platform_fee_settled_at = CASE
|
||||
WHEN payment_status = 'paid' THEN CURRENT_TIMESTAMP
|
||||
ELSE platform_fee_settled_at
|
||||
END,
|
||||
driver_payout_settled_at = CASE
|
||||
WHEN payment_status = 'cash' AND ${settleCash}::boolean
|
||||
THEN CURRENT_TIMESTAMP
|
||||
ELSE driver_payout_settled_at
|
||||
END
|
||||
WHERE ride_id = ${rideId}
|
||||
AND driver_id = ${driverId}
|
||||
AND status = 'en_route'
|
||||
RETURNING status, payment_status
|
||||
`;
|
||||
if (!rows[0]) {
|
||||
return Response.json(
|
||||
{ error: "Ride cannot transition to that state." },
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
return Response.json({ data: { status: rows[0].status } });
|
||||
return Response.json({
|
||||
data: {
|
||||
status: rows[0].status,
|
||||
payment_status: rows[0].payment_status,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return Response.json({ error: "Unknown status transition." }, { status: 400 });
|
||||
return Response.json(
|
||||
{ error: "Unknown status transition." },
|
||||
{ status: 400 },
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("[PATCH_RIDE]: ", error);
|
||||
return Response.json({ error: "Internal Server Error" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { sql } from "@/lib/db";
|
||||
import { requireAuth } from "@/lib/jwt";
|
||||
import { ACTIVE_STATUS_ARRAY, expireStaleRequests } from "@/lib/ride-lifecycle";
|
||||
|
||||
// GET — "does this rider have unfinished business?", answered in one call.
|
||||
//
|
||||
// active : a ride still in flight (requested/accepted/arrived/en_route).
|
||||
// Killing the app used to strand a rider away from their
|
||||
// tracking screen with no way back; the home banner reads
|
||||
// this to put them back on it.
|
||||
// pending_rating : a ride that finished recently and hasn't been rated yet,
|
||||
// so the prompt survives the app being backgrounded at
|
||||
// drop-off — the moment ratings are most often lost.
|
||||
export async function GET(req: Request) {
|
||||
const auth = requireAuth(req);
|
||||
if ("error" in auth) return auth.error;
|
||||
|
||||
try {
|
||||
// Sweep searches that have run past the TTL (unscoped — this is one of the
|
||||
// lazy paths that stands in for a background worker), so the banner never
|
||||
// advertises a ride that is really long dead.
|
||||
await expireStaleRequests();
|
||||
|
||||
const active = await sql<{
|
||||
ride_id: number;
|
||||
status: string;
|
||||
service: string;
|
||||
origin_address: string;
|
||||
destination_address: string;
|
||||
fare_price: number;
|
||||
driver_name: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
r.ride_id, r.status, r.service,
|
||||
r.origin_address, r.destination_address, r.fare_price,
|
||||
NULLIF(TRIM(COALESCE(d.first_name, '') || ' ' || COALESCE(d.last_name, '')), '')
|
||||
AS driver_name
|
||||
FROM rides r
|
||||
LEFT JOIN drivers d ON d.id = r.driver_id
|
||||
WHERE r.user_id = ${auth.userId}
|
||||
AND r.status = ANY(${ACTIVE_STATUS_ARRAY}::text[])
|
||||
ORDER BY r.created_at DESC
|
||||
LIMIT 1
|
||||
`;
|
||||
|
||||
// Only prompt for rides that ended in the last day — a week-old ride is a
|
||||
// nag, not a reminder.
|
||||
const pending = await sql<{
|
||||
ride_id: number;
|
||||
destination_address: string;
|
||||
driver_name: string | null;
|
||||
driver_avatar: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
r.ride_id, r.destination_address,
|
||||
NULLIF(TRIM(COALESCE(d.first_name, '') || ' ' || COALESCE(d.last_name, '')), '')
|
||||
AS driver_name,
|
||||
d.profile_image_url AS driver_avatar
|
||||
FROM rides r
|
||||
LEFT JOIN drivers d ON d.id = r.driver_id
|
||||
WHERE r.user_id = ${auth.userId}
|
||||
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 = 'rider'
|
||||
)
|
||||
ORDER BY r.completed_at DESC
|
||||
LIMIT 1
|
||||
`;
|
||||
|
||||
return Response.json({
|
||||
data: {
|
||||
active: active[0] ?? null,
|
||||
pending_rating: pending[0] ?? null,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[RIDE_ACTIVE]: ", error);
|
||||
return Response.json({ error: "Internal Server Error" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
+44
-118
@@ -1,18 +1,25 @@
|
||||
import { requireAuth } from "@/lib/jwt";
|
||||
import { sql, transaction } from "@/lib/db";
|
||||
import { getOrder, consumeOrderForRide } from "@/lib/payment-orders";
|
||||
import { matchNextDriver } from "@/lib/dispatch";
|
||||
import { sql } from "@/lib/db";
|
||||
import { broadcastRequest } from "@/lib/dispatch";
|
||||
import { isServiceId } from "@/lib/driver";
|
||||
import { ACTIVE_STATUS_ARRAY } from "@/lib/ride-lifecycle";
|
||||
import { DEFAULT_SERVICE } from "@/constants/services";
|
||||
|
||||
// Explicit missing check — a truthy check would reject legitimate 0 values
|
||||
// like latitude 0.0 (the equator) or a zero fare.
|
||||
const isMissing = (v: unknown): boolean => v === undefined || v === null;
|
||||
|
||||
// POST — request a ride. The rider no longer picks a driver; the ride is
|
||||
// created with status='requested' and driver_id=NULL, then auto-match offers
|
||||
// it to the nearest eligible driver of the requested service. `driver_id` in
|
||||
// the body is accepted for backward compatibility but ignored.
|
||||
// POST — open a ride request.
|
||||
//
|
||||
// This fires the moment the rider taps "Find now", before any payment
|
||||
// decision: the ride is created with status='requested', driver_id=NULL and
|
||||
// payment_status='pending', then broadcast to every eligible driver near the
|
||||
// pickup. Drivers volunteer, the rider picks one, and /ride/:id/select is
|
||||
// where the driver, the payment method and (for card) the paid order all land
|
||||
// together.
|
||||
//
|
||||
// Nothing is charged here, so there is nothing to refund if no driver takes
|
||||
// it — which is the point of moving payment behind the pick.
|
||||
export async function POST(request: Request) {
|
||||
const auth = requireAuth(request);
|
||||
if ("error" in auth) return auth.error;
|
||||
@@ -28,8 +35,6 @@ export async function POST(request: Request) {
|
||||
destination_longitude,
|
||||
ride_time,
|
||||
fare_price,
|
||||
payment_method,
|
||||
payment_order_id,
|
||||
service,
|
||||
} = body;
|
||||
|
||||
@@ -49,116 +54,33 @@ export async function POST(request: Request) {
|
||||
);
|
||||
}
|
||||
|
||||
if (payment_method !== "card" && payment_method !== "cash")
|
||||
return Response.json(
|
||||
{ error: "Invalid payment method." },
|
||||
{ status: 400 },
|
||||
);
|
||||
|
||||
const rideService = isServiceId(service) ? service : DEFAULT_SERVICE;
|
||||
const fareCents = Math.round(Number(fare_price));
|
||||
|
||||
if (payment_method === "card") {
|
||||
// Card: the ride is only recorded once a paid, server-authoritative
|
||||
// payment order is consumed. The client can no longer self-declare
|
||||
// payment_status='paid'.
|
||||
if (isMissing(payment_order_id))
|
||||
return Response.json(
|
||||
{ error: "Missing payment order id." },
|
||||
{ status: 400 },
|
||||
);
|
||||
|
||||
const order = await getOrder(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 },
|
||||
);
|
||||
|
||||
if (order.amount_cents !== fareCents)
|
||||
return Response.json(
|
||||
{ error: "Payment amount mismatch." },
|
||||
{ status: 400 },
|
||||
);
|
||||
|
||||
// Reconcile route intent (driver isn't known yet, so driver_id is no
|
||||
// longer part of the intent check). Null intent fields are skipped.
|
||||
const intentsMatch =
|
||||
(order.origin_address === null ||
|
||||
order.origin_address === origin_address) &&
|
||||
(order.destination_address === null ||
|
||||
order.destination_address === destination_address) &&
|
||||
(order.ride_time === null || order.ride_time === Number(ride_time));
|
||||
|
||||
if (!intentsMatch)
|
||||
return Response.json(
|
||||
{ error: "Payment does not match this ride." },
|
||||
{ status: 400 },
|
||||
);
|
||||
|
||||
// Consume the order and insert the ride on one connection, so a failure
|
||||
// rolls back both and no paid order is wasted without a ride.
|
||||
const inserted = await transaction(async (tx) => {
|
||||
const consumed = await consumeOrderForRide(
|
||||
payment_order_id,
|
||||
auth.userId,
|
||||
tx,
|
||||
);
|
||||
if (!consumed) throw new Error("PAYMENT_ORDER_NOT_CONSUMABLE");
|
||||
|
||||
const rows = await tx`
|
||||
INSERT INTO rides (
|
||||
origin_address,
|
||||
destination_address,
|
||||
origin_latitude,
|
||||
origin_longitude,
|
||||
destination_latitude,
|
||||
destination_longitude,
|
||||
ride_time,
|
||||
fare_price,
|
||||
payment_status,
|
||||
driver_id,
|
||||
user_id,
|
||||
payment_order_id,
|
||||
status,
|
||||
service
|
||||
) VALUES (
|
||||
${origin_address},
|
||||
${destination_address},
|
||||
${origin_latitude},
|
||||
${origin_longitude},
|
||||
${destination_latitude},
|
||||
${destination_longitude},
|
||||
${ride_time},
|
||||
${fareCents},
|
||||
'paid',
|
||||
NULL,
|
||||
${auth.userId},
|
||||
${payment_order_id},
|
||||
'requested',
|
||||
${rideService}
|
||||
)
|
||||
RETURNING *
|
||||
`;
|
||||
return rows[0];
|
||||
});
|
||||
|
||||
// Kick off auto-match asynchronously — don't block the response on it.
|
||||
void matchNextDriver(inserted.ride_id);
|
||||
|
||||
return Response.json({ data: inserted }, { status: 201 });
|
||||
if (!Number.isFinite(fareCents) || fareCents <= 0) {
|
||||
return Response.json({ error: "Invalid fare." }, { status: 400 });
|
||||
}
|
||||
|
||||
// One ride in flight per rider. Without this a rider who backs out of the
|
||||
// tracking screen and re-books ends up with two live requests broadcast to
|
||||
// the same drivers, who then see the same job twice from one person.
|
||||
const inFlight = await sql<{ ride_id: number; status: string }>`
|
||||
SELECT ride_id, status FROM rides
|
||||
WHERE user_id = ${auth.userId}
|
||||
AND status = ANY(${ACTIVE_STATUS_ARRAY}::text[])
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 1
|
||||
`;
|
||||
if (inFlight[0]) {
|
||||
return Response.json(
|
||||
{
|
||||
error: "You already have a ride in progress.",
|
||||
code: "RIDE_IN_PROGRESS",
|
||||
ride_id: inFlight[0].ride_id,
|
||||
},
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
|
||||
// Cash: settled directly with the driver at drop-off. No order involved.
|
||||
const response = await sql`
|
||||
INSERT INTO rides (
|
||||
origin_address,
|
||||
@@ -183,7 +105,7 @@ export async function POST(request: Request) {
|
||||
${destination_longitude},
|
||||
${ride_time},
|
||||
${fareCents},
|
||||
'cash',
|
||||
'pending',
|
||||
NULL,
|
||||
${auth.userId},
|
||||
'requested',
|
||||
@@ -192,11 +114,15 @@ export async function POST(request: Request) {
|
||||
RETURNING *
|
||||
`;
|
||||
|
||||
void matchNextDriver(response[0].ride_id);
|
||||
// Announce it to nearby drivers. Not awaited: the rider's screen should
|
||||
// open on "looking for drivers" immediately, and the rider's own status
|
||||
// poll re-drives the broadcast if this one loses its race with the push
|
||||
// service.
|
||||
void broadcastRequest(response[0].ride_id);
|
||||
|
||||
return Response.json({ data: response[0] }, { status: 201 });
|
||||
} catch (error) {
|
||||
console.error("[CREATE_RIDES]: ", error);
|
||||
return Response.json({ error: "Internal Server Error" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { requireAuth } from "@/lib/jwt";
|
||||
import { sql } from "@/lib/db";
|
||||
import { TERMINAL_STATUS_ARRAY } from "@/lib/ride-lifecycle";
|
||||
|
||||
// GET — the signed-in rider's ride history (completed + cancelled rides),
|
||||
// newest first, with the assigned driver (nullable via LEFT JOIN). This feeds
|
||||
@@ -27,6 +28,10 @@ export async function GET(req: Request) {
|
||||
r.created_at,
|
||||
r.completed_at,
|
||||
r.cancelled_at,
|
||||
r.cancelled_by,
|
||||
r.cancellation_reason,
|
||||
(SELECT rr.rating FROM ride_ratings rr
|
||||
WHERE rr.ride_id = r.ride_id AND rr.rater_type = 'rider') AS my_rating,
|
||||
json_build_object(
|
||||
'id', d.id,
|
||||
'first_name', d.first_name,
|
||||
@@ -41,7 +46,7 @@ export async function GET(req: Request) {
|
||||
FROM rides r
|
||||
LEFT JOIN drivers d ON d.id = r.driver_id
|
||||
WHERE r.user_id = ${auth.userId}
|
||||
AND r.status IN ('completed', 'cancelled')
|
||||
AND r.status = ANY(${TERMINAL_STATUS_ARRAY}::text[])
|
||||
ORDER BY r.created_at DESC
|
||||
`;
|
||||
|
||||
@@ -50,4 +55,4 @@ export async function GET(req: Request) {
|
||||
console.error("[GET_RIDE_LIST]: ", error);
|
||||
return Response.json({ error: "Internal Server Error" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user