File size: 6,149 Bytes
5c876be | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 | import { useState, useEffect, useCallback } from 'react';
import { eq, desc, and, inArray } from 'drizzle-orm';
import { useDatabase } from './useDatabase';
import { rides } from '../db/schema';
// βββ Types βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
type RideStatus = 'searching' | 'matched' | 'in_progress' | 'completed' | 'cancelled';
interface RideData {
id: string;
userId: string;
originAddress: string;
originLatitude: number;
originLongitude: number;
destinationAddress: string;
destinationLatitude: number;
destinationLongitude: number;
routePolyline: string | null;
scheduledTime: string | null;
status: RideStatus;
seatPrice: number | null;
totalDistance: number | null;
estimatedDuration: number | null;
createdAt: string | null;
updatedAt: string | null;
}
interface NewRide {
id: string;
userId: string;
originAddress: string;
originLatitude: number;
originLongitude: number;
destinationAddress: string;
destinationLatitude: number;
destinationLongitude: number;
routePolyline?: string;
scheduledTime?: string;
seatPrice?: number;
totalDistance?: number;
estimatedDuration?: number;
}
interface UseRidesReturn {
rides: RideData[];
activeRide: RideData | null;
loading: boolean;
createRide: (data: NewRide) => Promise<RideData | null>;
updateRideStatus: (rideId: string, status: RideStatus) => Promise<void>;
getRideById: (rideId: string) => Promise<RideData | null>;
refresh: () => Promise<void>;
}
// βββ Hook ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export function useRides(statusFilter?: RideStatus[]): UseRidesReturn {
const { db } = useDatabase();
const [ridesList, setRidesList] = useState<RideData[]>([]);
const [loading, setLoading] = useState(true);
// ββ Load rides βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const loadRides = useCallback(async () => {
try {
setLoading(true);
const activeStatuses: RideStatus[] = ['searching', 'matched', 'in_progress'];
// Always load active rides
const allRides = await db
.select()
.from(rides)
.orderBy(desc(rides.createdAt))
.all();
let filtered: typeof allRides = allRides;
if (statusFilter && statusFilter.length > 0) {
filtered = allRides.filter((r) => statusFilter.includes(r.status as RideStatus));
}
setRidesList(filtered as RideData[]);
} catch (error) {
console.error('[useRides] Failed to load rides:', error);
setRidesList([]);
} finally {
setLoading(false);
}
}, [db, statusFilter]);
useEffect(() => {
loadRides();
}, [loadRides]);
// ββ Active ride (first non-completed, non-cancelled) βββββββββββββββββββββββββ
const activeRide =
ridesList.find(
(r) => r.status === 'searching' || r.status === 'matched' || r.status === 'in_progress',
) ?? null;
// ββ Create ride ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const createRide = useCallback(
async (data: NewRide): Promise<RideData | null> => {
try {
await db.insert(rides).values({
id: data.id,
userId: data.userId,
originAddress: data.originAddress,
originLatitude: data.originLatitude,
originLongitude: data.originLongitude,
destinationAddress: data.destinationAddress,
destinationLatitude: data.destinationLatitude,
destinationLongitude: data.destinationLongitude,
routePolyline: data.routePolyline ?? null,
scheduledTime: data.scheduledTime ?? null,
seatPrice: data.seatPrice ?? null,
totalDistance: data.totalDistance ?? null,
estimatedDuration: data.estimatedDuration ?? null,
}).run();
await loadRides();
const created = ridesList.find((r) => r.id === data.id);
return (created as RideData) ?? null;
} catch (error) {
console.error('[useRides] Failed to create ride:', error);
return null;
}
},
[db, loadRides, ridesList],
);
// ββ Update ride status βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const updateRideStatus = useCallback(
async (rideId: string, status: RideStatus) => {
try {
await db
.update(rides)
.set({ status, updatedAt: new Date().toISOString() })
.where(eq(rides.id, rideId))
.run();
await loadRides();
} catch (error) {
console.error('[useRides] Failed to update ride status:', error);
}
},
[db, loadRides],
);
// ββ Get ride by ID βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const getRideById = useCallback(
async (rideId: string): Promise<RideData | null> => {
try {
const results = await db
.select()
.from(rides)
.where(eq(rides.id, rideId))
.all();
return (results[0] as RideData) ?? null;
} catch (error) {
console.error('[useRides] Failed to get ride:', error);
return null;
}
},
[db],
);
return {
rides: ridesList,
activeRide,
loading,
createRide,
updateRideStatus,
getRideById,
refresh: loadRides,
};
}
|