refactor(docs): consolidate and cleanup documentation

- Delete 9 deprecated/obsolete docs (~6,300 lines removed)
- Move test PDFs to tests/fixtures/ocr-samples/
- Create docs/DEPLOYMENT.md as principal guide
- Create tests/ocr-validation/README.md
- Update all refs for ultrathin monolith architecture
- Update OCR tests to use relative paths

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Claude Agent
2026-01-22 09:14:51 +00:00
parent 1b9ebf1d8f
commit 62f86250cc
55 changed files with 604 additions and 6334 deletions

View File

@@ -210,6 +210,5 @@ scp test.txt roa2web-prod:C:/Temp/
## Related Documentation
- [Windows Deployment](../windows/docs/WINDOWS_DEPLOYMENT.md)
- [Windows Deployment README](../windows/README.md)
- [Two-Tier IIS Architecture](../windows/docs/TWO-TIER-IIS-DEPLOYMENT.md)
- [ROA2WEB Console](../windows/scripts/ROA2WEB-Console.ps1)

View File

@@ -1,221 +0,0 @@
# 📦 Deployment Package Generation
This document explains how to generate deployment packages for ROA2WEB Windows deployment.
## ⚠️ Important Note
The `deploy-package/` directory is **NOT** committed to git. It contains build artifacts that are generated fresh each time you build.
## 🔨 Generating Deployment Packages
Use the unified build script **`Build-ROA2WEB.ps1`** to generate deployment packages:
### Build Complete Package (Recommended)
```powershell
cd deployment/windows/scripts
.\Build-ROA2WEB.ps1
```
This generates a complete deployment package containing:
- ✅ Frontend (Vue.js built static files)
- ✅ Backend (FastAPI Python application)
- ✅ Shared modules (auth, database, utils)
- ✅ Telegram Bot application
- ✅ Configuration templates
- ✅ Deployment scripts
**Output**: `deployment/windows/deploy-package/`
### Build Specific Components
```powershell
# Frontend + Backend only
.\Build-ROA2WEB.ps1 -Component Frontend
# Backend only (no frontend build)
.\Build-ROA2WEB.ps1 -Component Backend
# Telegram Bot only
.\Build-ROA2WEB.ps1 -Component TelegramBot
```
### Custom Output Path
```powershell
# Build to custom location with date suffix
.\Build-ROA2WEB.ps1 -OutputPath "D:\deployments\roa2web-$(Get-Date -Format 'yyyyMMdd')"
```
## 📂 Package Structure
After building, `deploy-package/` will contain:
```
deploy-package/
├── backend/ # FastAPI application files
│ ├── app/ # Application code
│ ├── requirements.txt # Python dependencies
│ └── ...
├── frontend/ # Built Vue.js static files
│ ├── assets/ # JS, CSS, fonts
│ ├── index.html # Main HTML
│ └── ...
├── telegram-bot/ # Telegram bot application
│ ├── app/ # Bot code
│ ├── requirements.txt # Bot dependencies
│ └── .env.example # Configuration template
├── shared/ # Shared Python modules
│ ├── auth/ # Authentication
│ ├── database/ # Oracle connection pool
│ └── utils/ # Utilities
├── config/ # Configuration templates
│ ├── .env.production.windows
│ ├── .env.production.windows.telegram
│ └── web.config # IIS configuration
├── scripts/ # Deployment scripts
│ ├── Install-ROA2WEB.ps1
│ ├── Install-TelegramBot.ps1
│ ├── Deploy-ROA2WEB.ps1
│ ├── Deploy-TelegramBot.ps1
│ ├── Manage-ROA2WEB.ps1
│ ├── Backup-TelegramDB.ps1
│ ├── Setup-DailyBackup.ps1
│ ├── Setup-ClaudeAuth.ps1
│ └── Enable-HTTPS.ps1
└── README.txt # Deployment instructions
```
## 🚀 Deployment Workflow
### 1. Build Package (Development Machine)
```powershell
# On WSL or development machine
cd deployment/windows/scripts
.\Build-ROA2WEB.ps1
```
### 2. Transfer to Windows Server
```powershell
# Via network share
Copy-Item -Path ./deploy-package -Destination \\SERVER\C$\Temp\roa2web-deploy -Recurse
# Or via RDP (manual copy)
```
### 3. Install on Server (First Time)
```powershell
# On Windows Server (as Administrator)
cd C:\Temp\roa2web-deploy\scripts
# Install main application
.\Install-ROA2WEB.ps1
# Install Telegram bot
.\Install-TelegramBot.ps1
```
### 4. Configure & Start
```powershell
# Configure environment
notepad C:\inetpub\wwwroot\roa2web\backend\.env
notepad C:\inetpub\wwwroot\roa2web\telegram-bot\.env
# Start services
.\Manage-ROA2WEB.ps1 -Action Start
```
### 5. Deploy Updates
```powershell
# Stop services
.\Manage-ROA2WEB.ps1 -Action Stop
# Deploy updates
.\Deploy-ROA2WEB.ps1
.\Deploy-TelegramBot.ps1
# Start services
.\Manage-ROA2WEB.ps1 -Action Start
```
## 🔧 Requirements
**Development Machine (for building):**
- Node.js 16+ (for Frontend builds)
- npm
- PowerShell 5.1+
**Windows Server (for deployment):**
- Windows Server 2016+ or Windows 10/11
- IIS with URL Rewrite Module
- Python 3.11+
- PowerShell 5.1+ (Administrator)
## 📝 Notes
- **Build artifacts are NOT version-controlled**: The `deploy-package/` directory is in `.gitignore`
- **Fresh builds recommended**: Always generate a fresh package before deploying
- **Virtual environments**: Not included in package (created automatically during installation)
- **.env files**: Not included in package (created from templates during installation)
- **Database files**: Excluded from package (SQLite for Telegram bot created on server)
## ⚙️ Advanced Options
### Transfer to Server Automatically
```powershell
# Using network share (Windows)
.\Build-ROA2WEB.ps1 -ServerHost "10.0.20.36" -ServerPath "C:\Temp\roa2web-deploy"
```
### Clean Build
The build script automatically cleans the output directory. To preserve existing output:
```powershell
.\Build-ROA2WEB.ps1 -Clean $false
```
## 🐛 Troubleshooting
### "Node.js not found"
Install Node.js 16+ from https://nodejs.org/
### "deploy-package already exists"
The script automatically cleans old builds. If you see errors, manually delete `deploy-package/` and retry.
### Build fails with "locked files"
Close VS Code, IDEs, and file explorers that might have files open in the source directories.
## 📚 Documentation
- **Complete Deployment Guide**: [`docs/WINDOWS_DEPLOYMENT.md`](docs/WINDOWS_DEPLOYMENT.md)
- **Script Reference**: [`scripts/README.md`](scripts/README.md)
- **Quick Start**: [`README.md`](README.md)
- **Project Documentation**: [`../../CLAUDE.md`](../../CLAUDE.md)
## 🔄 Migration from Old Build Scripts
If you were using the old build scripts, here's the mapping:
| Old Script | New Script | Equivalent Command |
|------------|------------|-------------------|
| `Build-Frontend.ps1` | `Build-ROA2WEB.ps1` | `.\Build-ROA2WEB.ps1 -Component Frontend` |
| `Build-TelegramBot.ps1` | `Build-ROA2WEB.ps1` | `.\Build-ROA2WEB.ps1 -Component TelegramBot` |
| Both scripts together | `Build-ROA2WEB.ps1` | `.\Build-ROA2WEB.ps1` (default: All) |
**Note**: Old scripts are marked as DEPRECATED and will be removed in a future version.
---
**Generated by**: ROA2WEB Team
**Last Updated**: 2025-11-11
**Version**: 2.0 (Unified Build System)

View File

