# Installing AvtoAmbor on Windows (7 or higher)

This guide installs AvtoAmbor as a background service that starts automatically
when the machine boots, and opens itself in the default browser on login. After
setup the shop staff just turn the computer on — the app is running at
`http://localhost:3000` before they log in, and a browser tab opens to it
right after they log in.

> **Node.js version note for Windows 7 / 8**
> Node.js 20 (used in the Docker dev image) officially supports Windows 10+
> only. On **Windows 7 or 8** install **Node.js 16.x** instead (the last line
> that runs on those versions). SvelteKit's Node adapter and `better-sqlite3`
> both run fine on Node 16. On **Windows 10 or 11** use **Node.js 20 LTS**.

---

## 1. Prepare the build on the dev machine

On the Linux dev box, produce a production build and gather the files needed
on the Windows host.

```sh
make build         # produces ./build (SvelteKit adapter-node output)
make db-init       # ensure data/avtoambor.db exists (skip if you already have one)
```

Then create a single folder you'll copy to Windows. Call it `avtoambor-dist`:

```
avtoambor-dist/
├── build/                  # entire ./build directory from `make build`
├── data/
│   └── avtoambor.db        # the SQLite database
├── package.json
├── package-lock.json
└── scripts/                # only if you want db-init available on the host
```

`node_modules/` is **not** copied — it will be reinstalled on Windows so the
native `better-sqlite3` binary matches the Windows Node version.

Zip the folder and transfer it (USB stick, network share, scp, etc.).

---

## 2. On the Windows machine — one-time install

### 2.1 Install Node.js

- **Windows 10 / 11**: download the LTS x64 MSI from <https://nodejs.org> and
  run the installer with defaults. Verify in a new `cmd` window:
  ```
  node --version
  npm --version
  ```
- **Windows 7 / 8**: download Node.js **v16.20.2** from
  <https://nodejs.org/dist/v16.20.2/> (`node-v16.20.2-x64.msi`). Install with
  defaults. Same verification.

If the `node` command isn't found in a new terminal, log out and back in (the
installer adds `PATH` entries that don't apply to already-open shells).

### 2.2 Install build tools for `better-sqlite3`

`better-sqlite3` is a native module and needs a C++ toolchain to compile on
first install:

```
npm install --global --production windows-build-tools
```

