Build driver app, Uber-style dispatch, POI suggestions; fix map tiles
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>
This commit is contained in:
+219
-107
@@ -1,136 +1,248 @@
|
||||
import { router } from "expo-router";
|
||||
import { Image, Text, View } from "react-native";
|
||||
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 { Payment } from "@/components/payment";
|
||||
import { RideLayout } from "@/components/ride-layout";
|
||||
import { icons } from "@/constants";
|
||||
import { formatLBP } from "@/lib/pricing";
|
||||
import { useSession } from "@/lib/session";
|
||||
import { Map } from "@/components/map";
|
||||
import { icons, images } from "@/constants";
|
||||
import { ApiError, fetchAPI } from "@/lib/fetch";
|
||||
import { formatTime } from "@/lib/utils";
|
||||
import { useDriverStore, useLocationStore } from "@/store";
|
||||
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 { user } = useSession();
|
||||
const { userAddress, destinationAddress } = useLocationStore();
|
||||
const { drivers, selectedDriver } = useDriverStore();
|
||||
const { id } = useLocalSearchParams<{ id: string }>();
|
||||
const rideId = Number(id);
|
||||
const setUserLocation = useLocationStore((s) => s.setUserLocation);
|
||||
const setDestinationLocation = useLocationStore((s) => s.setDestinationLocation);
|
||||
|
||||
const driverDetails = drivers?.filter(
|
||||
(driver) => +driver.id === selectedDriver,
|
||||
)[0];
|
||||
const [ride, setRide] = useState<Ride | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [cancelling, setCancelling] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
if (!driverDetails) {
|
||||
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 (
|
||||
<RideLayout title="Book Ride">
|
||||
<View className="flex-1 items-center justify-center">
|
||||
<Text className="text-base text-general-200 font-JakartaMedium text-center">
|
||||
No driver selected.{"\n"}Please go back and choose a driver first.
|
||||
</Text>
|
||||
|
||||
<CustomButton
|
||||
title="Choose a Driver"
|
||||
onPress={() => router.replace("/(root)/confirm-ride")}
|
||||
className="mt-6"
|
||||
/>
|
||||
</View>
|
||||
</RideLayout>
|
||||
<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 (
|
||||
<RideLayout title="Book Ride">
|
||||
<>
|
||||
<Text className="text-xl font-JakartaSemiBold mb-3">
|
||||
Ride Information
|
||||
<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>
|
||||
|
||||
<View className="flex flex-col w-full items-center justify-center mt-10">
|
||||
<Image
|
||||
source={{ uri: driverDetails?.profile_image_url }}
|
||||
alt="Driver Avatar"
|
||||
className="w-28 h-28 rounded-full"
|
||||
/>
|
||||
|
||||
<View className="flex flex-row items-center justify-center mt-5 space-x-2">
|
||||
<Text className="text-lg font-JakartaSemiBold">
|
||||
{driverDetails?.title}
|
||||
{/* 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}
|
||||
|
||||
<View className="flex flex-row items-center space-x-0.5">
|
||||
{/* 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={icons.star}
|
||||
alt="Star"
|
||||
className="w-5 h-5"
|
||||
resizeMode="contain"
|
||||
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>
|
||||
|
||||
<Text className="text-lg font-JakartaRegular">
|
||||
{driverDetails?.rating}
|
||||
<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>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
<View className="flex flex-col w-full items-start justify-center py-3 px-5 rounded-3xl bg-general-600 mt-5">
|
||||
<View className="flex flex-row items-center justify-between w-full border-b border-white py-3">
|
||||
<Text className="text-lg font-JakartaRegular">Ride Price</Text>
|
||||
{/* 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}
|
||||
|
||||
<View className="flex flex-col items-end">
|
||||
<Text className="text-lg font-JakartaRegular text-[#0CC25F]">
|
||||
${driverDetails?.price}
|
||||
{/* 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>
|
||||
|
||||
<Text className="text-xs font-JakartaRegular text-general-200">
|
||||
≈ {formatLBP(parseFloat(driverDetails?.price ?? "0"))}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View className="flex flex-row items-center justify-between w-full border-b border-white py-3">
|
||||
<Text className="text-lg font-JakartaRegular">Pickup Time</Text>
|
||||
|
||||
<Text className="text-lg font-JakartaRegular">
|
||||
{formatTime(driverDetails?.time!)}
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
<View className="flex flex-row items-center justify-between w-full py-3">
|
||||
<Text className="text-lg font-JakartaRegular">Car Seats</Text>
|
||||
|
||||
<Text className="text-lg font-JakartaRegular">
|
||||
{driverDetails?.car_seats}
|
||||
</Text>
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
</View>
|
||||
|
||||
<View className="flex flex-col w-full items-start justify-center mt-5">
|
||||
<View className="flex flex-row items-center justify-start mt-3 border-t border-b border-general-700 w-full py-3">
|
||||
<Image source={icons.to} alt="To" className="w-6 h-6" />
|
||||
|
||||
<Text className="text-lg font-JakartaRegular ml-2">
|
||||
{userAddress}
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
<View className="flex flex-row items-center justify-start border-b border-general-700 w-full py-3">
|
||||
<Image source={icons.point} alt="Point" className="w-6 h-6" />
|
||||
|
||||
<Text className="text-lg font-JakartaRegular ml-2">
|
||||
{destinationAddress}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<Payment
|
||||
fullName={user?.name ?? ""}
|
||||
email={user?.email ?? ""}
|
||||
amount={driverDetails?.price ?? "0"}
|
||||
driverId={driverDetails?.id}
|
||||
rideTime={driverDetails?.time ?? 0}
|
||||
/>
|
||||
</>
|
||||
</RideLayout>
|
||||
</View>
|
||||
</SafeAreaView>
|
||||
);
|
||||
};
|
||||
|
||||
export default BookRide;
|
||||
export default BookRide;
|
||||
Reference in New Issue
Block a user