# Local setup on Windows (from the handover package)

A step-by-step guide to running the ERP on a Windows 10 or 11 computer for the first time. Allow about
an hour. Every command is typed in **PowerShell** (Start menu → type `PowerShell` → open it).

When a command contains a path such as `C:\ERP\Bhagirath_ERP`, use the folder where you actually put
things.

---

## What you need before you start

| Item                  | Where it comes from                                                              |
| --------------------- | -------------------------------------------------------------------------------- |
| `Bhagirath_ERP.zip` | The application code and documentation                                           |
| `erp_db.dump`       | The database (structure and data). A PostgreSQL 18 archive, not a text SQL file. |
| `uploads.zip`       | Photos and documents uploaded in the app                                         |
| Administrator rights  | To install software                                                              |

---

## Step 1. Install the tools

Install these three programs, accepting the defaults unless the table says otherwise.

| Program                             | Download                                                                                          | During installation                                                                                                                                                                             |
| ----------------------------------- | ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Python 3.12**               | https://www.python.org/downloads/windows/ (choose the latest 3.12.x "Windows installer (64-bit)") | **Tick "Add python.exe to PATH"** on the first screen                                                                                                                                     |
| **Node.js LTS** (20 or newer) | https://nodejs.org                                                                                | Defaults are fine                                                                                                                                                                               |
| **PostgreSQL 18**             | https://www.postgresql.org/download/windows/ → "Download the installer"                          | Keep all components (server, pgAdmin 4, command line tools). Set a password for the`postgres` superuser and **write it down**. Keep port **5432**. Skip Stack Builder at the end. |

Close PowerShell and open a new one, so it sees the new programs. Then check each one:

```powershell
py -3.12 --version
node --version
npm --version
& "C:\Program Files\PostgreSQL\18\bin\psql.exe" --version
```

