# Deploying Wetroo Automation to a cPanel VPS Server

This guide explains how to deploy `wetroo-automation-shopify-app/wetroo-notify` to a **cPanel VPS server** (with root/SSH access) on **`https://shopify.wetroo.com`** for 24/7 production use and Shopify App Store readiness.

---

## Architecture on cPanel VPS

- **Runtime:** Node.js `>= 22.12` running `npm run start` (`node --env-file=.env ./node_modules/@react-router/serve/dist/cli.js ./build/server/index.js`) on `127.0.0.1:3000`, kept alive by **PM2**.
- **Web Server / SSL:** cPanel Apache proxies HTTPS traffic from `https://shopify.wetroo.com` to `http://127.0.0.1:3000`, while cPanel **AutoSSL** handles HTTPS certificates.
- **Database:** Embedded **SQLite** managed by Prisma ORM, stored outside `public_html` on disk (e.g. `/home/<user>/wetroo-data/app.sqlite`) so deployments never overwrite store data.

---

## Step 1: Prepare Subdomain & SSL in cPanel

1. In **cPanel → Domains**, create the subdomain **`shopify.wetroo.com`** with its document root (e.g. `/home/<user>/shopify.wetroo.com`).
2. Go to **cPanel → SSL/TLS Status** and run **AutoSSL** so `https://shopify.wetroo.com` has a valid SSL certificate. Shopify requires valid HTTPS for embedded apps, OAuth, and webhooks.

---

## Step 2: Install Node.js 22+ and PM2 on the VPS

`package.json` requires **Node.js `>= 22.12`**. On a cPanel VPS, running Node via **PM2 + Apache Reverse Proxy** is recommended over Phusion Passenger because Passenger puts idle apps to sleep and can interfere with ESM packages and the background job timer.

SSH into the VPS as `root` (or your cPanel user via `nvm`) and install Node 22 + PM2:

```bash
# Example on AlmaLinux / CloudLinux / Rocky Linux (WHM/cPanel VPS):
curl -fsSL https://rpm.nodesource.com/setup_22.x | sudo bash -
sudo dnf install -y nodejs

# Verify Node version (>= 22.12)
node -v

# Install PM2 globally to manage the Node process
sudo npm install -g pm2
```

> **Note:** Also verify build tools (`gcc-c++`, `make`, `python3`) are installed in case `better-sqlite3` needs to compile its native binary (`sudo dnf install -y gcc-c++ make python3`).

---

## Step 3: Upload Application Files (Outside `public_html`)

Log in as your cPanel user (or switch to `/home/<user>`) and create two directories:

```bash
mkdir -p /home/<user>/wetroo-notify
mkdir -p /home/<user>/wetroo-data
```

Upload the contents of `wetroo-automation-shopify-app/wetroo-notify/` into `/home/<user>/wetroo-notify/`.

**Do NOT upload from Windows:**
- `node_modules/` (contains Windows binaries for `better-sqlite3`; must be installed on Linux)
- `build/` (rebuild on the server)
- `.shopify/`
- `prisma/dev.sqlite` (local test database)
- local `.env` (contains local dev values)

**Make sure these ARE included:**
- `app/`, `extensions/`, `prisma/` (including `schema.prisma` and `migrations/`), `public/`, `scripts/patch-pkg.mjs`
- `package.json`, `package-lock.json`, `tsconfig.json`, `vite.config.ts`, `shopify.app.toml`

---

## Step 4: Create Production `.env`

Create `/home/<user>/wetroo-notify/.env` on the server:

```env
NODE_ENV=production
PORT=3000

# ---- Shopify (Partner Dashboard -> Apps -> wetroo-automation -> Client credentials) ----
SHOPIFY_API_KEY=9c0ff3df40679a9258f1e4214f7d4e79
SHOPIFY_API_SECRET=YOUR_PRODUCTION_CLIENT_SECRET
SHOPIFY_APP_URL=https://shopify.wetroo.com
SCOPES=read_orders,write_orders,read_customers,read_fulfillments,read_returns,write_app_proxy
SHOPIFY_APP_HANDLE=wetroo-automation

# ---- Billing (Shopify Managed Pricing) ----
# Set to 1 for Shopify App Store production; keep 0 only while testing without plans
BILLING_REQUIRED=1

# ---- Database (persistent path outside public_html) ----
DATABASE_URL="file:/home/<user>/wetroo-data/app.sqlite"

# ---- Security ----
# Generate once with: openssl rand -hex 32
# NEVER change this after stores connect, or stored Wetroo API keys will stop decrypting.
ENCRYPTION_KEY=REPLACE_WITH_64_CHAR_RANDOM_HEX

# ---- Wetroo ----
WETROO_API_BASE_URL=https://app.wetroo.com/api/shopify/v1
WETROO_MOCK=0

# ---- Public pages (/privacy and /support) ----
COMPANY_NAME=Wetroo Automation
SUPPORT_EMAIL=support@wetroo.com
SUPPORT_PHONE=
LOG_RETENTION_DAYS=90

# ---- Background jobs (abandoned cart reminders, review requests, campaigns) ----
# With PM2 running 24/7, keep DISABLE_JOB_WORKER=0 so the built-in 1-minute worker runs.
DISABLE_JOB_WORKER=0
CRON_SECRET=REPLACE_WITH_RANDOM_SECRET
CAMPAIGN_PER_MINUTE=60
```

Protect the `.env` file permissions:
```bash
chmod 600 /home/<user>/wetroo-notify/.env
```

---

## Step 5: Install Dependencies, Initialize Database & Build

Run these inside `/home/<user>/wetroo-notify`:

