# ShotTrack — cPanel Live Server Deployment Guide

## Prerequisites

Before starting, confirm your cPanel hosting plan includes:

- **Node.js Selector** (CloudLinux / EasyApache 4) — check with your host
- **SSH access** (Terminal in cPanel or PuTTY/terminal on your machine)
- **Node.js ≥ 20** available in the Node.js Selector
- At least **512 MB RAM** (1 GB+ recommended for Next.js build)

> **PostgreSQL Note:** cPanel typically offers **MySQL only**, not PostgreSQL.
> ShotTrack requires PostgreSQL. Use a free external PostgreSQL service:
> - [Neon](https://neon.tech) — Recommended (free tier, serverless, fast)
> - [Supabase](https://supabase.com) — Free tier, 500 MB
> - [Railway](https://railway.app) — Free tier
>
> Copy the **connection string** (e.g. `postgresql://user:pass@host/dbname?sslmode=require`) — you will need it in Step 5.

---

## Step 1 — Create a PostgreSQL Database (Neon Example)

1. Go to [neon.tech](https://neon.tech) → Sign up → **New Project**
2. Set region closest to your server
3. After creation, click **Connection Details**
4. Copy the **Connection string** that looks like:
   ```
   postgresql://username:password@ep-xxx.us-east-2.aws.neon.tech/neondb?sslmode=require
   ```
5. Save this — it becomes your `DATABASE_URL`

---

## Step 2 — Set Up a Domain / Subdomain in cPanel

1. Log into **cPanel** → **Domains** → **Create A New Domain** (or Subdomains)
2. Enter your domain (e.g. `shottrack.yourdomain.com`)
3. Set the **Document Root** (e.g. `/home/youraccount/shottrack`)
4. Note the document root path — you will deploy files here

---

## Step 3 — Upload the Project Files

### Option A — Git (Recommended if SSH is available)

```bash
# SSH into your server first
ssh youraccount@yourdomain.com

# Go to your home directory
cd ~

# Clone your repository
git clone https://github.com/yourrepo/shottrack.git shottrack

# Or if no git repo, upload via zip (see Option B)
```

### Option B — ZIP Upload via File Manager

1. On your local machine, **exclude** these folders before zipping:
   - `node_modules/`
   - `.next/`
   - `.env`
   - `docker-compose.yml`
2. Create the zip: right-click project folder → Compress
3. In cPanel → **File Manager** → navigate to your document root
4. Click **Upload** → upload the zip
5. Right-click the zip → **Extract**

---

## Step 4 — Set Up Node.js App in cPanel

1. In cPanel → **Software** → **Setup Node.js App**
2. Click **Create Application**
3. Fill in:

   | Field | Value |
   |-------|-------|
   | Node.js version | 20.x (or latest available) |
   | Application mode | Production |
   | Application root | `/home/youraccount/shottrack` |
   | Application URL | your domain/subdomain |
   | Application startup file | `server.js` *(we will create this)* |

4. Click **Create** — cPanel will set up the virtual environment

---

## Step 5 — Create the Startup File

cPanel's Node.js Selector needs a `server.js` entry point. Create this file in your project root:

**`server.js`**
```js
const { createServer } = require("http");
const { parse } = require("url");
const next = require("next");

const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
const port = process.env.PORT || 3000;

app.prepare().then(() => {
  createServer((req, res) => {
    const parsedUrl = parse(req.url, true);
    handle(req, res, parsedUrl);
  }).listen(port, (err) => {
    if (err) throw err;
    console.log(`> Ready on port ${port}`);
  });
});
```

Upload this file to your project root via File Manager or SSH.

---

## Step 6 — Configure Environment Variables

In cPanel → **Setup Node.js App** → click **Edit** on your app → scroll to **Environment Variables**. Add each variable:

| Key | Value |
|-----|-------|
| `NODE_ENV` | `production` |
| `DATABASE_URL` | `postgresql://user:pass@host/db?sslmode=require` |
| `NEXTAUTH_SECRET` | *(generate a strong random string — see below)* |
| `NEXTAUTH_URL` | `https://yourdomain.com` |
| `WHATSAPP_ACCESS_TOKEN` | *(your WhatsApp Cloud API token)* |
| `WHATSAPP_PHONE_NUMBER_ID` | *(your phone number ID)* |
| `NEXT_PUBLIC_APP_URL` | `https://yourdomain.com` |

**Generate NEXTAUTH_SECRET:**
```bash
# Run on any machine with Node.js
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
```

> After adding variables, click **Save** in the cPanel interface.

---

## Step 7 — Install Dependencies

In cPanel → **Setup Node.js App** → click **Run NPM Install** button.

OR via SSH:
```bash
cd ~/shottrack

# Activate the virtual environment created by cPanel
source /home/youraccount/nodevenv/shottrack/20/bin/activate

# Install production dependencies
npm install --omit=dev
```

---

## Step 8 — Build the Application

Via SSH (required — cannot do this via cPanel UI):

```bash
cd ~/shottrack

# Activate Node.js environment
source /home/youraccount/nodevenv/shottrack/20/bin/activate

# Build Next.js
npm run build
```

> The build will take **3–8 minutes**. You need at least 512 MB of free RAM.
> If the build fails with out-of-memory error, add this before the build:
> ```bash
> export NODE_OPTIONS="--max-old-space-size=512"
> npm run build
> ```

---

## Step 9 — Run Database Migrations

```bash
cd ~/shottrack

# Activate environment if not already active
source /home/youraccount/nodevenv/shottrack/20/bin/activate

# Deploy migrations (does NOT reset data — safe on live DB)
npx prisma migrate deploy

# Generate Prisma client (if needed)
npx prisma generate
```

---

## Step 10 — Seed the Database (First Time Only)

```bash
cd ~/shottrack
npx ts-node --compiler-options '{"module":"CommonJS"}' prisma/seed.ts
```

Or if you have a compiled seed:
```bash
npm run db:seed
```

> This creates the initial SUPER_ADMIN account. **Only run once.**
> Default credentials are in `prisma/seed.ts` — change the password immediately after first login.

---

## Step 11 — Start the Application

In cPanel → **Setup Node.js App** → click **Restart** on your app.

OR via SSH:
```bash
cd ~/shottrack
source /home/youraccount/nodevenv/shottrack/20/bin/activate
npm start
# or
node server.js
```

> cPanel's Phusion Passenger will manage the process automatically. You do not need PM2 with cPanel's Node.js Selector.

---

## Step 12 — Set Up SSL (HTTPS)

1. cPanel → **Security** → **SSL/TLS Status**
2. Find your domain → click **Run AutoSSL**
3. Or: cPanel → **Let's Encrypt SSL** → issue certificate for your domain
4. After SSL is active, update `NEXTAUTH_URL` to use `https://`

---

## Step 13 — File Upload Directory Permissions

The app saves OCR reading images to `public/uploads/readings/`. Ensure the directory exists and is writable:

```bash
cd ~/shottrack
mkdir -p public/uploads/readings
chmod 755 public/uploads/readings
```

---

## Step 14 — Verify the Deployment

1. Visit `https://yourdomain.com` — should show the login page
2. Log in with SUPER_ADMIN credentials from seed
3. Go to `/platform/settings` — verify environment variables show as **Configured**
4. Create a test factory and admin user
5. Log in as factory admin and test attendance, production tracking

---

## Troubleshooting

### App shows "Application Error" or 502
```bash
# Check the app log in cPanel → Setup Node.js App → Logs
# Or via SSH:
cat ~/logs/shottrack_error.log
```

### `prisma: command not found`
```bash
# Use full path
./node_modules/.bin/prisma migrate deploy
```

### Build fails — out of memory
```bash
export NODE_OPTIONS="--max-old-space-size=512"
npm run build
```

### `NEXTAUTH_URL` mismatch error
- Ensure `NEXTAUTH_URL` exactly matches your site URL including `https://` and no trailing slash

### Database connection refused
- Verify `DATABASE_URL` is correct
- For Neon: ensure `?sslmode=require` is at the end of the connection string
- Whitelist your server IP in Neon dashboard (or set to allow all: `0.0.0.0/0` for testing)

### Static files (images/CSS) not loading
- Ensure `.next/static` folder was included in your upload
- Check file permissions: `chmod -R 755 .next/`

### pg-boss job queue not processing
- pg-boss requires a running Node.js process — it starts automatically with the app
- Check that `DATABASE_URL` is reachable from the server

---

## Quick Reference — Useful Commands

```bash
# Restart the app
# Use cPanel → Setup Node.js App → Restart button

# Check Node.js version
node --version

# Check running processes
ps aux | grep node

# View recent app logs
tail -100 ~/logs/shottrack_access.log
tail -100 ~/logs/shottrack_error.log

# Rebuild after code update
source /home/youraccount/nodevenv/shottrack/20/bin/activate
npm install --omit=dev
npm run build
# Then restart via cPanel

# Run a one-off Prisma command
./node_modules/.bin/prisma studio  # GUI for DB (dev only)
./node_modules/.bin/prisma db push # Push schema without migration (use carefully on prod)
```

---

## Update Deployment Checklist

When pushing updates to the live server:

- [ ] Upload new files (exclude `node_modules`, `.next`, `.env`)
- [ ] SSH in and activate environment: `source .../nodevenv/shottrack/20/bin/activate`
- [ ] `npm install --omit=dev` (if `package.json` changed)
- [ ] `npm run build`
- [ ] `npx prisma migrate deploy` (if schema changed)
- [ ] Restart app via cPanel Node.js App Manager
- [ ] Verify site loads and test key flows
