# EasyPOS — Deployment Guide (Node.js on shared hosting)

EasyPOS runs as a single Node.js application. The server (`server.js`) serves the
web app in `app/` **and** provides the whole API under `/api`, so there is no PHP,
no Apache rewrite rules and no separate API folder to configure.

- Web app + API: `http://your-domain/` and `http://your-domain/api?q=…`
- Health check: `http://your-domain/api/health`
- Uploaded product images: `http://your-domain/uploads/products/…`

Everything that used to be in `app/api/*.php` is now handled by `server.js`, and
the database tables, first admin user and default settings are created
automatically the first time the server starts against an empty database.

---

## 0. What you need before you start

| Item | Detail |
| --- | --- |
| Node.js hosting | cPanel/DirectAdmin **with the "Setup Node.js App" feature**, Node 18 or newer |
| PostgreSQL | The hosting must offer PostgreSQL (cPanel → *PostgreSQL Databases*). MySQL alone is not enough — EasyPOS uses PostgreSQL |
| Domain | e.g. `pos.bibetech.co.ke`, pointed at the hosting account |
| SSL | AutoSSL / Let's Encrypt certificate (M-Pesa requires HTTPS) |
| M-Pesa | Daraja consumer key, secret, passkey and shortcode (only for live STK push) |

> If the cPanel account has no *PostgreSQL Databases* icon, ask the host to enable
> PostgreSQL for the account before continuing. EasyPOS will not start against MySQL.

---

## 1. Create the database

1. In cPanel open **PostgreSQL Databases**.
2. **Create New Database**: `posdb` → the host prefixes it, e.g. `bibetech_posdb`.
   Write the full name down.
3. **Add New User**: e.g. `posuser`, choose a strong password. Write both down.
4. **Add User To Database** → select the database and user → tick **ALL PRIVILEGES**.
5. Note the database **host** (almost always `localhost`) and **port** (`5432`).

You do **not** need to import `schema.sql` by hand — step 5 does it automatically.

---

## 2. Upload the application

1. In cPanel open **File Manager** and go to your home folder.
2. Create a folder for the app, e.g. `easypos` (keep it **outside** `public_html`
   if your host allows it, e.g. `/home/USER/easypos`).
3. Upload a zip of the project — `server.js`, `package.json`,
   `package-lock.json`, `schema.sql`, `.env.example` and the `app/` folder.
   **Do not upload `node_modules`** — it is installed on the server in step 6.
4. Right-click the zip → **Extract** → delete the zip afterwards.
5. Confirm this structure:

```
easypos/
├── server.js
├── package.json
├── package-lock.json
├── schema.sql
├── backup.sh
├── .env.example
└── app/
    ├── index.html
    ├── assets/          (css, js, vendor libraries)
    └── uploads/products/
```

> Make sure `app/uploads/products/` exists and is writable (permission `755`).
> Product images are saved there.

---

## 3. Create the `.env` file

The app reads its settings from `.env` in the same folder as `server.js`.
Real environment variables set in cPanel win over the file, so either place works.

1. In File Manager enable **Settings → Show Hidden Files (dotfiles)**.
2. Copy `.env.example` to `.env` (right-click → Copy, then rename).
3. Edit `.env`:

```ini
PORT=                                   # leave empty on cPanel — the host sets it
DB_HOST=localhost
DB_PORT=5432
DB_NAME=bibetech_posdb                  # the FULL name cPanel created
DB_USER=bibetech_posuser                # the FULL user name cPanel created
DB_PASSWORD=your-database-password
NODE_ENV=production                     # enables production checks
SECRET_KEY=paste-a-long-random-string   # 32+ characters, signs the login cookie
ADMIN_USERNAME=admin                    # first-run admin (only used if DB is empty)
ADMIN_PASSWORD=choose-a-strong-password # 10+ characters, required on production
```

Generate `SECRET_KEY` with anything random, e.g. `openssl rand -hex 32`.

`.env` must never be committed to source control or shared — it holds the
database password and the cookie signing key.

---

## 4. Set up the Node.js application

1. cPanel → **Setup Node.js App** → **Create Application**.
2. Fill in:
   - **Node.js version**: 18, 20 or 22 (anything ≥ 18 — the server uses global `fetch`)
   - **Application mode**: Production
   - **Application root**: `easypos` (the folder from step 2)
   - **Application URL**: `pos.bibetech.co.ke` (or the subfolder you want)
   - **Application startup file**: `server.js`
3. Click **Create**. cPanel writes a Passenger `.htaccess` for the app — do not
   replace it with your own SPA rewrite rules; `server.js` already serves
   `app/index.html` and every route.
4. Optional but recommended: add the same keys from `.env` under
   **Environment variables** in this screen. cPanel restarts the app whenever you
   change them.

---

## 5. Install dependencies

In the same **Setup Node.js App** screen:

1. Click **Run NPM Install** (runs `npm install` in the Application root), or use
   the terminal:
   ```bash
   source /home/USER/nodevenv/easypos/20/bin/activate
   cd /home/USER/easypos
   npm install --omit=dev
   ```
2. Wait for "dependencies installed" (installs `express`, `pg`, `bcryptjs`, `multer`).

---

## 6. First start — tables, admin user, settings

1. Click **Restart** in *Setup Node.js App*.
2. Open `https://pos.bibetech.co.ke/api/health`. You should get:

```json
{"status":"ok","message":"EasyPOS Node.js API is running","db":"ok","port":...}
```

A response of `503 {"status":"error","message":"Database unavailable"}` means the
Node process is up but cannot reach PostgreSQL — check the `DB_*` values.

On this first start the server:

- applies `schema.sql` to the empty database (tables, indexes),
- runs the column migrations (UOMs, pack/piece selling, staff PINs, etc.),
- seeds the currency/payment-method settings,
- creates the first administrator from `ADMIN_USERNAME` / `ADMIN_PASSWORD`
  (if the database already has users, nothing is overwritten).

If the health check fails, read the log first — see *Troubleshooting*.

3. Open `https://pos.bibetech.co.ke/` and sign in.
4. **Change the admin password immediately** in *Settings → Users*.

---

## 7. Moving your existing data (optional)

To bring the shop's current local data along:

```bash
# On the machine that has the working database
pg_dump -h localhost -U postgres -Fc posdb > easypos.dump

# Upload easypos.dump to the server, then on the host (SSH):
pg_restore -h localhost -U bibetech_posuser -d bibetech_posdb --no-owner easypos.dump
```

Alternatively, in the running app: *Products → Stock template / Upload stock* for
products, and re-enter staff under *Settings → Users*. Restart the Node app after
a restore so migrations run against the imported tables.

Copy `app/uploads/products/` from the old install to the server as well, so
product images keep working.

---

## 8. HTTPS

1. cPanel → **SSL/TLS Status** → **Run AutoSSL** for the domain (or install the
   certificate your host provides).
