# PBPS MIS V2 next to V1 (Apache, git, read-only mirror rebuilt every night)

V1 stays as it is on `mis.icosconsult.com` / `misapi.icosconsult.com`, and everyone keeps working in V1.
V2 runs beside it on the same server, from the **same git repository**:

```
/var/www/html/pbps-mis/            ← the git clone (V1 is already deployed here)
├── backend/                       ← V1 backend
├── frontend/                      ← V1 frontend
└── V2/
    ├── docs/                      ← this guide
    └── Source code/
        ├── backend/               ← V2 API + worker (PM2)
        ├── frontend/              ← V2 web app (TanStack, built to static files, served by Apache)
        └── ecosystem.config.cjs   ← PM2 file for V2
```

| Address | What it serves |
|---|---|
| `https://monitoring.icosconsult.com` | **Admin / web app**: the static files of `frontend/dist/client`, and the API under `/api/` (the browser needs both on one address for the sign-in cookie) |
| `https://monitoring-api.icosconsult.com` | **Backend**: the API only (`/api/v2/...`, `/health/ready`), for checks and tools |

V2 is **read-only** while V1 is the live system (`MIRROR_MODE=on`). People sign in with their V1 password and see everything. Every change is refused with "Make changes in V1", because the nightly rebuild would erase it.

V1 is only ever **read**. Nothing in V1, its uploads or its database is changed or deleted.

The folder name `Source code` has a space. Always keep the quotes shown below.

Replace these everywhere:

| Write | Meaning |
|---|---|
| `APP_PW`, `BACKUP_PW`, `MIGRATOR_PW`, `CONVERT_PW`, `DUMP_PW` | five new long passwords (letters and numbers only) |
| `V1_UPLOADS` | the full path of V1's `uploads` folder (the folder that directly holds the files), for example `/var/www/html/pbps-mis/backend/uploads` |

## How the code gets to the server

No `scp` and no second repository. On your computer you commit and push as usual (V1 and V2 are in the same repository). On the server, `git pull` in `/var/www/html/pbps-mis` brings both.

What git never carries (see `V2/.gitignore`): `.env` files, database dumps (`*.sql` at the top of V2, `*.zip`), `reports/` (exports with names and phones), the manual sources, the Windows `.cmd` scripts, `node_modules`, builds (`dist`), `storage/` and migration reports. The server makes its own `.env` files once (step 4) and builds the code itself.

## Step 1. DNS

At the DNS provider of icosconsult.com add two **A records** to the server's IP (the same IP as `mis`): `monitoring` and `monitoring-api`.
Wait until `ping monitoring.icosconsult.com` shows the server's IP.

## Step 2. Get the code and check the server

```bash
cd /var/www/html/pbps-mis && git pull
ls "V2/Source code"                                     # backend  ecosystem.config.cjs  frontend
node -v && mysql --version && apache2 -v && pm2 -v      # node 22.9 or newer (use nvm for this user if not)
free -h                                                 # about 2 GB free (or swap) to build
sudo ss -ltnp | grep -E ':4100'                         # must show nothing; else change PORT in step 4 and in step 7
sudo a2enmod proxy proxy_http headers ssl rewrite
sudo mkdir -p /var/lib/pbps/storage /var/backups/pbps/v1-nightly
sudo chown -R $USER: /var/lib/pbps /var/backups/pbps && chmod 700 /var/lib/pbps /var/backups/pbps
ls V1_UPLOADS | head                                    # must list V1's files
```

Run everything below, including PM2 and cron, as this same user.

### Copy V1's uploads to V2 (once)

V2 keeps its files in `/var/lib/pbps/storage`, outside git, so a pull never touches them and pushes stay small (the local `storage/` folder of 300+ MB is never committed). V1's uploads are only **copied**; V1's folder is not changed.

```bash
rsync -a V1_UPLOADS/ /var/lib/pbps/storage/legacy/           # copy, V1 keeps its files
du -sh V1_UPLOADS /var/lib/pbps/storage/legacy               # both about the same size
find /var/lib/pbps/storage/legacy -type f | wc -l            # same count as:
find V1_UPLOADS -type f | wc -l
# Writable by V2 (PM2 user) for files uploaded later, closed to everyone else:
sudo chown -R $USER: /var/lib/pbps
find /var/lib/pbps/storage -type d -exec chmod 700 {} +
find /var/lib/pbps/storage -type f -exec chmod 600 {} +
touch /var/lib/pbps/storage/.write-test && rm /var/lib/pbps/storage/.write-test && echo writable
```

