# ROA2WEB - Complete Deployment Workflow (Ultrathin Monolith)

**Last Updated:** 2025-12-29
**Architecture:** Ultrathin Monolith (Single Backend Service)

---

## 📋 Overview

ROA2WEB uses an **automated deployment pipeline** that transfers code from your development machine to the Windows Server and deploys automatically.

### Architecture Summary

**Before (Microservices - OBSOLETE):**
- 3 separate Windows services (ports 8000, 8002, 8003)
- Complex deployment with multiple scripts

**After (Ultrathin Monolith - CURRENT):**
- ✅ **1 Windows service:** `ROA2WEB-Backend` (port 8000)
- ✅ **1 unified backend:** All modules (Reports, Data Entry, Telegram)
- ✅ **Module control:** Enable/disable via `.env` flags
- ✅ **Simplified deployment:** Single service management

---

## 🔄 Complete Deployment Workflow

```
┌──────────────────────────────────────────────────────────────────┐
│ STEP 1: BUILD & TRANSFER (Dev Machine)                          │
├──────────────────────────────────────────────────────────────────┤
│                                                                  │
│  Developer runs:                                                 │
│  .\Publish-And-Deploy.ps1                                        │
│       │                                                           │
│       ├──> Calls Build-ROA2WEB.ps1                              │
│       │     ├── npm run build (Vue.js frontend)                 │
│       │     ├── Copy backend/ (Python FastAPI)                  │
│       │     ├── Copy shared/ (shared modules)                   │
│       │     └── Create ../deploy-package/                       │
│       │                                                           │
│       └──> Transfer to server                                    │
│             ├── Try: Windows Share (\\10.0.20.36\Temp)          │
│             └── Fallback: SSH/SCP (port 22122)                  │
│                                                                  │
│  Result: deploy-YYYYMMDD-HHmmss/ on server at C:\Temp\         │
│                                                                  │
└──────────────────────────────────────────────────────────────────┘
                              │
                              │ Package on server
                              ▼
┌──────────────────────────────────────────────────────────────────┐
│ STEP 2: AUTO-DETECTION (Windows Server - Scheduled Task)        │
├──────────────────────────────────────────────────────────────────┤
│                                                                  │
│  Check-And-Deploy.ps1 (runs every 5 minutes)                    │
│       │                                                           │
│       ├──> Scan C:\Temp for deploy-* folders                    │
│       ├──> Compare with last deployed (in state file)           │
│       └──> If NEW package found:                                 │
│               Call ROA2WEB-Console.ps1 -Action DeployAll         │
│                                                                  │
└──────────────────────────────────────────────────────────────────┘
                              │
                              │ New package detected
                              ▼
┌──────────────────────────────────────────────────────────────────┐
│ STEP 3: DEPLOYMENT EXECUTION (ROA2WEB-Console.ps1)              │
├──────────────────────────────────────────────────────────────────┤
│                                                                  │
│  1. STOP SERVICE                                                 │
│     └─> Stop-Service ROA2WEB-Backend                            │
│                                                                  │
│  2. BACKUP                                                       │
│     ├─> Backup backend/ → backups/backup-All-TIMESTAMP/        │
│     ├─> Backup shared/                                          │
│     └─> Backup frontend/                                        │
│                                                                  │
│  3. DEPLOY BACKEND                                               │
│     ├─> Copy backend/ files                                     │
│     ├─> Copy shared/ files                                      │
│     └─> Preserve .env file (MODULE flags!)                      │
│                                                                  │
│  4. DEPLOY FRONTEND                                              │
│     ├─> Copy frontend/ to IIS path                              │
│     └─> Copy web.config                                         │
│                                                                  │
│  5. START SERVICE                                                │
│     ├─> Start-Service ROA2WEB-Backend                           │
│     ├─> Wait for initialization (5 sec)                         │
│     └─> Test health endpoint (http://localhost:8000/health)     │
│                                                                  │
│  6. VERIFY                                                       │
│     └─> Check service status + module health                    │
│                                                                  │
└──────────────────────────────────────────────────────────────────┘
                              │
                              │ Deployment complete
                              ▼
                        ✅ PRODUCTION RUNNING
```

