Waseel: driver capture, chat/calls, dispatch, and session fixes

Driver onboarding now photographs the licence, ID card and vehicle
registration and reads the credential fields off them, plus a camera-only
profile selfie riders check the arriving driver against. Adds in-app chat
and WebRTC calls, push-backed ride offers, ratings, cancellation and
payment sheets, settlement, and the owner dashboard endpoints behind them.

Camera permission on Android:
  - Declare CAMERA and READ_MEDIA_IMAGES in the manifest. expo-image-picker's
    own plugin never declares CAMERA, and Android denies a request for an
    undeclared permission instantly and silently — no dialog is ever shown,
    which is indistinguishable from the app not asking at all.
  - Handle canAskAgain: once Android stops showing the dialog, repeating why
    we need it is a dead end, so offer Open Settings instead (lib/capture-
    permission.ts), matching what the location flow already did.

Session: a 401 on a request that carried a token now ends the session
instead of being reinterpreted per-screen — driver-home had been reading it
as "this user has no driver profile" and showing an onboarding form to an
already-onboarded driver. Requests without a token are exempt so a failed
sign-in doesn't sign you out, and the notification is latched per token so
concurrent polls tear the session down once. (root) gains the auth guard
that turns that into the sign-in screen; app/index.tsx only guarded the way
in, leaving a session that ended mid-screen with nowhere to go.

