Driver side (was a stub): - In-app driver onboarding: a driver-role user creates their own linked drivers profile (driver/profile+api GET/POST/PATCH). - Driver dashboard: online/offline toggle, today's earnings, incoming request cards (accept/decline), active ride panel (start/complete trip). Polls /driver/rides every 4s while online. - Location heartbeat (use-driver-location): watchPositionAsync pings /driver/location every ~5s; restarts the watch on app foreground so a backgrounded driver doesn't go permanently stale and miss requests. Dispatch (auto-match nearest, Uber-style): - Ride state machine: requested -> accepted -> en_route -> completed/cancelled with a nullable driver_id until matched (lib/dispatch.matchNextDriver). - matchNextDriver locks the ride (SELECT FOR UPDATE), expires 15s-stale offers, picks the nearest eligible driver of the matching service by haversine, offers one at a time. Called from ride/create, ride/[id] GET (lazy match on the rider's poll), and ride/[id]/respond (on decline). - ride/create is now a request endpoint (driver_id NULL, status=requested, service); drops the pre-match driver_id payment reconciliation. - ride/[id] GET returns status/service/nullable driver; PATCH handles rider cancel + driver en_route/completed. ride/list backs the history tabs. Rider flow (best experience): - confirm-ride is now a request screen: single trip fare + nearest-driver ETA + cash/card + Request Ride -> live status. Periodically polls online drivers of the selected service and disables Request when none are online (prevents the "stuck searching forever" state). - book-ride is the live ride-status screen (searching -> accepted -> en_route -> completed/cancelled + Cancel), polling every 3s. - lib/request-ride unifies the Areeba card flow + cash path. - Map reads /driver/nearby (real positions, service-filtered); lib/map adds calculateTripFare + service-aware fares. POI suggestions: - lib/places (Google Nearby Search) + nearby-suggestions chips for mall/hospital/pharmacy/restaurant on the home screen. Service categories now drive both matching and a per-service fare multiplier (car 1.0 / moto 0.7 / courier 0.85 / chauffeur 1.5). Map tiles: react-native-maps rendered blank on Android because no Google Maps key was set. Switched app.json -> app.config.js so android.config.googleMaps.apiKey is injected from EXPO_PUBLIC_GOOGLE_API_KEY at build time (keeps the key out of git). Requires a native rebuild (expo run:android) to take effect. Also includes the prior payment/auth hardening (server-authoritative payment_orders ledger with double-spend guards, peppered OTP, register TOCTOU fix, stats cents fix) that was left uncommitted. Co-Authored-By: Claude <noreply@anthropic.com>
248 lines
8.3 KiB
TypeScript
248 lines
8.3 KiB
TypeScript
import { router, useLocalSearchParams } from "expo-router";
|
|
import { useCallback, useEffect, useState } from "react";
|
|
import {
|
|
ActivityIndicator,
|
|
Alert,
|
|
Image,
|
|
Text,
|
|
TouchableOpacity,
|
|
View,
|
|
} from "react-native";
|
|
import { SafeAreaView } from "react-native-safe-area-context";
|
|
|
|
import { CustomButton } from "@/components/custom-button";
|
|
import { Map } from "@/components/map";
|
|
import { icons, images } from "@/constants";
|
|
import { ApiError, fetchAPI } from "@/lib/fetch";
|
|
import { formatTime } from "@/lib/utils";
|
|
import { useLocationStore } from "@/store";
|
|
import type { Ride } from "@/types/type";
|
|
|
|
const POLL_MS = 3000;
|
|
|
|
const statusLabel: Record<string, string> = {
|
|
requested: "Finding your driver…",
|
|
accepted: "Driver assigned — heading to you",
|
|
en_route: "On your trip",
|
|
completed: "You've arrived!",
|
|
cancelled: "Ride cancelled",
|
|
};
|
|
|
|
// book-ride is now the live ride-status screen. The rider lands here after
|
|
// requesting a ride and polls its status until it completes (or they cancel).
|
|
const BookRide = () => {
|
|
const { id } = useLocalSearchParams<{ id: string }>();
|
|
const rideId = Number(id);
|
|
const setUserLocation = useLocationStore((s) => s.setUserLocation);
|
|
const setDestinationLocation = useLocationStore((s) => s.setDestinationLocation);
|
|
|
|
const [ride, setRide] = useState<Ride | null>(null);
|
|
const [loading, setLoading] = useState(true);
|
|
const [cancelling, setCancelling] = useState(false);
|
|
const [error, setError] = useState<string | null>(null);
|
|
|
|
const load = useCallback(async () => {
|
|
try {
|
|
const res = await fetchAPI(`/(api)/ride/${rideId}`);
|
|
const r = res.data as Ride;
|
|
setRide(r);
|
|
|
|
// Keep the map's origin/destination in sync with the ride so the route
|
|
// line renders even if the rider reached this screen via history.
|
|
setUserLocation({
|
|
latitude: r.origin_latitude,
|
|
longitude: r.origin_longitude,
|
|
address: r.origin_address,
|
|
});
|
|
setDestinationLocation({
|
|
latitude: r.destination_latitude,
|
|
longitude: r.destination_longitude,
|
|
address: r.destination_address,
|
|
});
|
|
} catch (err) {
|
|
console.log("[BOOK_RIDE_LOAD]: ", err);
|
|
if (err instanceof ApiError && err.status === 404) {
|
|
setError("Ride not found.");
|
|
}
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}, [rideId, setUserLocation, setDestinationLocation]);
|
|
|
|
useEffect(() => {
|
|
void load();
|
|
}, [load]);
|
|
|
|
// Poll while the ride is still in a non-terminal state.
|
|
useEffect(() => {
|
|
const status = ride?.status;
|
|
if (!status || status === "completed" || status === "cancelled") return;
|
|
const timer = setInterval(() => void load(), POLL_MS);
|
|
return () => clearInterval(timer);
|
|
}, [ride?.status, load]);
|
|
|
|
const cancel = async () => {
|
|
setCancelling(true);
|
|
try {
|
|
await fetchAPI(`/(api)/ride/${rideId}`, {
|
|
method: "PATCH",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ status: "cancelled" }),
|
|
});
|
|
await load();
|
|
} catch (err) {
|
|
console.log("[BOOK_RIDE_CANCEL]: ", err);
|
|
Alert.alert("Error", "Could not cancel this ride. Please try again.");
|
|
} finally {
|
|
setCancelling(false);
|
|
}
|
|
};
|
|
|
|
if (loading) {
|
|
return (
|
|
<SafeAreaView className="flex-1 bg-white items-center justify-center">
|
|
<ActivityIndicator size="large" color="#0286ff" />
|
|
</SafeAreaView>
|
|
);
|
|
}
|
|
|
|
if (error || !ride) {
|
|
return (
|
|
<SafeAreaView className="flex-1 bg-white items-center justify-center px-7">
|
|
<Text className="text-base text-general-200 text-center">
|
|
{error ?? "Could not load this ride."}
|
|
</Text>
|
|
<CustomButton
|
|
title="Back Home"
|
|
onPress={() => router.replace("/(root)/(tabs)/home")}
|
|
className="mt-6"
|
|
/>
|
|
</SafeAreaView>
|
|
);
|
|
}
|
|
|
|
const driver = ride.driver;
|
|
const terminal = ride.status === "completed" || ride.status === "cancelled";
|
|
|
|
return (
|
|
<SafeAreaView className="flex-1 bg-general-500">
|
|
<View className="h-[45%] bg-blue-500">
|
|
<Map />
|
|
</View>
|
|
|
|
<View className="flex-1 px-5 pt-4">
|
|
<Text className="text-2xl font-JakartaExtraBold mb-2">
|
|
{statusLabel[ride.status] ?? ride.status}
|
|
</Text>
|
|
|
|
{/* Searching state */}
|
|
{ride.status === "requested" ? (
|
|
<View className="items-center mt-6">
|
|
<ActivityIndicator size="large" color="#0286ff" />
|
|
<Text className="text-general-200 mt-3 text-center">
|
|
We're matching you with the nearest {ride.service} driver.
|
|
</Text>
|
|
</View>
|
|
) : null}
|
|
|
|
{/* Driver card — shown once a driver is assigned. */}
|
|
{driver?.id ? (
|
|
<View className="bg-white rounded-2xl p-4 mt-2">
|
|
<View className="flex-row items-center">
|
|
<Image
|
|
source={{ uri: driver.profile_image_url ?? undefined }}
|
|
className="w-16 h-16 rounded-full"
|
|
/>
|
|
<View className="ml-4 flex-1">
|
|
<Text className="text-lg font-JakartaSemiBold">
|
|
{driver.first_name} {driver.last_name}
|
|
</Text>
|
|
<View className="flex-row items-center mt-1">
|
|
<Image source={icons.star} className="w-4 h-4" />
|
|
<Text className="ml-1 text-general-200">
|
|
{driver.rating?.toFixed(1) ?? "—"}
|
|
</Text>
|
|
{driver.car_model ? (
|
|
<Text className="ml-3 text-general-200">
|
|
{driver.car_model}
|
|
</Text>
|
|
) : null}
|
|
</View>
|
|
</View>
|
|
<Text className="text-xs text-general-200 capitalize">
|
|
{driver.service ?? ride.service}
|
|
</Text>
|
|
</View>
|
|
|
|
<View className="flex-row items-center gap-x-2 mt-4">
|
|
<Image source={icons.to} className="w-4 h-4" />
|
|
<Text className="font-JakartaMedium text-sm" numberOfLines={1}>
|
|
{ride.origin_address}
|
|
</Text>
|
|
</View>
|
|
<View className="flex-row items-center gap-x-2 mt-2">
|
|
<Image source={icons.point} className="w-4 h-4" />
|
|
<Text className="font-JakartaMedium text-sm" numberOfLines={1}>
|
|
{ride.destination_address}
|
|
</Text>
|
|
</View>
|
|
|
|
<View className="flex-row justify-between mt-4 pt-3 border-t border-neutral-100">
|
|
<Text className="text-general-200 text-xs">
|
|
{ride.payment_status === "cash"
|
|
? "💵 Cash to driver"
|
|
: "💳 Paid by card"}
|
|
</Text>
|
|
<Text className="font-JakartaBold text-emerald-600">
|
|
${(ride.fare_price / 100).toFixed(2)}
|
|
</Text>
|
|
</View>
|
|
</View>
|
|
) : null}
|
|
|
|
{/* Completed summary */}
|
|
{ride.status === "completed" ? (
|
|
<View className="bg-white rounded-2xl p-4 mt-4 items-center">
|
|
<Image source={images.check} className="w-12 h-12" />
|
|
<Text className="text-lg font-JakartaBold mt-3">
|
|
Fare: ${(ride.fare_price / 100).toFixed(2)}
|
|
</Text>
|
|
<Text className="text-general-200 text-sm mt-1">
|
|
Trip time {formatTime(ride.ride_time)}
|
|
</Text>
|
|
</View>
|
|
) : null}
|
|
|
|
{/* Cancelled */}
|
|
{ride.status === "cancelled" ? (
|
|
<View className="bg-white rounded-2xl p-4 mt-4 items-center">
|
|
<Text className="text-general-200">
|
|
This ride was cancelled.
|
|
</Text>
|
|
</View>
|
|
) : null}
|
|
|
|
<View className="mt-auto pt-6">
|
|
{terminal ? (
|
|
<CustomButton
|
|
title="Back Home"
|
|
onPress={() => router.replace("/(root)/(tabs)/home")}
|
|
/>
|
|
) : (
|
|
<TouchableOpacity
|
|
onPress={cancel}
|
|
disabled={cancelling}
|
|
className="rounded-full py-3 bg-white items-center border border-rose-300"
|
|
>
|
|
<Text className="font-JakartaBold text-rose-500">
|
|
{cancelling ? "Cancelling…" : "Cancel Ride"}
|
|
</Text>
|
|
</TouchableOpacity>
|
|
)}
|
|
</View>
|
|
</View>
|
|
</SafeAreaView>
|
|
);
|
|
};
|
|
|
|
export default BookRide; |