> On Node 16+ this package is deprecated but still works. Alternatively, install
> "Desktop development with C++" from the Visual Studio Build Tools 2019
> installer (<https://aka.ms/vs/16/release/vs_buildtools.exe>) plus Python 3.

### 2.3 Lay the app down

Pick a stable location — `C:\AvtoAmbor` is the convention used below. Extract
the zip so you end up with:

```
C:\AvtoAmbor\
├── build\
├── data\avtoambor.db
├── package.json
├── package-lock.json
└── scripts\
```

Open `cmd.exe` **as Administrator**, cd into the folder, and install
production dependencies:

```
cd C:\AvtoAmbor
npm ci --omit=dev
```

This compiles `better-sqlite3` against the installed Node version. It can take
a few minutes the first time.

### 2.4 Smoke-test

Still in `C:\AvtoAmbor`:

```
node build\index.js
```

You should see a line like `Listening on 0.0.0.0:3000`. Open
<http://localhost:3000> in any browser to confirm the UI loads. Press
`Ctrl+C` to stop.

---

## 3. Run as a Windows service that starts on boot

We use **NSSM** (the Non-Sucking Service Manager) — it's a single tiny `.exe`,
no installer needed, and runs identically on Windows 7 through 11.

### 3.1 Install NSSM

1. Download `nssm-2.24.zip` from <https://nssm.cc/release/nssm-2.24.zip>.
2. Extract it. Copy `nssm-2.24\win64\nssm.exe` to `C:\AvtoAmbor\nssm.exe`
   (use `win32\nssm.exe` instead if your Windows is 32-bit).

### 3.2 Register the service

In an **Administrator** `cmd.exe`:

```
cd C:\AvtoAmbor
nssm install AvtoAmbor
```

A GUI window opens. Fill in:

| Tab           | Field              | Value                                  |
| ------------- | ------------------ | -------------------------------------- |
| Application   | Path               | `C:\Program Files\nodejs\node.exe`     |
| Application   | Startup directory  | `C:\AvtoAmbor`                         |
| Application   | Arguments          | `build\index.js`                       |
| Details       | Display name       | `AvtoAmbor`                            |
| Details       | Description        | `Auto-parts inventory web app`         |
| Details       | Startup type       | `Automatic`                            |
| Log on        | (leave as)         | `Local System account`                 |
| Process       | Process priority   | `Normal`                               |
| I/O           | Output (stdout)    | `C:\AvtoAmbor\logs\out.log`            |
| I/O           | Error (stderr)     | `C:\AvtoAmbor\logs\err.log`            |
| File rotation | Rotate Files       | ✔ (rotate at 10 MB is fine)            |
| Environment   | (one var per line) | `NODE_ENV=production`                  |
|               |                    | `PORT=3000`                            |
|               |                    | `HOST=0.0.0.0`                         |
|               |                    | `TZ=Asia/Dushanbe`                     |

Create the log folder first:
```
mkdir C:\AvtoAmbor\logs
```

Click **Install service**, then start it:

```
nssm start AvtoAmbor
```

Verify:

```
sc query AvtoAmbor
```
Should report `STATE : 4 RUNNING`. Open <http://localhost:3000> in a browser
— the app should respond.

> **Prefer the command line?** The same service can be created without the
> GUI:
> ```
> nssm install AvtoAmbor "C:\Program Files\nodejs\node.exe" "build\index.js"
> nssm set AvtoAmbor AppDirectory C:\AvtoAmbor
> nssm set AvtoAmbor AppStdout C:\AvtoAmbor\logs\out.log
> nssm set AvtoAmbor AppStderr C:\AvtoAmbor\logs\err.log
> nssm set AvtoAmbor AppEnvironmentExtra NODE_ENV=production PORT=3000 HOST=0.0.0.0 TZ=Asia/Dushanbe
> nssm set AvtoAmbor Start SERVICE_AUTO_START
> nssm start AvtoAmbor
> ```

### 3.3 Allow port 3000 if other machines on the LAN need access

Skip this section if only the local machine ever opens the app.

```
netsh advfirewall firewall add rule name="AvtoAmbor 3000" dir=in action=allow protocol=TCP localport=3000
```

---

## 4. Open the app in a browser automatically on login

The service runs before any user logs in, but you probably want a browser tab
to open as soon as the shop user logs in.

1. Press `Win + R`, type `shell:startup`, press Enter.
   That opens `C:\Users\<user>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup`.
2. Right-click → **New → Shortcut**.
3. Location of the item:
   ```
   "C:\Program Files\Google\Chrome\Application\chrome.exe" --start-maximized --app=http://localhost:3000
   ```
   (Use `msedge.exe` from `C:\Program Files (x86)\Microsoft\Edge\Application\`
   if Chrome isn't installed, or `firefox.exe` from
   `C:\Program Files\Mozilla Firefox\`.)
4. Name the shortcut `AvtoAmbor`.

`--app=` opens the page in a kiosk-style frameless window — feels more like a
desktop app and hides the address bar. Drop the flag if you want a normal
browser window.

> **Tip — start the browser slightly after login**
> If Chrome opens before the service has fully started, the first load may
> fail. Replace the shortcut target with a small batch file
> (`C:\AvtoAmbor\open-browser.bat`) that waits a few seconds:
> ```bat
> @echo off
> timeout /t 5 /nobreak >nul
> start "" "C:\Program Files\Google\Chrome\Application\chrome.exe" --start-maximized --app=http://localhost:3000
> ```
> and point the Startup shortcut at that batch file.

---

## 5. Day-to-day operations

| Task                       | Command (Admin `cmd`)                          |
| -------------------------- | ---------------------------------------------- |
| Start the service          | `nssm start AvtoAmbor`                         |
| Stop the service           | `nssm stop AvtoAmbor`                          |
| Restart                    | `nssm restart AvtoAmbor`                       |
| Check status               | `sc query AvtoAmbor`                           |
| Edit service settings      | `nssm edit AvtoAmbor`                          |
| Remove the service         | `nssm remove AvtoAmbor confirm`                |
| Tail the app log           | `type C:\AvtoAmbor\logs\out.log`               |
| Tail the error log         | `type C:\AvtoAmbor\logs\err.log`               |

The Services snap-in (`services.msc`) also shows **AvtoAmbor** and can be
used by anyone with admin rights.

---

## 6. Backups

The SQLite database is a single file: `C:\AvtoAmbor\data\avtoambor.db`. Stop
the service before copying it, or use the in-app backup endpoint if one
exists. A minimal nightly backup with Task Scheduler:

1. Create `C:\AvtoAmbor\backup.bat`:
   ```bat
   @echo off
   set STAMP=%date:~-4%-%date:~-10,2%-%date:~-7,2%
   copy /Y "C:\AvtoAmbor\data\avtoambor.db" "C:\AvtoAmbor\backups\avtoambor-%STAMP%.db"
   ```
2. `mkdir C:\AvtoAmbor\backups`
3. Task Scheduler → **Create Basic Task** → Daily → run `backup.bat` at e.g.
   02:00 → "Run whether user is logged on or not" + highest privileges.

---

## 7. Upgrading to a new version of the app

```
nssm stop AvtoAmbor
```
Replace `C:\AvtoAmbor\build\` with the new `build/` directory. If
`package.json` or `package-lock.json` changed, also copy those over and run:
```
cd C:\AvtoAmbor
npm ci --omit=dev
```
Then:
```
nssm start AvtoAmbor
```

The database in `data\` is untouched by an upgrade.

---

## 8. Troubleshooting

- **Service won't start, no useful error**
  Check `C:\AvtoAmbor\logs\err.log`. The two most common causes are
  (a) `better-sqlite3` was compiled against a different Node version — rerun
  `npm ci --omit=dev`; (b) port 3000 is already in use — `netstat -ano | findstr :3000`
  to find the offending PID.
- **`Error: The module was compiled against a different Node.js version`**
  You upgraded Node. From `C:\AvtoAmbor` run `npm rebuild better-sqlite3`.
- **Browser shows "This site can't be reached" right after login**
  The service hadn't finished starting. Use the batch-file delay trick in §4.
- **Database is locked**
  Something else has the DB open — usually a stray `node.exe` from a previous
  manual run. End it in Task Manager, then `nssm restart AvtoAmbor`.
- **Need to access from another PC on the LAN**
  Confirm the firewall rule (§3.3) and open `http://<windows-host-ip>:3000`
  from the other machine. Find the IP with `ipconfig`.