Also ignore .uploads/ — it holds driver licence, ID and vehicle scans plus
profile photos, which are personal data and must not be committed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Krikorios
2026-08-26 02:17:55 +03:00
co-authored by Claude Opus 5
parent 1d84003e0a
commit 8807ff41c5
111 changed files with 14568 additions and 1411 deletions
+45 -7
View File
@@ -1,20 +1,58 @@
import { sql } from "@/lib/db";
import { requireAuth } from "@/lib/jwt";
export const corsHeaders: Record<string, string> = {
"Access-Control-Allow-Origin": process.env.ADMIN_CORS_ORIGIN ?? "*",
"Access-Control-Allow-Methods": "GET, POST, PATCH, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
// The owner API is cross-origin only for the admin dashboard, so the allowed
// origin has to be named explicitly. An unset ADMIN_CORS_ORIGIN used to fall
// back to "*", which meant a missing env var silently opened every owner
// endpoint to every website the owner happened to have open. Fail closed
// instead: with nothing configured we send no allow-origin header at all and
// the browser blocks the call, which is a loud, obvious failure to fix.
//
// A comma-separated list is accepted so dev (localhost) and production can be
// configured at once; the header echoes back whichever entry matched, since
// "Access-Control-Allow-Origin" only ever takes a single value.
const allowedOrigins = (): string[] =>
(process.env.ADMIN_CORS_ORIGIN ?? "")
.split(",")
.map((origin) => origin.trim())
.filter(Boolean);
export const corsHeaders = (req: Request): Record<string, string> => {
const headers: Record<string, string> = {
"Access-Control-Allow-Methods": "GET, POST, PATCH, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
Vary: "Origin",
};
const allowed = allowedOrigins();
if (allowed.length === 0) return headers;
// A wildcard is still honoured when it is configured deliberately — the
// change is that it is no longer what you get by forgetting to configure it.
if (allowed.includes("*")) {
headers["Access-Control-Allow-Origin"] = "*";
return headers;
}
const origin = req.headers.get("origin");
if (origin && allowed.includes(origin)) {
headers["Access-Control-Allow-Origin"] = origin;
}
return headers;
};
export const withCors = (response: Response): Response => {
for (const [key, value] of Object.entries(corsHeaders)) {
// Takes the request first so the origin it echoes is never accidentally
// omitted — a call site that forgets it won't compile.
export const withCors = (req: Request, response: Response): Response => {
for (const [key, value] of Object.entries(corsHeaders(req))) {
response.headers.set(key, value);
}
return response;
};
export const preflight = (): Response => withCors(new Response(null, { status: 204 }));
export const preflight = (req: Request): Response =>
withCors(req, new Response(null, { status: 204 }));
// Returns the authenticated owner or a ready-to-return error Response.
export const requireOwner = async (
+70
View File
@@ -0,0 +1,70 @@
import type * as ImagePicker from "expo-image-picker";
import { Alert, Linking } from "react-native";
type Copy = {
title: string;
/** Why we need it — shown while Android will still show its own dialog. */
message: string;
/** Shown once Android has stopped showing that dialog. */
blocked: string;
openSettings: string;
cancel: string;
};
/**
* Explains a refused camera or photo-library permission, and offers the only
* way out when there is one.
*
* `granted: false` covers two states that feel completely different to a
* driver. While `canAskAgain` is true the system dialog appeared and they
* declined it, so repeating why we need it and letting them tap the button
* again is the whole fix. Once `canAskAgain` is false Android stops showing
* that dialog altogether: `requestCameraPermissionsAsync()` returns denied
* without anything appearing on screen, so from the driver's side the app has
* simply stopped asking, and no amount of tapping will ever change it. The
* only remaining route is the system settings page for the app, so that case
* gets a button that opens it rather than a message telling them to allow
* something they are never going to be offered.
*
* Android also lands drivers in that second state through no choice of their
* own: requesting a runtime permission the manifest doesn't declare is
* auto-denied and flagged as permanently denied, and the flag survives an
* update install. A driver who ran a build predating the CAMERA declaration in
* app.config.js is stuck there until they either use this button or reinstall.
*/
export const alertPermissionDenied = (
permission: ImagePicker.PermissionResponse,
copy: Copy,
) => {
// Both branches below end in an alert and nothing else, which leaves no
// trace in the logs — the reason a driver reporting "it never asks me" is
// indistinguishable from one who never tapped the button. Logging the two
// fields that decide the branch makes that difference readable.
console.log(
"[CAPTURE_PERMISSION_DENIED]: ",
JSON.stringify({
status: permission.status,
canAskAgain: permission.canAskAgain,
}),
);
if (permission.canAskAgain) {
Alert.alert(copy.title, copy.message);
return;
}
Alert.alert(copy.title, copy.blocked, [
{ text: copy.cancel, style: "cancel" },
{
text: copy.openSettings,
onPress: () => {
// Failure here is not worth a second alert on top of this one: the
// driver is already reading instructions that name the settings
// screen, and reaching it by hand still works.
void Linking.openSettings().catch((error) =>
console.log("[CAPTURE_PERMISSION_SETTINGS]: ", error),
);
},
},
]);
};
+65 -6
View File
@@ -1,12 +1,74 @@
import { lookup, setDefaultResultOrder } from "dns";
import { Pool, type QueryResultRow } from "pg";
// Neon's host resolves to both IPv6 (AAAA) and IPv4 (A). This host has no IPv6
// route, so an IPv6-first connect fails instantly with ENETUNREACH and only
// then falls back to IPv4 — wasting a round-trip on every fresh connection and
// racing Neon's wake. Force IPv4 first so the working path is tried first.
setDefaultResultOrder("ipv4first");
// Neon free-tier scales compute to zero when idle; the first connection after a
// cold wake can take 1030s to establish. A 10s connect timeout 500s every
// request during that wake window, so allow 30s. Once a ride is active the
// driver-location + call polls keep the DB warm, so this only bites the first
// poll after a long idle.
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
max: 10,
idleTimeoutMillis: 30_000,
connectionTimeoutMillis: 10_000,
connectionTimeoutMillis: 30_000,
});
// A pooled client can die out from under us (Neon recycle, network blip).
// Without this handler Node logs an unhandled "idle client error" and the
// pool just drops the client; log it so a flaky connection is visible.
pool.on("error", (err) => {
console.error("[DB_POOL_ERROR]: ", err.message);
});
// Connection errors that are safe to retry on a fresh pool client. Neon's
// direct endpoint intermittently ETIMEDOUTs while the compute wakes; a single
// retry a second later almost always succeeds once the endpoint is warm.
const RETRY_CODES = new Set([
"ETIMEDOUT",
"ECONNRESET",
"ENETUNREACH",
"EHOSTUNREACH",
"EPIPE",
"08000",
"08006",
"08001",
"08004",
"57P03",
]);
const isRetryable = (err: unknown): boolean => {
const e = err as { code?: string };
return Boolean(e && typeof e.code === "string" && RETRY_CODES.has(e.code));
};
// Retry a pool.query a couple of times on transient connection errors. The
// query itself is idempotent from the pool's perspective: a connect failure
// means no statement ran, and pg removes the dead client before the next
// attempt, so we never double-execute a committed statement.
const queryWithRetry = async <R extends QueryResultRow = QueryResultRow>(
text: string,
values: SqlValue[],
): Promise<R[]> => {
let lastErr: unknown;
for (let attempt = 0; attempt < 3; attempt++) {
try {
const result = await pool.query<R>(text, values);
return result.rows;
} catch (err) {
lastErr = err;
if (!isRetryable(err) || attempt === 2) throw err;
// Back off ~1s, ~2s; Neon wake completes within a few seconds.
await new Promise((r) => setTimeout(r, 1000 * (attempt + 1)));
}
}
throw lastErr;
};
export type SqlValue = string | number | boolean | null | Date;
export async function sql<R extends QueryResultRow = QueryResultRow>(
@@ -19,17 +81,14 @@ export async function sql<R extends QueryResultRow = QueryResultRow>(
"",
);
const result = await pool.query<R>(text, values);
return result.rows;
return queryWithRetry<R>(text, values);
}
export async function query<R extends QueryResultRow = QueryResultRow>(
text: string,
values: SqlValue[] = [],
): Promise<R[]> {
const result = await pool.query<R>(text, values);
return result.rows;
return queryWithRetry<R>(text, values);
}
export async function transaction<T>(
+122 -90
View File
@@ -1,107 +1,139 @@
// Uber-style auto-match dispatch. A requested ride has no driver; this engine
// offers it to the nearest eligible driver of the matching service. Drivers
// accept/decline; a decline (or a 15s offer expiry) triggers the next-nearest
// match. There is no background worker — matchNextDriver is called lazily from
// the rider status poll and the driver poll, so matching progresses on every
// request cycle.
// Broadcast dispatch. A new request is put in front of every eligible driver
// near the pickup at once; each of them may volunteer for it (a row in
// ride_offers) and the rider picks between whoever did.
//
// The engine's whole job is therefore the announcement. There is no queue to
// advance, no timer to chase a declining driver with, and no background
// worker: drivers discover requests through their dashboard poll and their
// location heartbeat, and this module exists to make sure a phone that is
// face-down in a pocket still buzzes when a job appears nearby.
import { transaction } from "@/lib/db";
import { haversine } from "@/lib/utils";
import { sql } from "@/lib/db";
import { sendPushToDriver } from "@/lib/push";
import { boundingBox, haversine } from "@/lib/utils";
import { expireStaleRequests } from "@/lib/ride-lifecycle";
import {
BROADCAST_RADIUS_M,
DRIVER_STALE_SECONDS,
OFFER_CHANNEL_ID,
} from "@/constants/dispatch";
// A driver has this long to respond to an offer before it expires and the next
// driver is offered. Tuned short so a rider searching for a driver isn't left
// hanging on a phone that's face-down on a seat.
const OFFER_TTL_SECONDS = 15;
// A driver whose last location ping is older than this is treated as offline
// even if their `online` flag is still true (they closed the app without
// toggling off).
const DRIVER_STALE_SECONDS = 60;
// Fares are stored in cents; the notification shows what the rider is paying.
const formatFare = (cents: number): string => `$${(cents / 100).toFixed(2)}`;
type EligibleDriver = {
type NearbyDriverRow = {
id: number;
latitude: number;
longitude: number;
};
// Offer `rideId` to the nearest eligible driver, if no offer is already in
// flight for it. Idempotent: safe to call on every poll. Returns the driver id
// that was offered, or null if no driver was available.
export const matchNextDriver = async (
rideId: number,
): Promise<number | null> => {
/**
* Drivers who should see `rideId` right now: right service, vetted, online,
* fresh position, not already on a ride, and within the broadcast radius of
* the pickup.
*
* Exported because the driver's own poll asks the mirror-image question —
* "which open requests are near me?" — and the two must agree. If a driver
* could be pushed a request their dashboard then filtered out, they'd get a
* notification for a job that isn't there when they open the app.
*/
export const driversForRequest = async (rideId: number): Promise<number[]> => {
const rides = await sql<{
lat: number;
lng: number;
service: string;
status: string;
}>`
SELECT origin_latitude AS lat, origin_longitude AS lng, service, status
FROM rides WHERE ride_id = ${rideId}
`;
const ride = rides[0];
if (!ride || ride.status !== "requested") return [];
// A coarse bounding box does the work in the index, then a great-circle
// pass trims the corners — same two-step the rider's map search uses.
const box = boundingBox(ride.lat, ride.lng, BROADCAST_RADIUS_M);
const candidates = await sql<NearbyDriverRow>`
SELECT d.id, d.latitude, d.longitude
FROM drivers d
WHERE d.service = ${ride.service}
AND d.online = TRUE
AND d.approval_status = 'approved'
AND d.user_id IS NOT NULL
AND d.latitude IS NOT NULL
AND d.longitude IS NOT NULL
AND d.last_seen > CURRENT_TIMESTAMP - make_interval(secs => ${DRIVER_STALE_SECONDS})
AND d.latitude BETWEEN ${box.minLat} AND ${box.maxLat}
AND d.longitude BETWEEN ${box.minLng} AND ${box.maxLng}
AND NOT EXISTS (
SELECT 1 FROM rides r
WHERE r.driver_id = d.id
AND r.status IN ('accepted', 'arrived', 'en_route')
)
`;
return candidates
.filter(
(d) =>
haversine(ride.lat, ride.lng, d.latitude, d.longitude) <=
BROADCAST_RADIUS_M,
)
.map((d) => d.id);
};
/**
* Announce `rideId` to every eligible driver nearby.
*
* Idempotent, and deliberately so: it is called from the rider's status poll
* as well as from ride creation, and a request that buzzed forty phones once
* must not buzz them again every three seconds. `broadcast_at` is the latch —
* claimed with a guarded UPDATE so two concurrent callers can't both win it.
*
* Returns how many drivers were notified (0 if the announcement was already
* made, or nobody was in range).
*/
export const broadcastRequest = async (rideId: number): Promise<number> => {
try {
return await transaction(async (tx) => {
// Lock the ride row so concurrent matchers serialize on it.
const rides = await tx<{ status: string; service: string }>`
SELECT status, service FROM rides WHERE ride_id = ${rideId} FOR UPDATE
`;
const ride = rides[0];
if (!ride || ride.status !== "requested") return null;
// Give up on requests that have run past their window before announcing
// one — this is one of the lazy paths that stands in for a worker.
await expireStaleRequests(rideId);
// Expire any offers that have been sitting past their TTL.
await tx`
UPDATE ride_offers
SET status = 'expired', responded_at = CURRENT_TIMESTAMP
WHERE ride_id = ${rideId}
AND status = 'offered'
AND offered_at < CURRENT_TIMESTAMP - make_interval(secs => ${OFFER_TTL_SECONDS})
`;
// Claim the announcement. Whoever gets the row does the pushing.
const claimed = await sql<{
origin_address: string;
fare_price: number;
service: string;
}>`
UPDATE rides
SET broadcast_at = CURRENT_TIMESTAMP
WHERE ride_id = ${rideId}
AND status = 'requested'
AND broadcast_at IS NULL
RETURNING origin_address, fare_price, service
`;
if (!claimed[0]) return 0;
// If there is still an active (unexpired) offer in flight, leave it —
// don't stack a second offer on top.
const inFlight = await tx<{ n: number }>`
SELECT COUNT(*)::int AS n FROM ride_offers
WHERE ride_id = ${rideId} AND status = 'offered'
`;
if ((inFlight[0]?.n ?? 0) > 0) return null;
const drivers = await driversForRequest(rideId);
if (drivers.length === 0) return 0;
const rideOrigin = await tx<{ lat: number; lng: number }>`
SELECT origin_latitude AS lat, origin_longitude AS lng
FROM rides WHERE ride_id = ${rideId}
`;
const origin = rideOrigin[0];
if (!origin) return null;
const { origin_address: origin, fare_price: fare } = claimed[0];
// Eligible: right service, online, fresh, a real account, not on an
// active ride, and not already offered/declined for THIS ride.
const candidates = await tx<EligibleDriver>`
SELECT d.id, d.latitude, d.longitude
FROM drivers d
WHERE d.service = ${ride.service}
AND d.online = TRUE
AND d.user_id IS NOT NULL
AND d.latitude IS NOT NULL
AND d.longitude IS NOT NULL
AND d.last_seen > CURRENT_TIMESTAMP - make_interval(secs => ${DRIVER_STALE_SECONDS})
AND NOT EXISTS (
SELECT 1 FROM rides r
WHERE r.driver_id = d.id AND r.status IN ('accepted', 'en_route')
)
AND NOT EXISTS (
SELECT 1 FROM ride_offers ro
WHERE ro.ride_id = ${rideId} AND ro.driver_id = d.id
)
`;
if (candidates.length === 0) return null;
// Nearest by great-circle distance to the pickup point.
candidates.sort((a, b) => {
const da = haversine(origin.lat, origin.lng, a.latitude, a.longitude);
const db = haversine(origin.lat, origin.lng, b.latitude, b.longitude);
return da - db;
// Not awaited: dispatch must not stall on Expo's service, and a driver
// still finds the request through the dashboard poll and the location
// heartbeat regardless.
for (const driverId of drivers) {
void sendPushToDriver(driverId, {
title: "New ride request nearby",
body: `${formatFare(Number(fare))} · pickup at ${origin}`,
channelId: OFFER_CHANNEL_ID,
data: { type: "ride_request", rideId },
});
const nearest = candidates[0];
}
await tx`
INSERT INTO ride_offers (ride_id, driver_id, status)
VALUES (${rideId}, ${nearest.id}, 'offered')
`;
return nearest.id;
});
return drivers.length;
} catch (error) {
console.error("[MATCH_NEXT_DRIVER]: ", error);
return null;
console.error("[BROADCAST_REQUEST]: ", error);
return 0;
}
};
};
+511
View File
@@ -0,0 +1,511 @@
// Reading a driver's documents with Google Cloud Vision, then pulling the
// four credential fields out of the text it returns.
//
// Two things shape this file. First, Lebanese documents are trilingual: a
// driving licence carries Arabic and French on the same card, an ID card is
// Arabic with Arabic-Indic digits, and a vehicle registration mixes both. So
// every label we look for has an Arabic, a French and an English spelling, and
// digits are normalised before anything is matched.
//
// Second, OCR is a suggestion, never an answer. Everything here is best-effort
// and each field is returned independently — a licence whose number reads
// cleanly but whose expiry is smudged yields the number and leaves expiry
// empty. The driver reviews and corrects every field before submitting, and a
// human reviewer still approves the profile against the stored scan. Nothing
// downstream trusts these values because they came from a scan.
const VISION_ENDPOINT = "https://vision.googleapis.com/v1/images:annotate";
export const DOCUMENT_TYPES = ["license", "id", "vehicle_reg"] as const;
export type DocumentType = (typeof DOCUMENT_TYPES)[number];
export const isDocumentType = (v: unknown): v is DocumentType =>
typeof v === "string" && (DOCUMENT_TYPES as readonly string[]).includes(v);
/** Which drivers column stores the scan for each document type. */
export const DOCUMENT_COLUMNS: Record<DocumentType, string> = {
license: "license_image_url",
id: "id_image_url",
vehicle_reg: "vehicle_reg_image_url",
};
/**
* The subset of the onboarding form a scan can fill. Every key is optional:
* a field is present only when it was actually read off the document.
*/
export type ExtractedFields = {
license_number?: string;
/** Always normalised to YYYY-MM-DD, whatever the card printed. */
license_expiry?: string;
national_id?: string;
plate_number?: string;
car_model?: string;
};
// --- Normalisation --------------------------------------------------------
/**
* Lebanese ID cards print Arabic-Indic digits (٠١٢…), and Vision returns them
* verbatim. Everything downstream — the date parser, the digit-run fallbacks,
* the form itself — expects ASCII, so fold them first. Both the Arabic-Indic
* (U+0660) and Extended Arabic-Indic (U+06F0, used by some fonts) ranges show
* up in practice.
*/
const toAsciiDigits = (text: string): string =>
text.replace(/[٠-٩۰-۹]/g, (char) => {
const code = char.charCodeAt(0);
const base = code >= 0x06f0 ? 0x06f0 : 0x0660;
return String(code - base);
});
/**
* Arabic tashkeel (short-vowel marks) and the tatweel stretcher are decorative
* and appear inconsistently in OCR output, so a label match must not depend on
* them. Latin text is uppercased so one pattern covers "Permis" and "PERMIS".
*/
const normalise = (text: string): string =>
toAsciiDigits(text)
.replace(/[ً-ٟـٰ]/g, "")
.replace(/[--]/g, "")
.toUpperCase();
const lines = (text: string): string[] =>
text
.split(/\r?\n/)
.map((line) => line.trim())
.filter(Boolean);
// --- Dates ----------------------------------------------------------------
const MONTH_NAMES: Record<string, number> = {
JAN: 1,
FEV: 2,
FEB: 2,
MAR: 3,
AVR: 4,
APR: 4,
MAI: 5,
MAY: 5,
JUN: 6,
JUIN: 6,
JUL: 7,
JUIL: 7,
AOU: 8,
AUG: 8,
SEP: 9,
OCT: 10,
NOV: 11,
DEC: 12,
};
const isoDate = (year: number, month: number, day: number): string | null => {
if (month < 1 || month > 12 || day < 1 || day > 31) return null;
if (year < 1900 || year > 2100) return null;
const date = new Date(Date.UTC(year, month - 1, day));
// Rejects the likes of 31/02 that survive the range checks above.
if (date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day)
return null;
return `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
};
/**
* Every date on a line, normalised to YYYY-MM-DD.
*
* Lebanese documents print day-first (the French convention), so an ambiguous
* pair like 03/04 is read as 3 April. When the second component is above 12 the
* card must be month-first after all, so that reading wins instead — which is
* how a US-formatted document still parses correctly.
*/
const datesIn = (line: string): string[] => {
const found: string[] = [];
// Year-first: 2027-03-14
for (const match of line.matchAll(
/\b(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})\b/g,
)) {
const iso = isoDate(+match[1], +match[2], +match[3]);
if (iso) found.push(iso);
}
// Day-first or month-first: 14/03/2027
for (const match of line.matchAll(
/\b(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})\b/g,
)) {
const [, a, b, year] = match;
const iso = +b > 12 ? isoDate(+year, +a, +b) : isoDate(+year, +b, +a);
if (iso) found.push(iso);
}
// Spelled-out month: 14 MAR 2027
for (const match of line.matchAll(
/\b(\d{1,2})\s+([A-Z]{3,4})\.?\s+(\d{4})\b/g,
)) {
const month = MONTH_NAMES[match[2]];
const iso = month ? isoDate(+match[3], month, +match[1]) : null;
if (iso) found.push(iso);
}
return found;
};
// Label vocabularies. Arabic first because that is what an ID card leads with.
const EXPIRY_LABELS =
/صلاحية|الصلاحية|تنتهي|انتهاء|ينتهي|EXPIR|VALABLE|VALIDIT|VALID|JUSQU|UNTIL/;
const ISSUE_LABELS =
/اصدار|الاصدار|تاريخ الاصدار|DELIVR|ISSUE|ISSUED|EMIS|EMISSION/;
const BIRTH_LABELS = /ولادة|الولادة|مواليد|NAISSANCE|BIRTH|NE LE|DOB/;
/**
* The expiry date, which is the one date on a licence we actually want.
*
* A licence shows three dates — birth, issue, expiry — and picking the wrong
* one fails the driver's submission on a date they never typed. So a labelled
* expiry wins outright. Failing that, dates sitting on a birth or issue line
* are excluded, along with any the caller already identified by field code,
* and the latest remaining future date is taken — expiry is the only one of
* the three that can be in the future.
*/
const findExpiry = (
docLines: string[],
exclude: Set<string> = new Set(),
): string | undefined => {
const today = new Date().toISOString().slice(0, 10);
const unlabelled: string[] = [];
for (const line of docLines) {
const onLine = datesIn(line).filter((date) => !exclude.has(date));
if (onLine.length === 0) continue;
if (EXPIRY_LABELS.test(line)) {
// A line reading "issued 14/03/2022 expires 14/03/2027" carries both, and
// the later one is the expiry.
const future = onLine.filter((date) => date > today).sort();
if (future.length > 0) return future[future.length - 1];
return onLine.sort()[onLine.length - 1];
}
if (ISSUE_LABELS.test(line) || BIRTH_LABELS.test(line)) continue;
unlabelled.push(...onLine);
}
const future = unlabelled.filter((date) => date > today).sort();
return future.length > 0 ? future[future.length - 1] : undefined;
};
/**
* Value printed against a numbered field code.
*
* The Lebanese licence is an EU-format card (Directive 2006/126/EC), which
* means its fields are identified by a printed number rather than a word: 1 is
* the surname, 2 the given names, 3 the date of birth, 4a the issue date, 4b
* the expiry, 4c the issuing authority, 5 the licence number. Reading those
* codes is far more reliable than hunting for "expiry" in three languages,
* because the card never prints the word in any of them — the only prose on it
* is the "PERMIS DE CONDUIRE / DRIVING LICENSE" title.
*
* The value normally sits on the same line as its code; when Vision splits the
* label column from the value column, it lands on the next line instead, so
* both layouts are handled.
*
* `shape` is what makes the second layout safe. Reading a card whose codes are
* stacked ("1 / 2 / 3 / 4a / 4b / 5") followed by the values in their own
* block, "the line after code 5" is the *first* value, not the fifth — on the
* sample licence that is the surname. Requiring the value to look like the
* field it claims to be rejects that mismatch and lets the caller fall through
* to a fallback that gets it right.
*/
const ANY_FIELD_CODE = /^\d{1,2}[ABCD]?[.):]?$/;
const numberedField = (
docLines: string[],
code: string,
shape?: RegExp,
): string | undefined => {
// The leading (^|\s) is what stops code "5" matching inside "15." and code
// "3" matching inside "13B" — both of which are printed on this card.
const inline = new RegExp(`(?:^|\\s)${code}[.):\\s]\\s*(\\S.*)$`);
const bare = new RegExp(`^${code}[.):]?$`);
const fits = (value: string) =>
value.length > 0 && (!shape || shape.test(value));
for (let index = 0; index < docLines.length; index += 1) {
const match = docLines[index].match(inline);
const sameLine = match?.[1]?.trim();
if (sameLine && fits(sameLine)) return sameLine;
if (!bare.test(docLines[index])) continue;
const next = docLines[index + 1]?.trim();
// A code followed by another code is a label column; there is no value
// there to take.
if (next && !ANY_FIELD_CODE.test(next) && fits(next)) return next;
}
return undefined;
};
/** The single date in a numbered field's value, if it holds one. */
const numberedDate = (docLines: string[], code: string): string | undefined => {
const value = numberedField(
docLines,
code,
/\d{1,4}[-/.]\d{1,2}[-/.]\d{2,4}/,
);
return value ? datesIn(value)[0] : undefined;
};
// --- Field extraction -----------------------------------------------------
/**
* OCR routinely drops the separator between a label and its value, so a capture
* can arrive as "N 123456" or with trailing label text from the next column.
* Keep the leading run of value-shaped characters and drop the rest.
*/
const cleanValue = (raw: string, allowed: RegExp): string | undefined => {
const value = raw
.trim()
.replace(/^[:.\-–—\s]+/, "")
.split(/\s{2,}/)[0]
.trim();
const kept = value
.split("")
.filter((char) => allowed.test(char))
.join("")
.trim();
return kept.length >= 3 ? kept : undefined;
};
/** First capture across a list of patterns, tried in order of confidence. */
const firstMatch = (
docLines: string[],
patterns: RegExp[],
allowed: RegExp,
): string | undefined => {
for (const pattern of patterns) {
for (const line of docLines) {
const match = line.match(pattern);
const value = match?.[1] ? cleanValue(match[1], allowed) : undefined;
if (value) return value;
}
}
return undefined;
};
/**
* Last resort when no label was recognised: the longest plausible run of
* digits on the card. Dates are stripped first, otherwise "14/03/2027" reads
* as an eight-digit licence number.
*/
const longestDigitRun = (
docLines: string[],
min: number,
max: number,
): string | undefined => {
let best: string | undefined;
for (const line of docLines) {
const withoutDates = line
.replace(/\b\d{1,4}[-/.]\d{1,2}[-/.]\d{2,4}\b/g, " ")
.replace(/\b(19|20)\d{2}\b/g, " ");
for (const match of withoutDates.matchAll(/\d[\d\s-]{2,}\d/g)) {
const digits = match[0].replace(/[\s-]/g, "");
if (digits.length < min || digits.length > max) continue;
if (!best || digits.length > best.length) best = digits;
}
}
return best;
};
const ALPHANUMERIC = /[A-Z0-9/-]/;
const DIGITS_ONLY = /[0-9]/;
/** Lebanese plates pair digits with a letter group, Arabic or Latin. */
const PLATE_CHARS = /[A-Z0-9ء-ي/-]/;
const MODEL_CHARS = /[A-Z0-9 .-]/;
const extractLicense = (docLines: string[]): ExtractedFields => {
// Field 5 is the licence number on the EU-format card, and it is by far the
// most reliable read — so it is tried before any worded label. The word
// patterns cover older Lebanese licences that predate the numbered layout,
// and the digit-run fallback covers a card whose codes didn't survive OCR.
// A licence number is a run of digits, so requiring some is what keeps a
// stacked-label card from handing back the holder's surname here.
const field5 = numberedField(docLines, "5", /\d{3,}/);
const license_number =
(field5 ? cleanValue(field5, ALPHANUMERIC) : undefined) ??
firstMatch(
docLines,
[
/(?:رقم\s*(?:الرخصة|الاجازة|الرخصه)?|PERMIS\s*(?:DE\s*CONDUIRE\s*)?N|N[°ºO]\s*(?:DE\s*)?PERMIS|LICEN[CS]E\s*(?:NO|NUMBER|N[°ºO]))\s*[:.\-]?\s*([A-Z0-9][A-Z0-9/\- ]{3,19})/,
/\bN[°ºO]\s*[:.\-]?\s*([A-Z0-9][A-Z0-9/\- ]{4,19})/,
],
ALPHANUMERIC,
) ??
longestDigitRun(docLines, 5, 15);
// 3 is the date of birth and 4a the date of issue. Naming them explicitly
// does double duty: 4b gives the expiry outright, and knowing the other two
// keeps them out of the fallback, which would otherwise be free to mistake a
// recent issue date for an expiry.
const birth = numberedDate(docLines, "3");
const issued = numberedDate(docLines, "4A");
const expires = numberedDate(docLines, "4B");
const excluded = new Set([birth, issued].filter(Boolean) as string[]);
// A card that reads 4b but whose expiry has already passed is a real answer,
// not a misread — surface it so the driver sees why the form rejects it,
// rather than silently leaving the field blank.
const license_expiry = expires ?? findExpiry(docLines, excluded);
// A Lebanese licence carries the holder's register number too, but only
// behind an explicit label — a bare digit run on a licence is far more
// likely to be the licence number itself.
const national_id = firstMatch(
docLines,
[
/(?:رقم\s*(?:الهوية|السجل)|REGISTRE|SEJEL|ID\s*(?:NO|NUMBER)|IDENTITY\s*(?:NO|NUMBER))\s*[:.\-]?\s*([0-9][0-9\- ]{4,19})/,
],
DIGITS_ONLY,
);
return { license_number, license_expiry, national_id };
};
const extractId = (docLines: string[]): ExtractedFields => ({
national_id:
firstMatch(
docLines,
[
/(?:رقم\s*(?:الهوية|السجل|البطاقة)|N[°ºO]\s*(?:DE\s*)?(?:CARTE|REGISTRE)|REGISTRE|SEJEL|ID\s*(?:NO|NUMBER)|IDENTITY\s*(?:NO|NUMBER))\s*[:.\-]?\s*([0-9][0-9\- ]{4,19})/,
/\bرقم\s*[:.\-]?\s*([0-9][0-9\- ]{5,19})/,
],
DIGITS_ONLY,
) ?? longestDigitRun(docLines, 6, 14),
});
const extractVehicleRegistration = (docLines: string[]): ExtractedFields => {
const plate_number =
firstMatch(
docLines,
[
/(?:رقم\s*(?:اللوحة|السيارة)|اللوحة|PLAQUE|IMMATRICULATION|PLATE\s*(?:NO|NUMBER)?|REGISTRATION\s*(?:NO|NUMBER)?)\s*[:.\-]?\s*([0-9ء-يA-Z][0-9A-Zء-ي/\- ]{2,14})/,
// Unlabelled but unmistakable: digits, a slash, then the letter group.
/\b(\d{1,7}\s*\/\s*[A-Zء-ي]{1,3})\b/,
],
PLATE_CHARS,
) ?? undefined;
const car_model = firstMatch(
docLines,
[
/(?:نوع\s*(?:السيارة|المركبة)?|الطراز|MARQUE(?:\s*ET\s*TYPE)?|MODELE|MODÈLE|MAKE|MODEL)\s*[:.\-]?\s*([A-Z][A-Z0-9 .-]{2,29})/,
],
MODEL_CHARS,
);
return { plate_number, car_model };
};
/** Drops keys whose value came back empty so callers can spread the result. */
const compact = (fields: ExtractedFields): ExtractedFields =>
Object.fromEntries(
Object.entries(fields).filter(([, value]) => Boolean(value)),
) as ExtractedFields;
/** Pulls the credential fields out of already-recognised document text. */
export const parseDocumentText = (
text: string,
docType: DocumentType,
): ExtractedFields => {
const docLines = lines(normalise(text));
if (docLines.length === 0) return {};
switch (docType) {
case "license":
return compact(extractLicense(docLines));
case "id":
return compact(extractId(docLines));
case "vehicle_reg":
return compact(extractVehicleRegistration(docLines));
}
};
// --- Google Cloud Vision --------------------------------------------------
export class OcrUnavailableError extends Error {}
type VisionResponse = {
responses?: {
fullTextAnnotation?: { text?: string };
error?: { message?: string };
}[];
};
/**
* Runs Vision's document OCR over a scan and returns the recognised text.
*
* DOCUMENT_TEXT_DETECTION (rather than plain TEXT_DETECTION) is the dense-text
* model: it keeps the line structure of a card, which is what every label
* pattern above depends on. The language hints are the three that appear on
* Lebanese documents — without them Vision often transliterates Arabic instead
* of reading it.
*/
export const recogniseDocument = async (image: Buffer): Promise<string> => {
const key = process.env.GOOGLE_VISION_API_KEY;
if (!key) {
throw new OcrUnavailableError("GOOGLE_VISION_API_KEY is not configured.");
}
let response: Response;
try {
response = await fetch(
`${VISION_ENDPOINT}?key=${encodeURIComponent(key)}`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
requests: [
{
image: { content: image.toString("base64") },
features: [{ type: "DOCUMENT_TEXT_DETECTION", maxResults: 1 }],
imageContext: { languageHints: ["ar", "fr", "en"] },
},
],
}),
// A driver is watching a spinner; failing over to manual entry beats
// holding the screen while Vision is slow.
signal: AbortSignal.timeout(20_000),
},
);
} catch (error) {
throw new OcrUnavailableError(
`Vision request failed: ${(error as Error).message}`,
);
}
if (!response.ok) {
const detail = await response.text().catch(() => "");
throw new OcrUnavailableError(
`Vision responded ${response.status}: ${detail.slice(0, 200)}`,
);
}
const body = (await response.json()) as VisionResponse;
const result = body.responses?.[0];
// Vision reports per-image failures inside a 200 response, so the status
// code alone does not tell you the scan was read.
if (result?.error?.message) {
throw new OcrUnavailableError(`Vision error: ${result.error.message}`);
}
return result?.fullTextAnnotation?.text ?? "";
};
+45
View File
@@ -0,0 +1,45 @@
import Constants from "expo-constants";
/**
* Turns whatever sits in `drivers.profile_image_url` into something an
* `<Image>` can load.
*
* That column holds one of two things. A driver who took their photo in the
* app stores an opaque name ("a1b2….jpg") that only means anything to
* /(api)/driver/photo; an owner who filled the field in from the admin
* dashboard stores a full external URL. Both have to render, so the shape of
* the value decides how it is read — which also means older profiles carrying
* a real URL keep working untouched.
*/
const ABSOLUTE = /^(https?:|data:|file:|blob:)/i;
/**
* The origin an <Image> should fetch from.
*
* `fetchAPI` gets away with relative paths because expo-router resolves them,
* and in development it resolves them against the Metro dev server rather than
* the configured origin. An <Image> URL has to be absolute, so it has to make
* the same choice by hand — otherwise every API call goes to the laptop while
* every avatar goes to production (or, worse, to the placeholder origin in
* .env, and silently renders nothing).
*/
const apiOrigin = (): string => {
if (__DEV__) {
const hostUri = Constants.expoConfig?.hostUri;
if (hostUri) return `http://${hostUri}`;
}
return (process.env.EXPO_PUBLIC_SERVER_URL ?? "").replace(/\/+$/, "");
};
export const driverPhotoUri = (value?: string | null): string | undefined => {
if (!value) return undefined;
if (ABSOLUTE.test(value)) return value;
const origin = apiOrigin();
if (!origin) return undefined;
// The literal "(api)" is part of the path — this app's routes are addressed
// that way throughout, not as an expo-router group that gets stripped.
return `${origin}/(api)/driver/photo?name=${encodeURIComponent(value)}`;
};
+65 -4
View File
@@ -10,11 +10,32 @@ import type { ServiceId } from "@/constants/services";
type Auth = { userId: string; email: string };
/**
* Vetting state of a driver profile.
* pending — onboarded, waiting on an owner review. Cannot go online.
* approved — cleared to drive. The only state dispatch will match.
* rejected — review failed; the driver sees why and can resubmit.
* suspended — was approved, pulled by an owner.
*/
export const DRIVER_APPROVAL_STATUSES = [
"pending",
"approved",
"rejected",
"suspended",
] as const;
export type DriverApprovalStatus = (typeof DRIVER_APPROVAL_STATUSES)[number];
export const isApprovalStatus = (v: unknown): v is DriverApprovalStatus =>
typeof v === "string" &&
(DRIVER_APPROVAL_STATUSES as readonly string[]).includes(v);
export type DriverProfile = {
auth: Auth;
driverId: number;
service: ServiceId;
online: boolean;
approvalStatus: DriverApprovalStatus;
};
export type AuthError = { error: Response };
@@ -32,8 +53,14 @@ export const requireDriverProfile = async (
const auth = requireAuth(req);
if ("error" in auth) return { error: auth.error };
const rows = await sql<{ id: number; service: ServiceId; online: boolean }>`
SELECT id, service, online FROM drivers WHERE user_id = ${auth.userId}
const rows = await sql<{
id: number;
service: ServiceId;
online: boolean;
approval_status: DriverApprovalStatus;
}>`
SELECT id, service, online, approval_status
FROM drivers WHERE user_id = ${auth.userId}
`;
if (!rows[0]) {
@@ -45,6 +72,40 @@ export const requireDriverProfile = async (
};
}
const { id, service, online } = rows[0];
return { auth, driverId: id, service, online };
const { id, service, online, approval_status } = rows[0];
return {
auth,
driverId: id,
service,
online,
approvalStatus: approval_status,
};
};
/**
* Gate for anything a driver can only do once they've been cleared to drive:
* going online, taking an offer, moving a ride through its states. Returns a
* ready-to-return 403 carrying the current status, so the client can show the
* pending / rejected screen instead of a bare error.
*/
export const requireApprovedDriver = async (
req: Request,
): Promise<DriverProfile | AuthError> => {
const result = await requireDriverProfile(req);
if ("error" in result) return result;
if (result.approvalStatus !== "approved") {
return {
error: Response.json(
{
error: "Your driver account is not approved yet.",
code: "NOT_APPROVED",
approval_status: result.approvalStatus,
},
{ status: 403 },
),
};
}
return result;
};
+52 -1
View File
@@ -4,22 +4,56 @@ import { useState, useEffect, useCallback } from "react";
// callers never have to await SecureStore before every request.
let authToken: string | null = null;
// Whether the current token has already been reported dead. A signed-in screen
// usually has several requests in flight — the driver dashboard poll, the call
// watcher, a profile load — and a token that has expired fails all of them
// within a few milliseconds. Without this latch each one would separately tear
// the session down, and signing out is not free: it releases the push device
// and stops the location foreground service.
let unauthorizedNotified = false;
let onUnauthorized: (() => void) | null = null;
export const setAuthToken = (token: string) => {
authToken = token;
unauthorizedNotified = false;
};
export const clearAuthToken = () => {
authToken = null;
};
/**
* Registers what to do when the server rejects a token we actually sent.
*
* Lives at module scope for the same reason the token does: `fetchAPI` is a
* plain function called from stores, effects and helpers that have no React
* context to read. lib/session.tsx registers the real handler on mount.
*/
export const setUnauthorizedHandler = (handler: (() => void) | null) => {
onUnauthorized = handler;
};
/** Carries the HTTP status so callers can branch on it instead of on text. */
export class ApiError extends Error {
status: number;
/**
* The parsed error body, when there was one. Routes that reject with a
* recoverable state attach what the client needs to recover — a 409 on ride
* creation carries the `ride_id` already in progress, so the screen can send
* the rider there instead of just apologising.
*/
body: Record<string, unknown> | null;
constructor(status: number, message: string) {
constructor(
status: number,
message: string,
body: Record<string, unknown> | null = null,
) {
super(message);
this.name = "ApiError";
this.status = status;
this.body = body;
}
}
@@ -30,6 +64,13 @@ export const fetchAPI = async (url: string, options?: RequestInit) => {
headers.set("Authorization", `Bearer ${authToken}`);
}
// Only requests that carried a token can tell us anything about that
// token. Signing in is itself a 401 when the password is wrong, and that
// request is unauthenticated by definition — treating it as a dead session
// would sign the user out of the account they are in the middle of
// signing in to.
const authenticated = headers.has("Authorization");
const response = await fetch(url, { ...options, headers });
if (!response.ok) {
@@ -37,9 +78,19 @@ export const fetchAPI = async (url: string, options?: RequestInit) => {
// what actually went wrong instead of guessing from a status code.
const body = await response.json().catch(() => null);
// The token is gone or expired. Callers still get the ApiError — a
// screen may want to stop polling or hide a spinner — but none of them
// can recover from this one, and leaving the session in place is what
// let an expired token look like a missing driver profile.
if (response.status === 401 && authenticated && !unauthorizedNotified) {
unauthorizedNotified = true;
onUnauthorized?.();
}
throw new ApiError(
response.status,
body?.error ?? `Request failed with status ${response.status}.`,
body,
);
}
+57
View File
@@ -0,0 +1,57 @@
import { requireOptionalNativeModule } from "expo-modules-core";
import type * as ImagePickerModule from "expo-image-picker";
export type ImagePickerApi = typeof ImagePickerModule;
/** The native module expo-image-picker is a JS wrapper around. */
const NATIVE_MODULE = "ExponentImagePicker";
/**
* Whether photo capture can work at all in this build.
*
* `requireOptionalNativeModule` is the non-throwing twin of the
* `requireNativeModule` call that expo-image-picker makes as it loads: it
* returns null instead of raising `Cannot find native module
* 'ExponentImagePicker'`. Asking first means the error is never constructed,
* never logged, and never has a chance to escape into a driver's face — which
* beats importing the package and catching the throw, because a throw that
* happens while a module is evaluating can surface in places a try/catch
* around the import does not cover.
*
* expo-modules-core itself is part of every Expo binary, so importing it here
* is safe on exactly the old builds this is guarding against.
*/
export const isImagePickerAvailable = (): boolean =>
requireOptionalNativeModule(NATIVE_MODULE) !== null;
/**
* Loads expo-image-picker, or returns null when this binary predates it.
*
* The package resolves its native counterpart at *import* time, so importing
* it at the top of a screen doesn't fail politely at the camera button: it
* fails while the route tree is being built, taking the whole app down —
* riders included — on any build made before the package was added. Deferring
* the require moves that failure to the one tap that needs it and makes it
* recoverable.
*
* A null return means one thing only: the app needs rebuilding. Photo capture
* genuinely requires the native module; nothing here can substitute for it.
*/
let cached: ImagePickerApi | null = null;
export const loadImagePicker = (): ImagePickerApi | null => {
if (cached) return cached;
if (!isImagePickerAvailable()) return null;
try {
// Static string so Metro still bundles it — only the evaluation is
// deferred, not the packaging.
// eslint-disable-next-line @typescript-eslint/no-var-requires
cached = require("expo-image-picker") as ImagePickerApi;
return cached;
} catch (error) {
console.log("[IMAGE_PICKER_UNAVAILABLE]: ", error);
return null;
}
};
+214
View File
@@ -0,0 +1,214 @@
// Background location for drivers.
//
// Dispatch drops any driver whose last position ping is over 60 seconds old.
// The old foreground-only watch stopped the moment the app was backgrounded,
// so a driver who locked their phone went stale within a minute and quietly
// left the match pool — while the app still showed them as "Online".
//
// expo-location's task-based updates keep running behind an Android foreground
// service (the persistent "Waseel is finding you rides" notification), which
// both keeps the process alive and makes the location use visible to the
// driver, as it should be.
//
// The task must be defined at module scope, not inside a component: Android
// can restart the app process headlessly to deliver a location update, and the
// task has to already be registered when the JS bundle finishes evaluating.
// This module is imported from app/_layout.tsx for exactly that reason.
import * as Location from "expo-location";
import * as TaskManager from "expo-task-manager";
import { AppState } from "react-native";
import { fetchAPI, setAuthToken } from "@/lib/fetch";
import { notifyRequest } from "@/lib/notifications";
import { readStoredToken } from "@/lib/token-store";
export const DRIVER_LOCATION_TASK = "waseel-driver-location";
// Relative API paths ("/(api)/...") are resolved against the router origin,
// which is set up when the app's React tree boots. A location update can be
// delivered to a process Android restarted headlessly, where that hasn't
// necessarily happened — so the background ping addresses the server
// explicitly. Falls back to the relative path when no origin is configured,
// which is the normal in-app case.
const API_ORIGIN = (process.env.EXPO_PUBLIC_SERVER_URL ?? "").replace(
/\/+$/,
"",
);
const endpoint = (path: string): string =>
API_ORIGIN ? `${API_ORIGIN}${path}` : path;
// Last position we know about, shared between the background task and the
// foreground hook. The heartbeat re-sends this on a timer even when nothing
// new arrives, because "where the driver is" and "is the driver still there"
// are different questions and only the second one has a deadline.
export type DriverFix = {
latitude: number;
longitude: number;
/** Degrees clockwise from north, or null when the device can't tell. */
heading?: number | null;
/** km/h, or null when unknown. */
speedKph?: number | null;
};
let lastKnownCoords: DriverFix | null = null;
export const setLastKnownCoords = (fix: DriverFix): void => {
lastKnownCoords = fix;
};
export const getLastKnownCoords = () => lastKnownCoords;
// Set while the driver screen's heartbeat timer is running, so the background
// task doesn't send a second ping for the same position. When the app has been
// restarted headlessly there is no hook and no timer, and the task pings.
let heartbeatActive = false;
export const setHeartbeatActive = (active: boolean): void => {
heartbeatActive = active;
};
/**
* POST a position to the server and act on whatever came back with it.
*
* Exported because the foreground hook's heartbeat uses the same path — one
* place that knows how a ping is made, so the background and foreground routes
* can't drift apart.
*/
export const pingDriverLocation = async (fix: DriverFix): Promise<void> => {
setLastKnownCoords(fix);
// On a headless restart the module-level auth token in lib/fetch is empty —
// no React tree has run to set it — so seed it from secure storage before
// the request. A no-op in the normal foreground case.
const token = await readStoredToken();
if (!token) return;
setAuthToken(token);
const res = await fetchAPI(endpoint("/(api)/driver/location"), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
latitude: fix.latitude,
longitude: fix.longitude,
heading: fix.heading ?? null,
speed_kph: fix.speedKph ?? null,
}),
});
// The heartbeat carries the nearest open request this driver could take.
// When the app is in the foreground the dashboard already lists it, so we
// only interrupt with a notification when they can't see the screen.
const request = res?.data?.pending_request;
if (request && AppState.currentState !== "active") {
await notifyRequest(request);
}
};
/**
* Normalise an expo-location fix into what the server stores.
*
* expo-location reports -1 for an unknown heading and can report a negative
* speed on some devices; both mean "no reading", not "north" and "reversing".
*/
export const fixFromCoords = (
coords: Location.LocationObjectCoords,
): DriverFix => ({
latitude: coords.latitude,
longitude: coords.longitude,
heading:
typeof coords.heading === "number" && coords.heading >= 0
? coords.heading
: null,
speedKph:
typeof coords.speed === "number" && coords.speed >= 0
? coords.speed * 3.6
: null,
});
TaskManager.defineTask(DRIVER_LOCATION_TASK, async ({ data, error }) => {
if (error) {
console.log("[DRIVER_LOCATION_TASK]: ", error.message);
return;
}
const { locations } = (data ?? {}) as {
locations?: Location.LocationObject[];
};
const last = locations?.[locations.length - 1];
if (!last) return;
// Always record the position — this is what the heartbeat timer re-sends.
setLastKnownCoords(fixFromCoords(last.coords));
// The driver screen's timer owns the heartbeat whenever it's running. The
// task only pings when there is no timer, i.e. Android restarted the process
// headlessly to deliver this update and no React tree ever mounted.
if (heartbeatActive) return;
try {
await pingDriverLocation(fixFromCoords(last.coords));
} catch (err) {
// A failed ping is non-fatal — the next one retries. What takes a driver
// out of the match pool is last_seen going stale, not a single 500.
console.log("[DRIVER_LOCATION_TASK_PING]: ", err);
}
});
/** Is the background task currently delivering updates? */
export const isTrackingLocation = async (): Promise<boolean> => {
try {
return await Location.hasStartedLocationUpdatesAsync(DRIVER_LOCATION_TASK);
} catch {
return false;
}
};
/**
* Start background tracking. Returns false when the OS refused, so the caller
* can fall back to the foreground-only watch rather than leaving the driver
* with no tracking at all.
*/
export const startBackgroundTracking = async (): Promise<boolean> => {
try {
if (await isTrackingLocation()) return true;
await Location.startLocationUpdatesAsync(DRIVER_LOCATION_TASK, {
accuracy: Location.Accuracy.Balanced,
timeInterval: 5000,
// Deliberately 0, not a displacement threshold. On Android the time and
// distance conditions are AND-ed (distanceInterval becomes
// setSmallestDisplacement), so a driver parked at a taxi stand — the
// single most common way to wait for a ride — produces no updates at
// all, goes stale after 60s and silently drops out of the match pool
// while the app still says "Online". The ping IS the liveness signal, so
// it has to fire whether or not the car has moved.
distanceInterval: 0,
// Position updates are worthless late, and Android will otherwise hold
// them back to save battery.
deferredUpdatesInterval: 0,
pausesUpdatesAutomatically: false,
foregroundService: {
notificationTitle: "Waseel — you're online",
notificationBody: "Receiving ride requests. Tap to open.",
notificationColor: "#0286FF",
},
});
return true;
} catch (error) {
console.log("[DRIVER_LOCATION_START]: ", error);
return false;
}
};
/** Stop background tracking and tear down the foreground service. */
export const stopBackgroundTracking = async (): Promise<void> => {
try {
if (await isTrackingLocation()) {
await Location.stopLocationUpdatesAsync(DRIVER_LOCATION_TASK);
}
} catch (error) {
console.log("[DRIVER_LOCATION_STOP]: ", error);
}
};
+1 -1
View File
@@ -142,7 +142,7 @@ export const calculateDriverTimes = async ({
}
};
// A single trip-leg fare estimate for the confirm-ride screen. One Directions
// A single trip-leg fare estimate for the request screen. One Directions
// call instead of one per driver, since the trip leg is the same regardless of
// which driver arrives. Returns { fare, durationSeconds, distanceMeters } or
// null when the route is unreachable.
+191
View File
@@ -0,0 +1,191 @@
// Client half of ride-offer notifications.
//
// The driver dashboard polls every few seconds, but a poll only runs while the
// app is foregrounded and an offer expires in 15 seconds — so a locked phone
// was silently skipped by dispatch and the driver never learned a ride had
// been offered to them.
//
// There are two ways to fix that, and this app uses both:
//
// 1. LOCAL notifications, which work with no credentials at all. While a
// driver is online the app runs a location foreground service (see
// lib/location-task.ts), so JS is alive even with the screen off. Each
// location ping tells us whether an offer is waiting, and we raise a
// local notification for it. This is the path that works today.
//
// 2. REMOTE push through Expo, which additionally reaches a driver whose app
// has been killed outright. It needs an EAS project id and FCM/APNs
// credentials, neither of which is configured yet — so registerForPush
// returns null and the server simply has no tokens to send to. Nothing
// breaks; it lights up on its own once those credentials exist.
import * as Notifications from "expo-notifications";
import { Platform } from "react-native";
import { OFFER_CHANNEL_ID } from "@/constants/dispatch";
import { fetchAPI } from "@/lib/fetch";
/**
* How a notification behaves when it lands while the app is open. A ride offer
* is time-critical, so it is shown rather than swallowed — the driver may be
* on another screen, and four seconds of poll latency is a quarter of the
* window they have to answer.
*/
export const configureNotificationHandler = (): void => {
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: true,
shouldSetBadge: false,
}),
});
};
/**
* Android routes every notification through a channel, and the channel — not
* the message — decides whether it makes a sound, vibrates, or is allowed to
* interrupt. A ride offer needs all three, so it gets its own channel at MAX
* importance instead of riding on the default one.
*/
export const ensureOfferChannel = async (): Promise<void> => {
if (Platform.OS !== "android") return;
try {
await Notifications.setNotificationChannelAsync(OFFER_CHANNEL_ID, {
name: "Ride requests",
importance: Notifications.AndroidImportance.MAX,
// Distinctive double-buzz so an offer is recognisable from a pocket.
vibrationPattern: [0, 250, 150, 400],
sound: "default",
lockscreenVisibility: Notifications.AndroidNotificationVisibility.PUBLIC,
lightColor: "#0286FF",
});
} catch (error) {
console.log("[NOTIF_CHANNEL]: ", error);
}
};
/**
* Ask for the notification permission. Called when a driver goes online, which
* is the first moment the app has a concrete reason to interrupt them.
*/
export const ensureNotificationPermission = async (): Promise<boolean> => {
try {
await ensureOfferChannel();
const existing = await Notifications.getPermissionsAsync();
if (existing.status === "granted") return true;
const asked = await Notifications.requestPermissionsAsync();
return asked.status === "granted";
} catch (error) {
console.log("[NOTIF_PERMISSION]: ", error);
return false;
}
};
// An open request is re-reported by every location ping until this driver
// offers on it or it dies, so the notification has to be raised once per ride
// rather than once per ping — otherwise a driver gets a buzz every five
// seconds. Module-level because the location task is not a React component
// and has no state of its own.
let lastNotifiedRideId: number | null = null;
/**
* Raise a local notification for an open request nearby, at most once per
* ride. Returns whether a notification was actually presented.
*/
export const notifyRequest = async (request: {
ride_id: number;
origin_address: string;
fare_price: number;
}): Promise<boolean> => {
if (lastNotifiedRideId === request.ride_id) return false;
lastNotifiedRideId = request.ride_id;
try {
await ensureOfferChannel();
await Notifications.scheduleNotificationAsync({
content: {
title: "New ride request nearby",
body: `$${(request.fare_price / 100).toFixed(2)} · pickup at ${request.origin_address}`,
sound: "default",
priority: Notifications.AndroidNotificationPriority.MAX,
vibrate: [0, 250, 150, 400],
data: { type: "ride_request", rideId: request.ride_id },
},
// null means "present it now" rather than scheduling for later.
trigger: null,
});
return true;
} catch (error) {
console.log("[NOTIF_REQUEST]: ", error);
return false;
}
};
/** Clear the dedupe memory — called when the driver goes offline. */
export const resetOfferNotifications = (): void => {
lastNotifiedRideId = null;
};
/**
* Register this device for REMOTE push. Dormant until an EAS project id and
* FCM/APNs credentials are configured: without them getExpoPushTokenAsync
* throws, we log it and return null, and the server just has no token to send
* to. Local notifications above are unaffected.
*/
// Remembered so sign-out can release this device without the caller having to
// thread the token through the session.
let currentPushToken: string | null = null;
export const registerForPush = async (): Promise<string | null> => {
try {
const granted = await ensureNotificationPermission();
if (!granted) return null;
const { data: token } = await Notifications.getExpoPushTokenAsync();
if (!token) return null;
await fetchAPI("/(api)/push/token", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token, platform: Platform.OS }),
});
currentPushToken = token;
return token;
} catch (error) {
// Expected until push credentials exist. Not fatal by design.
console.log("[PUSH_REGISTER]: ", error);
return null;
}
};
/**
* Hand this device back on sign-out. Phones get shared — without this the
* previous account keeps receiving ride offers on a phone someone else is now
* signed in on. Safe to call when nothing was ever registered.
*/
export const releaseCurrentPush = async (): Promise<void> => {
const token = currentPushToken;
currentPushToken = null;
resetOfferNotifications();
if (token) await unregisterPush(token);
};
/**
* Release this device on sign-out, so the next person to use the phone doesn't
* receive the previous account's ride offers.
*/
export const unregisterPush = async (token: string): Promise<void> => {
try {
await fetchAPI("/(api)/push/token", {
method: "DELETE",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token }),
});
} catch (error) {
console.log("[PUSH_UNREGISTER]: ", error);
}
};
+46
View File
@@ -17,6 +17,52 @@ export const FARE = {
// Parallel market rate used for the L.B.P. cash equivalent shown in-app.
export const LBP_RATE = 89500;
/**
* The platform's cut of each completed fare.
*
* Until this existed, the driver's earnings and the rider's fare were the same
* number: the dashboard summed `fare_price` and called it "Today's earnings",
* so a rider reading their receipt was reading the driver's revenue, and the
* company's own books had no line of its own. Splitting the fare is what makes
* "what the driver keeps" and "what the company earns" separate, answerable
* questions.
*/
export const COMMISSION_RATE = 0.2;
export type FareSplit = {
/** What the rider pays. */
fareCents: number;
/** What the platform keeps. */
platformFeeCents: number;
/** What the driver is owed. */
driverPayoutCents: number;
/** The rate this split was computed at. */
rate: number;
};
/**
* Split a fare into the driver's payout and the platform's fee.
*
* The fee is rounded and the payout is the remainder, so the two always add
* back up to exactly the fare — computing both by multiplication would let a
* rounding cent go missing or be paid twice, which is the kind of discrepancy
* that surfaces months later as an unreconcilable ledger.
*/
export const splitFare = (
fareCents: number,
rate: number = COMMISSION_RATE,
): FareSplit => {
const fare = Math.max(0, Math.round(fareCents));
const platformFeeCents = Math.round(fare * rate);
return {
fareCents: fare,
platformFeeCents,
driverPayoutCents: fare - platformFeeCents,
rate,
};
};
export const calculateFare = (
{
distanceMeters,
+137
View File
@@ -0,0 +1,137 @@
// Server-side push delivery through Expo's push service.
//
// This is what makes dispatch work on a phone that is locked or in a pocket.
// The driver dashboard polls every few seconds, but a poll only runs while the
// app is foregrounded — and an offer expires in 15 seconds. Without a push, a
// driver who put their phone down is silently skipped by the matcher and never
// learns a ride was offered to them.
//
// No credentials are needed: Expo push tokens are addressed to Expo's service,
// which holds the FCM/APNs keys for the project. Delivery is best-effort by
// design — a failed push must never fail the request that triggered it, since
// the in-app poll is still there as a fallback.
import { sql } from "@/lib/db";
const EXPO_PUSH_URL = "https://exp.host/--/api/v2/push/send";
// Expo rejects a batch larger than this.
const MAX_BATCH = 100;
export type PushMessage = {
title: string;
body: string;
/** Delivered to the app so a tap can route to the right screen. */
data?: Record<string, unknown>;
/** Android channel; must match one created on the client. */
channelId?: string;
};
type ExpoTicket = {
status: "ok" | "error";
id?: string;
message?: string;
details?: { error?: string };
};
/**
* Drop tokens Expo tells us are dead. A token goes stale when the app is
* uninstalled or its notification credentials are rotated; left in the table
* it would be retried on every single dispatch, forever.
*/
const pruneDeadTokens = async (
tokens: string[],
tickets: ExpoTicket[],
): Promise<void> => {
const dead = tickets
.map((ticket, i) => ({ ticket, token: tokens[i] }))
.filter(
({ ticket }) =>
ticket?.status === "error" &&
ticket.details?.error === "DeviceNotRegistered",
)
.map(({ token }) => token)
.filter(Boolean);
if (dead.length === 0) return;
await sql`DELETE FROM push_tokens WHERE token = ANY(${`{${dead.join(",")}}`}::text[])`;
};
/** Send one message to a set of device tokens. Never throws. */
export const sendPush = async (
tokens: string[],
message: PushMessage,
): Promise<void> => {
if (tokens.length === 0) return;
for (let i = 0; i < tokens.length; i += MAX_BATCH) {
const batch = tokens.slice(i, i + MAX_BATCH);
try {
const response = await fetch(EXPO_PUSH_URL, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(
batch.map((to) => ({
to,
title: message.title,
body: message.body,
data: message.data ?? {},
sound: "default",
// A ride offer is worthless a few seconds late, so it must wake the
// device rather than being batched into a maintenance window.
priority: "high",
channelId: message.channelId ?? "default",
// Matches the offer TTL: if it hasn't been delivered by then, the
// ride has already moved to another driver.
ttl: 20,
})),
),
});
if (!response.ok) {
console.error("[PUSH_SEND]: HTTP", response.status);
continue;
}
const body = (await response.json()) as { data?: ExpoTicket[] };
if (body.data) await pruneDeadTokens(batch, body.data);
} catch (error) {
// Best-effort: the in-app poll still catches the offer.
console.error("[PUSH_SEND]: ", error);
}
}
};
/** Every device signed in as this user. */
export const tokensForUser = async (userId: string): Promise<string[]> => {
const rows = await sql<{ token: string }>`
SELECT token FROM push_tokens WHERE user_id = ${userId}
`;
return rows.map((r) => r.token);
};
/** Every device signed in as the account behind this driver profile. */
export const tokensForDriver = async (driverId: number): Promise<string[]> => {
const rows = await sql<{ token: string }>`
SELECT p.token
FROM push_tokens p
JOIN drivers d ON d.user_id = p.user_id
WHERE d.id = ${driverId}
`;
return rows.map((r) => r.token);
};
export const sendPushToUser = async (
userId: string,
message: PushMessage,
): Promise<void> => sendPush(await tokensForUser(userId), message);
export const sendPushToDriver = async (
driverId: number,
message: PushMessage,
): Promise<void> => sendPush(await tokensForDriver(driverId), message);
+64 -44
View File
@@ -4,33 +4,26 @@ import { ApiError, fetchAPI } from "@/lib/fetch";
import type { ServiceId } from "@/constants/services";
import type { Ride } from "@/types/type";
// The rider's request flow, used by the confirm-ride screen. This is the card
// (Areeba hosted checkout -> server verify -> consume order -> create ride)
// and cash (create ride directly) paths, now unified behind one entry point so
// the screen doesn't re-implement the gateway dance.
// The rider's side of dispatch, in two steps that used to be one.
//
// The ride is always created with status='requested' and driver_id=null; the
// server's auto-match engine assigns a driver asynchronously. Returns the
// created ride so the caller can navigate to the status screen.
// Asking for a ride and paying for it are now separate moments: the request
// goes out to nearby drivers the instant the rider taps "Find now", they watch
// offers come back, and money only changes hands once they have picked the
// driver they want. Nothing is charged for a ride nobody takes.
export type RequestInput = {
method: "cash" | "card";
service: ServiceId;
user: { name: string; email: string };
// Location snapshot at request time.
origin: { address: string; latitude: number; longitude: number };
destination: { address: string; latitude: number; longitude: number };
rideTimeSeconds: number;
fareCents: number;
};
export type RequestResult = { ride: Ride };
const recordRide = async (
input: RequestInput,
method: "cash" | "card",
orderId?: string,
): Promise<Ride> => {
/**
* Step one: open the request. Returns the created ride, which is already
* being broadcast to drivers by the time this resolves.
*/
export const createRideRequest = async (input: RequestInput): Promise<Ride> => {
const res = await fetchAPI("/(api)/ride/create", {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -43,44 +36,50 @@ const recordRide = async (
destination_longitude: input.destination.longitude,
ride_time: Math.round(input.rideTimeSeconds),
fare_price: input.fareCents,
payment_method: method,
service: input.service,
...(orderId ? { payment_order_id: orderId } : {}),
}),
});
return res.data as Ride;
};
export const requestRide = async (input: RequestInput): Promise<RequestResult> => {
if (input.method === "cash") {
const ride = await recordRide(input, "cash");
return { ride };
}
/**
* Take a card payment for a ride that already exists, and return the paid
* order id for the selection call.
*
* The order is only *consumed* when the driver is assigned, so if the pick
* then fails — the driver took another job while the rider was in the payment
* sheet — the same order id can be used for the next driver rather than the
* rider paying twice.
*/
export const payByCard = async (input: {
ride: Ride;
user: { name: string; email: string };
}): Promise<string> => {
const { ride, user } = input;
// Card: create an Areeba checkout session on our server.
const { orderId, checkoutUrl, error } = await fetchAPI(
"/(api)/(areeba)/create",
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: input.user.name || input.user.email,
email: input.user.email,
fare_cents: input.fareCents,
origin_address: input.origin.address,
destination_address: input.destination.address,
origin_latitude: input.origin.latitude,
origin_longitude: input.origin.longitude,
destination_latitude: input.destination.latitude,
destination_longitude: input.destination.longitude,
ride_time: Math.round(input.rideTimeSeconds),
name: user.name || user.email,
email: user.email,
fare_cents: ride.fare_price,
origin_address: ride.origin_address,
destination_address: ride.destination_address,
origin_latitude: ride.origin_latitude,
origin_longitude: ride.origin_longitude,
destination_latitude: ride.destination_latitude,
destination_longitude: ride.destination_longitude,
ride_time: ride.ride_time,
}),
},
);
if (error || !checkoutUrl) throw new Error(error || "No checkout URL");
// Open Areeba's hosted payment page. After payment the gateway redirects
// back to the app (waseel://book-ride).
// Areeba's hosted payment page. After payment the gateway redirects back to
// the app (waseel://book-ride).
const browserResult = await WebBrowser.openAuthSessionAsync(
checkoutUrl,
"waseel://book-ride",
@@ -88,12 +87,13 @@ export const requestRide = async (input: RequestInput): Promise<RequestResult> =
let resultIndicator: string | undefined;
if (browserResult.type === "success" && browserResult.url) {
resultIndicator = new URL(browserResult.url).searchParams.get(
"resultIndicator",
) ?? undefined;
resultIndicator =
new URL(browserResult.url).searchParams.get("resultIndicator") ??
undefined;
}
// Verify the payment server-side.
// The gateway's word is never taken from the client: the server asks Areeba
// directly before the order is marked paid.
const verification = await fetchAPI("/(api)/(areeba)/verify", {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -107,6 +107,26 @@ export const requestRide = async (input: RequestInput): Promise<RequestResult> =
);
}
const ride = await recordRide(input, "card", orderId);
return { ride };
};
return orderId as string;
};
/**
* Step two: pick a driver. This is the call that assigns the ride, records how
* it will be paid, and releases every other driver who offered.
*/
export const selectDriver = async (input: {
rideId: number;
offerId: number;
method: "cash" | "card";
orderId?: string;
}): Promise<void> => {
await fetchAPI(`/(api)/ride/${input.rideId}/select`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
offer_id: input.offerId,
payment_method: input.method,
...(input.orderId ? { payment_order_id: input.orderId } : {}),
}),
});
};
+46
View File
@@ -0,0 +1,46 @@
// Turning coordinates back into something a person recognises.
//
// Shared by the initial location fix and the map pin adjuster, so the address
// a rider sees while dragging the pin is formatted exactly like the one that
// was filled in for them automatically — two different shapes for the same
// place would read as a bug.
//
// Uses expo-location's on-device geocoder rather than the Places API: it costs
// nothing, works without the Google key, and this is a label, not a search.
import * as Location from "expo-location";
import { tr } from "@/lib/i18n";
/**
* A short, human address for a point — "Hamra, Beirut" — or the generic "your
* location" label when the geocoder has nothing useful. Never throws: a failed
* lookup costs the label, never the coordinates.
*/
export const addressForCoords = async (
latitude: number,
longitude: number,
): Promise<string> => {
try {
const [place] = await Location.reverseGeocodeAsync({ latitude, longitude });
if (!place) return tr("common.yourLocation");
// Street-level first, falling back through progressively coarser fields:
// a pin dropped in the middle of a field still deserves a name.
const line = [
place.name ?? place.street,
place.district ?? place.city ?? place.subregion,
place.region,
]
.filter(Boolean)
// The geocoder often repeats a value across fields ("Beirut, Beirut").
.filter((part, index, all) => all.indexOf(part) === index)
.slice(0, 2)
.join(", ");
return line || tr("common.yourLocation");
} catch (error) {
console.log("[REVERSE_GEOCODE]: ", error);
return tr("common.yourLocation");
}
};
+226
View File
@@ -0,0 +1,226 @@
// The ride state machine, shared by every endpoint that touches it.
//
// requested ──rider picks an offer──▶ accepted ──arrive──▶ arrived
// │ │ │ pickup code
// │ │ ▼
// │ │ en_route ──▶ completed
// │ │ │ │
// │ └─────────────┴────────────┴──── cancel ──▶ cancelled
// └── nobody offered in time ──▶ expired
//
// Dispatch is a broadcast, not a hand-off: a new request is put in front of
// every eligible driver near the pickup at once, each of them can volunteer
// for it (a row in ride_offers), and the rider chooses between whoever did.
// So a ride has exactly one moment of assignment — the rider's pick — rather
// than a driver claiming it and the rider being told after the fact.
//
// Keeping the status sets here (rather than inlining string arrays in each
// route) is what stops a new state like 'arrived' from being handled in one
// query and silently ignored in the next.
import { query, sql, type SqlValue } from "@/lib/db";
import { REQUEST_TTL_SECONDS } from "@/constants/dispatch";
export const RIDE_STATUSES = [
"requested",
"accepted",
"arrived",
"en_route",
"completed",
"cancelled",
"expired",
] as const;
export type RideStatus = (typeof RIDE_STATUSES)[number];
/** Ride is in flight for the rider: they should be on the tracking screen. */
export const ACTIVE_RIDE_STATUSES = [
"requested",
"accepted",
"arrived",
"en_route",
] as const;
/**
* Driver is committed to a ride and must not be shown new requests. Offering
* on a request costs a driver nothing and can be withdrawn, so it is the
* assignment — not the offer — that takes them off the board.
*/
export const DRIVER_BUSY_STATUSES = [
"accepted",
"arrived",
"en_route",
] as const;
/** Nothing more will happen to the ride. */
export const TERMINAL_RIDE_STATUSES = [
"completed",
"cancelled",
"expired",
] as const;
/** Chat and calls are open between the two parties in these states. */
export const CONNECTED_RIDE_STATUSES = [
"accepted",
"arrived",
"en_route",
] as const;
export const isTerminal = (status: string): boolean =>
(TERMINAL_RIDE_STATUSES as readonly string[]).includes(status);
// Postgres array literals for the sets above. Passed as a bound parameter and
// cast in the query — `status = ANY(${ACTIVE_STATUS_ARRAY}::text[])` — so a
// status list is defined once here instead of being retyped inline in every
// route, where adding a state means remembering every literal that needs it.
const pgArray = (v: readonly string[]): string => `{${v.join(",")}}`;
/** The rider may still call it off in these states — nobody is moving yet. */
export const RIDER_CANCELLABLE_STATUSES = [
"requested",
"accepted",
"arrived",
] as const;
/** The assigned driver's cancellation window: from being picked to the pickup. */
export const DRIVER_CANCELLABLE_STATUSES = [
"accepted",
"arrived",
] as const;
export const ACTIVE_STATUS_ARRAY = pgArray(ACTIVE_RIDE_STATUSES);
export const DRIVER_BUSY_ARRAY = pgArray(DRIVER_BUSY_STATUSES);
export const CONNECTED_STATUS_ARRAY = pgArray(CONNECTED_RIDE_STATUSES);
export const TERMINAL_STATUS_ARRAY = pgArray(TERMINAL_RIDE_STATUSES);
export const RIDER_CANCELLABLE_ARRAY = pgArray(RIDER_CANCELLABLE_STATUSES);
export const DRIVER_CANCELLABLE_ARRAY = pgArray(DRIVER_CANCELLABLE_STATUSES);
// Cancellation reasons the clients may send. Free text is rejected: these
// codes are what makes cancellations countable in the admin portal, and an
// open text field would turn that into an unqueryable mess.
export const CANCELLATION_REASONS = [
"changed_mind",
"wait_too_long",
"wrong_address",
"driver_no_show",
"rider_no_show",
"unreachable",
"vehicle_issue",
"other",
] as const;
export type CancellationReason = (typeof CANCELLATION_REASONS)[number];
export const isCancellationReason = (v: unknown): v is CancellationReason =>
typeof v === "string" &&
(CANCELLATION_REASONS as readonly string[]).includes(v);
// 4-digit pickup code. Not a secret worth hardening — it only has to be hard
// to guess on the first try in a parking lot, and the driver can only try it
// against a ride already assigned to them.
export const generatePickupCode = (): string =>
String(Math.floor(1000 + Math.random() * 9000));
/**
* Give up on `requested` rides nobody was picked for within
* REQUEST_TTL_SECONDS, and close whatever offers were sitting on them.
*
* Called from the lazy paths that stand in for a background worker — the
* rider's status poll, the driver's dashboard poll — so there is no daemon to
* keep alive.
*
* Unlike the old hand-off dispatch, a request with offers on it is expired
* like any other. Offers are volunteers, not commitments: a rider who never
* picked one has left three drivers holding a job that is never going to
* start, and the honest end of that is to close it and free them.
*/
export const expireStaleRequests = async (rideId?: number): Promise<number> => {
const values: SqlValue[] = [REQUEST_TTL_SECONDS];
let scope = "";
if (rideId !== undefined) {
values.push(rideId);
scope = ` AND ride_id = $${values.length}`;
}
try {
const rows = await query<{ ride_id: number }>(
`UPDATE rides
SET status = 'expired',
cancelled_at = CURRENT_TIMESTAMP,
cancelled_by = 'system',
cancellation_reason = 'no_drivers_available'
WHERE status = 'requested'
AND created_at < CURRENT_TIMESTAMP - make_interval(secs => $1)${scope}
RETURNING ride_id`,
values,
);
if (rows.length > 0) {
// Same sweep, so a driver's "waiting for the rider" card can never
// outlive the request it belongs to.
// Passed as a Postgres array literal and cast in the query, the same way
// the status sets above travel — SqlValue is deliberately scalar-only.
await query(
`UPDATE ride_offers
SET status = 'expired', responded_at = CURRENT_TIMESTAMP
WHERE status = 'offered'
AND ride_id = ANY($1::int[])`,
[`{${rows.map((r) => r.ride_id).join(",")}}`],
);
}
return rows.length;
} catch (error) {
console.error("[EXPIRE_STALE_REQUESTS]: ", error);
return 0;
}
};
/**
* Recompute a driver's headline rating from the ratings riders left them.
* Denormalised onto drivers.rating because every driver card and every match
* candidate reads it. Drivers with no ratings yet keep the 5.0 they onboard
* with, so a new driver isn't shown as unrated-and-therefore-bad.
*/
export const refreshDriverRating = async (driverId: number): Promise<void> => {
try {
await sql`
UPDATE drivers d
SET rating = COALESCE(agg.avg_rating, 5.0),
rating_count = COALESCE(agg.n, 0)
FROM (
SELECT
ROUND(AVG(rr.rating)::numeric, 1) AS avg_rating,
COUNT(*)::int AS n
FROM ride_ratings rr
JOIN rides r ON r.ride_id = rr.ride_id
WHERE rr.rater_type = 'rider' AND r.driver_id = ${driverId}
) AS agg
WHERE d.id = ${driverId}
`;
} catch (error) {
console.error("[REFRESH_DRIVER_RATING]: ", error);
}
};
/** The mirror of the above: what drivers thought of a rider. */
export const refreshRiderRating = async (userId: string): Promise<void> => {
try {
await sql`
UPDATE users u
SET rating = agg.avg_rating,
rating_count = COALESCE(agg.n, 0)
FROM (
SELECT
ROUND(AVG(rr.rating)::numeric, 1) AS avg_rating,
COUNT(*)::int AS n
FROM ride_ratings rr
JOIN rides r ON r.ride_id = rr.ride_id
WHERE rr.rater_type = 'driver' AND r.user_id = ${userId}
) AS agg
WHERE u.id = ${userId}
`;
} catch (error) {
console.error("[REFRESH_RIDER_RATING]: ", error);
}
};
+80
View File
@@ -0,0 +1,80 @@
// Shared ownership + liveness checks for anything scoped to a ride that both
// the rider and the assigned driver can touch (chat messages, calls). A
// rider authenticates via requireAuth (users.id UUID); a driver authenticates
// via requireDriverProfile (drivers.id INT). Because a single user account can
// be both a rider and a driver, we check the RIDER path first — otherwise a
// user who is also a driver would be misrouted to the driver branch for their
// own ride.
import { requireAuth } from "@/lib/jwt";
import { requireDriverProfile } from "@/lib/driver";
import { sql } from "@/lib/db";
import { CONNECTED_STATUS_ARRAY } from "@/lib/ride-lifecycle";
export type RideParticipant =
| { role: "rider"; userId: string; driverId: null }
| { role: "driver"; userId: string; driverId: number };
export type ParticipantError = { error: Response };
// Proves the caller is the ride's rider or its assigned driver and returns
// which one, so the caller can stamp sender_type / caller_type. Returns a
// ready-to-ship 403/401 error Response otherwise.
export const requireRideParticipant = async (
req: Request,
rideId: number,
): Promise<RideParticipant | ParticipantError> => {
// Rider path first: a user who owns the ride.
const auth = requireAuth(req);
if (!("error" in auth)) {
const riderRows = await sql<{ user_id: string }>`
SELECT user_id FROM rides WHERE ride_id = ${rideId} AND user_id = ${auth.userId}
`;
if (riderRows[0]) {
return { role: "rider", userId: auth.userId, driverId: null };
}
}
// Driver path: a user with a driver profile assigned to the ride.
const driver = await requireDriverProfile(req);
if ("error" in driver) {
// If the request had no valid auth at all, surface that 401 rather than a
// generic 403, so the client can re-authenticate.
if ("error" in auth) return { error: auth.error };
return {
error: Response.json(
{ error: "You are not part of this ride." },
{ status: 403 },
),
};
}
const driverRows = await sql<{ ride_id: number }>`
SELECT ride_id FROM rides WHERE ride_id = ${rideId} AND driver_id = ${driver.driverId}
`;
if (!driverRows[0]) {
return {
error: Response.json(
{ error: "You are not part of this ride." },
{ status: 403 },
),
};
}
return {
role: "driver",
userId: driver.auth.userId,
driverId: driver.driverId,
};
};
// A ride is "active" (chat/call allowed) while a driver is assigned and the
// ride is en route to or past acceptance but not yet terminal.
export const rideIsActive = async (rideId: number): Promise<boolean> => {
const rows = await sql<{ status: string }>`
SELECT status FROM rides
WHERE ride_id = ${rideId} AND driver_id IS NOT NULL
AND status = ANY(${CONNECTED_STATUS_ARRAY}::text[])
`;
return Boolean(rows[0]);
};
+27 -2
View File
@@ -9,9 +9,11 @@ import {
type ReactNode,
} from "react";
import { setAuthToken, clearAuthToken } from "./fetch";
import { setAuthToken, clearAuthToken, setUnauthorizedHandler } from "./fetch";
import { stopBackgroundTracking } from "./location-task";
import { releaseCurrentPush } from "./notifications";
import { TOKEN_KEY } from "./token-store";
const TOKEN_KEY = "waseel_auth_token";
const USER_KEY = "waseel_auth_user";
const REMEMBERED_EMAIL_KEY = "waseel_remembered_email";
const DEFAULT_TOKEN_TTL_SECONDS = 30 * 24 * 60 * 60;
@@ -171,6 +173,17 @@ export const SessionProvider = ({ children }: { children: ReactNode }) => {
);
const signOut = useCallback(async () => {
// Hand the device back before the token goes away — the release call needs
// to authenticate as the account that currently holds it. Phones get
// shared, and without this the previous account keeps receiving ride
// offers on a phone someone else is now signed in on.
await releaseCurrentPush();
// A driver who signs out is off shift: tear down the location foreground
// service too, or they're left with a "you're online" notification and a
// GPS drain for a session that has ended.
await stopBackgroundTracking();
clearAuthToken();
setUser(null);
@@ -178,6 +191,18 @@ export const SessionProvider = ({ children }: { children: ReactNode }) => {
await SecureStore.deleteItemAsync(USER_KEY);
}, []);
// The other half of the bargain struck in restore(): a token we cannot prove
// is expired stays in use until the server rejects it, and this is what
// happens when it does. Without it the app kept the dead token and every
// screen behind the session had to invent its own meaning for the resulting
// 401 — driver-home read it as "this user has no driver profile" and showed
// an onboarding form to a driver who had finished onboarding weeks ago.
useEffect(() => {
setUnauthorizedHandler(() => void signOut());
return () => setUnauthorizedHandler(null);
}, [signOut]);
const value = useMemo<SessionContextValue>(
() => ({
isLoaded,
+89
View File
@@ -0,0 +1,89 @@
// Who is holding the money, and who still has to hand it over.
//
// A completed ride splits into a driver payout and a platform fee, but the
// split alone doesn't say whether anyone has actually been paid. That depends
// on how the rider paid, because it decides who ends up holding the cash:
//
// Card — the rider pays the platform. The company already has its fee the
// moment the card settles, and now OWES THE DRIVER their payout.
//
// Cash — the driver takes the whole fare at the kerb. They already have
// their payout in their pocket, and now OWE THE COMPANY its fee.
//
// Unpaid — a cash ride the driver couldn't collect. Nobody has been paid and
// nothing is owed between them; the fare itself is simply lost.
//
// So "has the company collected?" has no single answer per ride — it's one
// question for card rides and the opposite question for cash ones. This module
// is the single place that knows the difference, so the admin ledger, the
// driver's balance and the settle endpoint can't drift apart.
/** Payment states in which a completed ride actually produced money. */
export const SETTLED_PAYMENT_STATUSES = ["paid", "cash_collected"] as const;
export const isPaidRide = (paymentStatus: string): boolean =>
(SETTLED_PAYMENT_STATUSES as readonly string[]).includes(paymentStatus);
/** Which side of a ride's money a settlement action refers to. */
export const SETTLEMENT_SIDES = ["platform_fee", "driver_payout"] as const;
export type SettlementSide = (typeof SETTLEMENT_SIDES)[number];
export const isSettlementSide = (v: unknown): v is SettlementSide =>
typeof v === "string" && (SETTLEMENT_SIDES as readonly string[]).includes(v);
export type RideMoney = {
status: string;
payment_status: string;
platform_fee_cents: number | null;
driver_payout_cents: number | null;
platform_fee_settled_at: string | null;
driver_payout_settled_at: string | null;
};
/**
* What a single completed ride still owes, and to whom.
*
* `companyOwedCents` is money the company is waiting on — a cash ride whose
* fee the driver hasn't remitted. `driverOwedCents` is money the company still
* has to pay out — a card ride the driver hasn't been paid for. A ride that
* never happened, or was never paid for, owes nothing in either direction.
*/
export const rideBalance = (
ride: RideMoney,
): { companyOwedCents: number; driverOwedCents: number } => {
if (ride.status !== "completed" || !isPaidRide(ride.payment_status)) {
return { companyOwedCents: 0, driverOwedCents: 0 };
}
const fee = ride.platform_fee_cents ?? 0;
const payout = ride.driver_payout_cents ?? 0;
return {
companyOwedCents: ride.platform_fee_settled_at === null ? fee : 0,
driverOwedCents: ride.driver_payout_settled_at === null ? payout : 0,
};
};
/**
* The settlement timestamps a ride should be born with, given how it was paid.
*
* Whoever physically ends up holding their own share is settled the instant
* the ride completes — there is no transfer left to make. Only the other side
* is left outstanding, and that's the one somebody has to act on.
*/
export const initialSettlement = (
paymentStatus: string,
): { platformFeeSettled: boolean; driverPayoutSettled: boolean } => {
switch (paymentStatus) {
// Company holds the fare: its fee is in hand, the driver is owed.
case "paid":
return { platformFeeSettled: true, driverPayoutSettled: false };
// Driver holds the fare: their payout is in hand, the company is owed.
case "cash_collected":
return { platformFeeSettled: false, driverPayoutSettled: true };
// Nobody was paid; there is nothing to settle between them.
default:
return { platformFeeSettled: false, driverPayoutSettled: false };
}
};
+22
View File
@@ -0,0 +1,22 @@
// Where the session token lives on disk.
//
// Split out of lib/session.tsx so the background location task can read the
// token without importing the session provider: the task module is imported
// by app/_layout at bundle evaluation, and sign-out needs to stop the task —
// pointing those two at each other would be an import cycle. Both depend on
// this leaf instead.
import * as SecureStore from "expo-secure-store";
export const TOKEN_KEY = "waseel_auth_token";
/**
* The stored session token, read straight from secure storage.
*
* Normal requests use the in-memory copy in lib/fetch, which the session
* provider sets on sign-in. The background location task can't rely on that:
* Android may restart the app process headlessly to deliver a location update,
* with no React tree run and therefore no token in memory.
*/
export const readStoredToken = (): Promise<string | null> =>
SecureStore.getItemAsync(TOKEN_KEY);
+314 -3
View File
@@ -135,6 +135,9 @@ export const ar = {
recentRides: "الرحلات الأخيرة",
noRecent: "لا توجد رحلات حديثة.",
noRecentAlt: "لا توجد رحلات حديثة",
activeRideWithDriver: "{name} في الطريق",
rateLastRide: "كيف كانت رحلتك الأخيرة؟",
rate: "قيّم",
},
rides: {
@@ -155,7 +158,38 @@ export const ar = {
title: "الدردشة",
messageAlt: "رسالة",
noMessages: "لا توجد رسائل بعد",
startConversation: "ابدأ محادثة مع أصدقائك وعائلتك",
startConversation: "تفتح المحادثة مع سائقك بمجرد مطابقة الرحلة.",
inputPlaceholder: "رسالة…",
send: "إرسال",
loadError: "تعذّر تحميل الرسائل. اسحب للأسفل لإعادة المحاولة.",
sendError: "تعذّر إرسال الرسالة. حاول مرة أخرى.",
cannotMessage: "لم تعد هذه الرحلة نشطة.",
call: "اتصال",
},
call: {
incoming: "مكالمة واردة",
outgoing: "جارٍ الاتصال…",
connecting: "جارٍ التوصيل…",
inCall: "أثناء المكالمة",
ended: "انتهت المكالمة",
missed: "مكالمة فائتة",
declined: "تم رفض المكالمة",
failed: "فشل الاتصال",
unavailable: "لا توجد رحلة نشطة للاتصال.",
accept: "قبول",
decline: "رفض",
end: "إنهاء المكالمة",
mute: "كتم",
unmute: "إلغاء الكتم",
speaker: "مكبر الصوت",
speakerOff: "إيقاف مكبر الصوت",
cancel: "إلغاء",
connectingWith: "جارٍ الاتصال بـ {name}…",
micDeniedTitle: "الميكروفون محظور",
micDeniedBody:
"يحتاج وسيط إلى ميكروفون لإجراء المكالمات. فعّله من الإعدادات.",
audioFailed: "تعذّر بدء الصوت. حاول مرة أخرى.",
},
profile: {
@@ -169,14 +203,34 @@ export const ar = {
emailPlaceholder: "بريدك الإلكتروني",
},
adjustPin: {
pickupLabel: "نقطة الصعود",
destinationLabel: "نقطة النزول",
locating: "جارٍ تحديد المكان…",
hint: "حرّك الخريطة لوضع الدبوس في المكان الذي تريده تمامًا.",
confirmPickup: "تأكيد نقطة الصعود",
confirmDestination: "تأكيد نقطة النزول",
recenter: "الذهاب إلى موقعي",
},
findRide: {
adjustOnMap: "حدّدها على الخريطة",
title: "الرحلة",
from: "من",
to: "إلى",
findNow: "ابحث الآن",
service: "نوع الرحلة",
nAvailable: "{n} قريب",
estimatedFare: "الأجرة التقديرية",
setBothPoints: "حدّد نقطة الانطلاق والوجهة",
payLaterHint:
"سيرى السائقون القريبون طلبك. أنت تختار من يأخذه، وتدفع بعد ذلك.",
sending: "جارٍ إرسال طلبك…",
},
confirmRide: {
noDriversInRadius: "لا يوجد سائقو {service} ضمن {km} كم",
tryInstead: "المتاح قربك الآن:",
title: "طلب رحلة",
yourTrip: "رحلتك",
pickup: "نقطة الصعود",
@@ -189,6 +243,13 @@ export const ar = {
lbpEstimate: "≈ {lbp}",
noDrivers: "لا يوجد سائقو {service} متصلون الآن",
findingDrivers: "جارٍ البحث عن سائقين قريبين…",
driversNearby: {
one: "سائق واحد قريب",
other: "{n} سائقين قريبين",
zero: "لا سائقين قريبين",
},
withinRadius: "ضمن {km} كم منك",
searchingRadius: "البحث ضمن {km} كم…",
nearestDriver: "أقرب سائق ≈ {eta} دقيقة",
requesting: "جارٍ الطلب…",
noDriversOnline: "لا يوجد سائقون متصلون",
@@ -202,20 +263,60 @@ export const ar = {
alertErrorFallback: "حدث خطأ أثناء حجز رحلتك. حاول مرة أخرى.",
alertPayCardTitle: "الدفع بالبطاقة",
alertPayCardBody: "سيتم خصم ${fare} من بطاقتك.",
alertInProgressTitle: "لديك رحلة جارية",
alertInProgressBody: "لديك رحلة جارية. أنهِها أو ألغِها قبل حجز رحلة أخرى.",
viewRide: "عرض الرحلة",
},
bookRide: {
status: {
requested: "جارٍ البحث عن سائقك…",
choosing: "اختر سائقك",
accepted: "تم تعيين سائق — في طريقه إليك",
enRoute: "أنت في الرحلة",
completed: "وصلت!",
cancelled: "تم إلغاء الرحلة",
arrived: "سائقك وصل",
expired: "لا يوجد سائق متاح",
},
rideNotFound: "الرحلة غير موجودة.",
couldNotLoad: "تعذّر تحميل هذه الرحلة.",
backHome: "العودة للرئيسية",
matchingDriver: "نطابقك مع أقرب سائق {service}.",
searchingFor: "جارٍ البحث منذ {seconds} ثانية",
match: {
driverFallback: "سائقك",
alertBody: "حدث خطأ ما. حاول مرة أخرى.",
},
offers: {
title: "سائقون متاحون",
count: {
one: "عرض واحد",
other: "{n} عروض",
zero: "لا عروض بعد",
},
away: "{eta} دقيقة · {distance}",
seats: {
one: "مقعد واحد",
other: "{n} مقاعد",
zero: "",
},
pick: "اختر",
goneTitle: "لم يعد هذا السائق متاحًا",
goneBody: "ارتبط برحلة أخرى. اختر سائقًا آخر من القائمة.",
goneBodyPaid:
"ارتبط برحلة أخرى. لم يُستخدم دفعك — اختر سائقًا آخر وسيذهب المبلغ إليه.",
},
payment: {
title: "كيف تريد الدفع؟",
titleNamed: "رحلة مع {name}",
subtitle: "الأجرة ${fare}",
cash: "الدفع نقدًا",
cashHint: "سلّم الأجرة للسائق عند الوصول.",
card: "الدفع بالبطاقة",
cardHint: "يُخصم الآن، قبل انطلاق السائق.",
working: "جارٍ التنفيذ…",
},
ratingFallback: "—",
paymentCash: "💵 نقدًا للسائق",
paymentCard: "💳 مدفوع بالبطاقة",
@@ -226,10 +327,25 @@ export const ar = {
cancelling: "جارٍ الإلغاء…",
alertErrorTitle: "خطأ",
alertErrorBody: "تعذّر إلغاء هذه الرحلة. حاول مرة أخرى.",
pickupCodeLabel: "رمز الصعود",
pickupCodeHint: "أعطِ هذا الرمز للسائق لبدء الرحلة.",
driverHere: "سائقك في الخارج",
cashDue: "ادفع ${amount} نقدًا للسائق.",
youRated: "قيّمت هذه الرحلة {n}★",
rateDriver: "قيّم سائقك",
noDriversFound:
"لم يقبل أي سائق طلبك. لم يتم خصم أي مبلغ — حاول مرة أخرى بعد قليل.",
cancelledByDriver: "ألغى السائق هذه الرحلة.",
enRouteNotice: "رحلة سعيدة — سينهي السائق الرحلة عند الوصول.",
},
driver: {
home: {
owesCompany: "العمولة المستحقة عليك",
owesCompanyHint: "من رحلاتك النقدية — سلّمها في المكتب.",
owedToDriver: "الشركة مدينة لك",
owedToDriverHint: "رحلات البطاقة، تُدفع لك.",
afterFee: "بعد عمولة ${fee}",
signOutAlt: "تسجيل الخروج",
driverMode: "وضع السائق",
online: "● متصل — يتلقّى طلبات الرحلات",
@@ -238,6 +354,7 @@ export const ar = {
completedToday: "المكتملة اليوم",
incomingRequests: "الطلبات الواردة",
incomingRequestsOffline: "الطلبات الواردة (غير متصل)",
finishCurrentRide: "أنهِ رحلتك الحالية لرؤية الطلبات الجديدة.",
waitingRequests: "بانتظار طلبات الرحلات…",
goOnlineStart: "اتصل لبدء القيادة.",
welcome: "أهلاً {name}",
@@ -256,35 +373,216 @@ export const ar = {
alertCreateBody: "تعذّر إنشاء ملف السائق. حاول مرة أخرى.",
alertToggleBody: "تعذّر تغيير حالتك. حاول مرة أخرى.",
noRequestsAlt: "لا توجد رحلات حديثة",
cashInHand: "النقد المحصّل اليوم",
uncollected: "أجرة غير محصّلة اليوم",
ratingCount: "{n} تقييم",
ratingNew: "سائق جديد",
alertOfflineBlocked: "أنهِ رحلتك الحالية أو ألغِها قبل قطع الاتصال.",
},
credentials: {
title: "أوراقك الثبوتية",
intro:
"ندقّق في أوراق كل سائق قبل أن يبدأ العمل. سيراجع فريقنا هذه المعلومات.",
licenseNumber: "رقم رخصة السوق",
licenseNumberPlaceholder: "كما هو مدوّن على الرخصة",
licenseExpiry: "تاريخ انتهاء الرخصة",
nationalId: "رقم الهوية",
nationalIdPlaceholder: "رقم بطاقة الهوية",
plateNumber: "رقم اللوحة",
plateNumberPlaceholder: "مثال: 123456/B",
reviewNote:
"يبقى حسابك غير متصل إلى أن تتم الموافقة عليه، وعادةً ما يستغرق ذلك أقل من يوم.",
submit: "إرسال للمراجعة",
errorTitle: "راجع معلوماتك",
errorMissing: "رقم الرخصة ورقم الهوية ورقم اللوحة كلها مطلوبة.",
errorExpiryFormat: "أدخل تاريخ انتهاء الرخصة بصيغة YYYY-MM-DD.",
errorExpired: "هذه الرخصة منتهية الصلاحية.",
errorScanRequired: "صوّر رخصة السوق قبل الإرسال.",
alertResubmitBody: "تعذّر إعادة إرسال معلوماتك. حاول مرة أخرى.",
},
captureUnavailable:
"التقاط الصور غير متوفّر في هذه النسخة من التطبيق. حدّث التطبيق إلى آخر إصدار وحاول مجددًا.",
photo: {
title: "صورتك",
hint: "تُلتقط الآن بالكاميرا، لا من معرض الصور. يراها الركاب بجانب اسمك عند اختيار السائق، ويتأكدون بها أنك أنت عند نقطة الانطلاق. انظر إلى الكاميرا في إضاءة جيدة.",
take: "التقط صورة",
retake: "أعد الالتقاط",
required: "التقط صورة شخصية قبل الإرسال.",
permissionTitle: "الإذن مطلوب",
permissionCamera:
"يحتاج وصيل إلى الكاميرا لالتقاط صورتك. اسمح بالوصول إلى الكاميرا للمتابعة.",
permissionCameraBlocked:
"الوصول إلى الكاميرا معطّل لتطبيق وصيل، ولن يسألك أندرويد مرة أخرى من هنا. افتح الإعدادات ثم فعّل «الكاميرا» ضمن الأذونات.",
errorTitle: "تعذّر حفظ الصورة",
errorBody: "حدث خطأ ما. حاول مرة أخرى.",
errorTooLarge: "الصورة كبيرة جدًا. جرّب التقاط صورة جديدة.",
errorRateLimit: "عدد المحاولات كبير. انتظر بضع دقائق وحاول مجددًا.",
errorUnsupported: "استخدم صورة بصيغة JPEG أو PNG أو WebP.",
},
scan: {
licenseLabel: "رخصة السوق",
licenseHint:
"ضعها على سطح مستوٍ واملأ بها الإطار. نقرأ منها الرقم وتاريخ الانتهاء.",
idLabel: "بطاقة الهوية",
idHint: "الوجه الذي يظهر فيه رقم الهوية.",
vehicle_regLabel: "رخصة سير السيارة",
vehicle_regHint: "الصفحة التي يظهر فيها رقم اللوحة ونوع السيارة.",
optional: "اختياري",
take: "التقط صورة",
retake: "أعد التصوير",
choose: "اختر صورة",
reading: "نقرأ المستند…",
filled: {
one: "عبّأنا معلومة واحدة — راجعها أدناه.",
other: "عبّأنا {n} معلومات — راجعها أدناه.",
},
savedNoFields:
"حفظنا الصورة، لكن تعذّرت قراءة المعلومات. أدخلها يدويًا أدناه.",
savedUnreadable:
"حفظنا الصورة. خدمة القراءة غير متوفّرة حاليًا — أدخل المعلومات يدويًا أدناه.",
alreadyOnFile: "لدينا صورة محفوظة مسبقًا. أعد التصوير عند الحاجة فقط.",
allRead: "قرأناها من أوراقك",
missingPrompt:
"تعذّرت قراءة هذه المعلومات من أوراقك. أضفها وينتهي الأمر.",
edit: "راجع المعلومات أو عدّلها",
done: "تم",
checkPrompt: "صحّح أي معلومة قُرئت خطأً، ثم اضغط تم.",
permissionTitle: "الإذن مطلوب",
permissionCamera:
"اسمح بالوصول إلى الكاميرا لتصوير أوراقك، أو اختر صورة موجودة بدلًا من ذلك.",
permissionCameraBlocked:
"الوصول إلى الكاميرا معطّل لتطبيق وصيل، ولن يسألك أندرويد مرة أخرى من هنا. افتح الإعدادات وفعّل «الكاميرا» ضمن الأذونات، أو اختر صورة موجودة بدلًا من ذلك.",
permissionLibrary: "اسمح بالوصول إلى الصور لاختيار صورة لأوراقك.",
permissionLibraryBlocked:
"الوصول إلى الصور معطّل لتطبيق وصيل، ولن يسألك أندرويد مرة أخرى من هنا. افتح الإعدادات وفعّل «الصور» ضمن الأذونات، أو التقط صورة بالكاميرا بدلًا من ذلك.",
errorTitle: "تعذّرت القراءة",
errorBody: "حدث خطأ ما. حاول مجددًا أو أدخل المعلومات يدويًا أدناه.",
errorTooLarge: "الصورة كبيرة جدًا. جرّب التقاط صورة جديدة.",
errorRateLimit: "عدد المحاولات كبير. انتظر بضع دقائق وحاول مجددًا.",
errorUnsupported: "استخدم صورة بصيغة JPEG أو PNG أو WebP.",
errorRetry: "لم يتم الرفع. حاول مجددًا أو أدخل المعلومات يدويًا أدناه.",
},
review: {
pendingTitle: "قيد المراجعة",
pendingBody:
"نراجع معلوماتك الآن. ستتمكّن من الاتصال فور الموافقة على حسابك.",
rejectedTitle: "لم تتم الموافقة",
rejectedBody: "لم تجتز معلوماتك المراجعة. صحّحها أدناه وأعد إرسالها.",
suspendedTitle: "الحساب موقوف",
suspendedBody:
"تم إيقاف حساب السائق الخاص بك. تواصل مع الدعم لمعالجة الأمر.",
approvedTitle: "تمت الموافقة",
approvedBody: "أنت جاهز للعمل.",
reasonLabel: "السبب",
checkAgain: "تحقّق مجددًا",
resubmitTitle: "صحّح معلوماتك",
resubmitIntro: "صحّح ما هو خاطئ وسنراجعه من جديد.",
resubmit: "إعادة الإرسال",
},
offerCard: {
youEarn: "أرباحك",
newRequest: "طلب جديد · {service}",
openFor: "متاح لمدة",
seconds: "{n} ث",
awayFromPickup: "{km} كم عن نقطة الصعود",
firstIn: "ستكون الأول",
rivals: {
one: "سائق آخر تقدّم",
other: "{n} سائقين آخرين تقدّموا",
zero: "ستكون الأول",
},
cash: "💵 نقدًا",
card: "💳 بطاقة",
fromAlt: "من",
toAlt: "إلى",
tripTime: "زمن الرحلة",
fare: "الأجرة",
decline: "رفض",
accept: "قبول",
offer: "تقدّم لهذه الرحلة",
withdraw: "سحب عرضي",
waitingOnRider: "تم التقديم — بانتظار اختيار الراكب",
lostTitle: "أُغلق الطلب",
lostBody:
"اختار الراكب سائقًا آخر، أو انتهت مهلة الطلب. أنت متاح للطلب التالي.",
alertOfferBody: "تعذّر إرسال عرضك. حاول مرة أخرى.",
alertWithdrawBody: "تعذّر سحب عرضك. حاول مرة أخرى.",
},
activeRide: {
youEarn: "أرباحك",
headToPickup: "اتجه إلى نقطة الصعود",
tripInProgress: "الرحلة جارية",
rider: "{name}",
pickupPin: "موقع صعود الراكب",
dropoffPin: "نقطة النزول",
navigateToPickup: "التوجّه إلى نقطة الصعود",
navigateToDropoff: "التوجّه إلى نقطة النزول",
alertNavigateBody: "تعذّر فتح تطبيق ملاحة على هذا الهاتف.",
fromAlt: "من",
toAlt: "إلى",
fare: "الأجرة",
message: "رسالة",
call: "اتصال",
startTrip: "ابدأ الرحلة",
completeTrip: "أنهِ الرحلة",
cancelRide: "إلغاء الرحلة",
cancelConfirmTitle: "إلغاء هذه الرحلة؟",
cancelConfirmBody: "سيتم إخطار الراكب وستُعلَّم الرحلة كملغاة.",
cancelConfirmDismiss: "الاحتفاظ بالرحلة",
cancelConfirmConfirm: "إلغاء الرحلة",
alertErrorTitle: "خطأ",
alertAcceptBody: "تعذّر قبول هذه الرحلة. ربما حُجزت أو انتهت صلاحيتها.",
alertDeclineBody: "تعذّر رفض هذه الرحلة. حاول مرة أخرى.",
alertUpdateBody: "تعذّر تحديث الرحلة. حاول مرة أخرى.",
alertCancelBody: "تعذّر إلغاء الرحلة. حاول مرة أخرى.",
imHere: "لقد وصلت",
atPickup: "عند نقطة الصعود — بانتظار الراكب",
askForCode: "اطلب من الراكب رمز الصعود المكوّن من 4 أرقام.",
cashConfirmTitle: "تحصيل الأجرة",
cashConfirmBody: "هل حصّلت ${amount} نقدًا من الراكب؟",
cashCollected: "نعم، حصّلتها",
cashNotCollected: "لم أحصّلها",
},
},
rating: {
rateDriverTitle: "كيف كانت رحلتك مع {name}؟",
rateRiderTitle: "كيف كان {name} كراكب؟",
subtitle: "تقييمك يبقى خاصًا ولا يُعرض للطرف الآخر.",
starLabel: "{n} نجوم",
commentPlaceholder: "أضف تعليقًا (اختياري)",
submit: "إرسال التقييم",
notNow: "ليس الآن",
error: "تعذّر إرسال تقييمك. حاول مرة أخرى.",
},
cancelSheet: {
title: "إلغاء هذه الرحلة؟",
subtitleRider: "أخبرنا بالسبب لتحسين المطابقة.",
subtitleDriver: "سيتم إخطار الراكب وستُعلَّم الرحلة كملغاة.",
confirm: "إلغاء الرحلة",
keepRide: "الاحتفاظ بالرحلة",
cancelling: "جارٍ الإلغاء…",
reasons: {
changed_mind: "غيّرت رأيي",
wait_too_long: "الانتظار طويل جدًا",
wrong_address: "عنوان صعود خاطئ",
driver_no_show: "السائق لم يصل",
rider_no_show: "الراكب لم يحضر",
unreachable: "تعذّر التواصل معه",
vehicle_issue: "مشكلة في المركبة",
other: "سبب آخر",
},
},
pickupCode: {
title: "ابدأ الرحلة",
subtitle: "أدخل الرمز المكوّن من 4 أرقام من شاشة الراكب.",
startTrip: "ابدأ الرحلة",
wrongCode: "الرمز غير مطابق. تحقّق مع الراكب.",
},
services: {
nearbyCount: "{n} قريب",
noneNearby: "لا يوجد قريب",
car: { label: "سيارة", tagline: "رحلة يومية، حتى 4 مقاعد." },
moto: { label: "موتور", tagline: "تجنّب الزحام — راكب واحد، بدون أمتعة." },
courier: {
@@ -374,6 +672,16 @@ export const ar = {
"الخريطة غير متاحة على الويب.\nافتح التطبيق على أندرويد أو iOS للتجربة الكاملة.",
},
rideCard: {
outcomeCompleted: "مكتملة",
outcomeCancelled: "ملغاة",
outcomeExpired: "لم يتم العثور على سائق",
cancelledByYou: "ألغيتها",
cancelledByDriver: "ألغاها السائق",
cancelledBySystem: "لا يوجد سائق متاح",
noDriver: "لم يُعيَّن سائق",
paymentNotCharged: "لم يتم الخصم",
paymentRefundDue: "مستحق الاسترداد",
paymentCashCollected: "دُفعت نقدًا",
mapAlt: "خريطة",
originAlt: "المصدر",
destinationAlt: "الوجهة",
@@ -470,6 +778,9 @@ export const ar = {
rtlRestartBody:
"سيُطبَّق التخطيط العربي بالكامل في المرة القادمة التي تفتح فيها التطبيق.",
},
general: {
title: "عام",
},
keepAwake: {
title: "عدم قفل الشاشة",
description: "إبقاء الشاشة مضاءة أثناء فتح التطبيق.",
+322 -3
View File
@@ -136,6 +136,9 @@ export const en = {
recentRides: "Recent Rides",
noRecent: "No recent rides found.",
noRecentAlt: "No recent rides found",
activeRideWithDriver: "{name} is on the way",
rateLastRide: "How was your last ride?",
rate: "Rate",
},
rides: {
@@ -156,7 +159,38 @@ export const en = {
title: "Chat",
messageAlt: "message",
noMessages: "No Messages Yet",
startConversation: "Start a conversation with your friends and family",
startConversation: "Messages open with your driver once a ride is matched.",
inputPlaceholder: "Message…",
send: "Send",
loadError: "Couldn't load messages. Pull to retry.",
sendError: "Couldn't send message. Try again.",
cannotMessage: "This ride is no longer active.",
call: "Call",
},
call: {
incoming: "Incoming call",
outgoing: "Calling…",
connecting: "Connecting…",
inCall: "In call",
ended: "Call ended",
missed: "Missed call",
declined: "Call declined",
failed: "Call failed",
unavailable: "No active ride to call.",
accept: "Accept",
decline: "Decline",
end: "End call",
mute: "Mute",
unmute: "Unmute",
speaker: "Speaker",
speakerOff: "Speaker off",
cancel: "Cancel",
connectingWith: "Connecting with {name}…",
micDeniedTitle: "Microphone blocked",
micDeniedBody:
"Waseel needs microphone access to make calls. Enable it in Settings.",
audioFailed: "Couldn't start audio. Please try again.",
},
profile: {
@@ -170,14 +204,34 @@ export const en = {
emailPlaceholder: "Your Email address",
},
adjustPin: {
pickupLabel: "Pickup point",
destinationLabel: "Drop-off point",
locating: "Finding this place…",
hint: "Drag the map to move the pin exactly where you want it.",
confirmPickup: "Confirm pickup point",
confirmDestination: "Confirm drop-off point",
recenter: "Go to my location",
},
findRide: {
adjustOnMap: "Set it on the map",
title: "Ride",
from: "From",
to: "To",
findNow: "Find now",
service: "Ride type",
nAvailable: "{n} nearby",
estimatedFare: "Estimated fare",
setBothPoints: "Set a pickup and destination",
payLaterHint:
"Drivers nearby will see your request. You choose who takes it, and pay after.",
sending: "Sending your request…",
},
confirmRide: {
noDriversInRadius: "No {service} drivers within {km} km",
tryInstead: "Available near you right now:",
title: "Request Ride",
yourTrip: "Your trip",
pickup: "Pickup",
@@ -190,6 +244,13 @@ export const en = {
lbpEstimate: "≈ {lbp}",
noDrivers: "No {service} drivers online right now",
findingDrivers: "Finding drivers nearby…",
driversNearby: {
one: "1 driver nearby",
other: "{n} drivers nearby",
zero: "No drivers nearby",
},
withinRadius: "Within {km} km of you",
searchingRadius: "Searching within {km} km…",
nearestDriver: "Nearest driver ≈ {eta} min away",
requesting: "Requesting…",
noDriversOnline: "No drivers online",
@@ -204,20 +265,61 @@ export const en = {
"Something went wrong while booking your ride. Please try again.",
alertPayCardTitle: "Pay by card",
alertPayCardBody: "Your card will be charged ${fare}.",
alertInProgressTitle: "Ride already in progress",
alertInProgressBody:
"You have a ride in progress. Finish or cancel it before booking another.",
viewRide: "View ride",
},
bookRide: {
status: {
requested: "Finding your driver…",
choosing: "Choose your driver",
accepted: "Driver assigned — heading to you",
enRoute: "On your trip",
completed: "You've arrived!",
cancelled: "Ride cancelled",
arrived: "Your driver is here",
expired: "No driver available",
},
rideNotFound: "Ride not found.",
couldNotLoad: "Could not load this ride.",
backHome: "Back Home",
matchingDriver: "We're matching you with the nearest {service} driver.",
searchingFor: "Searching for {seconds}s",
match: {
driverFallback: "Your driver",
alertBody: "Something went wrong. Please try again.",
},
offers: {
title: "Drivers available",
count: {
one: "1 offer",
other: "{n} offers",
zero: "No offers yet",
},
away: "{eta} min away · {distance}",
seats: {
one: "1 seat",
other: "{n} seats",
zero: "",
},
pick: "Choose",
goneTitle: "That driver is gone",
goneBody: "They took another ride. Pick someone else from the list.",
goneBodyPaid:
"They took another ride. Your payment hasn't been used — pick someone else and it will go to them.",
},
payment: {
title: "How would you like to pay?",
titleNamed: "Ride with {name}",
subtitle: "Fare ${fare}",
cash: "Pay cash",
cashHint: "Hand the fare to your driver at drop-off.",
card: "Pay by card",
cardHint: "Charged now, before your driver sets off.",
working: "Working…",
},
ratingFallback: "—",
paymentCash: "💵 Cash to driver",
paymentCard: "💳 Paid by card",
@@ -228,10 +330,26 @@ export const en = {
cancelling: "Cancelling…",
alertErrorTitle: "Error",
alertErrorBody: "Could not cancel this ride. Please try again.",
pickupCodeLabel: "Your pickup code",
pickupCodeHint: "Give this to your driver to start the trip.",
driverHere: "Your driver is outside",
cashDue: "Pay ${amount} in cash to your driver.",
youRated: "You rated this ride {n}★",
rateDriver: "Rate your driver",
noDriversFound:
"No driver picked up your request. Nothing was charged — try again in a moment.",
cancelledByDriver: "Your driver cancelled this ride.",
enRouteNotice:
"Enjoy your ride — your driver will end the trip on arrival.",
},
driver: {
home: {
owesCompany: "Commission you owe",
owesCompanyHint: "Your cash rides — hand this in at the office.",
owedToDriver: "The company owes you",
owedToDriverHint: "Card rides, paid out to you.",
afterFee: "after ${fee} platform fee",
signOutAlt: "Sign out",
driverMode: "Driver mode",
online: "● Online — receiving ride requests",
@@ -240,6 +358,7 @@ export const en = {
completedToday: "Completed today",
incomingRequests: "Incoming requests",
incomingRequestsOffline: "Incoming requests (offline)",
finishCurrentRide: "Finish your current ride to see new requests.",
waitingRequests: "Waiting for ride requests…",
goOnlineStart: "Go online to start driving.",
welcome: "Welcome, {name}",
@@ -260,36 +379,223 @@ export const en = {
"Could not create your driver profile. Please try again.",
alertToggleBody: "Could not change your status. Please try again.",
noRequestsAlt: "No recent rides found",
cashInHand: "Cash collected today",
uncollected: "Uncollected fares today",
ratingCount: "{n} ratings",
ratingNew: "New driver",
alertOfflineBlocked:
"Finish or cancel your current ride before going offline.",
},
credentials: {
title: "Your credentials",
intro:
"We check every driver before they can take a ride. These details are reviewed by our team.",
licenseNumber: "Driving licence number",
licenseNumberPlaceholder: "As printed on your licence",
licenseExpiry: "Licence expiry",
nationalId: "National ID number",
nationalIdPlaceholder: "Your ID card number",
plateNumber: "Plate number",
plateNumberPlaceholder: "e.g. 123456/B",
reviewNote:
"Your account stays offline until a reviewer approves it. This usually takes less than a day.",
submit: "Submit for review",
errorTitle: "Check your details",
errorMissing:
"Licence number, national ID and plate number are all required.",
errorExpiryFormat: "Enter the licence expiry as YYYY-MM-DD.",
errorExpired: "That licence has already expired.",
errorScanRequired: "Scan your driving licence before submitting.",
alertResubmitBody: "Could not resubmit your details. Please try again.",
},
captureUnavailable:
"Photo capture isn't available in this version of the app. Please update to the latest version and try again.",
photo: {
title: "Your photo",
hint: "Taken now with the camera, not from your gallery. Riders see it next to your name when they pick a driver, and use it to check it's you at pickup. Face the camera in good light.",
take: "Take photo",
retake: "Retake",
required: "Take a profile photo before submitting.",
permissionTitle: "Permission needed",
permissionCamera:
"Waseel needs the camera to take your photo. Allow camera access to continue.",
permissionCameraBlocked:
"Camera access is turned off for Waseel, and Android won't ask again from here. Open Settings, then turn on Camera under Permissions.",
errorTitle: "Couldn't save that photo",
errorBody: "Something went wrong. Please try again.",
errorTooLarge: "That photo is too large. Try taking a new one.",
errorRateLimit: "Too many uploads. Wait a few minutes and try again.",
errorUnsupported: "Use a JPEG, PNG or WebP photo.",
},
scan: {
licenseLabel: "Driving licence",
licenseHint:
"Lay it flat and fill the frame. We read the number and expiry off it.",
idLabel: "ID card",
idHint: "The side showing your ID number.",
vehicle_regLabel: "Vehicle registration",
vehicle_regHint: "The page showing the plate number and the car model.",
optional: "Optional",
take: "Take photo",
retake: "Rescan",
choose: "Choose photo",
reading: "Reading your document…",
filled: {
one: "Filled in 1 detail — check it below.",
other: "Filled in {n} details — check them below.",
},
savedNoFields:
"Photo saved, but we couldn't read the details. Type them in below.",
savedUnreadable:
"Photo saved. Scanning is unavailable right now — type the details in below.",
alreadyOnFile: "A scan is already on file. Rescan only if you need to.",
allRead: "Read from your documents",
missingPrompt:
"We couldn't read these off your documents. Please add them and you're done.",
edit: "Check or edit details",
done: "Done",
checkPrompt: "Correct anything that was read wrongly, then tap Done.",
permissionTitle: "Permission needed",
permissionCamera:
"Allow camera access to photograph your documents, or choose a photo instead.",
permissionCameraBlocked:
"Camera access is turned off for Waseel, and Android won't ask again from here. Open Settings and turn on Camera under Permissions — or choose an existing photo instead.",
permissionLibrary:
"Allow photo access to pick a picture of your documents.",
permissionLibraryBlocked:
"Photo access is turned off for Waseel, and Android won't ask again from here. Open Settings and turn on Photos under Permissions — or take a photo with the camera instead.",
errorTitle: "Couldn't scan that",
errorBody:
"Something went wrong. Try again, or type the details in below.",
errorTooLarge: "That photo is too large. Try taking a new one.",
errorRateLimit: "Too many scans. Wait a few minutes and try again.",
errorUnsupported: "Use a JPEG, PNG or WebP photo.",
errorRetry: "Not uploaded. Try again, or type the details in below.",
},
review: {
pendingTitle: "Under review",
pendingBody:
"We're checking your details. You'll be able to go online as soon as you're approved.",
rejectedTitle: "Not approved",
rejectedBody:
"Your details didn't pass review. Correct them below and submit again.",
suspendedTitle: "Account suspended",
suspendedBody:
"Your driver account has been suspended. Contact support to sort this out.",
approvedTitle: "Approved",
approvedBody: "You're cleared to drive.",
reasonLabel: "Reason",
checkAgain: "Check again",
resubmitTitle: "Correct your details",
resubmitIntro: "Fix what's wrong and we'll review it again.",
resubmit: "Submit again",
},
offerCard: {
youEarn: "You earn",
newRequest: "New request · {service}",
openFor: "On the board for",
seconds: "{n}s",
awayFromPickup: "{km} km from pickup",
firstIn: "You'd be first",
rivals: {
one: "1 other driver offered",
other: "{n} other drivers offered",
zero: "You'd be first",
},
cash: "💵 Cash",
card: "💳 Card",
fromAlt: "From",
toAlt: "To",
tripTime: "Trip time",
fare: "Fare",
decline: "Decline",
accept: "Accept",
offer: "Offer this ride",
withdraw: "Withdraw my offer",
waitingOnRider: "Offered — waiting for the rider to choose",
lostTitle: "Request closed",
lostBody:
"The rider went with another driver, or the request timed out. You're free for the next one.",
alertOfferBody: "Could not send your offer. Please try again.",
alertWithdrawBody: "Could not withdraw your offer. Please try again.",
},
activeRide: {
youEarn: "You earn",
headToPickup: "Head to pickup",
tripInProgress: "Trip in progress",
rider: "{name}",
pickupPin: "Rider pickup",
dropoffPin: "Drop-off",
navigateToPickup: "Navigate to pickup",
navigateToDropoff: "Navigate to drop-off",
alertNavigateBody: "Could not open a navigation app on this phone.",
fromAlt: "From",
toAlt: "To",
fare: "Fare",
message: "Message",
call: "Call",
startTrip: "Start trip",
completeTrip: "Complete trip",
cancelRide: "Cancel ride",
cancelConfirmTitle: "Cancel this ride?",
cancelConfirmBody:
"The rider will be notified and the ride will be marked as cancelled.",
cancelConfirmDismiss: "Keep ride",
cancelConfirmConfirm: "Cancel ride",
alertErrorTitle: "Error",
alertAcceptBody:
"Could not accept this ride. It may have been taken or expired.",
alertDeclineBody: "Could not decline this ride. Please try again.",
alertUpdateBody: "Could not update the ride. Please try again.",
alertCancelBody: "Could not cancel the ride. Please try again.",
imHere: "I've arrived",
atPickup: "At pickup — waiting for rider",
askForCode: "Ask the rider for their 4-digit pickup code.",
cashConfirmTitle: "Collect the fare",
cashConfirmBody: "Did you collect ${amount} in cash from the rider?",
cashCollected: "Yes, collected",
cashNotCollected: "Not collected",
},
},
rating: {
rateDriverTitle: "How was your ride with {name}?",
rateRiderTitle: "How was {name} as a passenger?",
subtitle: "Your rating stays private to the other person.",
starLabel: "{n} stars",
commentPlaceholder: "Add a comment (optional)",
submit: "Submit rating",
notNow: "Not now",
error: "Could not submit your rating. Please try again.",
},
cancelSheet: {
title: "Cancel this ride?",
subtitleRider: "Tell us why so we can improve matching.",
subtitleDriver: "The rider will be notified and the ride marked cancelled.",
confirm: "Cancel ride",
keepRide: "Keep ride",
cancelling: "Cancelling…",
reasons: {
changed_mind: "I changed my mind",
wait_too_long: "The wait is too long",
wrong_address: "Wrong pickup address",
driver_no_show: "The driver never arrived",
rider_no_show: "The rider never showed up",
unreachable: "I couldn't reach them",
vehicle_issue: "Vehicle problem",
other: "Another reason",
},
},
pickupCode: {
title: "Start the trip",
subtitle: "Enter the 4-digit code from the rider's screen.",
startTrip: "Start trip",
wrongCode: "That code doesn't match. Check with the rider.",
},
services: {
nearbyCount: "{n} nearby",
noneNearby: "None nearby",
car: { label: "Car", tagline: "An everyday ride, up to 4 seats." },
moto: {
label: "Moto",
@@ -385,6 +691,16 @@ export const en = {
"Map is not available on web.\nRun on Android/iOS for the full experience.",
},
rideCard: {
outcomeCompleted: "Completed",
outcomeCancelled: "Cancelled",
outcomeExpired: "No driver found",
cancelledByYou: "You cancelled",
cancelledByDriver: "Driver cancelled",
cancelledBySystem: "No driver available",
noDriver: "No driver assigned",
paymentNotCharged: "Not charged",
paymentRefundDue: "Refund due",
paymentCashCollected: "Cash paid",
mapAlt: "Map",
originAlt: "Origin",
destinationAlt: "Destination",
@@ -485,6 +801,9 @@ export const en = {
rtlRestartBody:
"Arabic layout will apply fully the next time you open the app.",
},
general: {
title: "General",
},
keepAwake: {
title: "Do not lock screen",
description: "Keep the display on while the app is open.",
+330 -3
View File
@@ -138,6 +138,9 @@ export const fr = {
recentRides: "Courses récentes",
noRecent: "Aucune course récente.",
noRecentAlt: "Aucune course récente",
activeRideWithDriver: "{name} arrive",
rateLastRide: "Comment s'est passée votre dernière course ?",
rate: "Noter",
},
rides: {
@@ -159,7 +162,38 @@ export const fr = {
messageAlt: "message",
noMessages: "Pas encore de messages",
startConversation:
"Démarrez une conversation avec vos amis et votre famille",
"La conversation s'ouvre avec votre chauffeur une fois la course attribuée.",
inputPlaceholder: "Message…",
send: "Envoyer",
loadError: "Impossible de charger les messages. Tirez pour réessayer.",
sendError: "Impossible d'envoyer le message. Réessayez.",
cannotMessage: "Cette course n'est plus active.",
call: "Appeler",
},
call: {
incoming: "Appel entrant",
outgoing: "Appel en cours…",
connecting: "Connexion…",
inCall: "En appel",
ended: "Appel terminé",
missed: "Appel manqué",
declined: "Appel refusé",
failed: "Échec de l'appel",
unavailable: "Aucune course active à appeler.",
accept: "Accepter",
decline: "Refuser",
end: "Terminer l'appel",
mute: "Muet",
unmute: "Activer le micro",
speaker: "Haut-parleur",
speakerOff: "Haut-parleur off",
cancel: "Annuler",
connectingWith: "Connexion à {name}…",
micDeniedTitle: "Microphone bloqué",
micDeniedBody:
"Waseel a besoin du microphone pour passer des appels. Activez-le dans les réglages.",
audioFailed: "Impossible de démarrer l'audio. Réessayez.",
},
profile: {
@@ -173,14 +207,35 @@ export const fr = {
emailPlaceholder: "Votre adresse e-mail",
},
adjustPin: {
pickupLabel: "Point de départ",
destinationLabel: "Point de dépose",
locating: "Localisation en cours…",
hint: "Faites glisser la carte pour placer le repère exactement où vous voulez.",
confirmPickup: "Confirmer le départ",
confirmDestination: "Confirmer la dépose",
recenter: "Aller à ma position",
},
findRide: {
adjustOnMap: "Placer sur la carte",
title: "Course",
from: "De",
to: "À",
findNow: "Rechercher",
service: "Type de course",
nAvailable: "{n} à proximité",
estimatedFare: "Tarif estimé",
setBothPoints: "Indiquez un départ et une destination",
payLaterHint:
"Les chauffeurs proches verront votre demande. Vous choisissez qui vous prend, et payez ensuite.",
sending: "Envoi de votre demande…",
},
confirmRide: {
noDriversInRadius: "Aucun chauffeur {service} dans un rayon de {km} km",
tryInstead: "Disponible près de vous maintenant :",
searchingRadius: "Recherche dans un rayon de {km} km…",
title: "Demander une course",
yourTrip: "Votre trajet",
pickup: "Départ",
@@ -193,6 +248,12 @@ export const fr = {
lbpEstimate: "≈ {lbp}",
noDrivers: "Aucun chauffeur {service} en ligne pour l'instant",
findingDrivers: "Recherche de chauffeurs à proximité…",
driversNearby: {
one: "1 chauffeur à proximité",
other: "{n} chauffeurs à proximité",
zero: "Aucun chauffeur à proximité",
},
withinRadius: "Dans un rayon de {km} km",
nearestDriver: "Chauffeur le plus proche ≈ {eta} min",
requesting: "Demande en cours…",
noDriversOnline: "Aucun chauffeur en ligne",
@@ -208,21 +269,63 @@ export const fr = {
"Une erreur est survenue lors de la réservation. Réessayez.",
alertPayCardTitle: "Payer par carte",
alertPayCardBody: "Votre carte sera débitée de ${fare}.",
alertInProgressTitle: "Course déjà en cours",
alertInProgressBody:
"Vous avez une course en cours. Terminez-la ou annulez-la avant d'en réserver une autre.",
viewRide: "Voir la course",
},
bookRide: {
status: {
requested: "Recherche de votre chauffeur…",
choosing: "Choisissez votre chauffeur",
accepted: "Chauffeur assigné — en route vers vous",
enRoute: "Course en cours",
completed: "Vous êtes arrivé !",
cancelled: "Course annulée",
arrived: "Votre chauffeur est arrivé",
expired: "Aucun chauffeur disponible",
},
rideNotFound: "Course introuvable.",
couldNotLoad: "Chargement de cette course impossible.",
backHome: "Retour à l'accueil",
matchingDriver:
"Nous vous mettons en relation avec le chauffeur {service} le plus proche.",
searchingFor: "Recherche depuis {seconds} s",
match: {
driverFallback: "Votre chauffeur",
alertBody: "Une erreur est survenue. Réessayez.",
},
offers: {
title: "Chauffeurs disponibles",
count: {
one: "1 proposition",
other: "{n} propositions",
zero: "Aucune proposition",
},
away: "{eta} min · {distance}",
seats: {
one: "1 place",
other: "{n} places",
zero: "",
},
pick: "Choisir",
goneTitle: "Ce chauffeur n'est plus libre",
goneBody:
"Il a pris une autre course. Choisissez-en un autre dans la liste.",
goneBodyPaid:
"Il a pris une autre course. Votre paiement n'a pas été utilisé — choisissez-en un autre et il lui sera versé.",
},
payment: {
title: "Comment souhaitez-vous payer ?",
titleNamed: "Course avec {name}",
subtitle: "Tarif ${fare}",
cash: "Payer en espèces",
cashHint: "Réglez la course au chauffeur à l'arrivée.",
card: "Payer par carte",
cardHint: "Débité maintenant, avant le départ du chauffeur.",
working: "En cours…",
},
ratingFallback: "—",
paymentCash: "💵 Espèces au chauffeur",
paymentCard: "💳 Payé par carte",
@@ -233,10 +336,26 @@ export const fr = {
cancelling: "Annulation…",
alertErrorTitle: "Erreur",
alertErrorBody: "Annulation de cette course impossible. Réessayez.",
pickupCodeLabel: "Votre code de prise en charge",
pickupCodeHint: "Donnez-le à votre chauffeur pour démarrer la course.",
driverHere: "Votre chauffeur est dehors",
cashDue: "Payez ${amount} en espèces à votre chauffeur.",
youRated: "Vous avez noté cette course {n}★",
rateDriver: "Noter votre chauffeur",
noDriversFound:
"Aucun chauffeur n'a accepté votre demande. Rien n'a été débité — réessayez dans un instant.",
cancelledByDriver: "Votre chauffeur a annulé cette course.",
enRouteNotice:
"Bonne route — votre chauffeur terminera la course à l'arrivée.",
},
driver: {
home: {
owesCompany: "Commission que vous devez",
owesCompanyHint: "Vos courses en espèces — à remettre au bureau.",
owedToDriver: "L'entreprise vous doit",
owedToDriverHint: "Courses par carte, à vous verser.",
afterFee: "après ${fee} de commission",
signOutAlt: "Déconnexion",
driverMode: "Mode chauffeur",
online: "● En ligne — réception des demandes",
@@ -245,6 +364,8 @@ export const fr = {
completedToday: "Terminées aujourd'hui",
incomingRequests: "Demandes entrantes",
incomingRequestsOffline: "Demandes entrantes (hors ligne)",
finishCurrentRide:
"Terminez votre course en cours pour voir les nouvelles demandes.",
waitingRequests: "En attente de demandes…",
goOnlineStart: "Passez en ligne pour commencer à rouler.",
welcome: "Bienvenue, {name}",
@@ -264,36 +385,229 @@ export const fr = {
alertCreateBody: "Création du profil chauffeur impossible. Réessayez.",
alertToggleBody: "Changement de statut impossible. Réessayez.",
noRequestsAlt: "Aucune course récente",
cashInHand: "Espèces encaissées aujourd'hui",
uncollected: "Courses non encaissées aujourd'hui",
ratingCount: "{n} évaluations",
ratingNew: "Nouveau chauffeur",
alertOfflineBlocked:
"Terminez ou annulez votre course en cours avant de passer hors ligne.",
},
credentials: {
title: "Vos documents",
intro:
"Chaque chauffeur est vérifié avant sa première course. Notre équipe examine ces informations.",
licenseNumber: "Numéro de permis de conduire",
licenseNumberPlaceholder: "Tel qu'inscrit sur le permis",
licenseExpiry: "Expiration du permis",
nationalId: "Numéro de carte d'identité",
nationalIdPlaceholder: "Votre numéro d'identité",
plateNumber: "Numéro de plaque",
plateNumberPlaceholder: "ex. 123456/B",
reviewNote:
"Votre compte reste hors ligne jusqu'à validation, généralement en moins d'une journée.",
submit: "Envoyer pour vérification",
errorTitle: "Vérifiez vos informations",
errorMissing:
"Le numéro de permis, la carte d'identité et la plaque sont tous obligatoires.",
errorExpiryFormat:
"Saisissez l'expiration du permis au format AAAA-MM-JJ.",
errorExpired: "Ce permis est déjà expiré.",
errorScanRequired: "Scannez votre permis de conduire avant d'envoyer.",
alertResubmitBody: "Renvoi de vos informations impossible. Réessayez.",
},
captureUnavailable:
"La prise de photo n'est pas disponible dans cette version de l'application. Mettez-la à jour et réessayez.",
photo: {
title: "Votre photo",
hint: "Prise maintenant avec l'appareil photo, pas depuis votre galerie. Les passagers la voient à côté de votre nom au moment de choisir un chauffeur, et s'en servent pour vérifier que c'est bien vous au départ. Regardez l'objectif, dans une bonne lumière.",
take: "Prendre une photo",
retake: "Reprendre",
required: "Prenez une photo de profil avant d'envoyer.",
permissionTitle: "Autorisation requise",
permissionCamera:
"Waseel a besoin de l'appareil photo pour prendre votre photo. Autorisez-y l'accès pour continuer.",
permissionCameraBlocked:
"L'accès à l'appareil photo est désactivé pour Waseel, et Android ne le redemandera plus depuis ici. Ouvrez les réglages, puis activez Appareil photo dans les autorisations.",
errorTitle: "Photo non enregistrée",
errorBody: "Une erreur s'est produite. Réessayez.",
errorTooLarge: "Cette photo est trop lourde. Prenez-en une nouvelle.",
errorRateLimit: "Trop d'envois. Attendez quelques minutes et réessayez.",
errorUnsupported: "Utilisez une photo JPEG, PNG ou WebP.",
},
scan: {
licenseLabel: "Permis de conduire",
licenseHint:
"Posez-le à plat et remplissez le cadre. Nous y lisons le numéro et l'expiration.",
idLabel: "Carte d'identité",
idHint: "La face où figure votre numéro d'identité.",
vehicle_regLabel: "Carte grise",
vehicle_regHint:
"La page où figurent le numéro de plaque et le modèle du véhicule.",
optional: "Facultatif",
take: "Photographier",
retake: "Rescanner",
choose: "Choisir une photo",
reading: "Lecture de votre document…",
filled: {
one: "1 information remplie — vérifiez-la ci-dessous.",
other: "{n} informations remplies — vérifiez-les ci-dessous.",
},
savedNoFields:
"Photo enregistrée, mais les informations n'ont pas pu être lues. Saisissez-les ci-dessous.",
savedUnreadable:
"Photo enregistrée. La lecture est indisponible pour le moment — saisissez les informations ci-dessous.",
alreadyOnFile:
"Un scan est déjà enregistré. Rescannez seulement si nécessaire.",
allRead: "Lu sur vos documents",
missingPrompt:
"Nous n'avons pas pu lire ces informations sur vos documents. Ajoutez-les et c'est terminé.",
edit: "Vérifier ou modifier",
done: "Terminé",
checkPrompt: "Corrigez ce qui a été mal lu, puis appuyez sur Terminé.",
permissionTitle: "Autorisation requise",
permissionCamera:
"Autorisez l'appareil photo pour photographier vos documents, ou choisissez une photo existante.",
permissionCameraBlocked:
"L'accès à l'appareil photo est désactivé pour Waseel, et Android ne le redemandera plus depuis ici. Ouvrez les réglages et activez Appareil photo dans les autorisations — ou choisissez une photo existante.",
permissionLibrary:
"Autorisez l'accès aux photos pour choisir une image de vos documents.",
permissionLibraryBlocked:
"L'accès aux photos est désactivé pour Waseel, et Android ne le redemandera plus depuis ici. Ouvrez les réglages et activez Photos dans les autorisations — ou prenez une photo avec l'appareil photo.",
errorTitle: "Scan impossible",
errorBody:
"Une erreur s'est produite. Réessayez ou saisissez les informations ci-dessous.",
errorTooLarge: "Cette photo est trop lourde. Prenez-en une nouvelle.",
errorRateLimit: "Trop de scans. Attendez quelques minutes et réessayez.",
errorUnsupported: "Utilisez une photo JPEG, PNG ou WebP.",
errorRetry:
"Envoi échoué. Réessayez ou saisissez les informations ci-dessous.",
},
review: {
pendingTitle: "En cours de vérification",
pendingBody:
"Nous vérifions vos informations. Vous pourrez passer en ligne dès validation.",
rejectedTitle: "Non validé",
rejectedBody:
"Vos informations n'ont pas été validées. Corrigez-les ci-dessous et renvoyez-les.",
suspendedTitle: "Compte suspendu",
suspendedBody:
"Votre compte chauffeur a été suspendu. Contactez le support pour régulariser.",
approvedTitle: "Validé",
approvedBody: "Vous êtes autorisé à rouler.",
reasonLabel: "Motif",
checkAgain: "Vérifier à nouveau",
resubmitTitle: "Corrigez vos informations",
resubmitIntro: "Corrigez ce qui ne va pas et nous vérifierons à nouveau.",
resubmit: "Renvoyer",
},
offerCard: {
youEarn: "Vous gagnez",
newRequest: "Nouvelle demande · {service}",
openFor: "Disponible encore",
seconds: "{n} s",
awayFromPickup: "{km} km du point de départ",
firstIn: "Vous seriez le premier",
rivals: {
one: "1 autre chauffeur s'est proposé",
other: "{n} autres chauffeurs se sont proposés",
zero: "Vous seriez le premier",
},
cash: "💵 Espèces",
card: "💳 Carte",
fromAlt: "De",
toAlt: "À",
tripTime: "Durée",
fare: "Tarif",
decline: "Refuser",
accept: "Accepter",
offer: "Proposer cette course",
withdraw: "Retirer ma proposition",
waitingOnRider: "Proposé — en attente du choix du passager",
lostTitle: "Demande close",
lostBody:
"Le passager a choisi un autre chauffeur, ou la demande a expiré. Vous êtes libre pour la suivante.",
alertOfferBody: "Envoi de votre proposition impossible. Réessayez.",
alertWithdrawBody: "Retrait de votre proposition impossible. Réessayez.",
},
activeRide: {
youEarn: "Vous gagnez",
dropoffPin: "Dépose",
navigateToPickup: "Naviguer vers le départ",
navigateToDropoff: "Naviguer vers la dépose",
alertNavigateBody:
"Impossible d'ouvrir une application de navigation sur ce téléphone.",
headToPickup: "Direction le départ",
tripInProgress: "Course en cours",
rider: "{name}",
pickupPin: "Départ du passager",
fromAlt: "De",
toAlt: "À",
fare: "Tarif",
message: "Message",
call: "Appeler",
startTrip: "Démarrer la course",
completeTrip: "Terminer la course",
cancelRide: "Annuler la course",
cancelConfirmTitle: "Annuler cette course ?",
cancelConfirmBody:
"Le passager sera averti et la course sera marquée comme annulée.",
cancelConfirmDismiss: "Garder la course",
cancelConfirmConfirm: "Annuler la course",
alertErrorTitle: "Erreur",
alertAcceptBody:
"Acceptation impossible. La course a peut-être été prise ou a expiré.",
alertDeclineBody: "Refus de la course impossible. Réessayez.",
alertUpdateBody: "Mise à jour de la course impossible. Réessayez.",
alertCancelBody: "Annulation de la course impossible. Réessayez.",
imHere: "Je suis arrivé",
atPickup: "Sur place — en attente du passager",
askForCode: "Demandez au passager son code à 4 chiffres.",
cashConfirmTitle: "Encaisser la course",
cashConfirmBody: "Avez-vous encaissé ${amount} en espèces ?",
cashCollected: "Oui, encaissé",
cashNotCollected: "Non encaissé",
},
},
rating: {
rateDriverTitle: "Comment s'est passée votre course avec {name} ?",
rateRiderTitle: "Comment était {name} comme passager ?",
subtitle: "Votre note reste privée vis-à-vis de l'autre personne.",
starLabel: "{n} étoiles",
commentPlaceholder: "Ajouter un commentaire (facultatif)",
submit: "Envoyer la note",
notNow: "Plus tard",
error: "Envoi de votre note impossible. Réessayez.",
},
cancelSheet: {
title: "Annuler cette course ?",
subtitleRider: "Dites-nous pourquoi pour améliorer nos attributions.",
subtitleDriver:
"Le passager sera averti et la course sera marquée comme annulée.",
confirm: "Annuler la course",
keepRide: "Garder la course",
cancelling: "Annulation…",
reasons: {
changed_mind: "J'ai changé d'avis",
wait_too_long: "L'attente est trop longue",
wrong_address: "Mauvaise adresse de départ",
driver_no_show: "Le chauffeur n'est jamais arrivé",
rider_no_show: "Le passager ne s'est pas présenté",
unreachable: "Impossible de le joindre",
vehicle_issue: "Problème de véhicule",
other: "Autre raison",
},
},
pickupCode: {
title: "Démarrer la course",
subtitle: "Saisissez le code à 4 chiffres affiché chez le passager.",
startTrip: "Démarrer",
wrongCode: "Ce code ne correspond pas. Vérifiez avec le passager.",
},
services: {
nearbyCount: "{n} à proximité",
noneNearby: "Aucun à proximité",
car: {
label: "Voiture",
tagline: "Une course quotidienne, jusqu'à 4 places.",
@@ -392,6 +706,16 @@ export const fr = {
"La carte n'est pas disponible sur le web.\nUtilisez Android ou iOS pour l'expérience complète.",
},
rideCard: {
outcomeCompleted: "Terminée",
outcomeCancelled: "Annulée",
outcomeExpired: "Aucun chauffeur trouvé",
cancelledByYou: "Vous avez annulé",
cancelledByDriver: "Le chauffeur a annulé",
cancelledBySystem: "Aucun chauffeur disponible",
noDriver: "Aucun chauffeur attribué",
paymentNotCharged: "Non débité",
paymentRefundDue: "Remboursement dû",
paymentCashCollected: "Payé en espèces",
mapAlt: "Carte",
originAlt: "Origine",
destinationAlt: "Destination",
@@ -492,6 +816,9 @@ export const fr = {
rtlRestartBody:
"La mise en page arabe s'appliquera pleinement à la prochaine ouverture de l'application.",
},
general: {
title: "Général",
},
keepAwake: {
title: "Ne pas verrouiller l'écran",
description:
+194
View File
@@ -0,0 +1,194 @@
// On-disk storage for the images a driver uploads.
//
// Two kinds, kept in separate directories because they have opposite audiences
// and must never be reachable through each other's route:
//
// "document" — licence, ID card and vehicle registration scans. Identity
// documents, so they are deliberately NOT served from a public static
// directory: every file gets an unguessable name, is written outside the
// web root, and is read back only through /(api)/driver/documents?name=…,
// which checks the caller owns the document or is an owner reviewing it.
//
// "photo" — the driver's profile photo, which exists precisely to be shown
// to riders choosing between drivers. Served unauthenticated (see
// /(api)/driver/photo) because it is rendered by plain <Image> tags all
// over the rider app; the unguessable name is what keeps it from being
// enumerable, and the route still refuses any name no driver row points at.
//
// The separate directories are the guarantee: a name that addresses a scan
// cannot resolve under the photo directory, so a bug in the public route can
// never hand out someone's ID card.
//
// The `drivers.profile_image_url` / `license_image_url` / `id_image_url` /
// `vehicle_reg_image_url` columns hold the bare stored name ("a1b2….jpg"), not
// a URL — the mobile app and the admin dashboard reach the API on different
// origins and each builds its own URL from the name. `profile_image_url` is
// the exception that also accepts a full external URL, because an owner can
// set one from the admin dashboard.
import { randomBytes } from "crypto";
import { mkdir, readFile, readdir, stat, unlink, writeFile } from "fs/promises";
import path from "path";
export type UploadKind = "document" | "photo";
/** Uploads live outside the bundle so a rebuild never wipes them. */
const uploadRoot = (): string =>
process.env.UPLOAD_DIR
? path.resolve(process.env.UPLOAD_DIR)
: path.join(process.cwd(), ".uploads");
const SUBDIRECTORY: Record<UploadKind, string> = {
document: "driver-documents",
photo: "driver-photos",
};
const uploadDir = (kind: UploadKind): string =>
path.join(uploadRoot(), SUBDIRECTORY[kind]);
/** Phone cameras produce JPEG; PNG and WebP cover gallery picks and screenshots. */
const EXTENSIONS: Record<string, string> = {
"image/jpeg": "jpg",
"image/jpg": "jpg",
"image/png": "png",
"image/webp": "webp",
};
export const SUPPORTED_IMAGE_TYPES = Object.keys(EXTENSIONS);
/**
* A document scan of a national ID at readable resolution is ~13 MB. 10 MB
* leaves room for a high-end camera without letting a client push arbitrary
* amounts of data onto the disk.
*/
export const MAX_UPLOAD_BYTES = 10 * 1024 * 1024;
/** Names are generated here, so anything not matching this was not. */
const NAME_PATTERN = /^[a-f0-9]{32}\.(jpg|png|webp)$/;
export const isStoredUploadName = (value: unknown): value is string =>
typeof value === "string" && NAME_PATTERN.test(value);
const MIME_BY_EXTENSION: Record<string, string> = {
jpg: "image/jpeg",
png: "image/png",
webp: "image/webp",
};
export const uploadMimeType = (name: string): string =>
MIME_BY_EXTENSION[name.split(".").pop() ?? ""] ?? "application/octet-stream";
/**
* Trusting the client's declared media type would let a caller store a .jpg
* that is really something else, so the magic bytes decide. Returns null when
* the buffer is not one of the formats we accept.
*/
export const sniffImageType = (buffer: Buffer): string | null => {
if (buffer.length < 12) return null;
// JPEG: FF D8 FF
if (buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) {
return "image/jpeg";
}
// PNG: 89 50 4E 47 0D 0A 1A 0A
if (buffer.subarray(0, 8).equals(Buffer.from("89504e470d0a1a0a", "hex"))) {
return "image/png";
}
// WebP: "RIFF" .... "WEBP"
if (
buffer.subarray(0, 4).toString("ascii") === "RIFF" &&
buffer.subarray(8, 12).toString("ascii") === "WEBP"
) {
return "image/webp";
}
return null;
};
/** Writes an upload under a random name and returns that name. */
export const storeUpload = async (
buffer: Buffer,
mimeType: string,
kind: UploadKind,
): Promise<string> => {
const extension = EXTENSIONS[mimeType];
if (!extension) throw new Error(`Unsupported image type: ${mimeType}`);
const dir = uploadDir(kind);
await mkdir(dir, { recursive: true });
const name = `${randomBytes(16).toString("hex")}.${extension}`;
await writeFile(path.join(dir, name), buffer);
return name;
};
/** Reads a stored upload back, or null when it is gone. */
export const readUpload = async (
name: string,
kind: UploadKind,
): Promise<Buffer | null> => {
if (!isStoredUploadName(name)) return null;
try {
// The name pattern already rules out separators and "..", so this join
// cannot escape the directory — the check above is the guard, not this.
return await readFile(path.join(uploadDir(kind), name));
} catch {
return null;
}
};
export const deleteUpload = async (
name: string,
kind: UploadKind,
): Promise<void> => {
if (!isStoredUploadName(name)) return;
try {
await unlink(path.join(uploadDir(kind), name));
} catch {
// Already gone, which is the state we wanted.
}
};
/**
* A driver who scans their licence and then abandons onboarding leaves a file
* behind that no row references. Sweeping anything older than a day that isn't
* referenced keeps identity documents from piling up indefinitely; the grace
* period is what keeps an upload alive between the upload and the submit.
*
* `referenced` must be the full set of names still in use for that kind —
* passing a partial set would delete live files, so the caller queries every
* column that can hold one.
*/
const ORPHAN_GRACE_MS = 24 * 60 * 60 * 1000;
export const pruneOrphanUploads = async (
referenced: Set<string>,
kind: UploadKind,
): Promise<number> => {
let removed = 0;
try {
const dir = uploadDir(kind);
const names = await readdir(dir);
const cutoff = Date.now() - ORPHAN_GRACE_MS;
for (const name of names) {
if (!isStoredUploadName(name) || referenced.has(name)) continue;
const info = await stat(path.join(dir, name)).catch(() => null);
if (!info || info.mtimeMs >= cutoff) continue;
await deleteUpload(name, kind);
removed += 1;
}
} catch {
// The directory may not exist yet. Nothing to prune either way.
}
return removed;
};
+439
View File
@@ -0,0 +1,439 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { Platform, PermissionsAndroid } from "react-native";
import InCallManager from "react-native-incall-manager";
import {
mediaDevices,
RTCPeerConnection,
type MediaStream,
} from "react-native-webrtc";
import { fetchAPI } from "@/lib/fetch";
import type { CallRecord, CallStatus } from "@/types/type";
// Poll cadence for call signaling — faster than chat (2.5s) and ride-status
// (3s) so the callee sees a ring without a long wait, but not so fast it
// hammers the DB.
const POLL_MS = 2000;
// Cap ICE gathering so a slow network can't stall the call forever; whatever
// candidates were gathered by then are sent (non-trickle).
const ICE_GATHER_TIMEOUT_MS = 3000;
// A serializable SDP. react-native-webrtc's RTCSessionDescriptionInit isn't
// exported, so we keep our own shape and pass it straight to
// setLocalDescription/setRemoteDescription (both accept { type, sdp }).
type SdpPayload = { type: "offer" | "answer"; sdp: string };
const sdpToString = (
desc: { type: string | null; sdp: string } | null,
): string =>
desc && desc.type ? JSON.stringify({ type: desc.type, sdp: desc.sdp }) : "";
const parseSdp = (raw: string | null | undefined): SdpPayload | null => {
if (!raw) return null;
try {
return JSON.parse(raw) as SdpPayload;
} catch {
return null;
}
};
const iceServers = (): RTCIceServer[] => {
const servers: RTCIceServer[] = [];
const stun = process.env.EXPO_PUBLIC_STUN_URL;
if (stun) servers.push({ urls: [stun] });
const turn = process.env.EXPO_PUBLIC_TURN_URL;
if (turn) {
servers.push({
urls: [turn],
username: process.env.EXPO_PUBLIC_TURN_USERNAME || "",
credential: process.env.EXPO_PUBLIC_TURN_CREDENTIAL || "",
});
}
return servers;
};
// Android needs the RECORD_AUDIO permission granted before getUserMedia; iOS
// prompts automatically on first getUserMedia call. Exported so callers (the
// chat screen, the driver dashboard) can prime it as soon as a ride is
// matched, rather than the first ask landing mid-handshake when the user taps
// Call — PermissionsAndroid.request no-ops instantly once already granted, so
// priming early costs nothing on the actual call attempt.
export const ensureMicPermission = async (): Promise<boolean> => {
if (Platform.OS !== "android") return true;
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
{
title: "Microphone permission",
message: "Waseel needs microphone access to make calls.",
buttonPositive: "Allow",
},
);
return granted === PermissionsAndroid.RESULTS.GRANTED;
};
// Resolve once ICE gathering is complete (candidate === null), or when the
// timeout fires — whichever first. Non-trickle: the caller waits for this so
// the local SDP it ships already contains all candidates.
const waitForIceGathering = (pc: RTCPeerConnection): Promise<void> =>
new Promise((resolve) => {
if (pc.iceGatheringState === "complete") return resolve();
let done = false;
const finish = () => {
if (done) return;
done = true;
pc.onicecandidate = null;
resolve();
};
// RN-webrtc types the icecandidate event as a bare Event; the candidate
// payload is on the runtime object, so cast to read it.
pc.onicecandidate = ((e: { candidate: unknown }) => {
if (e.candidate === null) finish();
}) as never;
setTimeout(finish, ICE_GATHER_TIMEOUT_MS);
});
type UseCallResult = {
status: CallStatus;
peerName: string | null;
incoming: CallRecord | null;
localStream: MediaStream | null;
remoteStream: MediaStream | null;
micError: boolean;
muted: boolean;
speakerOn: boolean;
toggleMute: () => void;
toggleSpeaker: () => void;
/** Caller: place the call. */
startCall: (
rideId: number,
role: "rider" | "driver",
peerName: string,
) => Promise<void>;
/** Callee: attach to a ride and poll for an incoming offer (no offer created). */
watch: (rideId: number, role: "rider" | "driver", peerName?: string) => void;
answerCall: () => Promise<void>;
declineCall: () => Promise<void>;
endCall: () => Promise<void>;
};
// Drive a WebRTC audio call over the DB-backed polling transport. The peer
// connection and streams live in refs (non-serializable); only the call
// status and streams the UI binds to are state. One active ride at a time.
export const useCall = (): UseCallResult => {
const [status, setStatus] = useState<CallStatus>("idle");
const [peerName, setPeerName] = useState<string | null>(null);
const [incoming, setIncoming] = useState<CallRecord | null>(null);
const [localStream, setLocalStream] = useState<MediaStream | null>(null);
const [remoteStream, setRemoteStream] = useState<MediaStream | null>(null);
const [micError, setMicError] = useState(false);
// Earpiece by default (standard telephony UX); the user opts into speaker.
const [speakerOn, setSpeakerOn] = useState(false);
const [muted, setMuted] = useState(false);
const pcRef = useRef<RTCPeerConnection | null>(null);
const localStreamRef = useRef<MediaStream | null>(null);
const rideIdRef = useRef<number | null>(null);
const roleRef = useRef<"rider" | "driver" | null>(null);
const callIdRef = useRef<number | null>(null);
const pollingRef = useRef<ReturnType<typeof setInterval> | null>(null);
const teardown = useCallback(() => {
if (pollingRef.current) {
clearInterval(pollingRef.current);
pollingRef.current = null;
}
try {
pcRef.current?.close();
} catch {
// ignore
}
pcRef.current = null;
localStreamRef.current?.getTracks().forEach((t) => t.stop());
localStreamRef.current = null;
setLocalStream(null);
setRemoteStream(null);
setIncoming(null);
callIdRef.current = null;
InCallManager.stop();
setSpeakerOn(false);
setMuted(false);
}, []);
// Set up the peer connection with the local mic, wire the remote-track
// handler, and return the stream to attach.
const createPeer =
useCallback(async (): Promise<RTCPeerConnection | null> => {
const ok = await ensureMicPermission();
if (!ok) {
setMicError(true);
return null;
}
setMicError(false);
const stream = await mediaDevices.getUserMedia({
audio: true,
video: false,
});
localStreamRef.current = stream;
setLocalStream(stream);
// Routes audio through the earpiece/speaker and engages the proximity
// sensor, same as the native phone dialer. Must start before the
// speaker/mute toggles below have any effect.
InCallManager.start({ media: "audio" });
const pc = new RTCPeerConnection({ iceServers: iceServers() });
stream.getTracks().forEach((track) => pc.addTrack(track, stream));
// RN-webrtc delivers the remote stream via ontrack's event payload; the
// type is a bare Event so cast to read .streams.
pc.ontrack = ((e: { streams: MediaStream[] }) => {
const remote = e.streams[0];
if (remote) setRemoteStream(remote);
}) as never;
pc.oniceconnectionstatechange = (() => {
const state = pc.iceConnectionState;
if (
state === "failed" ||
state === "disconnected" ||
state === "closed"
) {
// The peer connection died — end the call through the server so the
// other side sees it too.
if (rideIdRef.current) void endCallInternal("ended");
}
}) as never;
pcRef.current = pc;
return pc;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const stopPolling = useCallback(() => {
if (pollingRef.current) {
clearInterval(pollingRef.current);
pollingRef.current = null;
}
}, []);
// PATCH the call row to a terminal action. Kept outside the hook's public
// endCall so the iceconnectionstatechange handler can call it too.
const endCallInternal = useCallback(
async (action: "ended" | "declined") => {
const rideId = rideIdRef.current;
if (rideId === null) return;
try {
await fetchAPI(`/(api)/ride/${rideId}/call`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
action: action === "ended" ? "end" : "decline",
}),
});
} catch (err) {
console.log("[CALL_END]: ", err);
}
setStatus("ended");
teardown();
},
[teardown],
);
// Poll the call row and drive the state machine. The caller waits for the
// callee's answer (sdp_answer) to complete the handshake; the callee, while
// idle, watches for an incoming ringing offer to surface as `incoming`.
const poll = useCallback(async () => {
const rideId = rideIdRef.current;
if (rideId === null) return;
try {
const res = await fetchAPI(`/(api)/ride/${rideId}/call`);
const call = (res.data ?? null) as CallRecord | null;
if (!call) return;
callIdRef.current = call.id;
const isCaller = call.is_caller;
// Caller side: connect once the callee has answered with an SDP answer.
if (isCaller && call.status === "answered" && call.sdp_answer) {
const pc = pcRef.current;
const answer = parseSdp(call.sdp_answer);
if (pc && answer && pc.remoteDescription === null) {
await pc.setRemoteDescription(answer);
setStatus("in-call");
}
return;
}
// Either side: a terminal status ends the call locally.
if (
call.status === "ended" ||
call.status === "declined" ||
call.status === "missed"
) {
setStatus("ended");
teardown();
return;
}
// Callee side: an incoming ringing offer surfaces as `incoming` until
// answered/declined. Don't overwrite it if we're already past idle.
if (!isCaller && call.status === "ringing" && call.sdp_offer) {
setStatus((current) => {
if (current === "idle" || current === "incoming") {
setIncoming(call);
return "incoming";
}
return current;
});
}
} catch (err) {
console.log("[CALL_POLL]: ", err);
}
}, [teardown]);
const startPolling = useCallback(() => {
stopPolling();
pollingRef.current = setInterval(() => void poll(), POLL_MS);
}, [poll, stopPolling]);
// --- Caller flow: place a call. ---
const startCall = useCallback(
async (rideId: number, role: "rider" | "driver", name: string) => {
rideIdRef.current = rideId;
roleRef.current = role;
setPeerName(name);
setStatus("outgoing");
const pc = await createPeer();
if (!pc) {
setStatus("idle");
return;
}
try {
const offer = await pc.createOffer({ iceRestart: false });
await pc.setLocalDescription(offer);
await waitForIceGathering(pc);
const localOffer = pc.localDescription
? sdpToString(pc.localDescription)
: sdpToString(offer);
await fetchAPI(`/(api)/ride/${rideId}/call`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ sdp_offer: localOffer }),
});
startPolling();
} catch (err) {
console.log("[CALL_START]: ", err);
setStatus("failed" as CallStatus);
teardown();
}
},
[createPeer, startPolling, teardown],
);
// --- Callee flow: answer an incoming call. ---
const answerCall = useCallback(async () => {
const rideId = rideIdRef.current;
const offer = incoming?.sdp_offer;
if (rideId === null || !offer) return;
const pc = await createPeer();
if (!pc) {
setStatus("idle");
return;
}
try {
const remoteOffer = parseSdp(offer);
if (!remoteOffer) throw new Error("bad offer");
await pc.setRemoteDescription(remoteOffer);
const answer = await pc.createAnswer();
await pc.setLocalDescription(answer);
await waitForIceGathering(pc);
const localAnswer = pc.localDescription
? sdpToString(pc.localDescription)
: sdpToString(answer);
await fetchAPI(`/(api)/ride/${rideId}/call`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action: "answer", sdp_answer: localAnswer }),
});
setStatus("in-call");
setIncoming(null);
startPolling();
} catch (err) {
console.log("[CALL_ANSWER]: ", err);
setStatus("failed" as CallStatus);
teardown();
}
}, [createPeer, incoming, startPolling, teardown]);
const declineCall = useCallback(async () => {
await endCallInternal("declined");
}, [endCallInternal]);
const endCall = useCallback(async () => {
await endCallInternal("ended");
}, [endCallInternal]);
const toggleMute = useCallback(() => {
setMuted((current) => {
const next = !current;
// Mute at the WebRTC track level rather than InCallManager's OS-level
// mute: it's what actually stops audio reaching the peer, and it works
// the same on both platforms.
localStreamRef.current
?.getAudioTracks()
.forEach((track) => (track.enabled = !next));
return next;
});
}, []);
const toggleSpeaker = useCallback(() => {
setSpeakerOn((current) => {
const next = !current;
InCallManager.setSpeakerphoneOn(next);
return next;
});
}, []);
// --- Callee idle-watch: attach to a ride and poll for an incoming offer ---
// without creating one. Used by the call screen when opened for an incoming
// call (the call row already exists as 'ringing'); the poll surfaces it as
// `incoming` for the Accept/Decline UI.
const watch = useCallback(
(rideId: number, role: "rider" | "driver", name?: string) => {
rideIdRef.current = rideId;
roleRef.current = role;
if (name) setPeerName(name);
startPolling();
},
[startPolling],
);
// Clean up the peer connection on unmount.
useEffect(() => () => teardown(), [teardown]);
return {
status,
peerName,
incoming,
localStream,
remoteStream,
micError,
muted,
speakerOn,
toggleMute,
toggleSpeaker,
startCall,
watch,
answerCall,
declineCall,
endCall,
};
};
+124
View File
@@ -0,0 +1,124 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { ApiError, fetchAPI } from "@/lib/fetch";
import type { Message } from "@/types/type";
// Poll cadence for new messages. Staggered away from the ride-status poll
// (3s) and the call poll (2s) so the two tabs don't hammer the DB in lockstep.
const POLL_MS = 2500;
type UseChatResult = {
messages: Message[];
loading: boolean;
sending: boolean;
error: string | null;
sendMessage: (body: string) => Promise<void>;
reload: () => Promise<void>;
};
// Ride-scoped chat. Fetches the full history once, then polls for messages
// with id greater than the last one seen. Optimistic on send: the row the
// server returns is appended immediately, so the bubble appears before the
// next poll. `role` is the caller's role ("rider" | "driver") and is only
// used by the screen to align bubbles — the hook itself doesn't need it, but
// it takes it so the screen has one source of truth for the conversation.
export const useChat = (
rideId: number | null,
role: "rider" | "driver" | null,
): UseChatResult => {
const [messages, setMessages] = useState<Message[]>([]);
const [loading, setLoading] = useState(false);
const [sending, setSending] = useState(false);
const [error, setError] = useState<string | null>(null);
// Last message id we've seen — the polling cursor. Kept in a ref so the
// interval closure always reads the latest value without re-arming.
const cursorRef = useRef<number>(0);
const loadInitial = useCallback(async (id: number) => {
setLoading(true);
setError(null);
try {
const res = await fetchAPI(`/(api)/ride/${id}/messages`);
const rows = (res.data ?? []) as Message[];
setMessages(rows);
cursorRef.current = rows.length ? rows[rows.length - 1].id : 0;
} catch (err) {
console.log("[CHAT_LOAD]: ", err);
setError("chat.loadError");
} finally {
setLoading(false);
}
}, []);
const poll = useCallback(async (id: number) => {
try {
const res = await fetchAPI(
`/(api)/ride/${id}/messages?since=${cursorRef.current}`,
);
const rows = (res.data ?? []) as Message[];
if (rows.length) {
setMessages((prev) => [...prev, ...rows]);
cursorRef.current = rows[rows.length - 1].id;
}
} catch (err) {
// Swallow poll errors — a transient blip shouldn't wipe the list or
// flash an error banner; the next tick will retry.
console.log("[CHAT_POLL]: ", err);
}
}, []);
// Initial load + polling lifecycle. Re-arms when the ride id changes.
useEffect(() => {
if (rideId === null) {
setMessages([]);
cursorRef.current = 0;
return;
}
void loadInitial(rideId);
const timer = setInterval(() => void poll(rideId), POLL_MS);
return () => clearInterval(timer);
}, [rideId, loadInitial, poll]);
const sendMessage = useCallback(
async (body: string) => {
if (rideId === null) return;
const text = body.trim();
if (!text || sending) return;
setSending(true);
try {
const res = await fetchAPI(`/(api)/ride/${rideId}/messages`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ body: text }),
});
const message = res.data as Message;
setMessages((prev) => [...prev, message]);
cursorRef.current = Math.max(cursorRef.current, message.id);
} catch (err) {
if (err instanceof ApiError && err.status === 409) {
// Ride no longer active — surface that specifically so the UI can
// disable the input instead of retrying forever.
setError("chat.cannotMessage");
} else {
console.log("[CHAT_SEND]: ", err);
setError("chat.sendError");
}
} finally {
setSending(false);
}
},
[rideId, sending],
);
const reload = useCallback(async () => {
if (rideId !== null) await loadInitial(rideId);
}, [rideId, loadInitial]);
// `role` is accepted for API symmetry but the hook doesn't read it; keep the
// param so the screen's single conversation object carries the caller's role.
void role;
return { messages, loading, sending, error, sendMessage, reload };
};
+119 -30
View File
@@ -1,47 +1,68 @@
import * as Location from "expo-location";
import { AppState } from "react-native";
import { useEffect, useRef } from "react";
import { useEffect, useRef, useState } from "react";
import { fetchAPI } from "@/lib/fetch";
import {
fixFromCoords,
getLastKnownCoords,
pingDriverLocation,
setHeartbeatActive,
setLastKnownCoords,
startBackgroundTracking,
stopBackgroundTracking,
type DriverFix,
} from "@/lib/location-task";
import { resetOfferNotifications } from "@/lib/notifications";
// While the driver is online, watch their position and POST it to the server
// as a heartbeat. Each ping both updates the driver's lat/lng and refreshes
// last_seen/online, which is what keeps the driver eligible for matching. The
// watch is started when `online` flips true and torn down on false/unmount.
// last_seen, which is what keeps the driver eligible for matching.
//
// The watch must also restart when the app returns to the foreground: the OS
// suspends location updates in the background, and the subscription we hold
// does not auto-revive. Without this, a driver who briefly backgrounds the app
// goes permanently stale (last_seen older than the dispatch freshness window)
// and stops receiving ride requests until they toggle offline→online again.
// Two trackers run, and they do different jobs:
//
// Pings are throttled to every PING_INTERVAL_MS so a fast-moving driver
// doesn't hammer the server, and the location permission is only requested
// once the driver actually intends to go online.
// Background — expo-location's task-based updates behind an Android
// foreground service (lib/location-task.ts). This is the one that matters:
// it keeps pinging with the screen off, so a driver who pockets their phone
// stays in the match pool instead of going stale within a minute. It also
// carries offer notifications back.
//
// Foreground — a plain watchPositionAsync, purely so this hook can hand the
// driver's current coordinates back to the UI for the map. The background
// task can't update React state; it runs outside the component tree.
//
// The foreground watch only pings the server itself when background tracking
// was refused (an OS that denied the permission), so the two don't double up.
//
// The watch must restart when the app returns to the foreground: the OS
// suspends location updates in the background and the subscription we hold
// does not auto-revive.
const PING_INTERVAL_MS = 5000;
// Returns the driver's last-known position (updated alongside each ping) so
// the caller can center a map on it, e.g. to show the rider's pickup point
// relative to where the driver actually is.
export const useDriverLocation = (online: boolean) => {
const subscriptionRef = useRef<Location.LocationSubscription | null>(null);
const onlineRef = useRef(online);
onlineRef.current = online;
// True once the foreground service is running, in which case the foreground
// watch is display-only and must not ping as well.
const backgroundActive = useRef(false);
const [coords, setCoords] = useState<{
latitude: number;
longitude: number;
} | null>(null);
useEffect(() => {
if (!online) return;
let cancelled = false;
const ping = async (latitude: number, longitude: number) => {
try {
await fetchAPI("/(api)/driver/location", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ latitude, longitude }),
});
} catch (error) {
// A failed ping is non-fatal — the next one will retry. last_seen
// going stale is what takes a driver out of the match pool, not a 500.
console.log("[DRIVER_LOCATION_PING]: ", error);
}
// A new position updates the map and the shared last-known value. It does
// NOT ping on its own — see the heartbeat effect below for why.
const record = (fix: DriverFix) => {
setCoords({ latitude: fix.latitude, longitude: fix.longitude });
setLastKnownCoords(fix);
};
const start = async () => {
@@ -50,23 +71,39 @@ export const useDriverLocation = (online: boolean) => {
if (!(await Location.hasServicesEnabledAsync())) return;
// "Allow all the time" is requested but not required: the foreground
// service is what actually keeps updates flowing on Android, and a
// driver who only grants "while using" still gets tracked while the
// service notification is up.
try {
await Location.requestBackgroundPermissionsAsync();
} catch (error) {
console.log("[DRIVER_LOCATION_BG_PERMISSION]: ", error);
}
if (cancelled) return;
backgroundActive.current = await startBackgroundTracking();
// Seed the server with the last known position immediately, so the
// driver is matchable without waiting for the first watch callback.
const cached = await Location.getLastKnownPositionAsync({
maxAge: 5 * 60 * 1000,
});
if (!cancelled && cached) {
void ping(cached.coords.latitude, cached.coords.longitude);
record(fixFromCoords(cached.coords));
}
const subscription = await Location.watchPositionAsync(
{
accuracy: Location.Accuracy.Balanced,
timeInterval: PING_INTERVAL_MS,
distanceInterval: 20,
// 0, not a displacement threshold — see the note in
// lib/location-task.ts. A stationary driver must keep reporting, or
// dispatch treats them as gone.
distanceInterval: 0,
},
({ coords }) => {
if (!cancelled) void ping(coords.latitude, coords.longitude);
if (!cancelled) record(fixFromCoords(coords));
},
);
@@ -86,8 +123,9 @@ export const useDriverLocation = (online: boolean) => {
void start();
// Restart the watch whenever the app comes back to the foreground. While
// backgrounded the OS pauses location updates and the old subscription is
// dead; without re-starting it the driver never pings again.
// backgrounded the OS pauses the in-process watch and the old
// subscription is dead; the task-based updates carry on regardless, so
// this only restores the coordinates the UI draws with.
const onAppStateChange = (state: string) => {
if (state !== "active") return;
if (!onlineRef.current) return;
@@ -100,6 +138,57 @@ export const useDriverLocation = (online: boolean) => {
cancelled = true;
stop();
subscription.remove();
backgroundActive.current = false;
// Going offline must also tear down the foreground service, or the
// driver is left with a "you're online" notification and a GPS drain
// for a shift that has ended.
void stopBackgroundTracking();
resetOfferNotifications();
};
}, [online]);
};
// The heartbeat.
//
// This is a plain timer, deliberately, and it is the thing that keeps a
// driver in the match pool. Tying the heartbeat to position callbacks —
// which is what this did before — meant liveness depended on the OS deciding
// to emit a new fix, and a driver parked at a stand with the phone on the
// dashboard emits nothing at all: Android's fused provider had no reason to
// wake, so the pings stopped, last_seen aged past 60 seconds and the driver
// silently vanished from every rider's map while their own screen still read
// "Online — receiving ride requests".
//
// "Where is the driver" and "is the driver still there" are separate
// questions, and only the second one has a deadline. So the timer re-sends
// the last known position on a fixed cadence whether or not the car has
// moved — a stationary driver reporting the same coordinates is exactly the
// signal dispatch needs.
useEffect(() => {
if (!online) return;
setHeartbeatActive(true);
const beat = async () => {
const position = getLastKnownCoords();
if (!position) return;
try {
await pingDriverLocation(position);
} catch (error) {
// Non-fatal — the next beat retries. A dropped ping only matters if
// enough of them drop in a row to age last_seen out.
console.log("[DRIVER_HEARTBEAT]: ", error);
}
};
void beat();
const timer = setInterval(() => void beat(), PING_INTERVAL_MS);
return () => {
clearInterval(timer);
setHeartbeatActive(false);
};
}, [online]);
return coords;
};
+134
View File
@@ -0,0 +1,134 @@
// Progressive nearby-driver search for the rider side.
//
// /(api)/driver/nearby is bounded by a radius, so a single fixed value is
// always wrong in one direction: too tight and a rider in a quiet area sees an
// empty map, too wide and a rider in Beirut gets pins from cars that are forty
// minutes away and will never be matched to them.
//
// So the search starts tight — the handful of cars actually near the rider —
// and only widens when that comes back empty, in 5 km steps, until it finds
// someone or hits the cap. A rider in a busy street gets a close, honest map;
// a rider in the mountains still gets an answer a few seconds later.
//
// The radius is reported back so the UI can say what it's doing rather than
// showing a spinner that looks stuck.
import { useEffect, useRef, useState } from "react";
import { fetchAPI } from "@/lib/fetch";
import type { Driver } from "@/types/type";
/** First pass: only cars genuinely next to the rider. */
export const SEARCH_START_RADIUS_M = 2000;
/** Each unsuccessful pass widens the net by this much. */
export const SEARCH_STEP_M = 5000;
/** Ceiling, matching the server's own cap on the endpoint. */
export const SEARCH_MAX_RADIUS_M = 20000;
// Gap between widening attempts. Long enough not to hammer the endpoint with
// four requests in a single frame, short enough that a rider in an empty area
// reaches the full radius in a few seconds rather than half a minute.
const EXPAND_DELAY_MS = 1200;
// Once drivers are found (or the search has run out of room to widen), settle
// into a steady poll so the map keeps up with cars moving and going offline.
//
// Matched to the driver heartbeat (lib/use-driver-location PING_INTERVAL_MS):
// polling faster than drivers report would burn requests to redraw identical
// positions, and polling slower is what made the map look static — at 10s a
// car in traffic jumped a whole block between frames, which reads as a glitch
// rather than as movement. The markers interpolate between these updates, so
// this is the rate at which truth arrives, not the frame rate.
const SETTLED_POLL_MS = 5000;
// Rounding the rider's position to ~110 m before using it as an effect key.
// Raw GPS jitters by a few metres constantly, and without this every jitter
// would restart the search from the beginning and the radius would never
// climb.
const QUANTIZE = 1e3;
const quantize = (v: number): number => Math.round(v * QUANTIZE) / QUANTIZE;
export type NearbySearch = {
drivers: Driver[];
/** Radius the current result set came from, in metres. */
radius: number;
/** True while widening — i.e. nothing found yet and there's room to grow. */
expanding: boolean;
/** True until the first response lands, so callers can tell "none" from "not yet". */
loading: boolean;
};
export const useNearbyDrivers = (
service: string,
latitude: number | null,
longitude: number | null,
): NearbySearch => {
const [drivers, setDrivers] = useState<Driver[]>([]);
const [radius, setRadius] = useState(SEARCH_START_RADIUS_M);
const [expanding, setExpanding] = useState(false);
const [loading, setLoading] = useState(true);
// Quantized so GPS jitter doesn't restart the search; the raw values are
// still what gets sent to the server.
const latKey = latitude === null ? null : quantize(latitude);
const lngKey = longitude === null ? null : quantize(longitude);
const coords = useRef({ latitude, longitude });
coords.current = { latitude, longitude };
useEffect(() => {
if (latKey === null || lngKey === null) return;
let cancelled = false;
let timer: ReturnType<typeof setTimeout>;
let current = SEARCH_START_RADIUS_M;
setRadius(SEARCH_START_RADIUS_M);
setLoading(true);
const run = async () => {
const { latitude: lat, longitude: lng } = coords.current;
if (lat === null || lng === null) return;
try {
const res = await fetchAPI(
`/(api)/driver/nearby?service=${service}&lat=${lat}&lng=${lng}&radius=${current}`,
);
if (cancelled) return;
const found = (res.data ?? []) as Driver[];
setDrivers(found);
setRadius(current);
setLoading(false);
if (found.length === 0 && current < SEARCH_MAX_RADIUS_M) {
current = Math.min(current + SEARCH_STEP_M, SEARCH_MAX_RADIUS_M);
setExpanding(true);
timer = setTimeout(run, EXPAND_DELAY_MS);
return;
}
setExpanding(false);
timer = setTimeout(run, SETTLED_POLL_MS);
} catch {
// A failed request shouldn't collapse the search back to the start —
// retry at the same radius on the slow cadence.
if (cancelled) return;
setLoading(false);
setExpanding(false);
timer = setTimeout(run, SETTLED_POLL_MS);
}
};
void run();
return () => {
cancelled = true;
clearTimeout(timer);
};
}, [service, latKey, lngKey]);
return { drivers, radius, expanding, loading };
};
/** "2 km" / "20 km" — the radius as riders should read it. */
export const radiusKm = (meters: number): number => Math.round(meters / 1000);
+107
View File
@@ -0,0 +1,107 @@
// Which services actually have a driver near the rider.
//
// The map only ever shows the selected service, so an empty map means both
// "nobody is driving tonight" and "nobody is on a moto, though three cars are
// a street away" — and the rider has no way to tell which. That ambiguity is
// what leaves someone staring at a blank map instead of switching service and
// getting a ride.
//
// This answers it once for every service, so the picker can show availability
// and the request screen can point at a service that would actually work.
import { useEffect, useRef, useState } from "react";
import { SERVICES, type ServiceId } from "@/constants/services";
import { fetchAPI } from "@/lib/fetch";
import { SEARCH_MAX_RADIUS_M } from "@/lib/use-nearby-drivers";
// Slower than the map's own poll: this drives a hint, not the pins, and it
// scans every service rather than one.
const POLL_MS = 15000;
// ~110 m, so GPS jitter doesn't restart the request loop on every fix.
const QUANTIZE = 1e3;
const quantize = (v: number): number => Math.round(v * QUANTIZE) / QUANTIZE;
export type ServiceAvailability = {
/** Driver count per service, every service present (zeros included). */
counts: Record<ServiceId, number>;
/** Services with at least one driver in range. */
available: ServiceId[];
/** Radius the counts were measured over, in metres. */
radius: number;
loading: boolean;
};
const emptyCounts = (): Record<ServiceId, number> => {
const counts = {} as Record<ServiceId, number>;
for (const service of SERVICES) counts[service.id] = 0;
return counts;
};
export const useServiceAvailability = (
latitude: number | null,
longitude: number | null,
): ServiceAvailability => {
const [counts, setCounts] = useState<Record<ServiceId, number>>(emptyCounts);
const [radius, setRadius] = useState(SEARCH_MAX_RADIUS_M);
const [loading, setLoading] = useState(true);
const latKey = latitude === null ? null : quantize(latitude);
const lngKey = longitude === null ? null : quantize(longitude);
const coords = useRef({ latitude, longitude });
coords.current = { latitude, longitude };
useEffect(() => {
if (latKey === null || lngKey === null) return;
let cancelled = false;
let timer: ReturnType<typeof setTimeout>;
const run = async () => {
const { latitude: lat, longitude: lng } = coords.current;
if (lat === null || lng === null) return;
try {
const res = await fetchAPI(
`/(api)/driver/availability?lat=${lat}&lng=${lng}&radius=${SEARCH_MAX_RADIUS_M}`,
);
if (cancelled) return;
const data = res.data as {
radius: number;
counts: Record<string, number>;
};
// Merge onto a full set of zeros so a service the server didn't
// mention still renders as "none nearby" rather than blank.
const next = emptyCounts();
for (const service of SERVICES) {
next[service.id] = data.counts?.[service.id] ?? 0;
}
setCounts(next);
setRadius(data.radius ?? SEARCH_MAX_RADIUS_M);
} catch {
// Leave the last known counts in place — a dropped request shouldn't
// flash "no drivers anywhere" at the rider.
} finally {
if (!cancelled) {
setLoading(false);
timer = setTimeout(run, POLL_MS);
}
}
};
void run();
return () => {
cancelled = true;
clearTimeout(timer);
};
}, [latKey, lngKey]);
const available = SERVICES.map((s) => s.id).filter((id) => counts[id] > 0);
return { counts, available, radius, loading };
};
+29
View File
@@ -56,6 +56,35 @@ export function normalizePhone(raw: string): string {
return `+961${cleaned.replace(/^0+/, "")}`;
}
/**
* A lat/lng box that fully contains a circle of `radiusMeters` around a point.
*
* Used as a cheap first pass before the exact great-circle test: the box is
* something an index can answer, so the database only hands back the handful
* of rows worth measuring properly. It over-selects at the corners, which is
* why callers still filter with `haversine` afterwards.
*/
export function boundingBox(
latitude: number,
longitude: number,
radiusMeters: number,
): { minLat: number; maxLat: number; minLng: number; maxLng: number } {
// A degree of latitude is ~111.32 km everywhere; a degree of longitude
// shrinks with the cosine of the latitude. The cos is floored so the box
// stays finite near the poles instead of dividing by zero.
const latDelta = radiusMeters / 111_320;
const lngDelta =
radiusMeters /
(111_320 * Math.max(Math.cos((latitude * Math.PI) / 180), 0.01));
return {
minLat: latitude - latDelta,
maxLat: latitude + latDelta,
minLng: longitude - lngDelta,
maxLng: longitude + lngDelta,
};
}
// Great-circle distance between two lat/lng points, in meters. Used for
// nearest-driver matching and "X m away" POI chips. Haversine formula.
export function haversine(