# ROA2WEB - Windows Server Deployment Guide

Complete deployment guide for ROA2WEB on Windows Server with IIS and Oracle Database.

---

## 📋 Table of Contents

1. [Overview](#overview)
2. [Prerequisites](#prerequisites)
3. [Architecture](#architecture)
4. [Initial Setup](#initial-setup)
5. [Deployment Workflow](#deployment-workflow)
6. [Configuration](#configuration)
7. [Management](#management)
8. [Troubleshooting](#troubleshooting)
9. [Maintenance](#maintenance)

---

## 🎯 Overview

This guide provides step-by-step instructions for deploying ROA2WEB on Windows Server with:

- **Backend**: FastAPI as Windows Service (port 8000)
- **Frontend**: Vue.js static files served by IIS (port 80/443)
- **Database**: Direct connection to local Oracle DB (no SSH tunnel)
- **Reverse Proxy**: IIS with URL Rewrite for API routing

### Key Features

✅ Simple installation with PowerShell scripts
✅ Minimal dependencies (Python + IIS)
✅ Easy replication across multiple servers
✅ Windows Service for backend (auto-start, auto-restart)
✅ Production-ready configuration

---

## 📦 Prerequisites

### Server Requirements

| Component | Requirement | Notes |
|-----------|-------------|-------|
| **OS** | Windows Server 2016+ | Or Windows 10/11 Pro |
| **RAM** | 4GB minimum | 8GB recommended |
| **Disk** | 10GB free space | For application and logs |
| **CPU** | 2 cores minimum | 4 cores recommended |

### Software Requirements

#### Required (will be installed automatically)

- **IIS** (Internet Information Services)
- **Python 3.11+**
- **NSSM** (Non-Sucking Service Manager)
- **IIS URL Rewrite Module**
- **IIS Application Request Routing (ARR)**

#### Pre-installed

- **Oracle Database** (local or network-accessible)
- **Oracle Instant Client** (for Python oracledb)

#### On Development Machine

- **Node.js 16+** (for building frontend)
- **Git** (optional, for cloning repository)

---

## 🏗️ Architecture

### Deployment Structure

```
C:\inetpub\wwwroot\roa2web\
├── backend\                      # FastAPI application
│   ├── app\                      # Application code
│   ├── requirements.txt          # Python dependencies
│   ├── .env                      # Environment configuration
│   └── logs\                     # Application logs
│
├── frontend\                     # Vue.js static files
│   ├── index.html
│   ├── assets\
│   ├── web.config                # IIS configuration
│   └── ...
│
├── logs\                         # Service logs
│   ├── backend-stdout.log
│   └── backend-stderr.log
│
├── temp\                         # Temporary files
│
└── backups\                      # Deployment backups
    └── backup-YYYYMMDD-HHMMSS\
```

### Network Flow

```
Client Browser
    ↓
IIS (Port 80/443)
    ↓
    ├─→ /api/* ────→ Backend Service (localhost:8000)
    │                    ↓
    │                Oracle Database (localhost:1521)
    │
    └─→ /* ─────────→ Frontend Static Files
```

---

## 🚀 Initial Setup

### Step 1: Install IIS

Open PowerShell as Administrator:

```powershell
# Install IIS with required features
Install-WindowsFeature -Name Web-Server -IncludeManagementTools

# Verify installation
Get-WindowsFeature -Name Web-Server
```

### Step 2: Prepare Deployment Package

**On your development machine (WSL/Windows):**

```bash
# Navigate to deployment scripts
cd /mnt/e/proiecte/roa2web/roa2web/deployment/windows/scripts

# Build frontend and create deployment package
./Build-Frontend.ps1

# Output will be in: ./deploy-package
```

This creates a complete deployment package:
```
deploy-package/
├── backend/           # Backend files
├── frontend/          # Built Vue.js files
├── config/            # Configuration templates
└── README.txt         # Deployment instructions
```

### Step 3: Transfer to Server

**Option A: Network Share**
```powershell
# On development machine
Copy-Item -Path .\deploy-package -Destination \\SERVER-IP\C$\Temp\roa2web -Recurse
```

**Option B: Manual Transfer**
- Zip the `deploy-package` folder
- Transfer via RDP, FTP, or USB
- Extract on server to `C:\Temp\roa2web`

### Step 4: Run Installation Script

**On Windows Server (PowerShell as Administrator):**

```powershell
# Navigate to deployment scripts
cd C:\path\to\roa2web\deployment\windows\scripts

# Run installation
.\Install-ROA2WEB.ps1

# Installation will:
# - Install Python, NSSM, IIS modules
# - Create directory structure
# - Install Python dependencies
# - Create Windows Service
# - Configure IIS website
```

**Installation Parameters:**

```powershell
# Custom installation path
.\Install-ROA2WEB.ps1 -InstallPath "D:\Apps\roa2web"

# Custom service port
.\Install-ROA2WEB.ps1 -ServicePort 8001

# Skip Python installation (if already installed)
.\Install-ROA2WEB.ps1 -SkipPython

# Skip IIS configuration
.\Install-ROA2WEB.ps1 -SkipIIS
```

### Step 5: Configure Application

**Edit configuration file:**

```powershell
# Copy environment template
Copy-Item C:\inetpub\wwwroot\roa2web\backend\config\.env.production.windows `
          C:\inetpub\wwwroot\roa2web\backend\.env

# Edit with your values
notepad C:\inetpub\wwwroot\roa2web\backend\.env
```

**Required configuration:**

```env
# Oracle Database
ORACLE_USER=CONTAFIN_ORACLE
# Database password - configure in .env
ORACLE_HOST=localhost
ORACLE_PORT=1521
ORACLE_SID=ROA

# JWT Secret (generate new one!)
JWT_SECRET_KEY=GENERATE_STRONG_RANDOM_STRING_HERE
```

**Generate JWT Secret:**

```powershell
# PowerShell method
-join ((65..90) + (97..122) + (48..57) | Get-Random -Count 32 | % {[char]$_})

# Or use online tool: https://generate-secret.vercel.app/
```

### Step 6: Start Services

```powershell
# Start backend service
.\Start-ROA2WEB.ps1

# Check service status
Get-Service ROA2WEB-Backend

# Check logs
Get-Content C:\inetpub\wwwroot\roa2web\logs\backend-stdout.log -Tail 50
```

### Step 7: Verify Installation

**Test endpoints:**

```powershell
# Backend health check
Invoke-WebRequest -Uri "http://localhost:8000/health"

# API documentation
Start-Process "http://localhost:8000/docs"

# Frontend application
Start-Process "http://localhost"
```

---

## 🔄 Deployment Workflow

### For Updates and New Deployments

**1. Build on Development Machine:**

```bash
cd /mnt/e/proiecte/roa2web/roa2web/deployment/windows/scripts
./Build-Frontend.ps1 -OutputPath "./deploy-$(date +%Y%m%d)"
```

**2. Transfer to Server:**

```powershell
# Copy deployment package to server
Copy-Item -Path .\deploy-20250118 -Destination C:\Temp\roa2web-deploy -Recurse
```

**3. Deploy on Server:**

```powershell
cd C:\inetpub\wwwroot\roa2web\deployment\windows\scripts

# Run deployment script
.\Deploy-ROA2WEB.ps1 -SourcePath "C:\Temp\roa2web-deploy"

# The script will:
# - Create backup of current deployment
# - Stop backend service
# - Update backend and frontend files
# - Install new Python dependencies (if changed)
# - Restart backend service
# - Validate deployment health
```

**Deployment Options:**

```powershell
# Update only backend
.\Deploy-ROA2WEB.ps1 -UpdateFrontend $false

# Update only frontend
.\Deploy-ROA2WEB.ps1 -UpdateBackend $false

# Skip backup (not recommended)
.\Deploy-ROA2WEB.ps1 -BackupEnabled $false

# Skip service restart
.\Deploy-ROA2WEB.ps1 -RestartService $false
```

---

## ⚙️ Configuration

### Backend Configuration (.env)

**Location:** `C:\inetpub\wwwroot\roa2web\backend\.env`

**Essential settings:**

```env
# Environment
ENVIRONMENT=production
DEBUG=false

# Oracle Database
ORACLE_USER=CONTAFIN_ORACLE
# Database password - configure in .env
ORACLE_HOST=localhost
ORACLE_PORT=1521
ORACLE_SID=ROA

# Connection Pool
ORACLE_MIN_POOL_SIZE=2
ORACLE_MAX_POOL_SIZE=10

# JWT Authentication
JWT_SECRET_KEY=your_strong_secret_key
JWT_ALGORITHM=HS256
JWT_EXPIRE_MINUTES=480

# Server Settings
HOST=127.0.0.1
PORT=8000
# NOTE: WORKERS is NOT used in .env - configured in NSSM service (--workers 1)

# Logging
LOG_LEVEL=INFO
LOG_FILE=C:\inetpub\wwwroot\roa2web\backend\logs\app.log
```

**Important:** Worker count is configured in the NSSM Windows service (`--workers 1`), NOT in `.env`. This is required for Telegram bot functionality. See `TELEGRAM-BOT-DEPLOYMENT.md` for details.

### IIS Configuration (web.config)

**Location:** `C:\inetpub\wwwroot\roa2web\frontend\web.config`

This file is automatically created during installation. Key features:

- **SPA Routing**: All non-file requests fallback to `index.html`
- **API Reverse Proxy**: `/api/*` routed to backend service
- **Compression**: Gzip compression enabled
- **Caching**: Static assets cached for 1 year
- **Security Headers**: X-Frame-Options, CSP, HSTS

**No manual configuration needed** - works out of the box!

### Windows Service Configuration

**Service Name:** `ROA2WEB-Backend`
**Startup Type:** Automatic
**Recovery:** Restart on failure (5 second delay)

**View/Edit service:**

```powershell
# Service properties
Get-Service ROA2WEB-Backend | Format-List *

# Service configuration
sc.exe qc ROA2WEB-Backend

# Modify with NSSM GUI
nssm edit ROA2WEB-Backend
```

---

## 🔧 Management

### Service Management

**PowerShell Scripts:**

```powershell
# Start service
.\Start-ROA2WEB.ps1

# Stop service
.\Stop-ROA2WEB.ps1

# Restart service
.\Restart-ROA2WEB.ps1
```

**Manual Service Management:**

```powershell
# Start
Start-Service ROA2WEB-Backend

# Stop
Stop-Service ROA2WEB-Backend

# Restart
Restart-Service ROA2WEB-Backend

# Status
Get-Service ROA2WEB-Backend
```

**Windows Services GUI:**

```powershell
services.msc
# Find: ROA2WEB Backend Service
```

### Log Management

**Log Locations:**

```
C:\inetpub\wwwroot\roa2web\logs\
├── backend-stdout.log         # Service output
├── backend-stderr.log         # Service errors
└── app.log                    # Application log
```

**View Logs:**

```powershell
# Real-time monitoring
Get-Content C:\inetpub\wwwroot\roa2web\logs\backend-stdout.log -Tail 50 -Wait

# Last 100 lines
Get-Content C:\inetpub\wwwroot\roa2web\logs\backend-stderr.log -Tail 100

# Search for errors
Select-String -Path "C:\inetpub\wwwroot\roa2web\logs\*.log" -Pattern "ERROR|CRITICAL"

# Filter by date
Get-Content C:\inetpub\wwwroot\roa2web\logs\app.log |
    Select-String -Pattern "2025-01-18"
```

**Log Rotation:**

Logs are automatically rotated when they reach 10MB (configured in .env):

```env
LOG_MAX_SIZE=10485760      # 10 MB
LOG_BACKUP_COUNT=5         # Keep 5 old logs
```

### IIS Management

**PowerShell:**

```powershell
# Website status
Get-Website ROA2WEB

# Start/Stop website
Start-Website ROA2WEB
Stop-Website ROA2WEB

# Application pool
Get-WebAppPoolState ROA2WEB-AppPool
Restart-WebAppPool ROA2WEB-AppPool

# View configuration
Get-WebConfiguration -Filter "system.webServer/rewrite/rules"
```

**IIS Manager GUI:**

```powershell
inetmgr
# Navigate to: Sites → ROA2WEB
```

### Backup Management

**Deployment backups are automatic!**

```
C:\inetpub\wwwroot\roa2web\backups\
├── backup-20250118-103045\
├── backup-20250118-154512\
└── backup-20250117-090123\
```

Last 10 backups are kept automatically.

**Manual Backup:**

```powershell
# Create backup
$date = Get-Date -Format "yyyyMMdd-HHmmss"
Copy-Item -Path C:\inetpub\wwwroot\roa2web `
          -Destination C:\Backups\roa2web-$date `
          -Recurse -Exclude logs,temp,backups
```

**Restore from Backup:**

```powershell
# Stop service
.\Stop-ROA2WEB.ps1

# Restore files
Copy-Item -Path C:\inetpub\wwwroot\roa2web\backups\backup-20250118-103045\* `
          -Destination C:\inetpub\wwwroot\roa2web `
          -Recurse -Force

# Start service
.\Start-ROA2WEB.ps1
```

---

## 🐛 Troubleshooting

### Service Won't Start

**Symptom:** Backend service fails to start or stops immediately.

**Check:**

```powershell
# View error log
Get-Content C:\inetpub\wwwroot\roa2web\logs\backend-stderr.log -Tail 50

# Test Python manually
cd C:\inetpub\wwwroot\roa2web\backend
python -m uvicorn app.main:app --host 127.0.0.1 --port 8000
```

**Common Issues:**

1. **Python not found:**
   ```powershell
   # Check Python installation
   python --version
   # Add to PATH if needed
   ```

2. **Module import errors:**
   ```powershell
   # Reinstall dependencies
   cd C:\inetpub\wwwroot\roa2web\backend
   pip install -r requirements.txt
   ```

3. **Oracle connection failed:**
   ```powershell
   # Check Oracle listener
   lsnrctl status
   # Test connection
   sqlplus CONTAFIN_ORACLE/password@localhost:1521/ROA
   ```

4. **Port already in use:**
   ```powershell
   # Check what's using port 8000
   netstat -ano | findstr :8000
   # Kill process or change port in .env
   ```

### Frontend Not Loading

**Symptom:** Blank page or 404 errors.

**Check:**

```powershell
# IIS website running?
Get-Website ROA2WEB

# Files exist?
Test-Path C:\inetpub\wwwroot\roa2web\frontend\index.html

# Check IIS logs
Get-Content C:\inetpub\logs\LogFiles\W3SVC*\*.log -Tail 50
```

**Solutions:**

```powershell
# Restart IIS site
Stop-Website ROA2WEB
Start-Website ROA2WEB

# Restart app pool
Restart-WebAppPool ROA2WEB-AppPool

# Verify web.config
Test-Path C:\inetpub\wwwroot\roa2web\frontend\web.config
```

### API Calls Failing (502/504 errors)

**Symptom:** Frontend loads but API calls fail.

**Check:**

```powershell
# Backend service running?
Get-Service ROA2WEB-Backend

# Backend responding?
Invoke-WebRequest -Uri "http://localhost:8000/health"

# Check ARR proxy
Get-WebConfiguration -Filter "system.webServer/proxy"
```

**Solutions:**

1. **Enable ARR proxy:**
   ```powershell
   Set-WebConfigurationProperty -PSPath "MACHINE/WEBROOT/APPHOST" `
       -Filter "system.webServer/proxy" `
       -Name "enabled" `
       -Value "True"
   ```

2. **Check backend logs:**
   ```powershell
   Get-Content C:\inetpub\wwwroot\roa2web\logs\backend-stderr.log -Tail 100
   ```

3. **Test backend directly:**
   ```powershell
   Invoke-WebRequest -Uri "http://localhost:8000/api/health"
   ```

### Database Connection Issues

**Symptom:** Backend starts but database queries fail.

**Check:**

```powershell
# Oracle client installed?
dir $env:ORACLE_HOME

# TNS names configured?
$env:TNS_ADMIN
Get-Content $env:TNS_ADMIN\tnsnames.ora

# Test connection
sqlplus CONTAFIN_ORACLE/password@localhost:1521/ROA
```

**Solutions:**

1. **Install Oracle Instant Client:**
   - Download from: https://www.oracle.com/database/technologies/instant-client/downloads.html
   - Extract to C:\oracle\instantclient_19_x
   - Add to PATH

2. **Configure .env:**
   ```env
   ORACLE_HOST=localhost
   ORACLE_PORT=1521
   ORACLE_SID=ROA
   ```

3. **Check Oracle service:**
   ```powershell
   Get-Service Oracle*
   ```

### Permission Issues

**Symptom:** Access denied errors.

**Check:**

```powershell
# Check folder permissions
icacls C:\inetpub\wwwroot\roa2web

# Check service account
sc.exe qc ROA2WEB-Backend
```

**Solutions:**

```powershell
# Grant IIS user read access
icacls C:\inetpub\wwwroot\roa2web /grant IIS_IUSRS:(OI)(CI)RX

# Grant service account full access to backend
icacls C:\inetpub\wwwroot\roa2web\backend /grant "NT AUTHORITY\LOCAL SERVICE":(OI)(CI)F
```

### High CPU/Memory Usage

**Check:**

```powershell
# Service resource usage
Get-Process -Name python | Format-Table ProcessName, CPU, WS

# Check worker count (configured in NSSM, not .env)
nssm get ROA2WEB-Backend AppParameters
```

**Solutions:**

**Note:** ROA2WEB uses `--workers 1` by default (required for Telegram bot). This is configured in NSSM, not in .env.

```powershell
# Workers are configured in NSSM service parameters
# To reduce memory, adjust Oracle pool size in .env instead:
```

```env
# Reduce Oracle connection pool size
ORACLE_MAX_POOL_SIZE=5
ORACLE_MIN_POOL_SIZE=2
```

**Important:** Do NOT change `--workers 1` to a higher value - this will break the Telegram bot. See `docs/TELEGRAM-BOT-DEPLOYMENT.md` for details.

---

## 🔄 Maintenance

### Regular Maintenance Tasks

**Daily:**
- Check service status
- Monitor disk space
- Review error logs

```powershell
# Daily check script
Get-Service ROA2WEB-Backend
Get-PSDrive C | Select-Object Used,Free
Get-Content C:\inetpub\wwwroot\roa2web\logs\backend-stderr.log -Tail 20
```

**Weekly:**
- Clean old logs
- Verify backups
- Update dependencies (if needed)

```powershell
# Clean logs older than 30 days
Get-ChildItem C:\inetpub\wwwroot\roa2web\logs\*.log.* |
    Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-30)} |
    Remove-Item

# List backups
Get-ChildItem C:\inetpub\wwwroot\roa2web\backups
```

**Monthly:**
- Review security updates
- Performance optimization
- Database maintenance

### Updating Python Dependencies

```powershell
cd C:\inetpub\wwwroot\roa2web\backend

# Update all packages
pip install --upgrade -r requirements.txt

# Restart service
Restart-Service ROA2WEB-Backend
```

### Database Maintenance

```sql
-- Connect to Oracle
sqlplus CONTAFIN_ORACLE/password@localhost:1521/ROA

-- Check table statistics
SELECT table_name, num_rows, last_analyzed
FROM user_tables
ORDER BY last_analyzed;

-- Update statistics
EXEC DBMS_STATS.gather_schema_stats('CONTAFIN_ORACLE');
```

### Performance Monitoring

**Built-in health check:**

```powershell
Invoke-WebRequest -Uri "http://localhost:8000/health" |
    Select-Object StatusCode, Content
```

**Windows Performance Monitor:**

```powershell
perfmon
# Add counters:
# - Process > % Processor Time > python.exe
# - Process > Private Bytes > python.exe
# - Web Service > Current Connections
```

### Security Updates

**Windows Updates:**

```powershell
# Check for updates
Get-WindowsUpdate

# Install updates
Install-WindowsUpdate -AcceptAll
```

**Python Security Updates:**

```powershell
# Check for vulnerabilities
pip check

# Update specific package
pip install --upgrade fastapi
```

---

## 📚 Additional Resources

### Documentation Files

- `config/.env.production.windows` - Configuration template
- `config/web.config` - IIS configuration
- `scripts/*.ps1` - PowerShell scripts

### PowerShell Scripts Reference

| Script | Purpose | Usage |
|--------|---------|-------|
| `Install-ROA2WEB.ps1` | Initial installation | `.\Install-ROA2WEB.ps1` |
| `Deploy-ROA2WEB.ps1` | Deploy updates | `.\Deploy-ROA2WEB.ps1 -SourcePath <path>` |
| `Build-Frontend.ps1` | Build Vue.js frontend | `.\Build-Frontend.ps1` |
| `Start-ROA2WEB.ps1` | Start backend service | `.\Start-ROA2WEB.ps1` |
| `Stop-ROA2WEB.ps1` | Stop backend service | `.\Stop-ROA2WEB.ps1` |
| `Restart-ROA2WEB.ps1` | Restart backend service | `.\Restart-ROA2WEB.ps1` |

### Support

For issues or questions:
1. Check logs: `C:\inetpub\wwwroot\roa2web\logs\`
2. Review this documentation
3. Contact: development-team@your-company.com

---

## ✅ Quick Reference

### Essential Commands

```powershell
# Service management
.\Start-ROA2WEB.ps1
.\Stop-ROA2WEB.ps1
.\Restart-ROA2WEB.ps1

# Check status
Get-Service ROA2WEB-Backend
Get-Website ROA2WEB

# View logs
Get-Content C:\inetpub\wwwroot\roa2web\logs\backend-stdout.log -Tail 50 -Wait

# Health check
Invoke-WebRequest http://localhost:8000/health

# Deploy update
.\Deploy-ROA2WEB.ps1 -SourcePath "C:\Temp\roa2web-deploy"
```

### Key Locations

- **Application**: `C:\inetpub\wwwroot\roa2web\`
- **Backend**: `C:\inetpub\wwwroot\roa2web\backend\`
- **Frontend**: `C:\inetpub\wwwroot\roa2web\frontend\`
- **Logs**: `C:\inetpub\wwwroot\roa2web\logs\`
- **Config**: `C:\inetpub\wwwroot\roa2web\backend\.env`
- **Backups**: `C:\inetpub\wwwroot\roa2web\backups\`

### Access Points

- **Web App**: http://localhost or http://server-ip
- **API Docs**: http://localhost:8000/docs
- **Health Check**: http://localhost:8000/health

---

*Last Updated: 2025-01-18*
*Version: 2.0.0*
*ROA2WEB Windows Deployment Guide*
