# DEPLOYMENT.md

How the deployed sites are wired up. Read [`AGENTS.md`](./AGENTS.md) first.

---

## Environments

| Env | URL | Backend | Frontend | DB | Notes |
|-----|-----|---------|----------|-----|-------|
| **Production** | `https://binaplus.co.il` | Heroku (`bina-plus-...herokuapp.com`) | Netlify (or similar) | Atlas `bina-plus-main` | The original site. Owned by the upstream `origin` repo. We don't deploy here. |
| **Staging (V4 dev)** | `https://idev.binaplus.co.il` | Local Nest on this machine, port 1813 | Local Vue dev server, port 1814 | Local mongo `binaplus-local` | What we work against day-to-day. |
| **Local** | `http://localhost:1814` (or LAN IP) | localhost:1813 | localhost:1814 | localhost:27017 / `binaplus-local` | Same machine as staging — `idev` is a thin SSL-fronted alias. |

---

## Staging (`idev.binaplus.co.il`) — how it's wired

This is **not Heroku**. The staging site runs **on this machine** with **Nginx Proxy Manager (NPM)** in front for SSL termination + custom routing.

### DNS / SSL
- DNS: `idev.binaplus.co.il` is hosted on Netlify DNS (per the user — no Cloudflare in front).
- SSL: Let's Encrypt cert managed by NPM, auto-renewed.
- Port 80 → 443 redirect handled by NPM.

### NPM proxy host config
NPM forwards traffic to the local services:

- **Public host:** `idev.binaplus.co.il` → forward to `127.0.0.1:1814` (the Vue dev server).
- **Custom location `/api`** → forward to `http://127.0.0.1:1813` (the Nest backend).
- **Custom location `/socket.io`** → forward to `http://127.0.0.1:1813` with WebSocket support.

### Critical NPM directives (each location)
SSE streaming and Socket.IO break under default Nginx buffering. Each custom location MUST include:
```nginx
proxy_buffering off;
proxy_read_timeout 600s;
proxy_send_timeout 600s;
```
**Do not add other directives** like `gzip off` — those are invalid in the location block on OpenResty/NPM and cause the cert to fail to apply.

WebSocket support (the NPM checkbox "Websockets Support" must be on for the proxy host).

### Nginx-level extras
At the **proxy host level** (not location):
- "Block Common Exploits" — leave on.
- "Force SSL" — on.
- "HTTP/2 Support" — on.

---

## Backend (NestJS) — staging runtime

```bash
cd /home/user/bina_plus_workspace/main/backend
npm run start:dev          # NODE_ENV=stg, watch mode, port 1813
```

- Environment file: `backend/.env.stg`. Loaded via `selectEnv()` based on `NODE_ENV`.
- Hot-reload watches `src/`. Edits trigger rebuild + restart.
- Logs: `/tmp/v2_backend.log`.
- Port 1813 was previously bound to a stale Nest process — if `EADDRINUSE`, find with `lsof -i :1813 -t` and kill.

### Required staging env vars
Beyond the upstream defaults, these are set for V4 staging:

```ini
APP_PORT=1813
DATABASE_HOST=mongodb://localhost:27017
DATABASE_NAME=binaplus-local

# Closed beta — only these emails can log in:
BETA_USERS_WHITELIST=email1@x.com,email2@y.com,...

# Live debug panel — only these emails see it:
DEBUG_USERS_EMAILS=info@odma.co.il,israel25@enativ.com
```

API keys (OpenAI, Anthropic, Google, Replicate, OpenRouter, Stability.AI, AWS, GCP) are real billable keys copied from upstream staging. See `LOCAL_DEV_SETUP.md` § "API Keys".

A read-only backup of the original env: `backend/.env.stg.original`.

---

## Frontend — staging runtime

```bash
cd /home/user/bina_plus_workspace/main/frontend_v3
npm run serve             # vue-cli-service serve, port 1814
```