2. Make sure the *Application URL* is reached over `https://`. Login cookies are
   marked `Secure` automatically when the request arrives over HTTPS (the app
   trusts the host's proxy), so do not run the shop on plain HTTP.
3. If images or styles fail to load after enabling SSL, check the browser console
   for "mixed content" and confirm the site is opened with `https://`.

---

## 9. M-Pesa (only if you take STK payments)

1. Sign in → **Settings → M-Pesa**.
2. Set environment (sandbox for testing, production for live), shortcode,
   consumer key, consumer secret and passkey from the Daraja portal.
3. Callback URL — press **Use this site**:
   `https://pos.bibetech.co.ke/api?q=mpesa/callback`
   (the old `…/api/index.php?q=mpesa/callback` URL still works if it is already
   registered at Safaricom).
4. Save, then **Test connection**.
5. Register the same callback URL in the Daraja portal.

M-Pesa pushes only reach a **public HTTPS** URL, so this will never work from
`localhost`.

---

## 10. Backup and restore

Two things cannot be recreated if they are lost: the **PostgreSQL database**
(sales, stock, users, settings) and **`app/uploads/products/`** (product images).
`backup.sh` (in the application root, next to `server.js`) captures both in one
timestamped archive.

### Run a backup

```bash
cd /home/USER/easypos
./backup.sh
```

This writes `backups/easypos-backup-YYYYMMDD-HHMMSS.tar.gz` containing:

| Entry | Contents |
| --- | --- |
| `db.dump` | Full database, `pg_dump --format=custom` |
| `uploads.tar.gz` | The whole `app/uploads/` folder (product images) |
| `backup-info.txt` | When and from which database it was taken |

The script reads the same `.env` as the server, so there is nothing to configure.
It keeps the newest **14** archives and deletes older ones (`KEEP=30 ./backup.sh`
to change that, `KEEP=0` to keep everything). It needs `pg_dump` and `tar` — they
are on the host when PostgreSQL client tools are installed.

**Copy the archive off the server.** A backup that only exists on the machine it
protects is not a backup: download it in cPanel *File Manager*, or sync the
`backups/` folder to another location. Archives contain customer data and the
full user table — treat them like `.env`.

### Schedule it nightly

cPanel → **Cron Jobs** → *Add New Cron Job*, once a day (e.g. 02:30):

```bash
30 2 * * * cd /home/USER/easypos && mkdir -p backups && ./backup.sh >> backups/backup.log 2>&1
```

Check `backups/backup.log` after the first run — it prints one `==>` line per
step and any error.

### Restore a backup

Stop the app first (cPanel → *Setup Node.js App* → **Stop**), so nobody writes
to the database while it is being replaced. Then:

```bash
cd /home/USER/easypos
./backup.sh restore backups/easypos-backup-20261120-023000.tar.gz
```

It prints what the archive contains and asks you to type `restore`. It then:

1. `pg_restore --clean --if-exists` into the database from `.env` (existing
tables are dropped and recreated from the dump),
2. replaces `app/uploads/` with the archived copy.

Start the app again afterwards (**Start**/**Restart**). Add `--yes` to skip the
confirmation prompt when restoring from a script.

> Restoring **overwrites** current data. To look inside an archive without
> changing anything: `tar -tzf backups/easypos-backup-….tar.gz`.

### Testing the procedure

Restore into a scratch database once and check a sale opens, product images show
and staff can sign in. Verify the backup actually ran (the cron log and a recent
archive) — an untested backup is only a hope.

---

## 11. Day-to-day operation

| Task | How |
| --- | --- |
| Restart after a code change | cPanel → *Setup Node.js App* → **Restart** |
| Update a file | Upload it into place, then **Restart** (the server reads `app/` fresh) |
| Check the app is alive | `https://pos.bibetech.co.ke/api/health` |
| Change a setting | In the app: *Settings* (currency, payment methods, M-Pesa) |
| Backup database + images | `./backup.sh` → archive in `backups/` (see section 10) |
| Restore a backup | `./backup.sh restore backups/<archive>.tar.gz` (stop the app first) |

Back up the database **and** `app/uploads/` regularly — they are the two things
that cannot be regenerated, and `backup.sh` captures both.

---

## 12. Troubleshooting

**The site shows a 503 or "Application error"**
The Node process is not running: open *Setup Node.js App*, read the stderr log,
fix the reported error and press Restart. The most common causes are a wrong
`DB_*` value in `.env` or a missing `node_modules` (run *Run NPM Install*).

**`/api/health` works but the page does not load**
An old `.htaccess` from the PHP version is still rewriting requests. Delete any
`.htaccess` in the application root except the one cPanel created for Node
(Passenger). `server.js` serves `app/index.html` itself.

**"Could not connect to database" / startup migration failed**
Check `DB_NAME` and `DB_USER` include the cPanel account prefix, the password is
correct, and the user has ALL PRIVILEGES on the database. Test from the terminal:
`psql -h localhost -U USER -d DB -c 'select 1'`.

**Login works but you are logged out on every click**
The login cookie needs HTTPS. Use `https://` and confirm AutoSSL finished.

**Product images upload but do not show**
`app/uploads/products/` must be writable and must sit inside `app/` — images are
served from `/uploads/products/…`.

**M-Pesa "not configured yet"**
Consumer key, secret, passkey and shortcode are missing in *Settings → M-Pesa*.
"Needs a public HTTPS callback URL" means the callback in Settings is empty or not
`https://`.

**Node version error on start**
Pick Node 18+ in the cPanel app settings; older versions have no global `fetch`
and the M-Pesa integration will fail.

---

## 13. Production checklist

Run through this before the shop goes live:

- [ ] `NODE_ENV=production` is set (cPanel *Application mode: Production*).
- [ ] `SECRET_KEY` is 32+ random characters (`openssl rand -hex 32`). The server
      **refuses to start** in production with a missing or placeholder key.
- [ ] `ADMIN_PASSWORD` is 10+ characters for the first start on an empty database.
- [ ] The site is served over **HTTPS** (login cookies are `Secure`).
- [ ] `npm install --omit=dev` was run and `node --check server.js` passes.
- [ ] `/api/health` returns `db: "ok"`.
- [ ] Nightly `./backup.sh` is scheduled (section 10) and one archive has been
      restored into a scratch database successfully.
- [ ] `.env` is not committed or publicly downloadable (`/\.env` must 404).
- [ ] The admin password was changed after the first sign-in.

What the server does automatically in production:

| Behaviour | Detail |
| --- | --- |
| Fail-fast config | Exits with a clear message when `SECRET_KEY`/`ADMIN_PASSWORD` are unsafe |
| Security headers | `nosniff`, `X-Frame-Options: DENY`, `Referrer-Policy`, HSTS over HTTPS |
| Login throttling | 10 failed sign-ins per IP/username per 10 minutes (`LOGIN_MAX_ATTEMPTS`) |
| Cross-site protection | Non-GET `/api` requests with a foreign `Origin` are rejected |
| No caching | API responses are `Cache-Control: no-store`; HTML is revalidated |
| Error hygiene | Full errors go to the log; clients get a generic message |
| Resilience | Idle database errors are logged instead of crashing the process |
| Graceful restarts | `SIGTERM`/`SIGINT` drain requests, then close the database pool |
| Access log | One line per API request (`method path status ms ip`) |

For VPS/Docker hosts, run under a supervisor that restarts on failure (systemd,
pm2 or Docker `restart: unless-stopped`) and send stdout to a rotating log. Stop
the process with `SIGTERM` so in-flight sales finish before exit.

---

## 14. Local development (on your own computer)

```bash
npm install
cp .env.example .env     # then fill in your local PostgreSQL details
npm start                # http://localhost:3001
```

Requires PostgreSQL running locally and a `posdb` database. The same automatic
schema/admin bootstrap runs on the first start.
