# PBPS MIS V2: deployment guide

> **Superseded for now by [06_PARALLEL_DEPLOYMENT.md](06_PARALLEL_DEPLOYMENT.md)** (V2 beside V1, code by git pull, Apache). Since 2026-12-04 the web app is static files (`frontend/dist/client`, with `.htaccess`), so there is no `pbps-v2-web` process and no port 3000: where this file proxies `/` to port 3000, use the `DocumentRoot` block of 06, and leave `pbps-v2-web` out of the pm2 commands.

Server: Ubuntu, MySQL 8.0, Node 22.9 or newer, Apache with HTTPS, PM2.

**V2 replaces V1 on the same address.** Only one program can answer on `mis.icosconsult.com`, so V1 is switched **off** (step 6), not only put in maintenance. V1's files, database and Apache settings are kept unchanged, so you can switch back in a few minutes.

V2 serves the pages and the API from `https://mis.icosconsult.com` (the API under `/api/`). `misapi.icosconsult.com` is no longer needed: it forwards visitors to the new address.

Order of the day: step 1 (office computer, V1 in maintenance), steps 2 to 5 (server, V1 still running), step 6 (the switch, a few minutes), step 7 (checks).

Replace these everywhere:

| Write | Meaning |
|---|---|
| `APP_PASSWORD`, `BACKUP_PASSWORD` | two new, long passwords (letters and numbers only) |
| `SERVER` | your SSH login, for example `user@1.2.3.4` |

## Step 1. Final data (office computer)

1. Put V1 in **maintenance**, so nobody changes anything. Anything entered in V1 after this point is **not** in V2.
2. Export the `pbps_mis` database. Copy the whole `uploads` folder and unzip it. If you already have it, only the files added since are needed: `find uploads -newermt '2026-12-01' -type f` lists them.
3. Start MySQL with `V2\start-mysql.cmd`.
4. In `V2\Source code\backend`:
   ```
   npm run convert:production -- "C:\path\pbps_mis.sql" --uploads "C:\path\uploads"
   ```
   **Every check must say OK. If one fails, stop here.** `--uploads` must be the folder that directly holds V1's files, not a folder above it.
