# Local setup on macOS (from the handover package)

A step-by-step guide to running the ERP on a Mac (Apple silicon or Intel, macOS 13 or newer) for the
first time. The repository includes two scripts that do almost all of the work. Allow 30 to 45
minutes, mostly downloads.

All commands are typed in **Terminal** (Applications → Utilities → Terminal, or Spotlight → "Terminal").

---

## 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 |
| Your Mac password | Homebrew asks for it while installing |

---

## Step 1. Install Homebrew

Homebrew installs the other tools. Check whether you have it:

```bash
brew --version
```

If that prints "command not found", install it:

```bash
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
```

Follow the instructions it prints at the end. On Apple silicon these are two lines starting with
`echo >> ~/.zprofile` and `eval "$(/opt/homebrew/bin/brew shellenv)"`; run them, then close and reopen
Terminal. If macOS offers to install the "command line developer tools", accept.

---

## Step 2. Unpack the files

Copy `Bhagirath_ERP.zip`, `erp_db.dump` and `uploads.zip` into your **Downloads** folder, then:

```bash
mkdir -p ~/ERP && cd ~/ERP
unzip ~/Downloads/Bhagirath_ERP.zip
cd Bhagirath_ERP
unzip ~/Downloads/uploads.zip -d backend
chmod +x scripts/*.sh
```

You now have `~/ERP/Bhagirath_ERP` with `backend`, `frontend`, `docs` and `scripts`, and the photos in
`backend/uploads`.

---

## Step 3. Run the setup script

```bash
./scripts/setup_mac.sh ~/Downloads/erp_db.dump
```

It prints each step as it goes:

1. Installs PostgreSQL 18, Python 3.12 and Node.js with Homebrew (anything already installed is kept).
2. Starts PostgreSQL as a background service that also starts at login.
3. Creates the database login `erp_user` and the database `erp_db`.
4. Restores the dump into `erp_db` (`pg_restore --no-owner --no-privileges`). Any restore warnings are
   saved to a log file whose path it prints.
5. Creates the Python environment `backend/venv`, installs the packages, and writes `backend/.env`
   with a fresh random `SECRET_KEY` (only if `.env` does not exist yet).
6. Applies the database migrations (`alembic upgrade head`).
7. Installs the frontend packages (`npm install`).

The database password defaults to `erp_2026`. To choose your own, run it as
`DB_PASS='your-password' ./scripts/setup_mac.sh ~/Downloads/erp_db.dump`.

Running the script again is safe. To throw the database away and restore the dump again:

```bash
./scripts/setup_mac.sh ~/Downloads/erp_db.dump --reset-db
```

---

## Step 4. Start the app

```bash
./scripts/run_mac.sh
```

It starts PostgreSQL if needed, the API on port 8000 and the screens on port 5173, and stops any
earlier copy of the app first. Open:

- http://localhost:5173: the application
- http://localhost:8000/docs: API documentation

Press **Ctrl+C** in Terminal to stop both.

---

## Step 5. 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 create a password hash:

```bash
cd ~/ERP/Bhagirath_ERP/backend
./venv/bin/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 6).

---

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

Install it if you don't have it:

```bash
brew install --cask pgadmin4
```

1. Open **pgAdmin 4** from Applications.
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 `erp_2026` (or the one you chose), 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`.

If pgAdmin says the server was not found or the connection was refused, PostgreSQL is not running:
`brew services start postgresql@18`.

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 7. Use phones on the same Wi-Fi (optional)

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

```bash
./scripts/run_mac.sh --lan
```

It prints a `Phones:` address such as `http://192.168.1.20:5173`; open that on a phone connected to the
same Wi-Fi. If macOS asks whether Python or Node may accept incoming connections, choose **Allow**.

`backend/.env` must contain the `ALLOWED_ORIGIN_REGEX` line (new setups get it automatically; for an
older `.env`, copy the line from `backend/.env.example`).

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 8. 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

```bash
cd ~/ERP/Bhagirath_ERP
./scripts/run_mac.sh          # or --lan for phones
```

When you receive a newer version of the code, replace the folder contents (keep `backend/.env`, `backend/venv` and `backend/uploads`) and run the setup script again. With the database already in
place it skips the restore and only installs new packages and applies new migrations:

```bash
./scripts/setup_mac.sh
```

---

## Back up your data

```bash
export PATH="$(brew --prefix postgresql@18)/bin:$PATH"
PGPASSWORD=erp_2026 pg_dump -h localhost -U erp_user -d erp_db -Fc -f ~/ERP/erp_db_$(date +%Y%m%d).dump
```

Copy `~/ERP/Bhagirath_ERP/backend/uploads` alongside it.

---

## Doing it by hand (without the scripts)

```bash
brew install postgresql@18 python@3.12 node
brew services start postgresql@18
export PATH="$(brew --prefix postgresql@18)/bin:$PATH"     # add to ~/.zshrc to keep it

psql -d postgres -c "CREATE ROLE erp_user LOGIN PASSWORD 'erp_2026' CREATEDB"
psql -d postgres -c "CREATE DATABASE erp_db OWNER erp_user ENCODING 'UTF8' TEMPLATE template0"
PGPASSWORD=erp_2026 pg_restore -h localhost -U erp_user -d erp_db --no-owner --no-privileges ~/Downloads/erp_db.dump

cd ~/ERP/Bhagirath_ERP/backend
python3.12 -m venv venv && source venv/bin/activate
pip install -r requirements.txt
cp .env.example .env        # then edit: database password, SECRET_KEY (python -c "import secrets; print(secrets.token_hex(32))")
alembic upgrade head
uvicorn app.main:app --reload --port 8000

# second Terminal window
cd ~/ERP/Bhagirath_ERP/frontend && npm install && npm run dev
```

The dump was made on Windows with a Windows-only locale, which is why the database is created first
and restored into, rather than using `pg_restore --create`.

---

## Troubleshooting

| Problem | Cause and fix |
|---|---|
| `zsh: permission denied: ./scripts/setup_mac.sh` | Run `chmod +x scripts/*.sh` once, then repeat. |
| `unsupported version (1.16) in file header` | An older `pg_restore` is first on your PATH. Run `export PATH="$(brew --prefix postgresql@18)/bin:$PATH"` (add it to `~/.zshrc`). |
| Restore finished but the app shows no data | Run the setup with `--reset-db`; check the restore log path the script printed. |
| Port 5432 already in use | Another PostgreSQL (Postgres.app, an older Homebrew version, Docker) is running. Stop it, e.g. `brew services stop postgresql@16`. |
| `role "<your Mac user>" does not exist` | PostgreSQL was set up by a different install. Run `createuser -s $(whoami)` with that install's superuser, or remove the old data directory. |
| `password authentication failed for user "erp_user"` | `backend/.env` does not match the database password. Edit both `DATABASE_URL` lines. |
| `run_mac.sh` says setup hasn't finished | `backend/venv` or `frontend/node_modules` is missing. Run the setup script again. |
| `Port 8000 (or 5173) is used by another program` | The script names the program and its PID. Close it, or `kill <PID>`. |
| Browser shows "Unable to connect to the server" | The API stopped. Look at the Terminal output for the error. |
| Browser console shows a CORS error | The address in the browser is not allowed by `ALLOWED_ORIGINS` / `ALLOWED_ORIGIN_REGEX` in `backend/.env`. Restart after editing. |
| Photos and documents show as broken | `uploads.zip` was not unpacked into `backend` (Step 2). The folder must be `backend/uploads/...`. |
| Phone cannot open the page | Same Wi-Fi? Started with `--lan`? Allowed incoming connections when macOS asked? |
