# Vozex POS - Deployment Guide

## Prerequisites

- **Node.js** v18+ (v20 LTS recommended)
- **Database**: MySQL 5.7+ / MariaDB 10.3+ or PostgreSQL 14+
- **OS**: Linux (Ubuntu 22.04 LTS recommended), Windows Server, or cPanel
- **RAM**: 2GB minimum, 4GB+ recommended
- **Storage**: 20GB+

---

## 1. Database Setup

### MySQL / MariaDB
```sql
CREATE DATABASE pos_desktop CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'posuser'@'localhost' IDENTIFIED BY 'your-strong-password';
GRANT ALL PRIVILEGES ON pos_desktop.* TO 'posuser'@'localhost';
FLUSH PRIVILEGES;
```

### PostgreSQL
```sql
CREATE DATABASE pos_desktop;
CREATE USER posuser WITH PASSWORD 'your-strong-password';
GRANT ALL PRIVILEGES ON DATABASE pos_desktop TO posuser;
```

---

## 2. Environment Configuration

```bash
# Clone the repository
git clone <your-repo-url> vozex-pos
cd vozex-pos

# Copy and edit .env
cp .env.example .env
```

### `.env` Configuration

```env
# Database (choose one)
DATABASE_PROVIDER="mysql"
DATABASE_URL="mysql://posuser:your-password@localhost:3306/pos_desktop"

# For PostgreSQL:
# DATABASE_PROVIDER="postgresql"
# DATABASE_URL="postgresql://posuser:your-password@localhost:5432/pos_desktop?schema=public"

# Web hosting
PORT=8080
HOST="0.0.0.0"
POS_CORS_ORIGIN="https://pos.yourdomain.com"
POS_COOKIE_SECURE="1"

# License
LICENSE_PUBLIC_KEY="<your-rsa-public-key>"
LICENSE_DEMO_KEY="DEMO-HOSTED-ACTIVE"
LICENSE_DEMO_AUTO_ACTIVATE="1"
LICENSE_DEMO_PLAN="Hosted Demo"
LICENSE_DEMO_LICENSE_ID="demo-hosted"
LICENSE_DEMO_OFFLINE_GRACE_DAYS="3650"
VITE_DEMO_LICENSE_KEY="DEMO-HOSTED-ACTIVE"

# Frontend API URL
VITE_API_BASE_URL="https://pos.yourdomain.com"
```

---

## 3. Install Dependencies

```bash
npm install
```

---

## 4. Database Migration & Seed

```bash
# For MySQL
npm run prisma:generate:mysql
npm run prisma:dbpush:mysql

# For PostgreSQL
npm run prisma:generate:postgres
npm run prisma:dbpush:postgres

# Seed (creates: branch, warehouse, admin/manager/cashier users)
npm run prisma:seed
```

**Default users created by seed:**
| Username   | Password      | Role             |
|------------|--------------|------------------|
| admin      | ChangeMe123! | ADMIN            |
| manager    | ChangeMe123! | MANAGER          |
| cashier    | ChangeMe123! | CASHIER          |
| inventory  | ChangeMe123! | INVENTORY_CLERK  |
| accountant | ChangeMe123! | ACCOUNTANT       |

**Change passwords on first login.**

---

## 5. Build

```bash
npm run build
```

This builds:
- `dist/shared/` — shared contracts
- `dist/backend/` — backend API
- `dist/reporting-worker/` — reporting worker
- `dist/renderer/` — frontend (React SPA)

---

## 6. Deploy & Run

### Option A: Direct with PM2 (Linux)

```bash
# Install PM2
npm install -g pm2

# Create ecosystem file: ecosystem.config.js
cat > ecosystem.config.js << 'EOF'
module.exports = {
  apps: [
    {
      name: 'vozex-pos',
      script: 'scripts/web-host.cjs',
      env: {
        NODE_ENV: 'production',
        PORT: 8080,
        HOST: '0.0.0.0'
      },
      instances: 1,
      exec_mode: 'fork',
      max_memory_restart: '1G',
      error_file: 'logs/err.log',
      out_file: 'logs/out.log',
      merge_logs: true
    }
  ]
};
EOF

# Start
pm2 start ecosystem.config.js
pm2 save
pm2 startup  # Auto-start on reboot
```

