Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions backend/app/api/rides.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,12 +90,15 @@ async def ride_route(ride_id: str, user: User = Depends(current_user), ctx: AppC
pickup, drop = (ride.pickup_lat, ride.pickup_lng), (ride.drop_lat, ride.drop_lng)
trip = ctx.routes.estimate(pickup, drop, vehicle)
approach = None
approach_duration_s = None
if ride.driver_id and ride.status is RideStatus.DRIVER_ASSIGNED:
profile = await session.get(DriverProfile, ride.driver_id)
if profile and profile.lat is not None:
way = ctx.routes.estimate((profile.lat, profile.lng), pickup, vehicle)
approach = way.geometry if way else None
return RouteOut(trip=trip.geometry if trip else [pickup, drop], approach=approach)
if way:
approach = way.geometry
approach_duration_s = way.duration_s
return RouteOut(trip=trip.geometry if trip else [pickup, drop], approach=approach, approach_duration_s=approach_duration_s)


@router.post("/{ride_id}/accept", status_code=202)
Expand Down
2 changes: 1 addition & 1 deletion backend/app/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ class EstimateOption(BaseModel):
class RouteOut(BaseModel):
trip: list[tuple[float, float]] # pickup -> drop
approach: list[tuple[float, float]] | None = None # driver -> pickup, while the driver is on the way

approach_duration_s: int | None = None # estimated seconds for the driver to reach the pickup

class EstimateOut(BaseModel):
options: list[EstimateOption]
Expand Down
24 changes: 21 additions & 3 deletions backend/app/services/locations.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,16 @@

from sqlalchemy.ext.asyncio import AsyncSession

from routing import VehicleType

from ..context import AppContext
from ..models import DriverProfile, LocationPing, User
from ..models import DriverProfile, LocationPing, RideStatus, User
from ..schemas import LocationIn
from .rides import active_ride_of

ETA_INTERVAL_S = 15.0
_last_eta_at: dict[str, datetime] = {}


async def update_location(session: AsyncSession, ctx: AppContext, driver: User, profile: DriverProfile,
loc: LocationIn) -> None:
Expand All @@ -21,5 +26,18 @@ async def update_location(session: AsyncSession, ctx: AppContext, driver: User,
speed_kmh=loc.speed_kmh, heading=loc.heading, recorded_at=now))
await session.commit()
if ride:
await ctx.hub.send(ride.rider_id, "driver:location", {
"ride_id": ride.id, "lat": loc.lat, "lng": loc.lng, "heading": loc.heading})
payload: dict[str, object] = {
"ride_id": ride.id, "lat": loc.lat, "lng": loc.lng, "heading": loc.heading,
}
if ride.status is RideStatus.DRIVER_ASSIGNED:
last = _last_eta_at.get(ride.id)
if last is None or (now - last).total_seconds() >= ETA_INTERVAL_S:
way = ctx.routes.estimate(
(loc.lat, loc.lng), (ride.pickup_lat, ride.pickup_lng), VehicleType(ride.vehicle_type),
)
if way is not None:
payload["approach_duration_s"] = way.duration_s
_last_eta_at[ride.id] = now
else:
_last_eta_at.pop(ride.id, None)
await ctx.hub.send(ride.rider_id, "driver:location", payload)
18 changes: 16 additions & 2 deletions backend/tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,20 @@ def test_full_ride_lifecycle(client):
assert near.events("ride:confirmed") and far.events("ride:taken")
assert r.events("ride:driver_assigned")[0]["data"]["driver"]["id"] == near.id

route_assigned = r.get(f"/rides/{ride['id']}/route").json()
assert route_assigned["approach"] is not None
assert route_assigned["approach_duration_s"] > 0

assert near.post("/drivers/me/location", {"lat": 12.9720, "lng": 77.5946}).status_code == 204
assert r.events("driver:location")[-1]["data"]["lat"] == 12.9720
first_loc = r.events("driver:location")[-1]["data"]
assert first_loc["lat"] == 12.9720
assert first_loc["approach_duration_s"] > 0