---

## 📁 Script Descriptions

### Development Machine Scripts

#### **1. Build-ROA2WEB.ps1**
**Purpose:** Create deployment package locally

**Usage:**
```powershell
# Interactive menu
.\Build-ROA2WEB.ps1

# Non-interactive
.\Build-ROA2WEB.ps1 -Component All -OutputPath "D:\deploy-pkg"
```

**Components:**
- `All` - Backend + Frontend (recommended)
- `Frontend` - Frontend + Backend (same as All for monolith)
- `Backend` - Backend only (includes all modules)

**Output:** `../deploy-package/` with:
```
deploy-package/
├── backend/          # Unified backend (Reports, Data Entry, Telegram)
├── frontend/         # Unified Vue.js SPA
├── shared/           # Shared Python modules
├── config/           # web.config, .env.example
├── scripts/          # Deployment scripts
└── README.txt        # Deployment instructions
```

---

#### **2. Publish-And-Deploy.ps1**
**Purpose:** Build + Transfer to server

**Usage:**
```powershell
# Interactive menu (recommended)
.\Publish-And-Deploy.ps1

# Non-interactive (for CI/CD)
.\Publish-And-Deploy.ps1 -NonInteractive -Action Build -Component All

# Force specific transfer method
.\Publish-And-Deploy.ps1 -NonInteractive -Action Build -Component All -TransferMethod SSH
```

**Transfer Methods:**
- **Auto** (default) - Try Windows Share, fallback to SSH
- **WindowsShare** - Fast LAN transfer (`\\10.0.20.36\Temp`)
- **SSH** - Secure remote transfer (port 22122)

**What it does:**
1. Calls `Build-ROA2WEB.ps1` internally
2. Transfers package to server `C:\Temp\deploy-YYYYMMDD-HHmmss\`
3. Server auto-deploys within 5 minutes

---

### Server-Side Scripts

#### **3. Check-And-Deploy.ps1** ⏰
**Purpose:** Auto-deploy monitor (scheduled task)

**Scheduled Task:** Runs every 5 minutes automatically

**Manual Usage:**
```powershell
# Interactive mode
.\Check-And-Deploy.ps1 -Interactive

# Check only (no deploy)
.\Check-And-Deploy.ps1 -CheckOnly

# Non-interactive (as scheduled task)
.\Check-And-Deploy.ps1
```

**What it does:**
1. Scans `C:\Temp` for `deploy-*` folders
2. Checks state file: `C:\Temp\ROA2WEB-Scripts\last-deploy.json`
3. If NEW package found → calls `ROA2WEB-Console.ps1 -Action DeployAll`
4. Saves deployment history

**State File Location:** `C:\Temp\ROA2WEB-Scripts\last-deploy.json`
**Log File:** `C:\Temp\ROA2WEB-Scripts\Logs\check-and-deploy.log`

---

#### **4. ROA2WEB-Console.ps1** ⚙️
**Purpose:** Unified management console for monolith

**Interactive Mode:**
```powershell
.\ROA2WEB-Console.ps1

# Menu options:
[1] Deploy Backend
[2] Deploy Frontend
[3] Deploy All (Backend + Frontend)
[4] Start Service
[5] Stop Service
[6] Restart Service
[7] View Status
[8] View Logs
[Q] Quit
```

**Non-Interactive Mode:**
```powershell
# Deploy all
.\ROA2WEB-Console.ps1 -NonInteractive -Action DeployAll -PackagePath "C:\Temp\deploy-20250129-120000"

# Deploy backend only
.\ROA2WEB-Console.ps1 -NonInteractive -Action DeployBackend -PackagePath "C:\Temp\deploy-20250129-120000"

