# RateRight Scripts Reference

All utility scripts for database management and debugging.

---

## NPM Scripts

### Root `package.json`
```bash
npm start          # Start backend server (node src/index.js)
npm run dev        # Start with hot reload (nodemon src/index.js)
npm run build      # Build frontend and copy to public/
npm test           # Run Jest tests
```

### Admin `admin/package.json`
```bash
cd admin
npm run dev        # Start Vite dev server
npm run build      # Build for production
npm run lint       # Run ESLint
npm run preview    # Preview production build
```

---

## Utility Scripts (`scripts/`)

### 1. run-migration.js
**Purpose:** Run SQL migration files against Supabase

**Usage:**
```bash
node scripts/run-migration.js <migration-file>
node scripts/run-migration.js supabase/wisdom-migration.sql
```

**What it does:**
- Reads SQL file and splits into statements
- Handles $$ delimited functions
- Executes each statement via Supabase RPC
- Skips comment lines

---

### 2. list-tables.js
**Purpose:** List all tables in the public schema

**Usage:**
```bash
node scripts/list-tables.js
```

**What it does:**
- Queries information_schema.tables
- Lists all BASE TABLEs in public schema

---

### 3. check-leads.js
**Purpose:** Fetch and display all leads

**Usage:**
```bash
node scripts/check-leads.js
```

**What it does:**
- Fetches all leads (id, first_name, last_name, phone, company)
- Orders by created_at descending
- Outputs as JSON

---

### 4. clean-invalid-phones.js
**Purpose:** Delete leads with invalid Australian phone numbers

**Usage:**
```bash
node scripts/clean-invalid-phones.js
```

**What it does:**
- Validates phones against Australian format (+614XXXXXXXX for mobile, +61[2378]XXXXXXXX for landline)
- Deletes related records first (lead_intel, communications, tasks, notes, activities, etc.)
- Deletes invalid leads in batches of 20
- Reports final count

**Warning:** This is destructive! Permanently deletes leads.

---

### 5. check-tables.js
**Purpose:** Quick check if key tables exist

**Usage:**
```bash
node scripts/check-tables.js
```

**What it does:**
- Tests copilot_sessions, lead_intel, scripts tables
- Reports OK or MISSING for each

---

### 6. check-lead.js
**Purpose:** Check if a specific lead exists

**Usage:**
```bash
node scripts/check-lead.js
```

**What it does:**
- Hardcoded lead ID check (0fd75cdb-5fa1-4c8d-8de5-9edaa771c75d)
- Reports if found with name and company

---

### 7. test-live-intel-query.js
**Purpose:** Test the exact query used in the live-intel API route

**Usage:**
```bash
node scripts/test-live-intel-query.js
```

**What it does:**
- Runs the same query as `/api/ai/live-intel/:leadId`
- Helps debug 404 errors on intel fetch
- Shows what the API would return

---

## Environment Requirements

All scripts require these environment variables:
```
SUPABASE_URL=<your-supabase-url>
SUPABASE_SERVICE_ROLE_KEY=<your-service-role-key>
```

Load from `.env` automatically via `dotenv`.
