Driver side (was a stub): - In-app driver onboarding: a driver-role user creates their own linked drivers profile (driver/profile+api GET/POST/PATCH). - Driver dashboard: online/offline toggle, today's earnings, incoming request cards (accept/decline), active ride panel (start/complete trip). Polls /driver/rides every 4s while online. - Location heartbeat (use-driver-location): watchPositionAsync pings /driver/location every ~5s; restarts the watch on app foreground so a backgrounded driver doesn't go permanently stale and miss requests. Dispatch (auto-match nearest, Uber-style): - Ride state machine: requested -> accepted -> en_route -> completed/cancelled with a nullable driver_id until matched (lib/dispatch.matchNextDriver). - matchNextDriver locks the ride (SELECT FOR UPDATE), expires 15s-stale offers, picks the nearest eligible driver of the matching service by haversine, offers one at a time. Called from ride/create, ride/[id] GET (lazy match on the rider's poll), and ride/[id]/respond (on decline). - ride/create is now a request endpoint (driver_id NULL, status=requested, service); drops the pre-match driver_id payment reconciliation. - ride/[id] GET returns status/service/nullable driver; PATCH handles rider cancel + driver en_route/completed. ride/list backs the history tabs. Rider flow (best experience): - confirm-ride is now a request screen: single trip fare + nearest-driver ETA + cash/card + Request Ride -> live status. Periodically polls online drivers of the selected service and disables Request when none are online (prevents the "stuck searching forever" state). - book-ride is the live ride-status screen (searching -> accepted -> en_route -> completed/cancelled + Cancel), polling every 3s. - lib/request-ride unifies the Areeba card flow + cash path. - Map reads /driver/nearby (real positions, service-filtered); lib/map adds calculateTripFare + service-aware fares. POI suggestions: - lib/places (Google Nearby Search) + nearby-suggestions chips for mall/hospital/pharmacy/restaurant on the home screen. Service categories now drive both matching and a per-service fare multiplier (car 1.0 / moto 0.7 / courier 0.85 / chauffeur 1.5). Map tiles: react-native-maps rendered blank on Android because no Google Maps key was set. Switched app.json -> app.config.js so android.config.googleMaps.apiKey is injected from EXPO_PUBLIC_GOOGLE_API_KEY at build time (keeps the key out of git). Requires a native rebuild (expo run:android) to take effect. Also includes the prior payment/auth hardening (server-authoritative payment_orders ledger with double-spend guards, peppered OTP, register TOCTOU fix, stats cents fix) that was left uncommitted. Co-Authored-By: Claude <noreply@anthropic.com>
214 lines
8.9 KiB
JavaScript
214 lines
8.9 KiB
JavaScript
// Creates and seeds the Waseel database tables (local/self-hosted PostgreSQL).
|
|
// Usage: node scripts/seed-db.mjs (reads DATABASE_URL from .env)
|
|
|
|
import pg from "pg";
|
|
import { readFileSync } from "fs";
|
|
|
|
const env = readFileSync(new URL("../.env", import.meta.url), "utf8");
|
|
const databaseUrl = env
|
|
.split("\n")
|
|
.find((l) => l.startsWith("DATABASE_URL="))
|
|
?.split("=")
|
|
.slice(1)
|
|
.join("=")
|
|
.trim()
|
|
.replace(/^"|"$/g, "");
|
|
|
|
if (!databaseUrl) {
|
|
console.error("DATABASE_URL not found in .env");
|
|
process.exit(1);
|
|
}
|
|
|
|
const pool = new pg.Pool({ connectionString: databaseUrl });
|
|
|
|
const sql = async (strings, ...values) => {
|
|
const text = strings.reduce(
|
|
(acc, chunk, i) => acc + chunk + (i < values.length ? `$${i + 1}` : ""),
|
|
"",
|
|
);
|
|
const result = await pool.query(text, values);
|
|
return result.rows;
|
|
};
|
|
|
|
// Migrate databases created during the Clerk era (clerk_id column, no UNIQUE email).
|
|
const clerkCol = await sql`
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_name = 'users' AND column_name = 'clerk_id'
|
|
`;
|
|
if (clerkCol.length > 0) {
|
|
await sql`ALTER TABLE users DROP COLUMN clerk_id`;
|
|
console.log("Dropped legacy clerk_id column from users.");
|
|
}
|
|
|
|
// Rebuild legacy tables where users.id / rides.user_id are not UUID.
|
|
const idType = await sql`
|
|
SELECT data_type FROM information_schema.columns
|
|
WHERE table_name = 'users' AND column_name = 'id'
|
|
`;
|
|
if (idType.length > 0 && idType[0]?.data_type !== "uuid") {
|
|
console.log("Detected legacy non-UUID users schema, rebuilding users/rides...");
|
|
await sql`DROP TABLE IF EXISTS rides`;
|
|
await sql`DROP TABLE IF EXISTS users CASCADE`;
|
|
console.log("Legacy users/rides tables dropped (test data only).");
|
|
}
|
|
|
|
await sql`CREATE TABLE IF NOT EXISTS users (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
name VARCHAR(255) NOT NULL,
|
|
email VARCHAR(255) NOT NULL UNIQUE,
|
|
phone VARCHAR(20),
|
|
password_hash TEXT,
|
|
google_sub TEXT UNIQUE,
|
|
email_verified BOOLEAN NOT NULL DEFAULT FALSE,
|
|
role VARCHAR(20),
|
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
)`;
|
|
|
|
// For databases created before self-hosted auth existed.
|
|
await sql`ALTER TABLE users ADD COLUMN IF NOT EXISTS role VARCHAR(20)`;
|
|
await sql`ALTER TABLE users ADD COLUMN IF NOT EXISTS phone VARCHAR(20)`;
|
|
await sql`ALTER TABLE users ADD COLUMN IF NOT EXISTS password_hash TEXT`;
|
|
await sql`ALTER TABLE users ADD COLUMN IF NOT EXISTS google_sub TEXT`;
|
|
await sql`ALTER TABLE users ADD COLUMN IF NOT EXISTS email_verified BOOLEAN NOT NULL DEFAULT FALSE`;
|
|
|
|
// email must be UNIQUE for ON CONFLICT (email) upserts in register+api.ts.
|
|
const emailUnique = await sql`
|
|
SELECT 1 FROM pg_constraint
|
|
WHERE conrelid = 'users'::regclass AND contype = 'u'
|
|
AND conkey @> ARRAY[
|
|
(SELECT attnum::smallint FROM pg_attribute
|
|
WHERE attrelid = 'users'::regclass AND attname = 'email')
|
|
]
|
|
`;
|
|
if (emailUnique.length === 0) {
|
|
await sql`ALTER TABLE users ADD CONSTRAINT users_email_unique UNIQUE (email)`;
|
|
console.log("Added unique constraint on users.email.");
|
|
}
|
|
|
|
await sql`CREATE TABLE IF NOT EXISTS email_verification_codes (
|
|
email VARCHAR(255) PRIMARY KEY,
|
|
code_hash TEXT NOT NULL,
|
|
attempts INTEGER NOT NULL DEFAULT 0,
|
|
expires_at TIMESTAMP NOT NULL
|
|
)`;
|
|
|
|
await sql`CREATE TABLE IF NOT EXISTS password_reset_codes (
|
|
email VARCHAR(255) PRIMARY KEY,
|
|
code_hash TEXT NOT NULL,
|
|
attempts INTEGER NOT NULL DEFAULT 0,
|
|
expires_at TIMESTAMP NOT NULL
|
|
)`;
|
|
|
|
await sql`CREATE TABLE IF NOT EXISTS drivers (
|
|
id SERIAL PRIMARY KEY,
|
|
first_name VARCHAR(100) NOT NULL,
|
|
last_name VARCHAR(100) NOT NULL,
|
|
profile_image_url TEXT,
|
|
car_image_url TEXT,
|
|
car_seats INTEGER NOT NULL,
|
|
rating NUMERIC(2,1) NOT NULL
|
|
)`;
|
|
|
|
// Driver profiles are linked to a user account (in-app driver onboarding) and
|
|
// carry the live state the dispatch engine needs.
|
|
await sql`ALTER TABLE drivers ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES users(id) ON DELETE SET NULL`;
|
|
await sql`ALTER TABLE drivers ADD COLUMN IF NOT EXISTS service VARCHAR(20) NOT NULL DEFAULT 'car'`;
|
|
await sql`ALTER TABLE drivers ADD COLUMN IF NOT EXISTS latitude DOUBLE PRECISION`;
|
|
await sql`ALTER TABLE drivers ADD COLUMN IF NOT EXISTS longitude DOUBLE PRECISION`;
|
|
await sql`ALTER TABLE drivers ADD COLUMN IF NOT EXISTS online BOOLEAN NOT NULL DEFAULT FALSE`;
|
|
await sql`ALTER TABLE drivers ADD COLUMN IF NOT EXISTS last_seen TIMESTAMPTZ`;
|
|
await sql`ALTER TABLE drivers ADD COLUMN IF NOT EXISTS car_model VARCHAR(100)`;
|
|
// One driver profile per user account (legacy seed rows have NULL user_id).
|
|
await sql`CREATE UNIQUE INDEX IF NOT EXISTS drivers_user_id_key ON drivers(user_id) WHERE user_id IS NOT NULL`;
|
|
await sql`CREATE INDEX IF NOT EXISTS drivers_service_online_idx ON drivers(service, online)`;
|
|
|
|
await sql`CREATE TABLE IF NOT EXISTS rides (
|
|
ride_id SERIAL PRIMARY KEY,
|
|
origin_address TEXT NOT NULL,
|
|
destination_address TEXT NOT NULL,
|
|
origin_latitude DOUBLE PRECISION NOT NULL,
|
|
origin_longitude DOUBLE PRECISION NOT NULL,
|
|
destination_latitude DOUBLE PRECISION NOT NULL,
|
|
destination_longitude DOUBLE PRECISION NOT NULL,
|
|
ride_time INTEGER NOT NULL,
|
|
fare_price INTEGER NOT NULL,
|
|
payment_status VARCHAR(50) NOT NULL,
|
|
driver_id INTEGER NOT NULL REFERENCES drivers(id),
|
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
payment_order_id TEXT,
|
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
)`;
|
|
|
|
// Link a ride to the server-authoritative payment order that paid for it.
|
|
await sql`ALTER TABLE rides ADD COLUMN IF NOT EXISTS payment_order_id TEXT`;
|
|
|
|
// Ride lifecycle state machine: requested -> accepted -> en_route -> completed
|
|
// (or cancelled). A requested ride has no driver yet — auto-match assigns one
|
|
// when a driver accepts, so driver_id must be nullable.
|
|
await sql`ALTER TABLE rides ADD COLUMN IF NOT EXISTS status VARCHAR(20) NOT NULL DEFAULT 'requested'`;
|
|
await sql`ALTER TABLE rides ADD COLUMN IF NOT EXISTS service VARCHAR(20) NOT NULL DEFAULT 'car'`;
|
|
await sql`ALTER TABLE rides ADD COLUMN IF NOT EXISTS completed_at TIMESTAMPTZ`;
|
|
await sql`ALTER TABLE rides ADD COLUMN IF NOT EXISTS cancelled_at TIMESTAMPTZ`;
|
|
await sql`
|
|
ALTER TABLE rides ALTER COLUMN driver_id DROP NOT NULL
|
|
`;
|
|
await sql`CREATE INDEX IF NOT EXISTS rides_user_id_idx ON rides(user_id)`;
|
|
await sql`CREATE INDEX IF NOT EXISTS rides_driver_id_idx ON rides(driver_id)`;
|
|
await sql`CREATE INDEX IF NOT EXISTS rides_status_idx ON rides(status)`;
|
|
|
|
// Server-authoritative record of each card payment intent. The client never
|
|
// supplies payment_status or the successIndicator; both live here and are
|
|
// verified against the gateway before an order can be consumed for a ride.
|
|
await sql`CREATE TABLE IF NOT EXISTS payment_orders (
|
|
order_id TEXT PRIMARY KEY,
|
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
amount_cents INTEGER NOT NULL,
|
|
currency VARCHAR(8) NOT NULL DEFAULT 'USD',
|
|
driver_id INTEGER REFERENCES drivers(id),
|
|
origin_address TEXT,
|
|
destination_address TEXT,
|
|
origin_latitude DOUBLE PRECISION,
|
|
origin_longitude DOUBLE PRECISION,
|
|
destination_latitude DOUBLE PRECISION,
|
|
destination_longitude DOUBLE PRECISION,
|
|
ride_time INTEGER,
|
|
success_indicator TEXT,
|
|
status VARCHAR(20) NOT NULL DEFAULT 'pending',
|
|
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
|
|
paid_at TIMESTAMPTZ
|
|
)`;
|
|
|
|
await sql`CREATE INDEX IF NOT EXISTS payment_orders_user_id_idx ON payment_orders(user_id)`;
|
|
|
|
// Dispatch: each attempt to match a requested ride to a driver is recorded as
|
|
// an offer. A driver polls for status='offered' rows assigned to them; accept
|
|
// flips the ride to 'accepted', decline/expiry triggers the next-nearest match.
|
|
await sql`CREATE TABLE IF NOT EXISTS ride_offers (
|
|
id SERIAL PRIMARY KEY,
|
|
ride_id INTEGER NOT NULL REFERENCES rides(ride_id) ON DELETE CASCADE,
|
|
driver_id INTEGER NOT NULL REFERENCES drivers(id),
|
|
status VARCHAR(20) NOT NULL DEFAULT 'offered',
|
|
offered_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
|
|
responded_at TIMESTAMPTZ
|
|
)`;
|
|
await sql`CREATE INDEX IF NOT EXISTS ride_offers_driver_status_idx ON ride_offers(driver_id, status)`;
|
|
await sql`CREATE INDEX IF NOT EXISTS ride_offers_ride_idx ON ride_offers(ride_id)`;
|
|
|
|
const count = await sql`SELECT COUNT(*)::int AS n FROM drivers`;
|
|
if (count[0].n === 0) {
|
|
await sql`INSERT INTO drivers
|
|
(first_name, last_name, profile_image_url, car_image_url, car_seats, rating, service)
|
|
VALUES
|
|
('Karim', 'Haddad', 'https://randomuser.me/api/portraits/men/32.jpg', 'https://images.unsplash.com/photo-1555215695-3004980ad54e?w=600', 4, 4.8, 'car'),
|
|
('Rana', 'Khalil', 'https://randomuser.me/api/portraits/women/44.jpg', 'https://images.unsplash.com/photo-1552519507-da3b142c6e3d?w=600', 1, 4.9, 'moto'),
|
|
('Omar', 'Chehab', 'https://randomuser.me/api/portraits/men/75.jpg', 'https://images.unsplash.com/photo-1580273916550-e323be2ae537?w=600', 4, 4.6, 'car'),
|
|
('Layal', 'Abou-Jaoude', 'https://randomuser.me/api/portraits/women/68.jpg', 'https://images.unsplash.com/photo-1590362891991-f776e747a588?w=600', 2, 4.7, 'courier')`;
|
|
console.log("Seeded 4 drivers.");
|
|
} else {
|
|
console.log(`Drivers table already has ${count[0].n} rows, skipping seed.`);
|
|
}
|
|
|
|
console.log("Database ready.");
|
|
|
|
await pool.end();
|