import {onDocumentCreated, onDocumentUpdated} from "firebase-functions/v2/firestore"; import {Logger} from "../core/logger/logger"; import {NotificationTypes} from "../core/data/entities/notification_entity"; import {notificationsApi} from "../notifications/notifications_api"; import {driverRepository} from "./repositories/repositories"; import {RideEntityData} from "./entities/ride_entity"; // How far to look for a driver when a ride is requested. Matches // SEARCH_RADIUS_METERS in drive_functions.ts (default 5 km). See docs/drive.*.md. const SEARCH_RADIUS_METERS = 5000; /** New ride request: notify nearby online drivers so they can accept it. */ export const onRideCreated = onDocumentCreated("rides/{rideId}", async (event) => { if (!event.data) return; const logger = new Logger("onRideCreated"); const ride = event.data.data() as RideEntityData; const rideId = event.params.rideId; try { const nearbyDrivers = await driverRepository.findNearbyOnline( ride.pickupLat, ride.pickupLng, SEARCH_RADIUS_METERS, ); if (nearbyDrivers.length === 0) { logger.info(`No online drivers near ride ${rideId}`); return; } await notificationsApi.notify( nearbyDrivers.map((d) => d.id!), { title: "New ride request", body: `Pickup at ${ride.pickupAddress}`, systemNotification: { type: NotificationTypes.OTHER, rideId, }, }, ); } catch (e) { logger.error(`Error notifying drivers for ride ${rideId}: ${e}`); } }); /** Ride accepted: notify the passenger their driver is on the way. */ export const onRideUpdated = onDocumentUpdated("rides/{rideId}", async (event) => { if (!event.data) return; const logger = new Logger("onRideUpdated"); const before = event.data.before.data() as RideEntityData; const after = event.data.after.data() as RideEntityData; const rideId = event.params.rideId; if (before.status === "requested" && after.status === "accepted") { try { await notificationsApi.notify([after.passengerId], { title: "Driver on the way", body: "A driver has accepted your ride request", systemNotification: { type: NotificationTypes.OTHER, rideId, }, }); } catch (e) { logger.error(`Error notifying passenger for ride ${rideId}: ${e}`); } } });