The nightly run (step 6) copies V1's uploads again each night, the same way, so new files from V1 reach V2 by themselves. It then places every file V2 knows about under its V2 name in the same folder and checks its size. A file missing in V1 stops the switch.

## Step 3. MySQL users

`sudo mysql`, then (no databases are created here; the nightly run creates them):

```sql
-- V2 itself: reads and writes only the V2 database of the night, reads its archive.
CREATE USER pbps_app@localhost      IDENTIFIED BY 'APP_PW';
-- V2's own daily backup.
CREATE USER pbps_backup@localhost   IDENTIFIED BY 'BACKUP_PW';
GRANT PROCESS ON *.* TO pbps_backup@localhost;
-- The converter: reads the V1 copy, writes the new V2 database.
CREATE USER pbps_migrator@localhost IDENTIFIED BY 'MIGRATOR_PW';
-- Creates the nightly databases and gives the three users above their rights on them. Nothing else.
CREATE USER pbps_convert@localhost  IDENTIFIED BY 'CONVERT_PW';
GRANT ALL ON `v1\_prod\_%`.* TO pbps_convert@localhost WITH GRANT OPTION;
GRANT ALL ON `v2\_prod\_%`.* TO pbps_convert@localhost WITH GRANT OPTION;
GRANT SELECT ON mysql.user TO pbps_convert@localhost;
-- Copies V1 every night. Read-only.
CREATE USER pbps_v1_dump@localhost  IDENTIFIED BY 'DUMP_PW';
GRANT SELECT, LOCK TABLES, SHOW VIEW, TRIGGER ON pbps_mis.* TO pbps_v1_dump@localhost;
```

If V1's database is not called `pbps_mis`, use its real name here and in `V1_DB` (step 6).

## Step 4. Settings (once)

```bash
cd "/var/www/html/pbps-mis/V2/Source code/backend"
cp .env.production.example .env && chmod 600 .env
openssl rand -hex 32          # the encryption key: paste it below AND keep a copy somewhere safe
nano .env
```

| Line | Value |
|---|---|
| `APP_URL` | `https://monitoring.icosconsult.com` |
| `DATABASE_URL` | `mysql://pbps_app:APP_PW@127.0.0.1:3306/pbps_v2` (the database name is replaced by every nightly run) |
| `BACKUP_DATABASE_URL` | `mysql://pbps_backup:BACKUP_PW@127.0.0.1:3306/pbps_v2` |
| `ARCHIVE_DB` | leave it; the nightly run sets it |
| `APP_ENCRYPTION_KEY` | the key from `openssl` |
| `STORAGE_DIR` | `/var/lib/pbps/storage` (outside git, so a pull never touches files) |
| `MAIL_DELIVERY` | **off**: V1 already sends the reminders, V2 would send them a second time |
| `MIRROR_MODE` | **on** |

The converter's logins, and V1's read-only login for the copy:

```bash
cat > .env.migration <<'EOF'
MIGRATION_DATABASE_URL=mysql://pbps_migrator:MIGRATOR_PW@127.0.0.1:3306/pbps_v2
CONVERT_ADMIN_URL=mysql://pbps_convert:CONVERT_PW@127.0.0.1:3306
EOF
chmod 600 .env.migration
printf '[client]\nuser=pbps_v1_dump\npassword=DUMP_PW\nhost=127.0.0.1\n' > ~/.pbps-v1-dump.cnf && chmod 600 ~/.pbps-v1-dump.cnf
```

The developer footer of the web app:

```bash
cd "/var/www/html/pbps-mis/V2/Source code/frontend" && cp .env.example .env && nano .env
```

## Step 5. Build, first sync, start

```bash
cd "/var/www/html/pbps-mis/V2/Source code/backend"  && npm ci && npm run build    # npm ci also installs tsx, which the converter needs
cd "/var/www/html/pbps-mis/V2/Source code/frontend" && npm ci && npm run build    # TanStack build: static files in dist/client
ls -a "/var/www/html/pbps-mis/V2/Source code/frontend/dist/client"                # _shell.html  .htaccess  assets/ ...
cd "/var/www/html/pbps-mis/V2/Source code" && pm2 start ecosystem.config.cjs && pm2 save
pm2 startup                                       # only if PM2 does not start at boot yet; run the line it prints
chmod +x "/var/www/html/pbps-mis/V2/Source code/backend/tools/nightly-sync.sh"
V1_UPLOADS=V1_UPLOADS "/var/www/html/pbps-mis/V2/Source code/backend/tools/nightly-sync.sh"
```

PM2 runs two V2 programs: `pbps-v2-api` (port 4100) and `pbps-v2-worker`. The web app needs no program: Apache serves its files.