# Service management
.\ROA2WEB-Console.ps1 -NonInteractive -Action RestartService
.\ROA2WEB-Console.ps1 -NonInteractive -Action Status
.\ROA2WEB-Console.ps1 -NonInteractive -Action ViewLogs
```

**Actions:**
- `DeployBackend` - Deploy backend + shared (stops/starts service)
- `DeployFrontend` - Deploy frontend to IIS
- `DeployAll` - Full deployment (backend + frontend)
- `StartService` - Start ROA2WEB-Backend
- `StopService` - Stop ROA2WEB-Backend
- `RestartService` - Restart ROA2WEB-Backend
- `Status` - Show service status + health check
- `ViewLogs` - Display recent logs

**Service Configuration:**
- Service Name: `ROA2WEB-Backend`
- Port: `8000`
- Health Check: `http://localhost:8000/health`

**Paths:**
- Install Root: `C:\inetpub\wwwroot\roa2web\`
- Backend: `C:\inetpub\wwwroot\roa2web\backend\`
- Frontend: `C:\inetpub\wwwroot\roa2web\frontend\`
- Shared: `C:\inetpub\wwwroot\roa2web\shared\`
- Logs: `C:\inetpub\wwwroot\roa2web\logs\`
- Backups: `C:\inetpub\wwwroot\roa2web\backups\`

---

#### **5. Setup-AutoDeploy.ps1** 🔧
**Purpose:** Configure scheduled task for auto-deployment

**Usage (run once on server):**
```powershell
.\Setup-AutoDeploy.ps1
```

**What it does:**
- Creates scheduled task: `ROA2WEB-AutoDeploy`
- Runs `Check-And-Deploy.ps1` every 5 minutes
- Runs as SYSTEM account with highest privileges

**To verify:**
```powershell
Get-ScheduledTask -TaskName "ROA2WEB-AutoDeploy"
```

---

#### **6. Install-ROA2WEB.ps1** 🆕
**Purpose:** First-time installation (creates Windows service)

**Usage (run once during initial setup):**
```powershell
.\Install-ROA2WEB.ps1
```

**What it does:**
- Creates `ROA2WEB-Backend` Windows service (NSSM)
- Configures Python virtual environment
- Sets up IIS application
- Creates necessary directories

---

## 🎯 Common Scenarios

### Scenario 1: Normal Development Workflow

**On Dev Machine:**
```powershell
# Make your code changes, then:
.\Publish-And-Deploy.ps1
# Select [1] All Components
# Select [1] Auto-detect transfer method
```

**On Server:**
- Wait 5 minutes (auto-deploy via scheduled task)
- OR manually: `.\Check-And-Deploy.ps1 -Interactive` → `[2] Check and Deploy Now`

**Verify:**
- Check health: `http://10.0.20.36:8000/health`
- Check logs: `C:\inetpub\wwwroot\roa2web\logs\backend-stdout.log`

---

### Scenario 2: Backend-Only Deployment (Faster)

**Dev Machine:**
```powershell
.\Publish-And-Deploy.ps1 -NonInteractive -Action Build -Component Backend
```

**Server (manual):**
```powershell
.\ROA2WEB-Console.ps1 -NonInteractive -Action DeployBackend -PackagePath "C:\Temp\deploy-YYYYMMDD-HHmmss"
```

---

### Scenario 3: Emergency Rollback

**Option A: Restore from backup**
```powershell
cd C:\inetpub\wwwroot\roa2web\backups
dir  # Find latest backup

Stop-Service ROA2WEB-Backend
Copy-Item backup-All-YYYYMMDD-HHmmss\backend\* C:\inetpub\wwwroot\roa2web\backend\ -Recurse -Force
Copy-Item backup-All-YYYYMMDD-HHmmss\shared\* C:\inetpub\wwwroot\roa2web\shared\ -Recurse -Force
Start-Service ROA2WEB-Backend
```