# Immediate second GPS update (< 15 s) should not recalculate the approach route
assert near.post("/drivers/me/location", {"lat": 12.9718, "lng": 77.5946}).status_code == 204
second_loc = r.events("driver:location")[-1]["data"]
assert second_loc["lat"] == 12.9718
assert "approach_duration_s" not in second_loc
assert near.post("/drivers/me/online", {"online": False}).status_code == 409 # mid-ride

assert near.post(f"/rides/{ride['id']}/arrived").json()["status"] == "driver_arrived"
Expand Down Expand Up @@ -210,6 +222,7 @@ def test_admin_approves_pending_driver(make_client):
assert admin.post(f"/admin/drivers/{d.id}/approve").json()["status"] == "approved"
assert d.post("/drivers/me/online", {"online": True}).status_code == 200


def test_admin_map_is_admin_only_and_lists_online_drivers(make_client):
client = make_client(admin_phones=("+919999999999",))
admin = Actor(client, "rider", phone="+919999999999")
Expand Down Expand Up @@ -294,7 +307,8 @@ class Extract:
route = r.get(f"/rides/{ride['id']}/route").json()
assert [tuple(p) for p in route["trip"]] == [a, corner, c]
assert route["approach"] is None # no driver yet
assert route["approach_duration_s"] is None

far = {"lat": 13.5, "lng": 77.6} # nowhere near the mapped roads
res = r.post("/rides/estimate", {"pickup": pickup, "drop": far})
assert res.status_code == 422 and "outside" in res.json()["detail"]
assert res.status_code == 422 and "outside" in res.json()["detail"]
7 changes: 5 additions & 2 deletions mobile/src/app/rider/ride/[id].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,9 @@ export default function RiderRide() {
<RideMap initialCenter={ride.pickup} pickup={ride.pickup} drop={ride.drop} driver={driverPos} bottomInset={320}
route={roads?.trip} approach={ride.status === 'driver_assigned' ? roads?.approach : null} />
<Sheet>
<Title style={{ fontSize: 20 }}>{riderStatusText(ride.status)}</Title>
<Title style={{ fontSize: 20 }}>
{riderStatusText(ride.status, ride.status === 'driver_assigned' ? roads?.approach_duration_s : null)}
</Title>

{ride.driver && !isFinished(ride.status) ? (
<Row style={styles.driverRow}>
Expand All @@ -79,6 +81,7 @@ export default function RiderRide() {
) : null}

{ride.status === 'searching' ? <Body muted>Pinging {VEHICLE_LABEL[ride.vehicle_type].toLowerCase()} drivers near you…</Body> : null}
{ride.status === 'driver_assigned' && roads?.approach_duration_s != null ? <Body muted>Driver is on the way</Body> : null}
{ride.status === 'driver_arrived' ? <Body>Share the PIN with your driver to start the trip.</Body> : null}
{ride.status === 'in_progress' ? <Body muted>Heading to {shortAddress(ride.drop.lat, ride.drop.lng, ride.drop.address)}</Body> : null}

Expand Down Expand Up @@ -141,4 +144,4 @@ const styles = StyleSheet.create({
pinBox: { alignItems: 'center', backgroundColor: colors.primary, borderRadius: 10, paddingHorizontal: 12, paddingVertical: 6 },
pinLabel: { color: colors.primaryText, fontSize: 11, fontWeight: '600' },
pin: { color: colors.primaryText, fontSize: 22, fontWeight: '800', letterSpacing: 4 },
});
});
10 changes: 9 additions & 1 deletion mobile/src/lib/__tests__/format.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { expect, test } from '@jest/globals';
import { directionsUrl, formatDistance, formatDuration, formatFare, isFinished, normalizeIndianPhone } from '../format';
import { directionsUrl, formatDistance, formatDuration, formatFare, isFinished, normalizeIndianPhone, riderStatusText } from '../format';