The API restarts in a loop until the first sync has made a database. That is expected.
The sync must end with `OK: V2 now shows V1 as of ...`. If it says `FAILED`, send me the log it names; V2 keeps the database it had.

```bash
curl http://127.0.0.1:4100/health/ready      # {"status":"ok"}
```

## Step 6. The nightly copy from V1 to V2

`crontab -e`, add one line (02:30 every night; V1 keeps running during the copy):

```
30 2 * * * V1_UPLOADS=V1_UPLOADS V1_DB=pbps_mis "/var/www/html/pbps-mis/V2/Source code/backend/tools/nightly-sync.sh" >> /var/backups/pbps/v1-nightly/cron.log 2>&1
```

For fresher data run it more often, for example `30 */6 * * *` (every 6 hours). Each run signs everyone out of V2.

### The databases, and what one run does

```
 pbps_mis  (V1, live)                               only READ, by pbps_v1_dump
    │  1. mysqldump --single-transaction            one consistent moment; V1 is not stopped or locked
    ▼
 /var/backups/pbps/v1-nightly/pbps_mis_<time>.sql   the copy (also a nightly V1 backup)
    │  2. imported by pbps_convert
    ▼
 v1_prod_<time>                                     V1 as it was at <time>; the converter reads only this
    │  3. converted by pbps_migrator, every check run, V1 uploads copied to /var/lib/pbps/storage
    ▼
 v2_prod_<time>                 ← V2's data (pbps_app reads and writes; refused while MIRROR_MODE=on)
 v2_prod_<time>_v1_archive      ← every V1 table, unchanged (pbps_app reads, for audit)
    │  4. only if every check passed
    ▼
 backend/.env                   DATABASE_URL, BACKUP_DATABASE_URL and ARCHIVE_DB now name the new databases
                                (the old file is kept as .env.before-<time>), then V2 restarts
    │  5. if V2 is not healthy after 15 seconds
    ▼
 .env goes back to the previous night's databases, V2 restarts on them
```

| Database | Made by | Used by | Changed after the run? |
|---|---|---|---|
| `pbps_mis` | V1 | V1; read by the nightly copy | Only by V1 |
| `v1_prod_<time>` | step 2 | the converter, once | No |
| `v2_prod_<time>` | step 3 | V2 (`DATABASE_URL`) | No, while `MIRROR_MODE=on` |
| `v2_prod_<time>_v1_archive` | step 3 | V2, read-only (`ARCHIVE_DB`) | No |
| `v2_prod_<time>_restore_check` | V2's daily backup | the backup check, then emptied | Temporary |

| MySQL user | Rights |
|---|---|
| `pbps_v1_dump` | read `pbps_mis` |
| `pbps_convert` | create `v1_prod_*` / `v2_prod_*` and grant the users below on them |
| `pbps_migrator` | read `v1_prod_<time>`, write `v2_prod_<time>` and its archive |
| `pbps_app` | read and write `v2_prod_<time>`, read its archive |
| `pbps_backup` | read the V2 databases, use `*_restore_check` |

When a run fails, nothing is switched: V2 shows the previous night's data, and the log `/var/backups/pbps/v1-nightly/sync_<time>.log` says why. The most common reason is a **change to V1's database tables** (a new V1 migration): the converter stops until V2's conversion knows the new columns. Ask me to update V2 whenever you change V1's tables.

## Step 7. Apache

`sudo nano /etc/apache2/sites-available/pbps-v2.conf`:

```apache
# Never serve V2's backend, git, or any .env file from /var/www/html (the default site would otherwise show them).
<Directory "/var/www/html/pbps-mis/V2/Source code/backend">
  Require all denied
</Directory>
<Directory "/var/www/html/pbps-mis/.git">
  Require all denied
</Directory>
<FilesMatch "^\.env">
  Require all denied
</FilesMatch>

<VirtualHost *:80>
  ServerName monitoring.icosconsult.com
  DocumentRoot "/var/www/html/pbps-mis/V2/Source code/frontend/dist/client"
  <Directory "/var/www/html/pbps-mis/V2/Source code/frontend/dist/client">
    Options -Indexes +FollowSymLinks
    # Lets dist/client/.htaccess send a refreshed page (/p/1/trainees) to _shell.html instead of 404.
    AllowOverride All
    Require all granted
  </Directory>
  ProxyRequests Off
  ProxyPreserveHost On
  ProxyTimeout 600
  RequestHeader set X-Forwarded-Proto "https"
  LimitRequestBody 31457280
  <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/
  ErrorLog  ${APACHE_LOG_DIR}/pbps-v2-error.log
  CustomLog ${APACHE_LOG_DIR}/pbps-v2-access.log combined
</VirtualHost>

<VirtualHost *:80>
  ServerName monitoring-api.icosconsult.com
  ProxyRequests Off
  ProxyPreserveHost On
  ProxyTimeout 600
  RequestHeader set X-Forwarded-Proto "https"
  ProxyPass        /api/   http://127.0.0.1:4100/api/
  ProxyPassReverse /api/   http://127.0.0.1:4100/api/
  ProxyPass        /health http://127.0.0.1:4100/health
  RedirectMatch    ^/$     https://monitoring.icosconsult.com/
  ErrorLog  ${APACHE_LOG_DIR}/pbps-v2-api-error.log
  CustomLog ${APACHE_LOG_DIR}/pbps-v2-api-access.log combined
</VirtualHost>
```