### Option B: cPanel / Shared Hosting

1. Upload the entire project folder to your hosting
2. Run `npm install && npm run build` via SSH
3. Set up a **Node.js App** in cPanel:
   - **Application root**: `/home/user/vozex-pos`
   - **Entry point**: `scripts/web-host.cjs`
   - **Environment**: `NODE_ENV=production`
   - **Passenger log file**: `logs/passenger.log`

### Option C: Docker (manual)

```dockerfile
# Dockerfile
FROM node:20-alpine
WORKDIR /app
COPY package*.json .
RUN npm ci --omit=dev
COPY . .
RUN npm run prisma:generate:mysql && npm run build
EXPOSE 8080
CMD ["node", "scripts/web-host.cjs"]
```

```yaml
# docker-compose.yml
version: '3.8'
services:
  db:
    image: mysql:8.0
    environment:
      MYSQL_DATABASE: pos_desktop
      MYSQL_USER: posuser
      MYSQL_PASSWORD: your-password
      MYSQL_ROOT_PASSWORD: root-password
    volumes:
      - mysql-data:/var/lib/mysql
    ports:
      - "3306:3306"

  app:
    build: .
    ports:
      - "8080:8080"
    environment:
      NODE_ENV: production
      DATABASE_URL: mysql://posuser:your-password@db:3306/pos_desktop
      PORT: 8080
    depends_on:
      - db

volumes:
  mysql-data:
```

---

## 7. Nginx Reverse Proxy (Recommended)

```nginx
server {
    listen 443 ssl http2;
    server_name pos.yourdomain.com;

    ssl_certificate /etc/letsencrypt/live/pos.yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/pos.yourdomain.com/privkey.pem;

    client_max_body_size 50M;

    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
    }
}
```

### SSL with Let's Encrypt
```bash
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d pos.yourdomain.com
```

---

## 8. Post-Deployment

1. **Login** at `https://pos.yourdomain.com` with `admin` / `ChangeMe123!`
2. **Change password** immediately
3. **Configure settings**: Business profile, tax, receipt template
4. **Create categories** and **add your products**
5. **Create branches** if multi-branch
6. **Configure printers** in Settings > Printers

---

## 9. Backup Strategy

### Database backup (cron daily)
```bash
# MySQL
mysqldump -u posuser -p pos_desktop > /backups/pos-$(date +%Y%m%d).sql

# PostgreSQL
pg_dump -U posuser pos_desktop > /backups/pos-$(date +%Y%m%d).sql
```

### Automated backup script
```bash
#!/bin/bash
BACKUP_DIR="/backups"
DB_NAME="pos_desktop"
DB_USER="posuser"
DB_PASS="your-password"
RETENTION_DAYS=30

mysqldump -u "$DB_USER" -p"$DB_PASS" "$DB_NAME" | gzip > "$BACKUP_DIR/pos-$(date +%Y%m%d-%H%M%S).sql.gz"
find "$BACKUP_DIR" -name "pos-*.sql.gz" -mtime +$RETENTION_DAYS -delete
```

### Cron job
```bash
# Edit crontab
crontab -e

# Daily at 2 AM
0 2 * * * /home/user/backup-pos.sh
```

---

## 10. Monitoring

- **PM2 monitoring**: `pm2 monit`
- **Logs**: `tail -f logs/out.log`
- **Health check**: `curl https://pos.yourdomain.com/api/pos/getHealth`
- **Resource usage**: `htop`, `df -h`

---

## 11. Update Process

```bash
cd /home/user/vozex-pos
git pull origin main
npm install
npm run build
pm2 restart vozex-pos
```

---

## Quick Start (Fresh System)

```bash
# 1. Clone & install
git clone <repo> vozex-pos && cd vozex-pos
npm install

# 2. Configure .env with your database
cp .env.example .env
# Edit .env with your database URL

# 3. Setup database
npm run prisma:deploy:mysql   # MySQL
# OR
npm run prisma:setup:postgres # PostgreSQL

# 4. Build
npm run build

# 5. Run (development)
npm run dev:web

# 6. Run (production)
npm run start:web
```

Open `http://localhost:8080` and login with `admin` / `ChangeMe123!`.