Each should print a version number (`psql (PostgreSQL) 18.x`). If one says "not recognized", see
[Troubleshooting](#troubleshooting).

Allow PowerShell to run the Python environment's activation script (one time, for your user only):

```powershell
Set-ExecutionPolicy -Scope CurrentUser RemoteSigned
```

Answer `Y` if asked.

---

## Step 2. Unpack the files

1. Create the folder `C:\ERP`.
2. Copy `Bhagirath_ERP.zip`, `erp_db.dump` and `uploads.zip` into `C:\ERP`.
3. Right-click `Bhagirath_ERP.zip` → **Extract All...** → extract to `C:\ERP`. You now have
   `C:\ERP\Bhagirath_ERP` containing `backend`, `frontend`, `docs` and `README.md`. (If Windows
   created `C:\ERP\Bhagirath_ERP\Bhagirath_ERP`, move the inner folder up one level.)
4. Right-click `uploads.zip` → **Extract All...** → extract to `C:\ERP\Bhagirath_ERP\backend`, so
   the photos end up in `C:\ERP\Bhagirath_ERP\backend\uploads`.

```powershell
cd C:\ERP\Bhagirath_ERP
```

---

## Step 3. Create the database user and the empty database

To save typing, put the PostgreSQL tools folder in a variable for this window:

```powershell
$PG = "C:\Program Files\PostgreSQL\18\bin"
```

Create a login called `erp_user` and a database called `erp_db`. Choose your own password in place of
`ChooseAPassword` and use it again in Steps 4 and 5. Enter the `postgres` password from Step 1 when
asked.

```powershell
& "$PG\psql.exe" -U postgres -h localhost -c "CREATE ROLE erp_user LOGIN PASSWORD 'ChooseAPassword' CREATEDB"
& "$PG\psql.exe" -U postgres -h localhost -c "CREATE DATABASE erp_db OWNER erp_user ENCODING 'UTF8' TEMPLATE template0"
```

Both should answer `CREATE ROLE` and `CREATE DATABASE`.

---

## Step 4. Load the dump into the database

```powershell
$env:PGPASSWORD = "ChooseAPassword"
& "$PG\pg_restore.exe" -h localhost -U erp_user -d erp_db --no-owner --no-privileges "C:\ERP\erp_db.dump"
```

This takes a minute or two. A few lines of warnings about extensions or comments are normal.

Check that the data arrived:

```powershell
& "$PG\psql.exe" -h localhost -U erp_user -d erp_db -c "SELECT count(*) AS tables FROM information_schema.tables WHERE table_schema = 'public'"
& "$PG\psql.exe" -h localhost -U erp_user -d erp_db -c "SELECT count(*) AS chassis FROM chassis_master"
```

The first should show well over 100 tables, the second the number of chassis in the dump.

> Why not open the `.sql` file in pgAdmin's query tool? Because it is a binary archive. Only
> `pg_restore` can read it, and it must be version 18 or newer.

---

## Step 5. Set up the backend (API)

```powershell
cd C:\ERP\Bhagirath_ERP\backend
py -3.12 -m venv venv
.\venv\Scripts\Activate.ps1
```

The prompt now starts with `(venv)`. Install the Python packages (takes a few minutes):

```powershell
python -m pip install --upgrade pip
pip install -r requirements.txt
```

Create the settings file from the template and open it:

```powershell
Copy-Item .env.example .env
python -c "import secrets; print(secrets.token_hex(32))"
notepad .env
```

In Notepad:

1. In both `DATABASE_URL` lines, replace `CHANGE_ME` with the password from Step 3.
2. Replace `SECRET_KEY=CHANGE_ME` with the long random value the `python -c ...` command printed.
3. Save and close.

Bring the database schema up to date with the code. This is safe on a freshly restored dump:

```powershell
alembic upgrade head
```

It ends without errors (the last line names revision `g3b4c5d6e7f8` or later).

Start the API:

```powershell
uvicorn app.main:app --reload --port 8000
```

Leave this window open. In a browser, http://localhost:8000/docs should show the API documentation.

---

## Step 6. Set up the frontend (screens)

Open a **second** PowerShell window:

```powershell
cd C:\ERP\Bhagirath_ERP\frontend
npm install
npm run dev
```

`npm install` takes a few minutes the first time. When Vite prints `Local: http://localhost:5173/`,
open http://localhost:5173 in Chrome or Edge.

---

## Step 7. Sign in

Use any staff account that exists in the dump (employee code or email, and its password). The users
are in the `login_users` table. If you do not know a password, ask an administrator to reset it in
**Admin > Users & Access**, or set one from the API window:

```powershell
cd C:\ERP\Bhagirath_ERP\backend
.\venv\Scripts\Activate.ps1
python -c "from app.core.security import hash_password; print(hash_password('NewPassword123'))"
```

and put the printed value in that user's `password_hash` column (pgAdmin, Step 8).

---

## Step 8. Connect pgAdmin (to look at the data)

1. Open **pgAdmin 4** from the Start menu.
2. Right-click **Servers → Register → Server...**
3. **General** tab: Name `ERP local`.
4. **Connection** tab: Host `localhost`, Port `5432`, Maintenance database `erp_db`, Username `erp_user`,
   Password the one from Step 3, tick **Save password**.
5. **Save**. Expand **ERP local → Databases → erp_db → Schemas → public → Tables**.

Every table has a description: select it and look at **Properties → Comment**. The full list with
columns is in `docs\DATABASE_REFERENCE.md` inside the project folder, and how everything fits together
is in `docs\TECHNICAL_HANDOVER.md`.

To prove the screens and pgAdmin use the same database: change something in the app (for example a
dropdown value under **Setup > Production Masters > Dropdown Lists**), then in pgAdmin right-click the
matching table → **View/Edit Data → All Rows**.

---

## Step 9. Use phones on the same Wi-Fi (optional)

Operators and QA use phones for **My Station** and **QA Inspection**.

1. Find the computer's address: `ipconfig` → "IPv4 Address", e.g. `192.168.1.20`.
2. Make sure `backend\.env` contains the `ALLOWED_ORIGIN_REGEX` line from `.env.example`.
3. Start the API so it accepts connections from the network:
   ```powershell
   uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
   ```

   The frontend already listens on the network.
4. The first time, Windows asks whether to allow Python and Node through the firewall: allow on
   **Private networks**.
5. On the phone, open `http://192.168.1.20:5173`.

Phone browsers allow the camera only on secure (HTTPS) pages, so on this local setup operators pick or
type the chassis number instead of scanning it. Camera scanning works once the system is served over
HTTPS.

---

## Step 10. Give people their stations

**Setup > Station Staff**: choose the user, the station and the role (**Operator** or **QA**). A person
with several stations sees one tab per station. Someone without any assignment can act at every
station their role's permissions allow.

---

## Every day after this

Two PowerShell windows:

```powershell
# window 1: API
cd C:\ERP\Bhagirath_ERP\backend
.\venv\Scripts\Activate.ps1
uvicorn app.main:app --reload --port 8000
```

```powershell
# window 2: screens
cd C:\ERP\Bhagirath_ERP\frontend
npm run dev
```

PostgreSQL runs as a Windows service and starts with the computer. Stop the app with **Ctrl+C** in
each window.

When you receive a newer version of the code, replace the folder contents (keep `backend\.env`, `backend\venv` and `backend\uploads`) and run once:

```powershell
cd C:\ERP\Bhagirath_ERP\backend; .\venv\Scripts\Activate.ps1; pip install -r requirements.txt; alembic upgrade head
cd C:\ERP\Bhagirath_ERP\frontend; npm install
```

---

## Back up your data

```powershell
$env:PGPASSWORD = "ChooseAPassword"
& "C:\Program Files\PostgreSQL\18\bin\pg_dump.exe" -h localhost -U erp_user -d erp_db -Fc -f "C:\ERP\backup\erp_db_$(Get-Date -Format yyyyMMdd).dump"
```

Copy `C:\ERP\Bhagirath_ERP\backend\uploads` alongside it.

---

## Troubleshooting

| Problem                                                                 | Cause and fix                                                                                                                                                                                                                         |
| ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `psql` / `pg_restore` "is not recognized"                           | Use the full path as shown (`& "$PG\psql.exe"`), or add `C:\Program Files\PostgreSQL\18\bin` to the system PATH (Start → "Edit the system environment variables" → Environment Variables → Path → New) and reopen PowerShell. |
| `py -3.12` "No suitable Python runtime found"                         | Python 3.12 is not installed. Install it from python.org with "Add python.exe to PATH".                                                                                                                                               |
| `Activate.ps1 cannot be loaded because running scripts is disabled`   | Run`Set-ExecutionPolicy -Scope CurrentUser RemoteSigned` and try again.                                                                                                                                                             |
| `pg_restore: error: unsupported version (1.16) in file header`        | An older PostgreSQL's`pg_restore` ran. Use the version 18 path exactly as in Step 4.                                                                                                                                                |
| `pg_restore: error: input file does not appear to be a valid archive` | The file is incomplete or not the dump. Check its size and get it again.                                                                                                                                                              |
| `password authentication failed for user "erp_user"`                  | The password in`backend\.env` (both lines) differs from the one in Step 3.                                                                                                                                                          |
| `database "erp_db" does not exist` / `connection refused`           | PostgreSQL service is stopped: Start → Services →`postgresql-x64-18` → Start.                                                                                                                                                    |
| `pip install` fails on a package                                      | Check`python --version` inside the venv says 3.12. Delete the `venv` folder and repeat Step 5 with `py -3.12`.                                                                                                                  |
| `alembic upgrade head` errors                                         | Read the last lines. A`DuplicateTable` / `already exists` error usually means the dump already contains that change: tell the developer the revision named in the error.                                                          |
| Browser shows "Unable to connect to the server"                         | The API window is not running, or crashed. Look at its last lines.                                                                                                                                                                    |
| Browser console shows a CORS error                                      | The address in the browser is not in`ALLOWED_ORIGINS` / `ALLOWED_ORIGIN_REGEX` in `backend\.env`. Restart the API after editing.                                                                                                |
| `Port 8000 (or 5173) is already in use`                               | Another copy is running. Close the other PowerShell window, or find it with `netstat -ano                                                                                                                                             |
| Photos and documents show as broken                                     | `uploads.zip` was not extracted into `backend` (Step 2, point 4). The folder must be `backend\uploads\...`.                                                                                                                     |
| Phone cannot open the page                                              | Same Wi-Fi? API started with`--host 0.0.0.0`? Firewall allowed for private networks?                                                                                                                                                |