test('fares in rupees', () => {
expect(formatFare(12300)).toBe('₹123');
Expand Down Expand Up @@ -31,3 +31,11 @@ test('finished statuses and directions link', () => {
expect(isFinished('in_progress')).toBe(false);
expect(directionsUrl({ lat: 12.97, lng: 77.59 })).toContain('destination=12.97,77.59');
});

test('rider status text shows live arrival countdown', () => {
expect(riderStatusText('driver_assigned')).toBe('Driver is on the way');
expect(riderStatusText('driver_assigned', null)).toBe('Driver is on the way');
expect(riderStatusText('driver_assigned', 240)).toBe('Arriving in 4 min');
expect(riderStatusText('driver_assigned', 20)).toBe('Arriving in 1 min');
expect(riderStatusText('driver_arrived', 120)).toBe('Driver has arrived');
});
7 changes: 5 additions & 2 deletions mobile/src/lib/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,13 @@ export const VEHICLE_ICON: Record<VehicleType, string> = {

export const VEHICLE_ORDER: VehicleType[] = ['bike', 'auto_rickshaw', 'car'];

export function riderStatusText(status: RideStatus): string {
export function riderStatusText(status: RideStatus, approachDurationS?: number | null): string {
switch (status) {
case 'searching': return 'Finding you a driver…';
case 'driver_assigned': return 'Driver is on the way';
case 'driver_assigned':
return approachDurationS != null
? `Arriving in ${formatDuration(approachDurationS)}`
: 'Driver is on the way';
case 'driver_arrived': return 'Driver has arrived';
case 'in_progress': return 'On the trip';
case 'completed': return 'Trip completed';
Expand Down
5 changes: 3 additions & 2 deletions mobile/src/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export interface EstimateOption {
export interface RideRoute {
trip: Path;
approach: Path | null;
approach_duration_s?: number | null;
}

export interface Party {
Expand Down Expand Up @@ -125,14 +126,14 @@ export type ServerEvent =
| { event: 'ride:confirmed'; data: RideSummary }
| { event: 'ride:taken'; data: { ride_id: string } }
| { event: 'ride:driver_assigned'; data: RideSummary & { driver: Partial<DriverInfo> } }
| { event: 'driver:location'; data: { ride_id: string; lat: number; lng: number; heading: number | null } }
| { event: 'ride:driver_arrived'; data: RideSummary }
| { event: 'ride:started'; data: RideSummary }
| { event: 'ride:completed'; data: RideSummary & { fare_final_paise: number } }
| { event: 'ride:cancelled'; data: RideSummary & { by: Role } }
| { event: 'ride:driver_cancelled'; data: RideSummary & { reason: string | null } }
| { event: 'ride:no_drivers'; data: RideSummary }
| { event: 'pong'; data: Record<string, never> }
| { event: 'error'; data: { message: string } };
| { event: 'error'; data: { message: string } }
| { event: 'driver:location'; data: { ride_id: string; lat: number; lng: number; heading: number | null; approach_duration_s?: number | null } }

export type EventName = ServerEvent['event'];
13 changes: 10 additions & 3 deletions mobile/src/lib/useRideRoute.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { useEffect, useState } from 'react';

import { useSession } from './session';
import { useServerEvents, useSession } from './session';
import type { RideRoute, RideStatus } from './types';

/**
* Road geometry for a ride: the trip (pickup -> drop) and, while the driver is on the way,
* their path to the pickup. Refetched whenever the ride's status changes.
* their path to the pickup and live ETA. Refetched whenever the ride's status changes.
*/
export function useRideRoute(rideId: string, status: RideStatus | undefined): RideRoute | null {
const { api } = useSession();
Expand All @@ -22,5 +22,12 @@ export function useRideRoute(rideId: string, status: RideStatus | undefined): Ri
};
}, [api, rideId, status]);

useServerEvents((e) => {
if (e.event === 'driver:location' && e.data.ride_id === rideId && e.data.approach_duration_s != null) {
const duration = e.data.approach_duration_s;
setRoute((r) => (r ? { ...r, approach_duration_s: duration } : { trip: [], approach: null, approach_duration_s: duration }));
}
});

return route;
}
}