Enable it (V1's site files are **not** touched), then get the certificate:

```bash
sudo a2ensite pbps-v2
sudo apache2ctl configtest && sudo systemctl reload apache2       # must say "Syntax OK"
sudo certbot --apache -d monitoring.icosconsult.com -d monitoring-api.icosconsult.com --redirect
```

certbot writes `/etc/apache2/sites-available/pbps-v2-le-ssl.conf` (the same two sites with HTTPS) and makes plain http forward to https.

Checks:

```bash
curl -I https://monitoring.icosconsult.com/                         # 200
curl -I https://monitoring.icosconsult.com/p/1/trainees             # 200 (the .htaccess works; without it: 404)
curl -s https://monitoring-api.icosconsult.com/health/ready          # {"status":"ok"}
curl -s -o /dev/null -w '%{http_code}\n' https://mis.icosconsult.com/              # V1 still 200
curl -s -o /dev/null -w '%{http_code}\n' "http://127.0.0.1/pbps-mis/V2/Source%20code/backend/.env"   # 403 or 404, never 200
curl -s -o /dev/null -w '%{http_code}\n' "http://127.0.0.1/pbps-mis/backend/.env"                    # 403 or 404, never 200
```

If a refreshed page shows 404: `AllowOverride All` is missing, `rewrite` is not enabled (`sudo a2enmod rewrite`), or `dist/client/.htaccess` is missing (build again).

## Step 8. Check in the browser

- [ ] V1 opens and works as before.
- [ ] `https://monitoring.icosconsult.com`: sign in with a V1 account and password.
- [ ] Press F5 on any page: the same page comes back, no 404.
- [ ] Dashboard figures equal V1's (completers, certified, dropouts per provider).
- [ ] Saving anything shows "This is a read-only copy of V1".
- [ ] No demo buttons on the login page.
- [ ] The next morning `/var/backups/pbps/v1-nightly/cron.log` ends with `OK`.

## Updating after a commit

After you push from your computer, on the server:

```bash
cd /var/www/html/pbps-mis && git pull
# V1: build and restart it the way you always do.
# V2:
cd "V2/Source code/backend"  && npm ci && npm run build
cd ../frontend               && npm ci && npm run build
pm2 restart pbps-v2-api pbps-v2-worker
```

`.env` files, the databases and `/var/lib/pbps/storage` are not touched by a pull. If an update changes V2's database, [04_DB_CHANGE_LOG.md](04_DB_CHANGE_LOG.md) says so.

## Disk space

Nothing is deleted automatically. Each run keeps its V1 dump in `/var/backups/pbps/v1-nightly` and three new databases (V1 copy, V2, archive). Check once a week with `df -h` and `sudo du -sh /var/lib/mysql`. When you want, I can add a cleanup that keeps only the last 7 runs.

## When V2 becomes the live system

1. Put V1 in maintenance and run `nightly-sync.sh` once more by hand (last data).
2. Remove the cron line, set `MIRROR_MODE=off`, and `pm2 restart pbps-v2-api pbps-v2-worker`.
3. Point people to `monitoring`, or move V2 to `mis.icosconsult.com` (change `ServerName` and `APP_URL`, disable V1's site files, see step 6 of [05_DEPLOYMENT.md](05_DEPLOYMENT.md)).
4. Switch `MAIL_DELIVERY=on` only after V1 has stopped sending.

From then on nothing goes back from V2 to V1, so never run the sync again.

## Stopping V2 (V1 is not affected)

`pm2 stop pbps-v2-api pbps-v2-worker`, `sudo a2dissite pbps-v2 pbps-v2-le-ssl`, `sudo systemctl reload apache2`, and remove the cron line.