5. Put the lines it prints in `backend\.env` (the migration line in `backend\.env.migration`).
6. Check it a second way, directly against V1 (needs Python): `python tools\check-conversion.py v1_prod_<date> v2_prod_<date>` with the names it printed. Every line must say OK.
7. Start V2 here and compare the dashboard with V1.
8. Make the server files (stop V2 first):
   ```
   npm run export:server -- "C:\path\for_server"
   ```
   It writes `pbps_v2.sql`, `pbps_v2_v1_archive.sql` and `storage\`. Demo accounts are disabled; sessions and waiting emails are left out.

`for_server` holds personal data. Delete it from both computers when you are finished.

## Step 2. Copy to the server

In `V2\Source code` (PowerShell or Command Prompt):

```
tar -czf pbps-v2-code.tgz --exclude=node_modules --exclude=dist --exclude=.output --exclude=.tanstack --exclude=storage --exclude=backend/.env --exclude=backend/.env.migration --exclude=backend/migration --exclude=backend/parity backend frontend ecosystem.config.cjs
scp pbps-v2-code.tgz SERVER:
scp -r "C:\path\for_server" SERVER:
```

On the server:

```bash
node -v && mysql --version && apache2 -v && pm2 -v    # all four must answer; node 22.9+
free -h                                               # building needs about 2 GB free memory (or swap)
sudo ss -ltnp | grep -E ':4100|:3000'                 # must show nothing. If a port is taken, see "Ports" below
sudo apache2ctl -M | grep -E 'proxy_module|proxy_http|headers|ssl'   # all four; else: sudo a2enmod proxy proxy_http headers ssl
sudo mkdir -p /var/www/pbps-v2 /var/lib/pbps/storage /var/backups/pbps
sudo chown -R $USER: /var/www/pbps-v2 /var/lib/pbps /var/backups/pbps
chmod 700 /var/lib/pbps /var/backups/pbps
tar -xzf ~/pbps-v2-code.tgz -C /var/www/pbps-v2
cp -r ~/for_server/storage/. /var/lib/pbps/storage/
```

Run everything, including PM2, as this same user. If Node is older than 22.9, install Node 22 for this user with `nvm`, so V1's Node stays as it is for the way back. If `pm2` is missing: `npm install -g pm2`.

## Step 3. Database

`sudo mysql`, then:

```sql
CREATE DATABASE pbps_v2 CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE DATABASE pbps_v2_v1_archive CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER pbps_app@localhost IDENTIFIED BY 'APP_PASSWORD';
CREATE USER pbps_backup@localhost IDENTIFIED BY 'BACKUP_PASSWORD';
GRANT SELECT,INSERT,UPDATE,DELETE ON pbps_v2.* TO pbps_app@localhost;
GRANT SELECT ON pbps_v2_v1_archive.* TO pbps_app@localhost;
GRANT SELECT,LOCK TABLES,SHOW VIEW ON pbps_v2.* TO pbps_backup@localhost;
GRANT SELECT,LOCK TABLES,SHOW VIEW ON pbps_v2_v1_archive.* TO pbps_backup@localhost;
GRANT ALL ON pbps_v2_restore_check.* TO pbps_backup@localhost;
GRANT PROCESS ON *.* TO pbps_backup@localhost;
```

If `CREATE DATABASE` says the database exists, **stop**: do not import over it.

```bash
sudo mysql pbps_v2            < ~/for_server/pbps_v2.sql            && echo imported
sudo mysql pbps_v2_v1_archive < ~/for_server/pbps_v2_v1_archive.sql && echo imported
```

Both must print `imported`.

## Step 4. Settings

```bash
cd /var/www/pbps-v2/backend
cp .env.production.example .env && chmod 600 .env && nano .env
```

Change only these:

| Line | Value |
|---|---|
| `DATABASE_URL` | `APP_PASSWORD` in place of `CHANGE_ME` |
| `BACKUP_DATABASE_URL` | `BACKUP_PASSWORD` in place of `CHANGE_ME` |
| `APP_ENCRYPTION_KEY` | **the same key** as in `backend\.env` on the office computer. Keep a copy somewhere safe: without it the saved mail password and two-step codes are lost |
| `BACKUP_COPY_DIR` | a folder on another disk or computer, if you have one |

Keep `MAIL_DELIVERY=off` for now. The server needs no migration settings.

## Step 5. Build and start

```bash
cd /var/www/pbps-v2/backend  && npm ci && npm run build
cd /var/www/pbps-v2/frontend && npm ci && npm run build      # frontend/.env (developer footer) must be there first
cd /var/www/pbps-v2 && pm2 start ecosystem.config.cjs && pm2 save
pm2 startup                                                  # only if PM2 does not start at boot yet; run the line it prints
curl http://127.0.0.1:4100/health/ready                      # {"status":"ok"}
curl -I http://127.0.0.1:3000/                               # 200
```

## Step 6. The switch: V1 off, V2 on

**1. Keep V1's settings** (your way back):

```bash
sudo mkdir -p /root/apache-v1 && sudo cp -a /etc/apache2/sites-available /etc/apache2/sites-enabled /root/apache-v1/
grep -lE "mis(api)?\.icosconsult\.com" /etc/apache2/sites-enabled/*     # V1's site files
sudo certbot certificates                                                # certificate paths of mis and misapi
pm2 list; systemctl list-units --type=service | grep -iE "pbps|mis|node" # how V1's backend runs
```

**2. Write V2's site file** `sudo nano /etc/apache2/sites-available/pbps-v2.conf` (use the certificate paths you just saw):

```apache
<VirtualHost *:443>
  ServerName mis.icosconsult.com
  SSLEngine on
  SSLCertificateFile    /etc/letsencrypt/live/mis.icosconsult.com/fullchain.pem
  SSLCertificateKeyFile /etc/letsencrypt/live/mis.icosconsult.com/privkey.pem
  ProxyRequests Off
  ProxyPreserveHost On
  ProxyTimeout 600
  RequestHeader set X-Forwarded-Proto "https"
  LimitRequestBody 31457280
  # Evidence, as in V1: 100 MB per file, up to 25 files. V2 itself enforces the limits.
  <LocationMatch "^/api/v2/projects/[0-9]+/(obligations/[0-9]+/submissions|verification/subjects/[0-9]+/evidence)$">
    LimitRequestBody 0
  </LocationMatch>
  ProxyPass        /api/ http://127.0.0.1:4100/api/
  ProxyPassReverse /api/ http://127.0.0.1:4100/api/
  ProxyPass        /     http://127.0.0.1:3000/
  ProxyPassReverse /     http://127.0.0.1:3000/
  ErrorLog  ${APACHE_LOG_DIR}/pbps-v2-error.log
  CustomLog ${APACHE_LOG_DIR}/pbps-v2-access.log combined
</VirtualHost>
<VirtualHost *:80>
  ServerName mis.icosconsult.com
  Redirect permanent / https://mis.icosconsult.com/
</VirtualHost>
# The old API address sends people to the new one.
<VirtualHost *:443>
  ServerName misapi.icosconsult.com
  SSLEngine on
  SSLCertificateFile    /etc/letsencrypt/live/misapi.icosconsult.com/fullchain.pem
  SSLCertificateKeyFile /etc/letsencrypt/live/misapi.icosconsult.com/privkey.pem
  Redirect permanent / https://mis.icosconsult.com/
</VirtualHost>
```

**3. Switch** (this is when V1 goes down):

```bash
pm2 stop <V1 backend name>          # or: sudo systemctl stop <V1 service>, as seen in 1
sudo a2dissite <V1 site files>      # the files that hold mis and misapi; their copies are in /root/apache-v1
sudo a2ensite pbps-v2
sudo apache2ctl configtest && sudo systemctl reload apache2
curl -I https://mis.icosconsult.com/                 # 200
curl -s -o /dev/null -w '%{http_code}
' https://mis.icosconsult.com/api/v2/public/stats   # 200
```

`configtest` must say "Syntax OK". If it complains, run `sudo a2dissite pbps-v2`, `sudo a2ensite <V1 site files>`, reload, start V1 again, and send me the message.

Never delete V1's folder or the `pbps_mis` database. Ports 4100, 3000 and 3306 must stay closed to the outside.

## Step 7. Check before inviting providers

- [ ] The public page opens and its numbers are right.
- [ ] The administrator can sign in with the V1 password.
- [ ] Dashboard figures equal those of the office computer.
- [ ] An old evidence file opens, and a new file above 30 MB can be uploaded and opened.
- [ ] One account of each provider sees only its own data.
- [ ] The employment placement template downloads for Mohas and DAB and lists their certified trainees.
- [ ] The login page shows **no** demo buttons.
- [ ] Administration, Backups: "Back up now" ends with "ok".
- [ ] Mail & reminders: check the outbox and the settings. Then set `MAIL_DELIVERY=on` in `.env`, run `pm2 restart pbps-v2-api pbps-v2-worker`, and send a test email.
- [ ] Restart the server once. V2 comes back by itself.

Then open V2 to providers, and keep V1 in maintenance.

## Ports

If 4100 is taken: change `PORT` in `.env` and the two `/api/` lines in `pbps-v2.conf`. If 3000 is taken: change `PORT` in `ecosystem.config.cjs` and the two `/` lines. V1's own ports stay as they are.

## Updating V2 later

Press "Back up now" first. Copy the new code as in step 2, then:

```bash
cp -r /var/www/pbps-v2 /var/www/pbps-v2-old           # the way back
tar -xzf ~/pbps-v2-code.tgz -C /var/www/pbps-v2
cd /var/www/pbps-v2/backend  && npm ci && npm run build
cd /var/www/pbps-v2/frontend && npm ci && npm run build
pm2 restart pbps-v2-api pbps-v2-worker pbps-v2-web
```

`.env`, the database and the uploaded files are not touched. If an update changes the database, [04_DB_CHANGE_LOG.md](04_DB_CHANGE_LOG.md) says so: run its SQL as root **before** the restart.

## Going back

- **To V1:** `pm2 stop pbps-v2-api pbps-v2-worker pbps-v2-web`, `sudo a2dissite pbps-v2`, `sudo a2ensite <V1 site files>`, `sudo apache2ctl configtest && sudo systemctl reload apache2`, start V1's backend again, then take V1 out of maintenance. What people entered in V2 stays in V2 and is **not** in V1.
- **To the code before an update:** swap the folder with `/var/www/pbps-v2-old` and restart.
- **To a backup:** never over the database in use.
  ```bash
  sudo mysql -e "CREATE DATABASE pbps_v2_restored CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; GRANT ALL ON pbps_v2_restored.* TO pbps_backup@localhost; GRANT SELECT,INSERT,UPDATE,DELETE ON pbps_v2_restored.* TO pbps_app@localhost"
  cd /var/www/pbps-v2/backend && npm run backup:restore -- /var/backups/pbps/FOLDER pbps_v2_restored
  ```
  Then change the database name in `DATABASE_URL` and `BACKUP_DATABASE_URL` and restart. For backups to go on, give `pbps_backup` the same rights on `pbps_v2_restored_restore_check` as in step 3.

## When something is wrong

| You see | Look at |
|---|---|
| 502 or 503 | `pm2 status`, then `pm2 logs pbps-v2-api --lines 50`, and `sudo tail /var/log/apache2/pbps-v2-error.log` |
| API stops at once | A setting in `.env`: the log names it |
| Sign-in does nothing, or "origin" refused | `APP_URL` must be exactly the address in the browser, with https |
| `Access denied for user` | The password in `.env`, or the GRANT lines |
| Reports, emails or backups stay waiting | `pm2 logs pbps-v2-worker` |
| Upload refused as too large | `LimitRequestBody` in `pbps-v2.conf`. If a service such as Cloudflare stands before the server, it has its own limit |
| Build ends with "Killed" | Not enough memory: add swap |