```bash
cd /home/<user>/wetroo-notify

# 1. Install dependencies (also runs scripts/patch-pkg.mjs via postinstall)
npm ci

# 2. Generate Prisma client and run SQLite migrations (creates app.sqlite)
npm run setup

# 3. Generate React Router types and build production client + server bundles
npx react-router typegen
npm run build
```

Verify that `/home/<user>/wetroo-data/app.sqlite` was created.

---

## Step 6: Start the App 24/7 with PM2

Start the React Router server using PM2 as your cPanel user:

```bash
cd /home/<user>/wetroo-notify
pm2 start npm --name "wetroo-notify" -- run start
pm2 save
```

Enable PM2 on server reboot (run the command printed by `pm2 startup` as `root` if prompted):

```bash
pm2 startup
```

Verify it is listening locally:

```bash
pm2 status
curl -I http://127.0.0.1:3000/privacy
```

You should see `HTTP/1.1 200 OK`.

---

## Step 7: Configure Apache Reverse Proxy in cPanel

Route HTTPS requests from `https://shopify.wetroo.com` to `http://127.0.0.1:3000`.

### Option A: Using `.htaccess` inside the subdomain's document root (simplest on cPanel)

Make sure `mod_proxy` and `mod_proxy_http` are enabled in WHM → **EasyApache 4** (enabled by default on most cPanel VPS setups).

Create `/home/<user>/shopify.wetroo.com/.htaccess`:

```apache
RewriteEngine On

# Allow cPanel AutoSSL certificate verification to serve from disk
RewriteRule ^\.well-known/ - [L]

# Force HTTPS
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# Forward all app, webhook, and proxy traffic to the Node.js server
RequestHeader set X-Forwarded-Proto "https"
RewriteRule ^(.*)$ http://127.0.0.1:3000/$1 [P,L]
```

### Option B: WHM Apache VirtualHost Include (cleanest for high traffic)

In WHM, create `/etc/apache2/conf.d/userdata/ssl/2_4/<user>/shopify.wetroo.com/proxy.conf`:

```apache
ProxyPreserveHost On
RequestHeader set X-Forwarded-Proto "https"

ProxyPass /.well-known/ !
ProxyPass / http://127.0.0.1:3000/
ProxyPassReverse / http://127.0.0.1:3000/
```

Then rebuild Apache config and restart Apache as `root`:

```bash
/scripts/rebuildhttpdconf
/scripts/restartsrv_httpd
```

Verify publicly:

```bash
curl -I https://shopify.wetroo.com/privacy
curl -I https://shopify.wetroo.com/support
```

Both should return `HTTP/2 200` (or `HTTP/1.1 200 OK`).

---

## Step 8: Deploy Production URLs & Extensions to Shopify

`shopify.app.toml` is already updated for `https://shopify.wetroo.com`:

```toml
client_id = "9c0ff3df40679a9258f1e4214f7d4e79"
name = "wetroo-automation"
application_url = "https://shopify.wetroo.com"
embedded = true

[access_scopes]
scopes = "read_orders,write_orders,read_customers,read_fulfillments,read_returns,write_app_proxy"

[auth]
redirect_urls = [
  "https://shopify.wetroo.com/api/auth/callback",
  "https://shopify.wetroo.com/auth/callback"
]

[app_proxy]
url = "https://shopify.wetroo.com/proxy"
subpath = "wetroo"
prefix = "apps"
```

Push the configuration and theme app extension to Shopify (from your local machine or server via Shopify CLI):

```bash
cd wetroo-automation-shopify-app/wetroo-notify
npm run deploy
```

---

## Step 9: Post-Deployment Verification

1. **Install / Open the app** on your development store (`wetroo-automation.myshopify.com`).
2. **Reconnect Wetroo once:** Go to **Connect Wetroo** in the app and save your Wetroo API key so Wetroo updates its registered webhook URL to `https://shopify.wetroo.com/webhooks/wetroo/<token>`.
3. **Verify Templates & Notifications:** Open **Templates** and confirm approved templates (`ss_order_confirmation`, `ss_cod_verification`, `ss_order_fulfilled`, etc.) show **Approved** and notifications are active.
4. **Test Live Flows:**
   - Place a COD / regular test order and check **Message logs** + WhatsApp delivery.
   - Open **Sync CRM**, check **Name / Email / Phone Number**, and click **Sync to Wetroo CRM**.
5. **Check PM2 logs** on the VPS for any runtime errors:
   ```bash
   pm2 logs wetroo-notify --lines 100
   ```

---

## Optional: Using Passenger Instead of PM2

If you decide to use cPanel's built-in **Application Manager / Setup Node.js App** (Phusion Passenger) instead of PM2:
1. Set `DISABLE_JOB_WORKER=1` in `.env` (Passenger shuts down idle processes).
2. Add a **cPanel Cron Job** running every minute (`* * * * *`) so abandoned cart reminders, review requests, and campaigns still send on time:
   ```bash
   curl -fsS "https://shopify.wetroo.com/cron?secret=YOUR_CRON_SECRET" > /dev/null
   ```
3. Run periodic log cleanup or hit your retention schedule separately if needed, because `cleanupOldData()` runs inside `startJobWorker()`.

---

## Routine Future Updates (Redeploy Checklist)

When deploying code updates to the VPS:

```bash
cd /home/<user>/wetroo-notify

# Pull or upload updated source files (never overwrite /home/<user>/wetroo-data/app.sqlite or .env)
npm ci
npm run setup
npx react-router typegen
npm run build
pm2 restart wetroo-notify
```

If `shopify.app.toml` or files under `extensions/` changed, also run:

```bash
npm run deploy
```