@@ -1,492 +1,200 @@
# ROA2WEB - Windows Deployment Package
# ROA2WEB - Windows Deployment
Complete deployment solution for ROA2WEB on Windows Server with IIS and Oracle Database.
**Includes:**
- **Reports App** - Read-only Oracle reports (Port 8000)
- **Telegram Bot** - Telegram integration (Port 8002)
- **Data Entry App** - Receipt data entry with approval workflow (Port 8003)
**Arhitectură:** Ultrathin Monolith | **Serviciu:** `ROA2WEB-Backend` (port 8000)
---
## 📂 Package Contents
## Quick Start
```
deployment/windows/
├── config/ # Configuration files
│ ├── web.config # IIS config for Reports App
│ ├── web.config.data-entry # IIS config for Data Entry App
│ └── .env.production.windows # Environment variables template
├── scripts/ # PowerShell automation scripts
│ ├── Build-ROA2WEB.ps1 # Build all components (interactive menu)
│ ├── ROA2WEB-Console.ps1 # Unified deployment & management console
│ ├── Install-ROA2WEB.ps1 # Initial Reports App installation
│ ├── Install-TelegramBot.ps1 # Telegram Bot installation
│ └── deploy-config.json # Deployment configuration
├── docs/ # Documentation
│ └── WINDOWS_DEPLOYMENT.md # Complete deployment guide
└── README.md # This file
```
---
## 🎯 Quick Start
### Prerequisites
- **Windows Server** 2016+ (or Windows 10/11 Pro)
- **IIS** installed
- **Oracle Database** (local or network-accessible)
- **PowerShell 5.1+**
- **Administrator privileges**
### Installation Steps
#### 1. Build Frontend (on development machine)
```bash
# On WSL/Linux/Mac
cd roa2web/deployment/windows/scripts
./Build-Frontend.ps1
# This creates: ./deploy-package/
```
#### 2. Transfer to Server
Copy the entire project to Windows Server:
```
C:\roa2web\deployment\windows\
```
#### 3. Run Installation
### 1. Instalare Server Nou
```powershell
# On Windows Server (PowerShell as Administrator)
cd C:\roa2web\deployment\windows\scripts
# Install everything
# Pe Windows Server (PowerShell Administrator)
cd C:\path\to\deployment\windows\scripts
.\Install-ROA2WEB.ps1
```
This will:
- ✅ Install Python 3.11+
- ✅ Install NSSM (service manager)
- ✅ Install IIS URL Rewrite and ARR
- ✅ Create directory structure
- ✅ Install Python dependencies
- ✅ Create Windows Service
- ✅ Configure IIS website
#### 4. Configure Application
### 2. Configurare
```powershell
# Copy and edit environment file
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
# Module control:
MODULE_REPORTS_ENABLED=true
MODULE_DATA_ENTRY_ENABLED=true
MODULE_TELEGRAM_ENABLED=true
```
**Required settings:**
Configure these variables in `.env`:
- Database credentials (user, password, host, port, SID)
- JWT secret key for authentication
- Other application-specific settings
Example structure:
```env
ORACLE_USER=CONTAFIN_ORACLE
ORACLE_HOST=localhost
ORACLE_PORT=1521
ORACLE_SID=ROA
# Add password and JWT secret here
```
#### 5. Deploy Application Files
### 3. Start
```powershell
# Deploy frontend and backend
.\Deploy-ROA2WEB.ps1 -SourcePath "C:\path\to\deploy-package"
Start-Service ROA2WEB-Backend
```
#### 6. Verify Installation
---
## Deployment (Actualizări)
### Opțiunea A: Din Windows (Publish-And-Deploy.ps1)
```powershell
# Check service
# Pe mașina de dezvoltare Windows
cd deployment\windows\scripts
.\Publish-And-Deploy.ps1
# Non-interactiv:
.\Publish-And-Deploy.ps1 -NonInteractive -Action Build -Component All
```
### Opțiunea B: Din Linux/LXC (deploy.sh)
```bash
# Pe mașina de dezvoltare Linux
cd deployment/linux
./deploy.sh # Full deploy (frontend + backend)
./deploy.sh frontend # Doar frontend
./deploy.sh backend # Doar backend
./deploy.sh test # Test conexiune SSH
```
**Ambele metode:**
1. Build frontend (npm) + copiere backend
2. Transfer la server (`C:\Temp\deploy-YYYYMMDD-HHmmss\`)
3. Server-ul auto-deploy în 5 minute (sau manual)
---
## Management
### Consolă Interactivă (Recomandat)
```powershell
.\ROA2WEB-Console.ps1
```
### Comenzi Rapide
```powershell
# Service
Start-Service ROA2WEB-Backend
Stop-Service ROA2WEB-Backend
Restart-Service ROA2WEB-Backend
Get-Service ROA2WEB-Backend
# Test backend
# Status & Health
.\ROA2WEB-Console.ps1 -NonInteractive -Action Status
Invoke-WebRequest http://localhost:8000/health
# Open application
Start-Process "http://localhost"
# Logs
Get-Content C:\inetpub\wwwroot\roa2web\logs\backend-stdout.log -Tail 50
Get-Content C:\inetpub\wwwroot\roa2web\logs\backend-stderr.log -Tail 20
# Deploy manual
.\ROA2WEB-Console.ps1 -NonInteractive -Action DeployAll -PackagePath "C:\Temp\deploy-XXXXXXXX"
```
---
## 🔄 Update Workflow
For deploying updates to existing installation:
**1. Build on development machine:**
```bash
cd roa2web/deployment/windows/scripts
./Build-Frontend.ps1 -OutputPath "./deploy-$(date +%Y%m%d)"
```
**2. Transfer to server:**
```powershell
Copy-Item .\deploy-20250118 -Destination C:\Temp\roa2web-deploy -Recurse
```
**3. Deploy on server:**
```powershell
cd C:\inetpub\wwwroot\roa2web\deployment\windows\scripts
.\Deploy-ROA2WEB.ps1 -SourcePath "C:\Temp\roa2web-deploy"
```
---
## 🔧 Management Commands
### Interactive Console (Recommended)
```powershell
# Open unified management console
cd C:\inetpub\wwwroot\roa2web\deployment\windows\scripts
.\ROA2WEB-Console.ps1
# Menu options:
# [1] Deploy Components
# [2] Manage Services
# [3] Check Status
```
### Non-Interactive Commands
```powershell
# Deploy all components
.\ROA2WEB-Console.ps1 -NonInteractive -Action DeployAll
# Deploy specific component
.\ROA2WEB-Console.ps1 -NonInteractive -Action DeployBackend
.\ROA2WEB-Console.ps1 -NonInteractive -Action DeployTelegramBot
.\ROA2WEB-Console.ps1 -NonInteractive -Action DeployDataEntry
# Service management
.\ROA2WEB-Console.ps1 -NonInteractive -Action StartAll
.\ROA2WEB-Console.ps1 -NonInteractive -Action StopAll
.\ROA2WEB-Console.ps1 -NonInteractive -Action RestartAll
# Data Entry service management
.\ROA2WEB-Console.ps1 -NonInteractive -Action StartDataEntry
.\ROA2WEB-Console.ps1 -NonInteractive -Action StopDataEntry
.\ROA2WEB-Console.ps1 -NonInteractive -Action RestartDataEntry
# Check status
.\ROA2WEB-Console.ps1 -NonInteractive -Action Status
```
### Direct Service Commands
```powershell
# Check all ROA2WEB services
Get-Service ROA2WEB-*
# View logs
Get-Content C:\inetpub\wwwroot\roa2web\logs\backend-stdout.log -Tail 50 -Wait
Get-Content C:\inetpub\wwwroot\roa2web\data-entry-backend\logs\stdout.log -Tail 50 -Wait
# Check IIS
Get-Website | Where-Object { $_.Name -like "*roa2web*" -or $_.Name -like "*data-entry*" }
```
---
## 📊 Architecture
### Components
| Component | Type | Port | Purpose |
|-----------|------|------|---------|
| **Reports Frontend** | IIS Static Files | 80/443 | Vue.js SPA (Reports) |
| **Reports Backend** | Windows Service | 8000 | FastAPI API (Reports) |
| **Telegram Bot** | Windows Service | 8002 | Telegram integration |
| **Data Entry Frontend** | IIS Static Files | 80/443 | Vue.js SPA (Data Entry) |
| **Data Entry Backend** | Windows Service | 8003 | FastAPI API (Data Entry) |
| **Database** | Oracle | 1521 | Reports data (read-only) |
| **SQLite** | File | - | Data Entry local storage |
### Network Flow
```
Client → IIS (port 80/443)
├─ /roa2web/api/* → Reports Backend (localhost:8000) → Oracle DB
├─ /roa2web/* → Reports Frontend (Vue.js)
├─ /data-entry/api/* → Data Entry Backend (localhost:8003) → SQLite
└─ /data-entry/* → Data Entry Frontend (Vue.js)
```
### Windows Services
| Service Name | Description | Port |
|-------------|-------------|------|
| ROA2WEB-Backend | Reports API | 8000 |
| ROA2WEB-TelegramBot | Telegram Bot | 8002 |
| ROA2WEB-DataEntry | Data Entry API | 8003 |
---
## 📋 Directory Structure After Installation
## Structura Server
```
C:\inetpub\wwwroot\roa2web\
├── backend\ # Reports Backend (FastAPI)
│ ├── app\
│ ├── requirements.txt
│ ├── venv\
│ └── .env
├── frontend\ # Reports Frontend (Vue.js)
│ ├── index.html
│ ├── assets\
│ └── web.config
├── telegram-bot\ # Telegram Bot
│ ├── app\
│ ├── data\telegram_bot.db
│ ├── requirements.txt
│ ├── venv\
│ └── .env
├── data-entry-backend\ # Data Entry Backend (FastAPI)
│ ├── app\
│ ├── migrations\
│ ├── data\receipts.db # SQLite database
│ ├── data\uploads\ # Uploaded receipts
│ ├── requirements.txt
│ ├── venv\
│ └── .env
├── data-entry-frontend\ # Data Entry Frontend (Vue.js)
│ ├── index.html
│ ├── assets\
│ └── web.config
├── shared\ # Shared Python modules
│ ├── auth\
│ ├── database\
│ └── utils\
├── logs\ # Service logs
│ ├── backend-stdout.log
│ └── backend-stderr.log
└── backups\ # Automatic backups
└── backup-YYYYMMDD-HHMMSS\
├── backend\ # FastAPI (Reports, Data Entry, Telegram modules)
│ └── .env # Configurare (MODULE_*_ENABLED flags)
├── frontend\ # Vue.js SPA + web.config
├── shared\ # Module Python partajate (auth, db)
├── logs\ # backend-stdout.log, backend-stderr.log
└── backups\ # Backup-uri automate
```
---
## 🆘 Troubleshooting
## Arhitectură
### Service won't start
```powershell
# Check logs
Get-Content C:\inetpub\wwwroot\roa2web\logs\backend-stderr.log -Tail 50
# Test manually
cd C:\inetpub\wwwroot\roa2web\backend
python -m uvicorn app.main:app --host 127.0.0.1 --port 8000
```
Client → IIS (80/443)
├─ /roa2web/api/* → ROA2WEB-Backend (localhost:8000)
│ ├── Reports Module → Oracle DB
│ ├── Data Entry Module → SQLite
│ └── Telegram Module
└─ /roa2web/* → Frontend (Vue.js SPA)
```
### Frontend not loading
**Single Service:** `ROA2WEB-Backend` pe port 8000
**Module Control:** Via `.env` flags (fără restart cod)
```powershell
# Restart IIS
iisreset
---
## Workflow Deployment
# Check website status
Get-Website ROA2WEB
Start-Website ROA2WEB
```
DEV MACHINE WINDOWS SERVER
─────────── ──────────────
### API calls failing (502/504)
```powershell
# Check backend service
Get-Service ROA2WEB-Backend
.\Restart-ROA2WEB.ps1
# Test backend directly
Invoke-WebRequest http://localhost:8000/health
```
### Database connection issues
```powershell
# Test Oracle connection
sqlplus CONTAFIN_ORACLE/password@localhost:1521/ROA
# Check Oracle service
Get-Service Oracle*
# Check .env configuration
Get-Content C:\inetpub\wwwroot\roa2web\backend\.env | Select-String ORACLE
Publish-And-Deploy.ps1
sau ───► C:\Temp\deploy-*\
deploy.sh (Linux) │
Check-And-Deploy.ps1
(scheduled task, 5 min)
ROA2WEB-Console.ps1
├── Stop Service
├── Backup
├── Deploy Files
├── Start Service
└── Health Check
✅ PRODUCTION RUNNING
```
---
## 📖 Full Documentation
## Troubleshooting
For complete documentation, see:
- **[WINDOWS_DEPLOYMENT.md](docs/WINDOWS_DEPLOYMENT.md)** - Comprehensive deployment guide
- **[.env.production.windows](config/.env.production.windows)** - Configuration reference
| Problemă | Verificare | Soluție |
|----------|------------|---------|
| Service nu pornește | `Get-Content ...\backend-stderr.log -Tail 30` | Verifică .env, port 8000 |
| API 502/504 | `Invoke-WebRequest http://localhost:8000/health` | Restart service |
| Frontend nu se încarcă | `iisreset` | Verifică IIS, web.config |
| Auto-deploy nu merge | `Get-ScheduledTask ROA2WEB-AutoDeploy` | `.\Setup-AutoDeploy.ps1` |
---
## 🔑 Key Features
## Fișiere web.config
**Simple Installation** - One PowerShell script installs everything
**Minimal Dependencies** - Only Python + IIS (already on Windows Server)
**Easy Replication** - Same scripts work on all servers
**Automatic Backups** - Every deployment creates a backup
**Windows Service** - Backend runs as service with auto-start/restart
**Production Ready** - Optimized for performance and reliability
| Fișier | Scop | Când se folosește |
|--------|------|-------------------|
| `public/web.config` | Sub-aplicație IIS (/roa2web) | La fiecare deploy (via Vite) |
| `deployment/windows/config/web.config` | Server IIS complet | La instalare nouă |
**Notă:** Ambele au configurat `no-cache` pentru API (backend gestionează cache-ul).
---
## 📊 System Requirements
## Documentație Detaliată
| Resource | Minimum | Recommended |
|----------|---------|-------------|
| **OS** | Windows Server 2016 | Windows Server 2019+ |
| **RAM** | 4 GB | 8 GB (16 GB if using OCR) |
| **CPU** | 2 cores | 4 cores |
| **Disk** | 10 GB free | 20 GB free |
| **Network** | 100 Mbps | 1 Gbps |
- **HTTPS Setup:** `docs/HTTPS_SETUP.md`
- **2-Tier IIS:** `docs/TWO-TIER-IIS-DEPLOYMENT.md`
- **Telegram Bot:** `docs/TELEGRAM-BOT-DEPLOYMENT.md`
---
## 🔍 OCR Dependencies (Data Entry App)
## Cerințe Sistem
Data Entry App foloseste OCR pentru extragerea automata a datelor din bonuri fiscale. Pe Windows trebuie instalate manual:
### 1. Poppler (conversie PDF → imagini)
```powershell
# Descarca de la: https://github.com/osborn/poppler-windows/releases
# Extrage in: C:\Program Files\poppler\
# Adauga la System PATH: C:\Program Files\poppler\Library\bin
# Verificare instalare:
pdfinfo --version
```
### 2. Tesseract OCR (engine OCR backup)
```powershell
# Descarca installer: https://github.com/UB-Mannheim/tesseract/wiki
# Selecteaza limbile: English + Romanian
# Default path: C:\Program Files\Tesseract-OCR\
# Adauga la System PATH
# Verificare instalare:
tesseract --version
```
### 3. Python OCR Packages
```powershell
cd C:\inetpub\wwwroot\roa2web\data-entry-backend
.\venv\Scripts\activate
pip install paddlepaddle>=2.5.0
pip install paddleocr>=2.7.0
pip install opencv-python>=4.8.0
pip install pytesseract>=0.3.10
pip install pdf2image>=1.16.0
# Restart serviciu
nssm restart ROA2WEB-DataEntry
```
### Note importante
- **PaddleOCR** descarca modele (~200MB) la prima rulare
- **RAM**: PaddleOCR necesita ~2GB RAM disponibil
- **PATH**: Dupa modificari PATH, restart serviciul backend
- **Test OCR**: `curl http://localhost:8003/api/ocr/status`
| Resursă | Minim | Recomandat |
|---------|-------|------------|
| OS | Windows Server 2016 | Windows Server 2019+ |
| RAM | 4 GB | 8 GB (16 GB cu OCR) |
| CPU | 2 cores | 4 cores |
| Python | 3.11+ | 3.11+ |
| IIS | URL Rewrite + ARR | URL Rewrite + ARR |
---
## 🔐 Security Recommendations
1. **Generate Strong JWT Secret:**
```powershell
-join ((65..90) + (97..122) + (48..57) | Get-Random -Count 32 | % {[char]$_})
```
2. **Secure .env File:**
```powershell
icacls C:\inetpub\wwwroot\roa2web\backend\.env /inheritance:r /grant:r Administrators:F
```
3. **Enable HTTPS:** ⭐ **RECOMMENDED**
```powershell
# Quick setup with automated script
cd C:\roa2web\deployment\windows\scripts
.\Enable-HTTPS.ps1
# For detailed instructions, see:
# docs/HTTPS_SETUP.md
```
**What it does:**
- Creates/installs SSL certificate
- Configures HTTPS binding (port 443)
- Enables HTTP to HTTPS redirect
- Activates HSTS (Strict Transport Security)
**Access your application securely:**
- `https://10.0.20.36/roa2web` (or your domain)
4. **Regular Updates:**
- Keep Windows Server updated
- Update Python packages monthly
- Monitor security advisories
- Renew SSL certificates before expiry
---
## 📞 Support
For issues or questions:
1. Check logs: `C:\inetpub\wwwroot\roa2web\logs\`
2. Review [WINDOWS_DEPLOYMENT.md](docs/WINDOWS_DEPLOYMENT.md)
3. Contact: development-team@your-company.com
---
## 📝 Version History
| Version | Date | Changes |
|---------|------|---------|
| 2.1.0 | 2025-12-18 | Added Data Entry App deployment support |
| 2.0.0 | 2025-01-18 | Initial Windows deployment package |
---
*ROA2WEB - Modern ERP Application (Reports + Data Entry)*
*Windows Server Deployment Package v2.1.0*
*ROA2WEB - Ultrathin Monolith Architecture*
*Last Updated: 2025-01-22*

View File

@@ -1,240 +0,0 @@
# web.config Files - Which Goes Where?
## ⚠️ IMPORTANT - Read Before Deployment!
ROA2WEB uses a **2-tier IIS architecture** with **2 different web.config files** for **2 different servers**.
---
## Architecture Overview
```
Internet
Public Server (10.0.20.122) - roa2web.romfast.ro
↓ HTTPS reverse proxy
Internal Server (10.0.20.36) - application host
↓ API proxy to localhost
Backend Service (localhost:8000 on 10.0.20.36)
```
---
## File Mapping
### File: `web.config.10.0.20.122-PUBLIC`
**Server**: 10.0.20.122 (Public IIS - roa2web.romfast.ro)
**Role**: Public gateway, reverse proxy to internal server
**Purpose**:
- Proxies ALL requests to `https://10.0.20.36/{REQUEST_PATH}`
- Sets forwarding headers (`X-Forwarded-Proto`, `X-Forwarded-Host`, `X-Real-IP`)
- Redirects root `/` to `/roa2web/`
**Key Rule**:
```xml
<match url="(.*)" />
<action type="Rewrite" url="https://10.0.20.36/{R:1}" />
```
**Deployment Location**:
```
10.0.20.122:
C:\inetpub\wwwroot\[ROOT]\web.config
```
---
### File: `web.config.10.0.20.36-INTERNAL`
**Server**: 10.0.20.36 (Internal IIS - application host)
**Role**: Serves frontend, proxies API to localhost backend
**Purpose**:
- Serves Vue.js frontend static files
- Proxies `/roa2web/api/*` to `http://localhost:8000/api/*`
- Proxies `/roa2web/uploads/*` to `http://localhost:8000/uploads/*`
- SPA fallback for client-side routing
**Key Rules**:
```xml
<match url="^roa2web/api/(.*)" />
<action type="Rewrite" url="http://localhost:8000/api/{R:1}" />
<match url="^roa2web/uploads/(.*)" />
<action type="Rewrite" url="http://localhost:8000/uploads/{R:1}" />
<match url="^roa2web/.*" />
<action type="Rewrite" url="/roa2web/index.html" />
```
**Deployment Location**:
```
10.0.20.36:
C:\inetpub\wwwroot\roa2web\web.config
```
**Note**: This file is also in `public/web.config` (repository root) and is automatically copied to `dist/` during Vite build.
---
## Deployment Checklist
### ✅ Public Server (10.0.20.122)
```powershell
# Copy public server config
Copy-Item deployment/windows/config/web.config.10.0.20.122-PUBLIC `
C:\inetpub\wwwroot\[ROOT]\web.config
# Verify
Get-Content C:\inetpub\wwwroot\[ROOT]\web.config | Select-String "10.0.20.36"
```
**Expected**: Should see `url="https://10.0.20.36/{R:1}"`
### ✅ Internal Server (10.0.20.36)
**Option A: From built dist/ (recommended)**:
```powershell
# After building frontend with `npm run build`
# web.config is automatically in dist/
# Deploy entire dist/ folder
Copy-Item dist\* C:\inetpub\wwwroot\roa2web\ -Recurse -Force
```
**Option B: Manual copy**:
```powershell
# Copy internal server config
Copy-Item deployment/windows/config/web.config.10.0.20.36-INTERNAL `
C:\inetpub\wwwroot\roa2web\web.config
# Verify
Get-Content C:\inetpub\wwwroot\roa2web\web.config | Select-String "roa2web/api"
```
**Expected**: Should see `url="^roa2web/api/(.*)"` and `url="http://localhost:8000/api/{R:1}"`
---
## Verification
### Test Public Server (10.0.20.122)
```powershell
# Should proxy to internal server
Invoke-WebRequest https://roa2web.romfast.ro/roa2web/ -UseBasicParsing
# Check response headers
(Invoke-WebRequest https://roa2web.romfast.ro/roa2web/).Headers
```
**Expected**: Request should be proxied to 10.0.20.36
### Test Internal Server (10.0.20.36)
```powershell
# Test backend directly
Invoke-WebRequest http://localhost:8000/health
# Test through IIS proxy
Invoke-WebRequest https://localhost/roa2web/api/health
# Test frontend
Invoke-WebRequest https://localhost/roa2web/
```
**Expected**: All should return 200 OK
---
## Common Mistakes ❌
### ❌ WRONG: Using internal config on public server
```xml
<!-- On 10.0.20.122 - WRONG! -->
<match url="^roa2web/api/(.*)" />
<action type="Rewrite" url="http://localhost:8000/api/{R:1}" />
```
**Problem**: Public server doesn't have backend on localhost:8000
### ❌ WRONG: Using public config on internal server
```xml
<!-- On 10.0.20.36 - WRONG! -->
<match url="(.*)" />
<action type="Rewrite" url="https://10.0.20.36/{R:1}" />
```
**Problem**: Creates infinite redirect loop
### ❌ WRONG: Missing /roa2web/ prefix on internal server
```xml
<!-- On 10.0.20.36 - WRONG! -->
<match url="^api/(.*)" /> <!-- Missing roa2web prefix! -->
<action type="Rewrite" url="http://localhost:8000/api/{R:1}" />
```
**Problem**: Requests come as `/roa2web/api/...` from public server, so `^api/` won't match
---
## Troubleshooting
### Issue: 404 on API calls
**Symptom**: Frontend loads but API returns 404
**Check**: web.config on 10.0.20.36
```powershell
# On 10.0.20.36
Get-Content C:\inetpub\wwwroot\roa2web\web.config | Select-String "roa2web/api"
```
**Fix**: Update to correct internal server config (see above)
### Issue: Infinite redirect loop
**Symptom**: Browser shows "Too many redirects"
**Check**: Verify you didn't put public config on internal server
### Issue: Backend not reachable
**Symptom**: 502 Bad Gateway on API calls
**Check**: Backend service on 10.0.20.36
```powershell
# On 10.0.20.36
Get-Service ROA2WEB-Backend
Invoke-WebRequest http://localhost:8000/health
```
---
## Quick Reference
| Server | IP | Config File | Key Pattern | Proxies To |
|--------|----|----|-------------|------------|
| **Public** | 10.0.20.122 | `web.config.10.0.20.122-PUBLIC` | `url="(.*)"` | `https://10.0.20.36/{R:1}` |
| **Internal** | 10.0.20.36 | `web.config.10.0.20.36-INTERNAL` | `url="^roa2web/api/(.*)"` | `http://localhost:8000/api/{R:1}` |
---
## Documentation
For complete architecture details, see:
- `deployment/windows/docs/TWO-TIER-IIS-DEPLOYMENT.md`
- `DIAGNOSIS-2025-12-30.md`
---
*Last Updated: 2025-12-30*
*ROA2WEB Deployment Configuration Guide*

View File

@@ -124,16 +124,27 @@
</rules>
<!-- Outbound Rules (optional - for modifying responses) -->
<!-- Outbound Rules for response headers -->
<outboundRules>
<!-- HSTS Header for HTTPS connections -->
<rule name="Add HSTS Header" preCondition="IsHTTPS">
<match serverVariable="RESPONSE_Strict-Transport-Security" pattern=".*" />
<action type="Rewrite" value="max-age=31536000; includeSubDomains" />
</rule>
<!-- API responses: NO browser/proxy caching (backend cache handles this) -->
<rule name="No Cache for API" preCondition="IsAPIRequest">
<match serverVariable="RESPONSE_Cache-Control" pattern=".*" />
<action type="Rewrite" value="no-store, no-cache, must-revalidate, proxy-revalidate" />
</rule>
<preConditions>
<preCondition name="IsHTTPS">
<add input="{HTTPS}" pattern="on" />
</preCondition>
<preCondition name="IsAPIRequest">
<add input="{URL}" pattern="^/api/" />
</preCondition>
</preConditions>
</outboundRules>
</rewrite>

View File

@@ -422,8 +422,8 @@ Get-Content "C:\ROA2WEB-Scripts\last-deploy.json" | ConvertFrom-Json | Format-Li
### Check Service Status (Server)
```powershell
# After deployment, verify services
Get-Service -Name "ROA2WEB-Backend", "ROA2WEB-TelegramBot"
# After deployment, verify service
Get-Service -Name "ROA2WEB-Backend"
# Or use ROA2WEB-Console.ps1
cd C:\inetpub\wwwroot\roa2web\scripts
@@ -669,14 +669,13 @@ Get-Content "C:\Temp\ROA2WEB-Scripts\Logs\check-and-deploy.log" -Tail 30
```
```powershell
# Verify services are running:
Get-Service -Name "ROA2WEB-Backend", "ROA2WEB-TelegramBot"
# Verify service is running:
Get-Service -Name "ROA2WEB-Backend"
# Expected output:
# Status Name DisplayName
# ------ ---- -----------
# Running ROA2WEB-Backend ROA2WEB Backend Service
# Running ROA2WEB-TelegramBot ROA2WEB Telegram Bot Service
```
#### Step 5: Verify Web Application

View File

@@ -1,247 +0,0 @@
# Telegram Bot Deployment Notes
## Overview
The ROA2WEB application includes an integrated Telegram bot module that runs as part of the unified FastAPI backend. This requires special configuration when deploying as a Windows service.
## Critical Configuration: Single Worker Only
### The Problem
**Symptom**: Telegram bot errors in logs:
```
telegram.error.Conflict: Conflict: terminated by other getUpdates request;
make sure that only one bot instance is running
```
**Root Cause**:
- Uvicorn is configured to run with multiple workers (e.g., `--workers 4`)
- Each worker process spawns its own Telegram bot instance
- Telegram API allows **only ONE instance** per bot token to poll for updates
- Multiple instances conflict with each other → continuous errors
### The Solution
**✅ ALWAYS use `--workers 1` for the backend service**
The NSSM service MUST be configured with:
```powershell
--workers 1
```
**Why this works**:
- Single uvicorn worker = Single bot instance
- No polling conflicts
- Telegram bot runs cleanly
**Performance Impact**:
- ✅ Minimal - the application is I/O bound (Oracle database queries), not CPU bound
- ✅ Single worker can handle hundreds of concurrent requests with async/await
- ✅ Connection pooling (Oracle + SQLite) ensures efficient resource usage
## Deployment Instructions
### New Installation
When installing with `Install-ROA2WEB.ps1`, the script now **automatically** uses `--workers 1` (as of 2025-12-29).
No manual configuration needed.
### Existing Installation (Upgrade)
If you have an existing installation with `--workers 4`, run the fix script:
```powershell
cd C:\TEMP\ROA2WEB-Scripts
.\Fix-TelegramWorkers.ps1
```
This script will:
1. Stop the ROA2WEB-Backend service
2. Update NSSM parameters to `--workers 1`
3. Restart the service
4. Verify health and check logs for errors
### Manual Fix (Alternative)
If you prefer to fix manually:
```powershell
# Stop service
Stop-Service ROA2WEB-Backend
# Update NSSM parameters
nssm set ROA2WEB-Backend AppParameters "-m uvicorn main:app --host 127.0.0.1 --port 8000 --workers 1"
# Verify
nssm get ROA2WEB-Backend AppParameters
# Start service
Start-Service ROA2WEB-Backend
# Monitor logs
Get-Content C:\inetpub\wwwroot\roa2web\logs\backend-stderr.log -Tail 50 -Wait
```
## Verification
### 1. Check Service Parameters
```powershell
nssm get ROA2WEB-Backend AppParameters
```
Expected output:
```
-m uvicorn main:app --host 127.0.0.1 --port 8000 --workers 1
```
### 2. Check Logs for Bot Startup
```powershell
Get-Content C:\inetpub\wwwroot\roa2web\logs\backend-stderr.log -Tail 50
```
Expected output (should appear **ONCE**, not 4 times):
```
22:42:39 - main - INFO - [TELEGRAM] Starting bot...
22:42:40 - main - INFO - [TELEGRAM] ✅ Bot running: @ROA2WEBBot
```
### 3. Verify No Conflict Errors
After waiting 1-2 minutes, check logs again:
```powershell
Get-Content C:\inetpub\wwwroot\roa2web\logs\backend-stderr.log -Tail 100 | Select-String "Conflict"
```
Expected output: **No results** (no conflict errors)
### 4. Check Process Count
```powershell
Get-Process -Name python | Where-Object { $_.MainWindowTitle -eq "" }
```
You should see:
- **1 parent process** (uvicorn master)
- **1 child process** (the single worker)
- **Total: 2 python processes**
With `--workers 4`, you would see 5 processes (1 parent + 4 workers) ❌
## Troubleshooting
### Still seeing conflict errors after fix?
1. **Verify service parameters**:
```powershell
nssm get ROA2WEB-Backend AppParameters
```
Should show `--workers 1`
2. **Fully restart the service**:
```powershell
Stop-Service ROA2WEB-Backend -Force
Start-Sleep -Seconds 5
Start-Service ROA2WEB-Backend
```
3. **Check for old processes**:
```powershell
Get-Process python | Stop-Process -Force
Start-Service ROA2WEB-Backend
```
### Service won't start after change?
1. **Check logs** for the actual error:
```powershell
Get-Content C:\inetpub\wwwroot\roa2web\logs\backend-stderr.log -Tail 50
```
2. **Common issues**:
- Oracle connection timeout → Check SSH tunnel or Oracle listener
- Module import errors → Verify PYTHONPATH in NSSM config
- Port already in use → Kill process using port 8000
### Cache stats endpoint (502 error)
The `/api/reports/cache/stats` endpoint may return 502 Bad Gateway with multiple workers because:
- Multiple workers try to access the same SQLite cache database file
- SQLite locking conflicts cause worker crashes
- **Resolved by using `--workers 1`** ✅
## Related Issues
### Pydantic v2 Warnings
**Warning**:
```
UserWarning: Valid config keys have changed in V2:
* 'schema_extra' has been renamed to 'json_schema_extra'
```
**Fix**: Updated in `backend/modules/reports/models/trial_balance.py` (2025-12-29)
**Not critical** - just warnings, doesn't affect functionality.
### PTB Handler Warning
**Warning**:
```
PTBUserWarning: If 'per_message=False', 'CallbackQueryHandler' will not be tracked for every message.
```
**Location**: `backend/modules/telegram/bot/email_handlers.py:742`
**Impact**: Informational warning, bot works correctly
**Fix**: Add `per_message=True` to ConversationHandler (optional enhancement)
## Architecture Notes
### Why Not Multiple Workers?
**Question**: Why not run the Telegram bot in a separate process/service?
**Answer**: Possible, but current architecture is simpler:
**Current (Recommended)**:
- ✅ Single service manages everything
- ✅ Unified logging and monitoring
- ✅ Simpler deployment
- ✅ Single process to debug
- ⚠️ Must use `--workers 1`
**Alternative (Separate Bot Service)**:
- ✅ Could use `--workers 4` for web backend
- ❌ Requires two Windows services
- ❌ More complex deployment
- ❌ Two processes to monitor
- ❌ Coordination required
**Decision**: Keep integrated bot with single worker. Performance is excellent for our use case.
### Performance Characteristics
With `--workers 1`:
- **Concurrent requests**: Handled via async/await (100+ concurrent)
- **Database pooling**: 5-10 connections in Oracle pool (shared)
- **Memory usage**: ~300-500 MB per worker
- **CPU usage**: Low (I/O bound, not CPU bound)
- **Response times**: 50-200ms (mostly database query time)
Performance is **more than adequate** for:
- 50-100 concurrent users
- 1000+ requests per minute
- Multiple modules (Reports, Data Entry, Telegram)
## Conclusion
**Always deploy ROA2WEB backend with `--workers 1` to avoid Telegram bot conflicts.**
The fix script (`Fix-TelegramWorkers.ps1`) makes this change automatically for existing installations.
New installations (Install-ROA2WEB.ps1) are pre-configured correctly.

View File

@@ -1,855 +0,0 @@
# ROA2WEB Telegram Bot - Windows Server Deployment Guide
> ⚠️ **DEPRECATED ARCHITECTURE**
>
> This documentation refers to the OLD microservices architecture where the Telegram bot
> ran as a separate service on port 8002. The current architecture is an **ultrathin monolith**
> where everything runs on a single port (8000/8001) via `backend/main.py`.
>
> **Current Architecture**: Telegram bot runs as a background task within the unified backend.
> Internal API endpoints are now at `/api/telegram/internal/*` on the main port.
>
> See `CLAUDE.md` and `QUICK-START.md` for the current architecture.
**Target Server**: Windows Server (10.0.20.36)
**Deployment Method**: Windows Service (NSSM) - No Docker
**Service Name**: ROA2WEB-TelegramBot
**Internal API Port**: ~~8002~~ (DEPRECATED - now via main backend)
**Created**: 2025-10-22
**Last Updated**: 2025-10-22
---
## Table of Contents
1. [Overview](#overview)
2. [Prerequisites](#prerequisites)
3. [Deployment Architecture](#deployment-architecture)
4. [Installation Steps](#installation-steps)
5. [Configuration](#configuration)
6. [Service Management](#service-management)
7. [Database Backup](#database-backup)
8. [Monitoring & Troubleshooting](#monitoring--troubleshooting)
9. [Security Considerations](#security-considerations)
10. [Maintenance Procedures](#maintenance-procedures)
---
## Overview
The ROA2WEB Telegram Bot is deployed as a Windows Service on the same server as the backend (10.0.20.36). It provides an alternative conversational interface to ROA2WEB using Claude Agent SDK.
### Key Features
- **Conversational AI**: Claude Agent SDK with 5 custom tools
- **Account Linking**: Secure linking between Telegram and Oracle accounts
- **Real-time Queries**: Dashboard, invoices, treasury, exports
- **Database**: Standalone SQLite for Telegram-specific data
- **Internal API**: FastAPI endpoint for backend callbacks (port 8002)
- **Production Ready**: All components use real backend integration (no mocks)
### Deployment Method
- **Windows Service**: Runs via NSSM (Non-Sucking Service Manager)
- **No Docker**: Direct Windows deployment (same pattern as backend)
- **Auto-start**: Service starts automatically on server boot
- **Auto-recovery**: Service restarts automatically on failure
---
## Prerequisites
### Server Requirements
- **Operating System**: Windows Server 2016+ or Windows 10/11
- **Python**: 3.11 or higher
- **RAM**: Minimum 512 MB (dedicated to service)
- **Disk Space**: Minimum 500 MB
- **Network**: Access to localhost:8000 (backend API)
### Required Credentials
1. **Telegram Bot Token**
- Get from @BotFather on Telegram
- Command: `/newbot` or `/mybots`
- Example: `123456789:ABCdefGHIjklMNOpqrsTUVwxyz`
2. **Claude Authentication** (Choose ONE method)
**Method A: Claude Pro/Max Subscription****RECOMMENDED**
-**NO API key needed**
-**NO additional costs** (included in your subscription)
- ✅ Uses browser authentication
- See: [Claude Authentication Setup](#claude-authentication-setup) below
**Method B: Claude API Key** (Alternative)
- Get from Anthropic Console: https://console.anthropic.com/settings/keys
- Example: `sk-ant-api03-XXXXXXXX...`
- ⚠️ Usage-based billing applies
- Takes precedence over Method A if both are configured
3. **Backend Access**
- Backend should be running on http://localhost:8000
- Verify: `Invoke-WebRequest http://localhost:8000/health`
### Software Prerequisites
- **PowerShell 5.1+**: Built into Windows Server
- **Python 3.11+**: Will be installed if missing (via Chocolatey)
- **NSSM**: Will be installed automatically by installation script
---
## Deployment Architecture
### Directory Structure
```
C:\inetpub\wwwroot\roa2web\telegram-bot\
├── app\ # Application source code
│ ├── main.py # Entry point, Claude Agent wrapper
│ ├── bot\ # Telegram bot handlers
│ ├── agent\ # Claude Agent tools and sessions
│ ├── auth\ # Account linking logic
│ ├── db\ # SQLite database operations
│ ├── api\ # Backend API client
│ └── internal_api.py # FastAPI internal API
├── venv\ # Python virtual environment
├── data\ # SQLite database
│ └── telegram_bot.db # Main database file
├── logs\ # Application logs
│ ├── stdout.log # Service output
│ ├── stderr.log # Service errors
│ └── backup.log # Backup operations
├── backups\ # Database backups
├── temp\ # Temporary files
├── scripts\ # PowerShell management scripts
├── config\ # Configuration templates
├── requirements.txt # Python dependencies
└── .env # Environment configuration
```
### Service Integration
```
┌─────────────────────────────────────────────────────────────┐
│ Windows Server 10.0.20.36 │
│ │
│ ┌──────────────────┐ ┌──────────────────┐ │
│ │ IIS (Port 80) │ │ ROA2WEB-Backend │ │
│ │ Frontend Static │ │ (Port 8000) │ │
│ └──────────────────┘ └────────┬─────────┘ │
│ │ │
│ │ HTTP API Calls │
│ │ │
│ ┌─────────────────▼──────────────┐ │
│ │ ROA2WEB-TelegramBot │ │
│ │ (Port 8002 - Internal API) │ │
│ │ - Telegram Bot Handlers │ │
│ │ - Claude Agent SDK │ │
│ │ - SQLite Database │ │
│ └────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
│ Telegram Bot API
┌─────────────────┐
│ Telegram │
│ Cloud │
└─────────────────┘
```
---
## Installation Steps
### Step 1: Build Deployment Package (Development Machine)
On your development machine (WSL/Linux), run:
```bash
cd /mnt/e/proiecte/roa2web/roa2web/deployment/windows/scripts
./Build-TelegramBot.ps1
```
This creates the deployment package at:
```
../deploy-package/telegram-bot/
```
**Package Contents**:
- `app/` - Application source code
- `requirements.txt` - Python dependencies
- `.env.example` - Configuration template
- `scripts/` - PowerShell management scripts
- `config/` - Production config templates
- `README.txt` - Deployment instructions
### Step 2: Transfer Package to Server
**Option A: Network Share** (Recommended)
```powershell
# On development machine
Copy-Item -Path ./deploy-package/telegram-bot -Destination \\10.0.20.36\C$\Temp\telegram-bot-deploy -Recurse
```
**Option B: RDP**
1. Connect to server via RDP: `mstsc /v:10.0.20.36`
2. Manually copy deployment package to `C:\Temp\telegram-bot-deploy`
### Step 3: Run Installation Script
On Windows Server (10.0.20.36), open PowerShell as Administrator:
```powershell
cd C:\Temp\telegram-bot-deploy\scripts
.\Install-TelegramBot.ps1
```
**Installation Process**:
1. ✅ Checks Python 3.11+ installation
2. ✅ Installs NSSM (service manager)
3. ✅ Creates directory structure
4. ✅ Creates Python virtual environment
5. ✅ Installs Python dependencies
6. ✅ Creates Windows Service (ROA2WEB-TelegramBot)
7. ✅ Creates .env configuration template
**Installation Output**:
```
====================================================================
ROA2WEB TELEGRAM BOT INSTALLATION COMPLETED
====================================================================
Installation Details:
Install Path: C:\inetpub\wwwroot\roa2web\telegram-bot
Service Name: ROA2WEB-TelegramBot
Internal API Port: 8002
Next Steps:
1. Edit configuration: C:\inetpub\wwwroot\roa2web\telegram-bot\.env
2. Start service: .\Start-TelegramBot.ps1
```
### Step 4: Configure Environment
Edit the `.env` file:
```powershell
notepad C:\inetpub\wwwroot\roa2web\telegram-bot\.env
```
**Required Configuration**:
```env
# CRITICAL: Update this value
TELEGRAM_BOT_TOKEN=your_production_bot_token_from_@BotFather
# Claude Authentication: Leave empty to use Claude Pro/Max subscription
CLAUDE_API_KEY=
# Verify these are correct
BACKEND_URL=http://localhost:8000
SQLITE_DB_PATH=C:\inetpub\wwwroot\roa2web\telegram-bot\data\telegram_bot.db
INTERNAL_API_PORT=8002
LOG_LEVEL=INFO
ENVIRONMENT=production
```
**Get Bot Token**:
1. Open Telegram, search for `@BotFather`
2. Send `/newbot` or `/mybots`
3. Copy token to `TELEGRAM_BOT_TOKEN`
### Step 4a: Claude Authentication Setup
**Choose ONE authentication method:**
#### **Method A: Claude Pro/Max Subscription** ⭐ **RECOMMENDED**
If you have a Claude Pro or Claude Max subscription, use this method (NO API key needed!):
```powershell
cd C:\inetpub\wwwroot\roa2web\telegram-bot\scripts
.\Setup-ClaudeAuth.ps1
```
**What happens:**
1. Script installs `claude-code` CLI (if not already installed)
2. Opens your browser for authentication
3. Log in with your Claude Pro/Max account
4. Authorize the application
5. Credentials are saved to: `%APPDATA%\claude\credentials.json`
**Expected Output:**
```
====================================================================
IMPORTANT: Browser Authentication Required
====================================================================
1. A browser window will open
2. Log in with your Claude Pro/Max account
3. Authorize the application
4. Return to this window after authentication
====================================================================
[*] Opening browser for authentication...
[OK] Authentication successful!
[OK] Credentials file found and valid
[OK] .env will use Claude Pro subscription (browser login)
====================================================================
CLAUDE AUTHENTICATION SETUP COMPLETE
====================================================================
```
**Alternative: Copy credentials from development machine**
If the server doesn't have browser access, authenticate on your local machine and copy credentials:
```powershell
# On local machine (with browser):
npm install -g @anthropic-ai/claude-code
claude-code login
# Copy credentials file to server
Copy-Item "$env:APPDATA\claude\credentials.json" -Destination "\\10.0.20.36\C$\Temp\claude-credentials.json"
# On server:
cd C:\inetpub\wwwroot\roa2web\telegram-bot\scripts
.\Setup-ClaudeAuth.ps1 -Method copy -CredentialsPath "C:\Temp\claude-credentials.json"
```
#### **Method B: Claude API Key** (Alternative)
If you prefer to use an API key instead:
1. Visit https://console.anthropic.com/settings/keys
2. Create new key
3. Edit `.env` and set `CLAUDE_API_KEY=sk-ant-api03-XXXXXXXX...`
4. ⚠️ Usage-based billing applies
**Note:** API key takes precedence over browser login if both are configured.
### Step 5: Start Service
```powershell
cd C:\inetpub\wwwroot\roa2web\telegram-bot\scripts
.\Start-TelegramBot.ps1
```
**Expected Output**:
```
[*] Starting ROA2WEB Telegram Bot Service...
[*] Service start command issued
[*] Waiting for service to start... (5/30)
[OK] Service started successfully
[OK] Health check passed: healthy
[OK] Database: connected
```
### Step 6: Verify Installation
**Check Service Status**:
```powershell
Get-Service ROA2WEB-TelegramBot
```
Expected: `Status = Running`
**Check Health Endpoint**:
```powershell
Invoke-WebRequest http://localhost:8002/internal/health | ConvertFrom-Json
```
Expected Output:
```json
{
"status": "healthy",
"timestamp": "2025-10-22T14:30:00",
"database": {
"status": "connected",
"users": 0,
"pending_codes": 0
}
}
```
**Test Bot on Telegram**:
1. Open Telegram
2. Search for your bot (name from @BotFather)
3. Send `/start`
4. Expected: Welcome message with linking instructions
---
## Configuration
### Environment Variables Reference
See `.env.production.windows.telegram` in `config/` directory for complete reference.
**Key Settings**:
| Variable | Default | Description |
|----------|---------|-------------|
| `TELEGRAM_BOT_TOKEN` | *required* | Bot token from @BotFather |
| `CLAUDE_API_KEY` | *required* | API key from Anthropic |
| `BACKEND_URL` | `http://localhost:8000` | Backend API URL |
| `SQLITE_DB_PATH` | `C:\...\telegram_bot.db` | Database file location |
| `INTERNAL_API_PORT` | `8002` | Internal API port |
| `LOG_LEVEL` | `INFO` | Logging level (DEBUG/INFO/WARN/ERROR) |
| `ENVIRONMENT` | `production` | Environment name |
| `AUTH_CODE_EXPIRY_MINUTES` | `15` | Linking code expiry time |
| `SESSION_TIMEOUT_MINUTES` | `60` | User session timeout |
| `MAX_CONVERSATION_HISTORY` | `20` | Max messages per session |
### Applying Configuration Changes
After editing `.env`:
```powershell
cd C:\inetpub\wwwroot\roa2web\telegram-bot\scripts
.\Restart-TelegramBot.ps1
```
---
## Service Management
### Start Service
```powershell
cd C:\inetpub\wwwroot\roa2web\telegram-bot\scripts
.\Start-TelegramBot.ps1
```
### Stop Service
```powershell
.\Stop-TelegramBot.ps1
```
### Restart Service
```powershell
.\Restart-TelegramBot.ps1
```
### Check Service Status
```powershell
Get-Service ROA2WEB-TelegramBot
# Detailed info
Get-Service ROA2WEB-TelegramBot | Select-Object *
```
### View Logs
**Real-time Logs** (tail -f equivalent):
```powershell
Get-Content C:\inetpub\wwwroot\roa2web\telegram-bot\logs\stdout.log -Tail 50 -Wait
```
**Error Logs**:
```powershell
Get-Content C:\inetpub\wwwroot\roa2web\telegram-bot\logs\stderr.log -Tail 100
```
**Backup Logs**:
```powershell
Get-Content C:\inetpub\wwwroot\roa2web\telegram-bot\logs\backup.log -Tail 50
```
---
## Database Backup
### Manual Backup
```powershell
cd C:\inetpub\wwwroot\roa2web\telegram-bot\scripts
.\Backup-TelegramDB.ps1
```
**Output**:
- Backup file: `backups/telegram_bot_backup_YYYYMMDD-HHMMSS.db.zip`
- Compressed and timestamped
- Integrity tested automatically
### Setup Automated Daily Backup
```powershell
cd C:\inetpub\wwwroot\roa2web\telegram-bot\scripts
.\Setup-DailyBackup.ps1
```
**Configuration**:
- Runs daily at 2:00 AM
- Keeps last 30 days of backups
- Runs as SYSTEM account
- Logs all operations
**Verify Scheduled Task**:
```powershell
Get-ScheduledTask -TaskName "ROA2WEB-TelegramBot-Backup"
```
**Run Backup Manually** (via Task Scheduler):
```powershell
Start-ScheduledTask -TaskName "ROA2WEB-TelegramBot-Backup"
```
### Restore from Backup
1. Stop service:
```powershell
.\Stop-TelegramBot.ps1
```
2. Find backup file:
```powershell
Get-ChildItem C:\inetpub\wwwroot\roa2web\telegram-bot\backups | Sort-Object LastWriteTime -Descending
```
3. Extract backup (if compressed):
```powershell
Expand-Archive -Path "backups\telegram_bot_backup_YYYYMMDD-HHMMSS.db.zip" -DestinationPath "temp\"
```
4. Replace database:
```powershell
Copy-Item -Path "temp\telegram_bot_backup_YYYYMMDD-HHMMSS.db" -Destination "data\telegram_bot.db" -Force
```
5. Start service:
```powershell
.\Start-TelegramBot.ps1
```
---
## Monitoring & Troubleshooting
### Health Checks
**Service Health**:
```powershell
Get-Service ROA2WEB-TelegramBot | Select-Object Name, Status, StartType
```
**API Health**:
```powershell
Invoke-WebRequest http://localhost:8002/internal/health
```
**Database Stats**:
```powershell
(Invoke-WebRequest http://localhost:8002/internal/stats).Content | ConvertFrom-Json
```
### Common Issues
#### Service Won't Start
**Symptoms**: Service shows "Stopped" or "Starting" forever
**Diagnosis**:
```powershell
Get-Content C:\inetpub\wwwroot\roa2web\telegram-bot\logs\stderr.log -Tail 100
```
**Common Causes**:
1. **Missing .env file** → Create from `.env.example`
2. **Invalid bot token** → Check `TELEGRAM_BOT_TOKEN`
3. **Invalid Claude API key** → Check `CLAUDE_API_KEY`
4. **Port 8002 already in use** → Change `INTERNAL_API_PORT`
5. **Backend not running** → Start ROA2WEB-Backend service
**Solutions**:
```powershell
# Fix config
notepad C:\inetpub\wwwroot\roa2web\telegram-bot\.env
# Check port availability
Get-NetTCPConnection -LocalPort 8002
# Restart service
.\Restart-TelegramBot.ps1
```
#### Bot Not Responding on Telegram
**Symptoms**: Bot doesn't reply to messages
**Diagnosis**:
1. Check service status:
```powershell
Get-Service ROA2WEB-TelegramBot
```
2. Check health endpoint:
```powershell
Invoke-WebRequest http://localhost:8002/internal/health
```
3. Check logs for errors:
```powershell
Get-Content logs\stderr.log -Tail 50
```
**Common Causes**:
1. **Service stopped** → Start service
2. **Invalid bot token** → Update `.env`
3. **Network issues** → Check internet connectivity
4. **Bot blocked by user** → User must /start bot again
#### Account Linking Fails
**Symptoms**: `/link CODE` returns error
**Diagnosis**:
```powershell
# Check internal API
Invoke-WebRequest http://localhost:8002/internal/stats
# Check backend connectivity
Invoke-WebRequest http://localhost:8000/health
```
**Common Causes**:
1. **Code expired** (15 min) → Generate new code
2. **Backend unreachable** → Check ROA2WEB-Backend service
3. **Database error** → Check SQLite file permissions
#### Database Errors
**Symptoms**: "Database locked" or "Cannot open database"
**Diagnosis**:
```powershell
# Check database file
Test-Path C:\inetpub\wwwroot\roa2web\telegram-bot\data\telegram_bot.db
# Check file permissions
icacls C:\inetpub\wwwroot\roa2web\telegram-bot\data\telegram_bot.db
```
**Solutions**:
```powershell
# Stop service
.\Stop-TelegramBot.ps1
# Fix permissions
icacls C:\inetpub\wwwroot\roa2web\telegram-bot\data /grant "SYSTEM:(OI)(CI)F" /T
# Restart service
.\Start-TelegramBot.ps1
```
---
## Security Considerations
### Secrets Management
**NEVER**:
- Commit `.env` to git
- Share bot token or API keys
- Log sensitive data
**ALWAYS**:
- Keep backups of `.env` in secure location
- Rotate API keys periodically
- Use strong file permissions
**File Permissions**:
```powershell
# Restrict .env to SYSTEM and Administrators only
icacls C:\inetpub\wwwroot\roa2web\telegram-bot\.env /grant "SYSTEM:F" /grant "Administrators:F" /inheritance:r
```
### Network Security
- **Internal API (8002)**: Bind to 127.0.0.1 (localhost only)
- **Backend API (8000)**: Already on localhost
- **No Firewall Rules Needed**: All communication is local
### Bot Security
- **Account Linking**: 8-character codes, 15-minute expiry
- **JWT Tokens**: Signed and verified by backend
- **Rate Limiting**: Built into authentication middleware
- **Session Timeout**: 60 minutes of inactivity
---
## Maintenance Procedures
### Updates and Deployments
1. **Build new deployment package** (dev machine):
```bash
./Build-TelegramBot.ps1
```
2. **Transfer to server**:
```powershell
Copy-Item -Path ./deploy-package/telegram-bot -Destination \\10.0.20.36\C$\Temp\telegram-bot-update -Recurse
```
3. **Deploy update** (server):
```powershell
cd C:\Temp\telegram-bot-update\scripts
.\Deploy-TelegramBot.ps1
```
**Deployment Features**:
- ✅ Automatic backup before deployment
- ✅ Stops service, updates files, restarts service
- ✅ Preserves `.env` configuration
- ✅ Automatic rollback on failure
- ✅ Health check after deployment
### Log Rotation
Logs are automatically rotated by Python logging:
- **Max size**: 10 MB per file
- **Backups**: 5 old log files kept
- **Location**: `C:\inetpub\wwwroot\roa2web\telegram-bot\logs\`
**Manual cleanup**:
```powershell
# Delete old logs (older than 30 days)
Get-ChildItem C:\inetpub\wwwroot\roa2web\telegram-bot\logs\*.log |
Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-30) } |
Remove-Item -Force
```
### Database Maintenance
**Cleanup expired data** (automatic via scheduled task):
- Expired auth codes (older than 15 minutes)
- Old sessions (inactive for 60+ minutes)
- Runs hourly automatically
**Manual cleanup**:
```sql
-- Connect to database
sqlite3 C:\inetpub\wwwroot\roa2web\telegram-bot\data\telegram_bot.db
-- Delete expired codes
DELETE FROM telegram_auth_codes WHERE created_at < datetime('now', '-15 minutes');
-- Delete old sessions
DELETE FROM telegram_sessions WHERE updated_at < datetime('now', '-60 minutes');
```
### Service Health Monitoring
**Daily Checks** (manual or script):
```powershell
# Service status
Get-Service ROA2WEB-TelegramBot
# Health endpoint
Invoke-WebRequest http://localhost:8002/internal/health
# Check logs for errors
Get-Content logs\stderr.log -Tail 50 | Select-String "ERROR"
# Check database size
(Get-Item data\telegram_bot.db).Length / 1MB
```
**Weekly Checks**:
- Review backup logs
- Check backup retention (30 days)
- Review disk space usage
- Check for Windows updates
---
## Appendix
### PowerShell Scripts Reference
| Script | Purpose |
|--------|---------|
| `Install-TelegramBot.ps1` | Initial installation |
| `Deploy-TelegramBot.ps1` | Deploy updates |
| `Build-TelegramBot.ps1` | Build deployment package |
| `Start-TelegramBot.ps1` | Start service |
| `Stop-TelegramBot.ps1` | Stop service |
| `Restart-TelegramBot.ps1` | Restart service |
| `Backup-TelegramDB.ps1` | Manual database backup |
| `Setup-DailyBackup.ps1` | Configure automated backups |
### API Endpoints
| Endpoint | Method | Description |
|----------|--------|-------------|
| `/internal/health` | GET | Health check |
| `/internal/stats` | GET | Database statistics |
| `/internal/save-code` | POST | Save auth code (from backend) |
| `/internal/verify-code` | POST | Verify auth code |
### Database Schema
**telegram_users**:
```sql
CREATE TABLE telegram_users (
telegram_user_id INTEGER PRIMARY KEY,
oracle_user_id INTEGER NOT NULL,
oracle_username TEXT NOT NULL,
jwt_token TEXT NOT NULL,
jwt_refresh_token TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```
**telegram_auth_codes**:
```sql
CREATE TABLE telegram_auth_codes (
code TEXT PRIMARY KEY,
oracle_user_id INTEGER NOT NULL,
oracle_username TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
expires_at TIMESTAMP NOT NULL,
used INTEGER DEFAULT 0
);
```
**telegram_sessions**:
```sql
CREATE TABLE telegram_sessions (
telegram_user_id INTEGER PRIMARY KEY,
conversation_history TEXT, -- JSON
session_data TEXT, -- JSON
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```
---
## Support
**Documentation**:
- Project README: `/mnt/e/proiecte/roa2web/roa2web/backend/modules/telegram/README.md`
- Progress Tracker: `/mnt/e/proiecte/roa2web/roa2web/development/TELEGRAM_BOT_PROGRESS.md`
- Production Deployment Plan: `/mnt/e/proiecte/roa2web/roa2web/development/TELEGRAM_BOT_PRODUCTION_DEPLOYMENT.md`
**Logs Location**:
- Service Output: `C:\inetpub\wwwroot\roa2web\telegram-bot\logs\stdout.log`
- Service Errors: `C:\inetpub\wwwroot\roa2web\telegram-bot\logs\stderr.log`
- Backups: `C:\inetpub\wwwroot\roa2web\telegram-bot\logs\backup.log`
**Contact**: ROA2WEB Development Team
---
**Document Version**: 1.0
**Last Updated**: 2025-10-22
**Status**: Production Ready

View File

@@ -1,546 +0,0 @@
# ROA2WEB Telegram Bot - Windows Deployment Troubleshooting Guide
> ⚠️ **DEPRECATED ARCHITECTURE**
>
> This documentation refers to the OLD microservices architecture (port 8002).
> The current architecture is an **ultrathin monolith** - everything on port 8000/8001.
> Telegram internal API is now at `/api/telegram/internal/*` on the main backend.
This guide helps diagnose and fix common issues with Telegram bot integration on Windows Server deployments.
## Problem: "Link invalid sau expirat" (Invalid or expired link)
When users generate a linking code in the web frontend but the Telegram bot says the code is invalid or expired, this indicates a communication problem between the backend and telegram bot services.
### Root Cause
The backend cannot communicate with the Telegram bot's internal API to save the generated linking codes.
### Diagnostic Steps
Run these PowerShell commands on the Windows Server (10.0.20.36) to diagnose:
#### 1. Check Telegram Bot Service Status
```powershell
# Check if service is running
Get-Service ROA2WEB-TelegramBot
# Expected output:
# Status Name DisplayName
# ------ ---- -----------
# Running ROA2WEB-TelegramBot ROA2WEB Telegram Bot Service
```
If service is **not running**, start it:
```powershell
cd C:\inetpub\wwwroot\roa2web\telegram-bot\scripts
.\Start-TelegramBot.ps1
```
#### 2. Check Internal API Port (8002)
```powershell
# Check if port 8002 is listening
netstat -ano | findstr :8002
# Expected output (should show LISTENING):
# TCP 127.0.0.1:8002 0.0.0.0:0 LISTENING <PID>
```
If port is **not listening**, the telegram bot service may not have started correctly. Check logs:
```powershell
# View service logs
Get-Content C:\inetpub\wwwroot\roa2web\telegram-bot\logs\stdout.log -Tail 50
# View error logs
Get-Content C:\inetpub\wwwroot\roa2web\telegram-bot\logs\stderr.log -Tail 50
```
#### 3. Test Internal API Health Endpoint
```powershell
# Test if internal API responds
Invoke-WebRequest http://localhost:8002/internal/health
# Expected output:
# StatusCode : 200
# StatusDescription : OK
# Content : {"status":"healthy","timestamp":"2025-...","database_stats":{...}}
```
If this **fails**, the internal API is not running. Check telegram bot service logs.
#### 4. Check Backend .env Configuration
```powershell
# View backend .env file
notepad C:\inetpub\wwwroot\roa2web\backend\.env
# Look for this line:
# TELEGRAM_BOT_INTERNAL_API=http://localhost:8002
```
If the line is **missing or incorrect**, add/fix it:
```
TELEGRAM_BOT_INTERNAL_API=http://localhost:8002
```
Then restart backend service:
```powershell
Restart-Service ROA2WEB-Backend
```
#### 5. Check Telegram Bot .env Configuration
```powershell
# View telegram bot .env file
notepad C:\inetpub\wwwroot\roa2web\telegram-bot\.env
# Verify these settings:
# TELEGRAM_BOT_TOKEN=<your_production_bot_token>
# BACKEND_URL=http://localhost:8000
# INTERNAL_API_PORT=8002
# INTERNAL_API_HOST=127.0.0.1
```
If TELEGRAM_BOT_TOKEN is wrong (e.g., still using DEV token), update it and restart:
```powershell
cd C:\inetpub\wwwroot\roa2web\telegram-bot\scripts
.\Restart-TelegramBot.ps1
```
#### 6. Test Full Linking Flow
```powershell
# 1. Test backend can reach telegram bot internal API
Invoke-WebRequest -Method POST -Uri http://localhost:8002/internal/save-code -Headers @{"Content-Type"="application/json"} -Body '{"code":"TEST1234","telegram_user_id":0,"oracle_username":"testuser","expires_in_minutes":15}'
# Expected output:
# StatusCode: 201 (Created)
# Content: {"success":true,"code":"TEST1234","expires_at":"...","message":"..."}
# 2. Verify code was saved
Invoke-WebRequest -Method POST -Uri http://localhost:8002/internal/verify-code -Headers @{"Content-Type"="application/json"} -Body '{"code":"TEST1234"}'
# Expected output:
# StatusCode: 200 (OK)
# Content: {"valid":true,"oracle_username":"testuser","message":"Code is valid"}
```
If step 1 **fails**, there's a network/firewall issue blocking localhost:8002.
### Solution Checklist
Fix the issue by following this checklist in order:
- [ ] **Telegram bot service is running**
```powershell
Get-Service ROA2WEB-TelegramBot
# If stopped: cd C:\inetpub\wwwroot\roa2web\telegram-bot\scripts; .\Start-TelegramBot.ps1
```
- [ ] **Internal API port 8002 is listening**
```powershell
netstat -ano | findstr :8002
# Should show LISTENING on 127.0.0.1:8002
```
- [ ] **Internal API responds to health checks**
```powershell
Invoke-WebRequest http://localhost:8002/internal/health
# Should return 200 OK with status "healthy"
```
- [ ] **Backend .env has TELEGRAM_BOT_INTERNAL_API configured**
```powershell
notepad C:\inetpub\wwwroot\roa2web\backend\.env
# Add: TELEGRAM_BOT_INTERNAL_API=http://localhost:8002
```
- [ ] **Backend service restarted after .env changes**
```powershell
Restart-Service ROA2WEB-Backend
```
- [ ] **Telegram bot .env has correct TELEGRAM_BOT_TOKEN**
```powershell
notepad C:\inetpub\wwwroot\roa2web\telegram-bot\.env
# Should have ROA2WEBBot token, not ROA2WEBDEVBot token
```
- [ ] **Test full linking flow from web frontend**
- Log in to web frontend (http://10.0.20.36)
- Generate linking code
- Send code to @ROA2WEBBot via `/start CODE12345`
- Should receive success message from bot
---
## Problem: "Cannot connect to backend" / Connection Errors
After successfully generating a linking code, the Telegram bot finds the code but fails to complete the linking with error messages like:
- `httpcore.ConnectError: All connection attempts failed`
- `Cannot connect to backend at http://localhost:8000`
- `AttributeError: 'ConnectError' object has no attribute 'response'` (fixed in latest version)
### Root Cause
The Telegram bot cannot communicate with the FastAPI backend to verify the Oracle user and obtain a JWT token. This happens when:
1. Backend service is not running
2. Backend is running on wrong port
3. BACKEND_URL in telegram bot .env is incorrect
4. Firewall blocking communication
### Diagnostic Steps
#### 1. Check Backend Service Status
```powershell
# Check if backend service is running
Get-Service ROA2WEB-Backend
# Expected output:
# Status Name DisplayName
# ------ ---- -----------
# Running ROA2WEB-Backend ROA2WEB Backend Service
```
If service is **not running**, start it:
```powershell
cd C:\inetpub\wwwroot\roa2web\scripts
.\Start-ROA2WEB.ps1
```
#### 2. Check Backend Port (8000)
```powershell
# Check if port 8000 is listening
netstat -ano | findstr :8000
# Expected output (should show LISTENING):
# TCP 0.0.0.0:8000 0.0.0.0:0 LISTENING <PID>
```
If port is **not listening**, check backend logs:
```powershell
# View backend service logs
Get-Content C:\inetpub\wwwroot\roa2web\backend\logs\*.log -Tail 50
```
#### 3. Test Backend Health Endpoint
```powershell
# Test if backend API responds
Invoke-WebRequest http://localhost:8000/health
# Expected output:
# StatusCode : 200
# Content : {"status":"healthy",...}
```
If this **fails**, backend is not accessible. Check service logs.
#### 4. Check Telegram Bot BACKEND_URL Configuration
```powershell
# View telegram bot .env file
notepad C:\inetpub\wwwroot\roa2web\telegram-bot\.env
# Verify this line exists and is correct:
# BACKEND_URL=http://localhost:8000
```
**Common mistakes:**
- Using `http://localhost:8001` (dev port instead of production port 8000)
- Missing `http://` prefix
- Using IP address instead of localhost
If BACKEND_URL is **incorrect**, fix it and restart:
```powershell
cd C:\inetpub\wwwroot\roa2web\telegram-bot\scripts
.\Restart-TelegramBot.ps1
```
#### 5. Test Backend Verify-User Endpoint
```powershell
# Test the specific endpoint telegram bot uses
Invoke-WebRequest -Method POST -Uri http://localhost:8000/api/telegram/auth/verify-user `
-Headers @{"Content-Type"="application/json"} `
-Body '{"linking_code":"TESTCODE","oracle_username":"testuser"}'
# Expected output (will fail with 400/404 for test data, but confirms endpoint is reachable):
# StatusCode: 400 or 404 (NOT connection error)
```
If you get **connection error** instead of 400/404, backend is not running or port is wrong.
### Solution Checklist
Fix the issue by following this checklist:
- [ ] **Backend service is running**
```powershell
Get-Service ROA2WEB-Backend
# If stopped: cd C:\inetpub\wwwroot\roa2web\scripts; .\Start-ROA2WEB.ps1
```
- [ ] **Backend port 8000 is listening**
```powershell
netstat -ano | findstr :8000
# Should show LISTENING on 0.0.0.0:8000
```
- [ ] **Backend health check responds**
```powershell
Invoke-WebRequest http://localhost:8000/health
# Should return 200 OK
```
- [ ] **Telegram bot .env has correct BACKEND_URL**
```powershell
notepad C:\inetpub\wwwroot\roa2web\telegram-bot\.env
# Must be: BACKEND_URL=http://localhost:8000
```
- [ ] **Telegram bot service restarted after .env changes**
```powershell
cd C:\inetpub\wwwroot\roa2web\telegram-bot\scripts
.\Restart-TelegramBot.ps1
```
- [ ] **Test full linking flow**
- Generate code in web frontend
- Send code to @ROA2WEBBot: `/start CODE12345`
- Should receive success message (not connection error)
---
### Common Issues
#### Issue 1: Port 8002 Already in Use
**Symptoms:**
- Telegram bot service fails to start
- Logs show "Address already in use" or "Port 8002 is already allocated"
**Solution:**
```powershell
# Find process using port 8002
netstat -ano | findstr :8002
# Kill the process (replace <PID> with actual process ID)
taskkill /PID <PID> /F
# Restart telegram bot service
cd C:\inetpub\wwwroot\roa2web\telegram-bot\scripts
.\Restart-TelegramBot.ps1
```
#### Issue 2: Firewall Blocking Localhost
**Symptoms:**
- Backend cannot reach http://localhost:8002
- Connection timeout errors in backend logs
**Solution:**
```powershell
# Add firewall rule for port 8002 (localhost only)
New-NetFirewallRule -DisplayName "ROA2WEB Telegram Bot Internal API" -Direction Inbound -LocalPort 8002 -Protocol TCP -Action Allow -LocalAddress 127.0.0.1
```
#### Issue 3: Wrong Bot Token
**Symptoms:**
- Telegram bot service runs but doesn't respond to commands
- Logs show "Unauthorized" or "Invalid bot token"
**Solution:**
```powershell
# Update .env with correct token from @BotFather
notepad C:\inetpub\wwwroot\roa2web\telegram-bot\.env
# Change TELEGRAM_BOT_TOKEN to production bot token:
# TELEGRAM_BOT_TOKEN=<production_bot_token>
# Restart service
cd C:\inetpub\wwwroot\roa2web\telegram-bot\scripts
.\Restart-TelegramBot.ps1
```
#### Issue 4: SQLite Database Locked
**Symptoms:**
- Telegram bot logs show "database is locked" errors
- Commands fail intermittently
**Solution:**
```powershell
# Stop service
cd C:\inetpub\wwwroot\roa2web\telegram-bot\scripts
.\Stop-TelegramBot.ps1
# Wait 10 seconds for locks to release
Start-Sleep -Seconds 10
# Start service
.\Start-TelegramBot.ps1
```
#### Issue 5: Backend Service Not Running
**Symptoms:**
- Telegram bot logs show "Cannot connect to backend" errors
- `httpcore.ConnectError: All connection attempts failed`
- Linking codes are found but linking fails
**Solution:**
```powershell
# Check backend service status
Get-Service ROA2WEB-Backend
# If stopped, start it
cd C:\inetpub\wwwroot\roa2web\scripts
.\Start-ROA2WEB.ps1
# Verify backend is listening on port 8000
netstat -ano | findstr :8000
# Test backend health
Invoke-WebRequest http://localhost:8000/health
```
**Check backend logs for startup errors:**
```powershell
Get-Content C:\inetpub\wwwroot\roa2web\backend\logs\*.log -Tail 50
```
**Common backend startup issues:**
- Oracle database not accessible
- Missing environment variables in backend `.env`
- Port 8000 already in use by another process
- Python dependencies not installed
#### Issue 6: Wrong Backend URL in Telegram Bot
**Symptoms:**
- Connection errors to backend
- Logs show wrong URL (e.g., `http://localhost:8001` instead of `http://localhost:8000`)
**Solution:**
```powershell
# Edit telegram bot .env
notepad C:\inetpub\wwwroot\roa2web\telegram-bot\.env
# Ensure this line is correct:
# BACKEND_URL=http://localhost:8000
# (Production uses port 8000, not 8001 which is dev port)
# Restart telegram bot service
cd C:\inetpub\wwwroot\roa2web\telegram-bot\scripts
.\Restart-TelegramBot.ps1
```
### Verification Steps
After fixing, verify the complete flow works:
1. **Backend can save codes to telegram bot:**
```powershell
Invoke-WebRequest -Method POST -Uri http://localhost:8002/internal/save-code -Headers @{"Content-Type"="application/json"} -Body '{"code":"VERIFY01","telegram_user_id":0,"oracle_username":"testuser","expires_in_minutes":15}'
```
Expected: `201 Created` with success message
2. **Telegram bot can verify codes:**
```powershell
Invoke-WebRequest -Method POST -Uri http://localhost:8002/internal/verify-code -Headers @{"Content-Type"="application/json"} -Body '{"code":"VERIFY01"}'
```
Expected: `200 OK` with `"valid":true`
3. **End-to-end test from web frontend:**
- Open web app: http://10.0.20.36
- Login with Oracle credentials
- Click "Link Telegram Account"
- Copy the 8-character code
- Send to @ROA2WEBBot: `/start CODE12345`
- Should receive: "Contul tău Telegram a fost asociat cu succes!"
### Getting Help
If issues persist after following this guide:
1. **Collect diagnostic information:**
```powershell
# Service status
Get-Service ROA2WEB-TelegramBot | Format-List *
# Port listening
netstat -ano | findstr :8002
# Recent logs (last 100 lines)
Get-Content C:\inetpub\wwwroot\roa2web\telegram-bot\logs\stdout.log -Tail 100
Get-Content C:\inetpub\wwwroot\roa2web\telegram-bot\logs\stderr.log -Tail 100
# Backend logs
Get-Content C:\inetpub\wwwroot\roa2web\backend\logs\*.log -Tail 100
```
2. **Check configuration files:**
```powershell
# Backend .env (sanitize sensitive data before sharing!)
Get-Content C:\inetpub\wwwroot\roa2web\backend\.env
# Telegram bot .env (sanitize bot token before sharing!)
Get-Content C:\inetpub\wwwroot\roa2web\telegram-bot\.env
```
3. **Contact support** with the collected diagnostic information.
---
## Quick Reference Commands
### Service Management
```powershell
# Check status
Get-Service ROA2WEB-TelegramBot
# Start
cd C:\inetpub\wwwroot\roa2web\telegram-bot\scripts
.\Start-TelegramBot.ps1
# Stop
.\Stop-TelegramBot.ps1
# Restart
.\Restart-TelegramBot.ps1
```
### Monitoring
```powershell
# Watch logs in real-time
Get-Content C:\inetpub\wwwroot\roa2web\telegram-bot\logs\stdout.log -Wait -Tail 50
# Check health
Invoke-WebRequest http://localhost:8002/internal/health
# Check database stats
Invoke-WebRequest http://localhost:8002/internal/stats
```
### Configuration
```powershell
# Edit backend config
notepad C:\inetpub\wwwroot\roa2web\backend\.env
# Edit telegram bot config
notepad C:\inetpub\wwwroot\roa2web\telegram-bot\.env
# Restart after changes
Restart-Service ROA2WEB-Backend
cd C:\inetpub\wwwroot\roa2web\telegram-bot\scripts
.\Restart-TelegramBot.ps1
```

View File

@@ -1,623 +0,0 @@
# 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! 🎉

View File

@@ -1,491 +0,0 @@
# 🛠️ ROA2WEB Windows Deployment Scripts
Complete reference for ROA2WEB Windows deployment PowerShell scripts (v2.0 - Unified System).
## 📋 Script Overview
### ⭐ Unified Scripts (Recommended)
#### **Build-ROA2WEB.ps1** - Unified Build System
**Purpose**: Build deployment packages for all components with interactive menu
**Usage**:
```powershell
# Interactive mode - shows menu
.\Build-ROA2WEB.ps1
# Non-interactive mode - specific component
.\Build-ROA2WEB.ps1 -Component All # Complete package
.\Build-ROA2WEB.ps1 -Component Frontend # Frontend + Backend
.\Build-ROA2WEB.ps1 -Component Backend # Backend only
.\Build-ROA2WEB.ps1 -Component TelegramBot # Telegram Bot only
# Custom output path
.\Build-ROA2WEB.ps1 -Component All -OutputPath "D:\builds\roa2web-$(Get-Date -Format 'yyyyMMdd')"
```
**Interactive Menu**:
```
[1] All Components (Frontend + Backend + Telegram Bot)
[2] Frontend + Backend (Vue.js build + FastAPI backend)
[3] Backend Only (FastAPI backend + shared modules)
[4] Telegram Bot Only (Standalone package)
[Q] Quit
```
**Parameters**:
- `-Component` All|Frontend|Backend|TelegramBot (optional - shows menu if not specified)
- `-OutputPath` (default: `./deploy-package`)
- `-Clean` $true|$false (default: $true)
**Features**:
- ✅ Interactive menu for component selection
- ✅ Isolated temp directory for frontend builds (doesn't corrupt WSL node_modules)
- ✅ Automatic dependency installation (including devDependencies)
- ✅ Auto-cleanup after build
- ✅ Generates deployment README
**Output**: Creates `deploy-package/` with complete deployment files
---
#### **ROA2WEB-Console.ps1** - Unified Deployment & Management Console
**Purpose**: All-in-one console for deploying and managing ROA2WEB services
**Usage**:
```powershell
# Interactive mode - shows main menu
.\ROA2WEB-Console.ps1
# Non-interactive mode - specific actions
.\ROA2WEB-Console.ps1 -NonInteractive -Action DeployAll
.\ROA2WEB-Console.ps1 -NonInteractive -Action DeployBackend
.\ROA2WEB-Console.ps1 -NonInteractive -Action DeployTelegramBot
.\ROA2WEB-Console.ps1 -NonInteractive -Action StartAll
.\ROA2WEB-Console.ps1 -NonInteractive -Action StopAll
.\ROA2WEB-Console.ps1 -NonInteractive -Action RestartAll
.\ROA2WEB-Console.ps1 -NonInteractive -Action Status
```
**Interactive Main Menu**:
```
[1] Deploy Components
- Deploy Backend + Frontend
- Deploy Telegram Bot
- Deploy All Components
[2] Manage Services
- Start/Stop/Restart All
- Start/Stop/Restart Backend
- Start/Stop/Restart Telegram Bot
[3] Check Status
- Service status
- Health checks
[Q] Quit
```
**Parameters**:
- `-NonInteractive` Switch to enable non-interactive mode
- `-Action` DeployBackend|DeployTelegramBot|DeployAll|StartAll|StopAll|RestartAll|Status
**Features**:
- ✅ Unified interface for deploy + management
- ✅ Interactive menus with easy navigation
- ✅ Automatic backups before deployment
- ✅ Smart dependency updates (only if requirements.txt changed)
- ✅ Health checks after operations
- ✅ Color-coded status output
- ✅ Both interactive and non-interactive modes
- ✅ Preserves .env configuration files
**Replaces**:
-`Deploy-ROA2WEB.ps1` (removed)
-`Deploy-TelegramBot.ps1` (removed)
-`Manage-ROA2WEB.ps1` (removed)
---
### 🚀 Installation Scripts (First-Time Setup)
#### **Install-ROA2WEB.ps1**
**Purpose**: First-time installation of Backend + Frontend
**Usage**:
```powershell
.\Install-ROA2WEB.ps1
# Custom parameters
.\Install-ROA2WEB.ps1 -InstallPath "C:\Apps\roa2web" -ServicePort 8000
```
**What it does**:
1. Installs Chocolatey, Python 3.11+, NSSM
2. Installs IIS URL Rewrite & ARR modules
3. Creates directory structure
4. Creates Python virtual environment
5. Installs Python dependencies
6. Creates Windows Service (ROA2WEB-Backend)
7. Configures IIS website & application
**Parameters**:
- `-InstallPath` (default: `C:\inetpub\wwwroot\roa2web`)
- `-ServicePort` (default: 8000)
- `-IISSiteName`, `-IISAppName`
- `-CreateNewSite`, `-SkipPython`, `-SkipIIS`
---
#### **Install-TelegramBot.ps1**
**Purpose**: First-time installation of Telegram Bot
**Usage**:
```powershell
.\Install-TelegramBot.ps1
# Custom parameters
.\Install-TelegramBot.ps1 -InstallPath "C:\Apps\telegram-bot" -ServicePort 8002
```
**What it does**:
1. Validates Python 3.11+ installation
2. Installs NSSM (if needed)
3. Creates directory structure (data/, logs/, backups/)
4. Creates Python virtual environment
5. Installs Python dependencies
6. Creates Windows Service (ROA2WEB-TelegramBot)
7. Creates .env template
**Parameters**:
- `-InstallPath` (default: `C:\inetpub\wwwroot\roa2web\telegram-bot`)
- `-ServicePort` (default: 8002)
- `-SourcePath` (auto-detected)
---
### 🛠️ Utility Scripts
#### **Backup-TelegramDB.ps1**
**Purpose**: Backup Telegram bot SQLite database
**Usage**:
```powershell
# Basic backup
.\Backup-TelegramDB.ps1
# Compressed backup
.\Backup-TelegramDB.ps1 -Compress $true
# Keep more backups
.\Backup-TelegramDB.ps1 -RetentionCount 20
```
**What it does**:
1. Stops bot service gracefully
2. Creates timestamped backup of `telegram_bot.db`
3. Optionally compresses backup
4. Restarts service
5. Cleans old backups (configurable retention)
---
#### **Setup-DailyBackup.ps1**
**Purpose**: Schedule automated daily database backups
**Usage**:
```powershell
# Setup daily backup at 2 AM
.\Setup-DailyBackup.ps1
# Custom time and retention
.\Setup-DailyBackup.ps1 -Time "03:00" -RetentionDays 30
```
**What it does**:
1. Creates Windows Scheduled Task
2. Runs `Backup-TelegramDB.ps1` daily at specified time
3. Configurable time, retention, and compression
---
#### **Setup-ClaudeAuth.ps1**
**Purpose**: Setup Claude API authentication for Telegram bot
**Usage**:
```powershell
.\Setup-ClaudeAuth.ps1
```
**What it does**:
1. **Method 1 (Recommended)**: Browser-based Claude Pro/Max login
- Runs `claude-code login` if available
- Copies credentials to bot installation directory
2. **Method 2**: Manual API key entry
3. Validates credentials
4. Updates .env file
5. Restarts bot service
**Features**:
- ✅ Supports both Claude Pro/Max and API key
- ✅ Auto-detects credentials location
- ✅ Validates authentication before applying
---
#### **Enable-HTTPS.ps1**
**Purpose**: Enable HTTPS for IIS website
**Usage**:
```powershell
# Create self-signed certificate
.\Enable-HTTPS.ps1
# Use existing certificate
.\Enable-HTTPS.ps1 -CertPath "C:\Certs\roa2web.pfx" -CertPassword "password"
```
**What it does**:
1. Creates/imports SSL certificate
2. Configures HTTPS binding (port 443)
3. Enables HTTP to HTTPS redirect
4. Activates HSTS (HTTP Strict Transport Security)
---
## 🚀 Quick Reference Guide
### 📦 First-Time Deployment Workflow
```powershell
# ========================================
# STEP 1: Build on Development Machine (WSL/Linux)
# ========================================
cd deployment/windows/scripts
.\Build-ROA2WEB.ps1
# Select [1] All Components from menu
# ========================================
# STEP 2: Transfer Package to Windows Server
# ========================================
# Transfer deploy-package/ to server (e.g., C:\Deploy\roa2web-package)
# ========================================
# STEP 3: Install on Windows Server (as Administrator)
# ========================================
cd C:\Deploy\roa2web-package\scripts
# Install Backend + Frontend
.\Install-ROA2WEB.ps1
# Install Telegram Bot
.\Install-TelegramBot.ps1
# ========================================
# STEP 4: Configure
# ========================================
notepad C:\inetpub\wwwroot\roa2web\backend\.env
notepad C:\inetpub\wwwroot\roa2web\telegram-bot\.env
# ========================================
# STEP 5: Start Services via Console
# ========================================
.\ROA2WEB-Console.ps1
# Select [2] Manage Services -> [1] Start All Services
```
---
### 🔄 Deploy Updates Workflow
```powershell
# ========================================
# STEP 1: Build New Package on Development Machine
# ========================================
cd deployment/windows/scripts
.\Build-ROA2WEB.ps1
# Select component to update from menu
# ========================================
# STEP 2: Transfer to Windows Server
# ========================================
# Transfer new deploy-package/ to server
# ========================================
# STEP 3: Deploy via Console (as Administrator)
# ========================================
cd C:\Deploy\new-package\scripts
.\ROA2WEB-Console.ps1
# Option A: Interactive Menu
# [1] Deploy Components -> Select what to deploy
# Option B: Non-Interactive
.\ROA2WEB-Console.ps1 -NonInteractive -Action DeployAll
```
---
### 🎛️ Daily Operations via Console
```powershell
# Launch console
.\ROA2WEB-Console.ps1
# Main Menu Navigation:
# [1] Deploy Components -> Deploy/update application files
# [2] Manage Services -> Start/Stop/Restart services
# [3] Check Status -> View service status and health
# [Q] Quit
# Non-Interactive Quick Commands:
.\ROA2WEB-Console.ps1 -NonInteractive -Action Status
.\ROA2WEB-Console.ps1 -NonInteractive -Action RestartAll
```
---
### 📊 Utility Operations
```powershell
# Backup database
.\Backup-TelegramDB.ps1
# Setup automated daily backups
.\Setup-DailyBackup.ps1 -Time "02:00" -RetentionDays 14
# Configure Claude API
.\Setup-ClaudeAuth.ps1
# Enable HTTPS
.\Enable-HTTPS.ps1
```
---
## 📊 Script Comparison: v1.0 vs v2.0
| Capability | v1.0 (Old) | v2.0 (Unified) |
|-----------|-----------|----------------|
| **Build Scripts** | 3 separate | 1 unified (`Build-ROA2WEB.ps1`) |
| **Deploy Scripts** | 2 separate | 1 unified console (`ROA2WEB-Console.ps1`) |
| **Manage Scripts** | 1 basic | Integrated in console |
| **Total Scripts** | 13 scripts | 8 scripts |
| **Interactive Menus** | ❌ No | ✅ Yes |
| **Non-Interactive Mode** | ⚠️ Partial | ✅ Full support |
| **Health Checks** | ⚠️ Basic | ✅ Comprehensive |
| **Backup Management** | ⚠️ Manual | ✅ Automatic |
| **Dependency Updates** | ⚠️ Always reinstall | ✅ Smart (only if changed) |
| **WSL Compatibility** | ❌ Corrupts node_modules | ✅ Isolated builds |
---
## 🗂️ Complete Script List (v2.0)
### Core Scripts (2)
1.**Build-ROA2WEB.ps1** - Unified build system with menu
2.**ROA2WEB-Console.ps1** - Unified deployment & management console
### Installation Scripts (2)
3. **Install-ROA2WEB.ps1** - First-time Backend + Frontend setup
4. **Install-TelegramBot.ps1** - First-time Telegram Bot setup
### Utility Scripts (4)
5. **Backup-TelegramDB.ps1** - Database backup
6. **Setup-DailyBackup.ps1** - Automated backup scheduling
7. **Setup-ClaudeAuth.ps1** - Claude API configuration
8. **Enable-HTTPS.ps1** - HTTPS setup for IIS
### Removed Scripts (5)
-`Build-Frontend.ps1` → Use `Build-ROA2WEB.ps1 -Component Frontend`
-`Build-TelegramBot.ps1` → Use `Build-ROA2WEB.ps1 -Component TelegramBot`
-`Deploy-ROA2WEB.ps1` → Use `ROA2WEB-Console.ps1` menu option [1] Deploy
-`Deploy-TelegramBot.ps1` → Use `ROA2WEB-Console.ps1` menu option [1] Deploy
-`Manage-ROA2WEB.ps1` → Use `ROA2WEB-Console.ps1` menu option [2] Manage
---
## 💡 Best Practices
### Development Machine (WSL/Linux)
```powershell
# Always use Build-ROA2WEB.ps1 for building
# It isolates npm builds to prevent WSL corruption
.\Build-ROA2WEB.ps1
```
### Windows Server
```powershell
# Use ROA2WEB-Console.ps1 for all operations
# Interactive mode for manual operations
.\ROA2WEB-Console.ps1
# Non-interactive mode for automation/scripts
.\ROA2WEB-Console.ps1 -NonInteractive -Action DeployAll
```
### Configuration Management
-`.env` files are NEVER overwritten during deployment
- ✅ Backups are created automatically before any deployment
- ✅ Old backups are auto-cleaned (keeps last 10)
- ✅ Dependencies only reinstalled if `requirements.txt` changes
### Service Management
- ✅ Always use ROA2WEB-Console for service operations
- ✅ Health checks are automatic after service starts
- ✅ Color-coded output makes status clear
- ✅ Services can be managed individually or together
---
## 🐛 Troubleshooting
### Script Execution Policy Error
```powershell
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
```
### Build Fails on WSL
- Ensure Node.js 16+ is installed: `node -v`
- Close all IDEs (file locks prevent builds)
- Run as Administrator in PowerShell
### Service Won't Start
```powershell
# Check status via console
.\ROA2WEB-Console.ps1 -NonInteractive -Action Status
# View backend logs
Get-Content C:\inetpub\wwwroot\roa2web\logs\backend-stderr.log -Tail 50
# View Telegram bot logs
Get-Content C:\inetpub\wwwroot\roa2web\telegram-bot\logs\stderr.log -Tail 50
```
### Deployment Fails
```powershell
# ROA2WEB-Console.ps1 creates automatic backups
# Check backup location if rollback needed
Get-ChildItem C:\inetpub\wwwroot\roa2web\backups\ | Sort-Object Name -Descending
```
### Frontend Build Corrupts WSL node_modules
-**Fixed in v2.0!** Build-ROA2WEB.ps1 uses isolated temp directory
- The temp directory is automatically cleaned after build
---
## 📚 Documentation
- **Quick Start**: [`../README.md`](../README.md)
- **Complete Deployment Guide**: [`../docs/WINDOWS_DEPLOYMENT.md`](../docs/WINDOWS_DEPLOYMENT.md)
- **Deployment Package Guide**: [`../DEPLOY_PACKAGE.md`](../DEPLOY_PACKAGE.md)
- **Telegram Bot Troubleshooting**: [`../docs/TELEGRAM_BOT_TROUBLESHOOTING.md`](../docs/TELEGRAM_BOT_TROUBLESHOOTING.md)
- **HTTPS Setup**: [`../docs/HTTPS_SETUP.md`](../docs/HTTPS_SETUP.md)
- **Project Documentation**: [`../../../CLAUDE.md`](../../../CLAUDE.md)
---
**Version**: 2.0 (Unified System)
**Last Updated**: 2025-11-12
**Author**: ROA2WEB Team