- `vue.config.js` configures the dev server:
  - `host: '0.0.0.0'`, `port: 1814`, `allowedHosts: 'all'`.
  - HMR WebSocket: `client: { webSocketURL: 'auto://0.0.0.0:0/ws' }` so it uses `wss://` on HTTPS pages (Mixed Content fix).
  - Proxy `/api` and `/socket.io` to `http://127.0.0.1:1813` with `proxy_buffering` disabled equivalents (`onProxyReq` sets `X-Accel-Buffering: no`; `onProxyRes` strips `content-encoding` / `content-length` and forces `cache-control: no-cache, no-transform`).
- Env files:
  - `.env.development` — used by `npm run serve`. `VUE_APP_API_URL=/api` so it goes through the local proxy.
  - `.env.local` (gitignored) — same as development for local-only overrides.
  - `.env.staging` — points to the upstream Heroku staging backend (used by `npm run build:staging`). **Don't use this for our V4 staging** — we serve from local Nest.
  - `.env.production` — points to upstream Heroku prod. Same caveat.

---

## MongoDB — staging

- `mongod` runs as a **systemd service** on this machine.
- **Replica set enabled** (`rs0`) — required because the codebase uses MongoDB transactions in a few places. Single-node replica set is fine.
- Database name: `binaplus-local`.
- 18 collections imported from production (no `chathistories` / `imagehistories` / `blockedimages` — saved 707 MB).
- See `LOCAL_DEV_SETUP.md` § "How to refresh the local DB" for the dump/restore command using the read-only Atlas user.

---

## Admin panel — staging

```bash
cd /home/user/bina_plus_workspace/main/admin_frontend
PATH=/usr/local/n/versions/node/20.19.6/bin:$PATH npm run dev   # Vite, port 1815
```

- Requires Node 20+ (Vite 7 uses `crypto.hash` introduced in Node 20). System Node is 18; Node 20 lives at `/usr/local/n/versions/node/20.19.6/bin`.
- Public URL: typically `http://95.217.88.138:1815` (LAN/VPN) or proxied separately by NPM if the user has set that up.
- Login: any super_admin from the imported `adminusers` collection (`israel25@enativ.com`, `g.hananel20@gmail.com`).

---

## Deploying changes — V4 workflow

1. Edit code in `frontend_v3/` or `backend/`.
2. The dev servers auto-reload — staging at `idev.binaplus.co.il` reflects the change as soon as compilation finishes.
3. Test in browser.
4. Commit: `git add -A && git commit -m "..."` on the appropriate branch (usually `main` in the trunk worktree, or `feature/<x>` in a feature worktree).
5. `git push v4 <branch>`.

There is no separate "deploy" step for staging — running the dev servers IS the deployment. To restart them cleanly:
```bash
pkill -f "v2/backend.*nest start"
pkill -f "v2/frontend_v3.*vue-cli-service"
# then re-run the start commands
```

Or use the existing `/tmp/v2_backend.log` / `/tmp/v2_frontend.log` files to tail what's happening.

---

## Pushing to the original (production) repo

**Don't do this without explicit user permission.**

If approved:
1. Confirm the feature branch is isolated (`git diff origin/main feature/<x>` shows only relevant files).
2. `git push origin feature/<x>` — pushes to the **original** repo's feature namespace.
3. Open a PR against `origin/dev` via GitHub.
4. The upstream maintainer merges `dev → stg → main`, which deploys the original `binaplus.co.il` (Heroku-driven).

The original site's deployment is owned by the original repo's CI — we don't touch that pipeline.

---

## Quick sanity checks

```bash
# Backend up?
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:1813/api/app-config        # → 200

# Frontend up?
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:1814                       # → 200

# Public staging up?
curl -s -o /dev/null -w "%{http_code}\n" https://idev.binaplus.co.il                 # → 200

# SSE actually streaming (not buffered)?
curl -N -X POST https://idev.binaplus.co.il/api/chat/create-conversation \
  -H "Authorization: Bearer <token>" -H "Content-Type: application/json" \
  -d '{"chat":{"content":"hi","type":"text"}}'
# Expect: chunks arriving over time, NOT a single blob at the end.
```