**Option B: Re-deploy previous package**
```powershell
cd C:\Temp
dir deploy-*  # Find previous package

.\scripts\ROA2WEB-Console.ps1 -NonInteractive -Action DeployAll -PackagePath "C:\Temp\deploy-PREVIOUS"
```

---

### Scenario 4: Module Control (Enable/Disable Modules)

**Edit .env file:**
```powershell
notepad C:\inetpub\wwwroot\roa2web\backend\.env

# Change flags:
MODULE_REPORTS_ENABLED=true        # Enable Reports
MODULE_DATA_ENTRY_ENABLED=false    # Disable Data Entry
MODULE_TELEGRAM_ENABLED=true       # Enable Telegram
```

**Restart service:**
```powershell
.\ROA2WEB-Console.ps1 -NonInteractive -Action RestartService
```

**Verify:**
```powershell
.\ROA2WEB-Console.ps1 -NonInteractive -Action Status
# Shows which modules are enabled/disabled
```

---

## 🔍 Monitoring & Troubleshooting

### Check Service Status
```powershell
# Via Console (recommended)
.\ROA2WEB-Console.ps1 -NonInteractive -Action Status

# Via Windows Services
Get-Service ROA2WEB-Backend

# Detailed status
Get-Service ROA2WEB-Backend | Format-List *
```

### View Logs
```powershell
# Via Console (recommended - last 30 lines)
.\ROA2WEB-Console.ps1 -NonInteractive -Action ViewLogs

# Manual log access
Get-Content C:\inetpub\wwwroot\roa2web\logs\backend-stdout.log -Tail 50
Get-Content C:\inetpub\wwwroot\roa2web\logs\backend-stderr.log -Tail 20
```

### Check Deployment History
```powershell
# View state file
Get-Content C:\Temp\ROA2WEB-Scripts\last-deploy.json | ConvertFrom-Json | Format-List

# View auto-deploy log
Get-Content C:\Temp\ROA2WEB-Scripts\Logs\check-and-deploy.log -Tail 100
```

### Test Health Endpoint
```powershell
Invoke-WebRequest http://localhost:8000/health
Invoke-WebRequest http://localhost:8000/docs
```

---

## 🚨 Common Issues

### Issue 1: Service Won't Start

**Symptoms:**
```powershell
Get-Service ROA2WEB-Backend
# Status: Stopped
```

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

# Common causes:
# - Port 8000 already in use
# - .env file missing/invalid
# - Python venv issues
# - Oracle connection issues
```

**Fix:**
```powershell
# Check port
netstat -ano | findstr :8000

# Verify .env file
Test-Path C:\inetpub\wwwroot\roa2web\backend\.env

# Restart service
.\ROA2WEB-Console.ps1 -NonInteractive -Action RestartService
```

---

### Issue 2: Auto-Deploy Not Working

**Check scheduled task:**
```powershell
Get-ScheduledTask -TaskName "ROA2WEB-AutoDeploy" | Format-List *
Get-ScheduledTaskInfo -TaskName "ROA2WEB-AutoDeploy"
```

**Check logs:**
```powershell
Get-Content C:\Temp\ROA2WEB-Scripts\Logs\check-and-deploy.log -Tail 50
```

**Manual trigger:**
```powershell
Start-ScheduledTask -TaskName "ROA2WEB-AutoDeploy"
```

**Re-setup scheduled task:**
```powershell
.\Setup-AutoDeploy.ps1
```

---

### Issue 3: Transfer Fails (Publish-And-Deploy)

**Windows Share not accessible:**
```powershell
# Test share access
Test-Path \\10.0.20.36\Temp

# If fails, use SSH
.\Publish-And-Deploy.ps1 -NonInteractive -Action Build -Component All -TransferMethod SSH
```

**SSH connection fails:**
```powershell
# Test SSH
.\Publish-And-Deploy.ps1 -NonInteractive -Action TestConnections

