The drivers table was seeded with 4 fake fixtures (Karim/Rana/Omar/Layal) using randomuser.me/unsplash placeholder images. They had no user_id, no position, and were excluded from matching and the rider map by design, so they only ever cluttered the dashboard. The table now starts empty — real drivers are created in-app via onboarding (driver/profile POST), which links a row to a real user account and gives it a live GPS position. Dropped the dead random-offset scatter in generateMarkersFromData that fabricated fake driver positions for drivers without GPS. It was already unreachable (the null-position filter excluded those drivers), so this is stub cleanup, not a behavior change — drivers without a real position simply aren't rendered. The 4 fixture rows were also removed from the live Neon DB (user_id IS NULL); real onboarded drivers were untouched. Co-Authored-By: Claude <noreply@anthropic.com>
203 lines
8.2 KiB
JavaScript
203 lines
8.2 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)`;
|
|
|
|
// No seed drivers: the drivers table starts empty. Real drivers are created
|
|
// in-app via onboarding (driver/profile POST), which links a drivers row to a
|
|
// real user account and gives it a live GPS position for matching.
|
|
console.log("Database ready.");
|
|
|
|
await pool.end();
|