# Check SSH key
Test-Path ~/.ssh/id_ed25519
```

---

## 📊 Deployment Verification Checklist

After deployment, verify:

- [ ] **Service Status**
  ```powershell
  Get-Service ROA2WEB-Backend
  # Status: Running
  ```

- [ ] **Health Check**
  ```powershell
  Invoke-WebRequest http://localhost:8000/health
  # StatusCode: 200
  ```

- [ ] **API Docs**
  ```powershell
  Invoke-WebRequest http://localhost:8000/docs
  # Should show Swagger UI
  ```

- [ ] **Module Status**
  ```powershell
  .\ROA2WEB-Console.ps1 -NonInteractive -Action Status
  # Check all enabled modules
  ```

- [ ] **Frontend Access**
  - Open browser: `http://10.0.20.36/roa2web`
  - Verify login page loads

- [ ] **No Errors in Logs**
  ```powershell
  Get-Content C:\inetpub\wwwroot\roa2web\logs\backend-stderr.log -Tail 10
  # Should be empty or only INFO/WARNING
  ```

---

## 🔄 Complete Workflow Diagram

```
DEV MACHINE                        NETWORK                     WINDOWS SERVER
─────────────                      ────────                    ──────────────

Code Changes
     │
     ├─► Build-ROA2WEB.ps1
     │        │
     │        ├── npm build
     │        ├── copy files
     │        └── ../deploy-package/
     │
     ├─► Publish-And-Deploy.ps1
     │        │
     │        ├── calls Build-ROA2WEB.ps1
     │        └─► Transfer ───────────────────────► C:\Temp\deploy-*\
                                                              │
                                                              │
                                                    ┌─────────▼──────────┐
                                                    │ Scheduled Task     │
                                                    │ (every 5 minutes)  │
                                                    └────────┬───────────┘
                                                             │
                                                    Check-And-Deploy.ps1
                                                             │
                                                             ├─ Scan C:\Temp
                                                             ├─ Check state
                                                             └─ If NEW:
                                                                    │
                                                          ROA2WEB-Console.ps1
                                                                    │
                                                          ┌─────────▼──────────┐
                                                          │ 1. Stop Service    │
                                                          │ 2. Backup          │
                                                          │ 3. Deploy Backend  │
                                                          │ 4. Deploy Frontend │
                                                          │ 5. Start Service   │
                                                          │ 6. Health Check    │
                                                          └─────────┬──────────┘
                                                                    │
                                                                    ▼
                                                          ✅ DEPLOYMENT COMPLETE

                                                          ROA2WEB-Backend
                                                          ├── Reports Module
                                                          ├── Data Entry Module
                                                          └── Telegram Module
                                                               (Port 8000)
```

---

## 📚 Additional Resources

- **Main Documentation:** `/deployment/windows/docs/WINDOWS_DEPLOYMENT.md`
- **Architecture Guide:** `/CLAUDE.md`
- **Troubleshooting:** `/deployment/windows/docs/TELEGRAM_BOT_TROUBLESHOOTING.md`
- **Obsolete Scripts:** `/deployment/windows/scripts/obsolete/` (old microservices setup)

---

## ✅ Summary

**Ultrathin Monolith Benefits:**
- ✅ **1 service** instead of 3 (simpler management)
- ✅ **Shared resources** (Oracle pool, auth, cache)
- ✅ **Faster deployment** (single service restart)
- ✅ **Module control** via .env flags (no code changes needed)
- ✅ **Automated workflow** (5-minute auto-deploy)
- ✅ **Automatic backups** (last 5 kept)
- ✅ **Rollback capability** (restore from backup)

**Key Scripts:**
1. `Publish-And-Deploy.ps1` - Dev machine (build + transfer)
2. `Check-And-Deploy.ps1` - Server (auto-deploy monitor)
3. `ROA2WEB-Console.ps1` - Server (deployment execution + management)

**Normal Workflow:**
1. Make code changes
2. Run `Publish-And-Deploy.ps1`
3. Wait 5 minutes (auto-deploy)
4. Verify deployment

That's it! 🎉
