Initial commit: ROA2WEB - FastAPI + Vue.js + Telegram Bot

Modern ERP Reports Application with microservices architecture

Tech Stack:
- Backend: FastAPI + python-oracledb (Oracle DB integration)
- Frontend: Vue.js 3 + PrimeVue + Vite
- Telegram Bot: python-telegram-bot + SQLite
- Infrastructure: Shared database pool, JWT authentication, SSH tunnel

Features:
- FastAPI backend with async Oracle connection pool
- Vue.js 3 responsive frontend with PrimeVue components
- Telegram bot alternative interface
- Microservices architecture with shared components
- Complete deployment support (Linux Docker + Windows IIS)
- Comprehensive testing (Playwright E2E + pytest)

Repository Structure:
- reports-app/ - Main application (backend, frontend, telegram-bot)
- shared/ - Shared components (database pool, auth, utils)
- deployment/ - Deployment scripts (Linux & Windows)
- docs/ - Project documentation
- security/ - Security scanning and git hooks
This commit is contained in:
2025-10-25 14:55:08 +03:00
commit 6b13ffa183
237 changed files with 70035 additions and 0 deletions

View File

@@ -0,0 +1,572 @@
# HTTPS Setup Guide for ROA2WEB on IIS
Complete guide for enabling HTTPS on ROA2WEB deployed on Windows Server with IIS.
---
## 🎯 Quick Start
### Option 1: Automated Setup (Recommended)
Run the automated PowerShell script:
```powershell
# On Windows Server (PowerShell as Administrator)
cd C:\path\to\roa2web\deployment\windows\scripts
# Enable HTTPS with self-signed certificate
.\Enable-HTTPS.ps1
# Or specify custom settings
.\Enable-HTTPS.ps1 -IISSiteName "Default Web Site" -CertificateDnsName "10.0.20.36"
```
### Option 2: Manual Setup
Follow the step-by-step instructions in the [Manual Configuration](#manual-configuration) section below.
---
## 🔐 Certificate Options
### Self-Signed Certificate (Development/Testing)
**Pros:**
- Quick setup (5 minutes)
- No cost
- Works immediately
**Cons:**
- Browser security warnings
- Not trusted by default
- Not recommended for production
**Use when:**
- Internal development
- Testing HTTPS functionality
- Private internal network
### CA-Issued Certificate (Production)
**Pros:**
- Trusted by all browsers
- No security warnings
- Professional appearance
**Cons:**
- Requires domain name
- May have cost (unless using Let's Encrypt)
- More setup steps
**Use when:**
- Production deployment
- Public-facing application
- Customer/client access
---
## 🚀 Automated Setup Details
### Prerequisites
- Windows Server 2016+ (or Windows 10/11 Pro)
- IIS installed and configured
- Administrator privileges
- ROA2WEB already deployed
### Running the Script
**Basic usage (auto-detect settings):**
```powershell
.\Enable-HTTPS.ps1
```
The script will:
1. Auto-detect your server's hostname and IP
2. Create a self-signed certificate
3. Configure HTTPS binding on IIS
4. Enable HTTP to HTTPS redirect
5. Test the configuration
**Custom DNS name:**
```powershell
.\Enable-HTTPS.ps1 -CertificateDnsName "roa2web.company.com"
```
**Use existing certificate:**
```powershell
# List available certificates
Get-ChildItem cert:\LocalMachine\My | Select-Object Thumbprint, Subject, FriendlyName
# Use specific certificate
.\Enable-HTTPS.ps1 -UseExistingCert -CertThumbprint "ABC123..."
```
**For IIS application (not site root):**
```powershell
.\Enable-HTTPS.ps1 -IISSiteName "Default Web Site"
```
**Custom HTTPS port:**
```powershell
.\Enable-HTTPS.ps1 -Port 8443
```
### Script Parameters
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `IISSiteName` | String | "Default Web Site" | IIS site name |
| `CertificateDnsName` | String | Auto-detect | DNS name for certificate |
| `UseExistingCert` | Switch | False | Use existing certificate |
| `CertThumbprint` | String | "" | Thumbprint of existing cert |
| `Port` | Int | 443 | HTTPS port |
| `IPAddress` | String | "*" | Bind to specific IP or all (*) |
---
## 🔧 Manual Configuration
### Step 1: Create SSL Certificate
#### Option A: Self-Signed Certificate
```powershell
# Create certificate for IP address (10.0.20.36)
$cert = New-SelfSignedCertificate `
-DnsName "10.0.20.36" `
-CertStoreLocation "cert:\LocalMachine\My" `
-NotAfter (Get-Date).AddYears(5) `
-FriendlyName "ROA2WEB SSL Certificate" `
-KeyUsage DigitalSignature, KeyEncipherment `
-TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.1")
# Display certificate info
$cert | Select-Object Subject, Thumbprint, NotAfter
```
#### Option B: CA-Issued Certificate
**Using IIS Manager:**
1. Open IIS Manager (`inetmgr`)
2. Select your server in the left panel
3. Double-click "Server Certificates"
4. Click "Create Certificate Request..." in right panel
5. Fill in certificate details:
- Common Name: `10.0.20.36` (or your domain)
- Organization: Your company name
- City, State, Country
6. Save the CSR file
7. Submit CSR to Certificate Authority (CA)
8. Once received, import certificate:
- Click "Complete Certificate Request..."
- Browse to certificate file
- Give it a friendly name: "ROA2WEB SSL Certificate"
**Popular Certificate Authorities:**
- **Let's Encrypt** (Free, automated): https://letsencrypt.org/
- **DigiCert** (Commercial): https://www.digicert.com/
- **Sectigo** (Commercial): https://sectigo.com/
- **GlobalSign** (Commercial): https://www.globalsign.com/
### Step 2: Configure HTTPS Binding
```powershell
Import-Module WebAdministration
# Add HTTPS binding to site
New-WebBinding -Name "Default Web Site" -Protocol "https" -Port 443 -IPAddress "*"
# Attach certificate to binding
$cert = Get-ChildItem -Path "cert:\LocalMachine\My" |
Where-Object {$_.FriendlyName -eq "ROA2WEB SSL Certificate"}
Push-Location
Set-Location IIS:\SslBindings
$cert | New-Item "0.0.0.0!443"
Pop-Location
```
### Step 3: Enable HTTP to HTTPS Redirect
**Option A: Automatic (via script)**
The `Enable-HTTPS.ps1` script will offer to add the redirect rule automatically.
**Option B: Manual Edit**
Edit `C:\inetpub\wwwroot\roa2web\frontend\web.config`:
```xml
<rewrite>
<rules>
<!-- Add this rule FIRST (before other rules) -->
<rule name="Force HTTPS" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="off" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
</rule>
<!-- Existing rules below... -->
<rule name="API Reverse Proxy" stopProcessing="true">
<!-- ... -->
</rule>
</rules>
</rewrite>
```
**Option C: IIS Manager GUI**
1. Open IIS Manager
2. Navigate to your site
3. Double-click "URL Rewrite"
4. Click "Add Rule(s)..." → "Blank rule"
5. Configure:
- Name: `Force HTTPS`
- Match URL: `(.*)`
- Conditions: Add condition
- Input: `{HTTPS}`
- Pattern: `off`
- Action:
- Type: `Redirect`
- URL: `https://{HTTP_HOST}/{R:1}`
- Redirect type: `Permanent (301)`
### Step 4: Test Configuration
```powershell
# Restart IIS site
Restart-Website "Default Web Site"
# Test HTTPS locally (self-signed cert)
Invoke-WebRequest https://localhost -SkipCertificateCheck
# Test from browser
Start-Process "https://10.0.20.36/roa2web"
```
---
## 🧪 Testing HTTPS Configuration
### Browser Testing
1. **Access via HTTPS:**
```
https://10.0.20.36/roa2web
```
2. **Check for security warnings:**
- **Self-signed cert**: You'll see a warning - this is normal
- **CA-issued cert**: No warning - connection is secure
3. **Verify redirect:**
- Try accessing: `http://10.0.20.36/roa2web`
- Should automatically redirect to: `https://10.0.20.36/roa2web`
4. **Check console for mixed content:**
- Open browser DevTools (F12)
- Look for mixed content warnings
- All resources should load over HTTPS
### PowerShell Testing
```powershell
# Test HTTPS binding
Get-WebBinding -Name "Default Web Site" -Protocol "https"
# Test certificate
$cert = Get-ChildItem cert:\LocalMachine\My |
Where-Object {$_.FriendlyName -eq "ROA2WEB SSL Certificate"}
$cert | Select-Object Subject, Thumbprint, NotAfter, DnsNameList
# Test HTTPS response
Invoke-WebRequest https://localhost/roa2web -SkipCertificateCheck
# Test from external IP
Invoke-WebRequest https://10.0.20.36/roa2web -SkipCertificateCheck
# View IIS SSL bindings
netsh http show sslcert
```
### Network Testing
```bash
# Test from Linux/Mac client
curl -k https://10.0.20.36/roa2web
# Check certificate details
openssl s_client -connect 10.0.20.36:443 -servername 10.0.20.36
# Test redirect
curl -I http://10.0.20.36/roa2web
# Should return: HTTP/1.1 301 Moved Permanently
# Location: https://10.0.20.36/roa2web
```
---
## 🐛 Troubleshooting
### HTTPS Not Working
**Symptom:** Can't access site via HTTPS
**Check:**
```powershell
# Verify HTTPS binding exists
Get-WebBinding -Name "Default Web Site"
# Check if port 443 is listening
netstat -ano | findstr :443
# View SSL certificate bindings
netsh http show sslcert
```
**Fix:**
```powershell
# Remove and recreate binding
Remove-WebBinding -Name "Default Web Site" -Protocol "https" -Port 443
New-WebBinding -Name "Default Web Site" -Protocol "https" -Port 443
# Reattach certificate
$cert = Get-ChildItem cert:\LocalMachine\My |
Where-Object {$_.FriendlyName -eq "ROA2WEB SSL Certificate"}
Push-Location IIS:\SslBindings
$cert | New-Item "0.0.0.0!443" -Force
Pop-Location
```
### Certificate Warning in Browser
**Symptom:** Browser shows "Your connection is not private" or similar warning
**Cause:**
- Self-signed certificate (not trusted by default)
- Expired certificate
- Hostname mismatch
**Solutions:**
1. **For Development (self-signed):**
- Click "Advanced" → "Proceed anyway"
- This is expected behavior for self-signed certificates
2. **For Production:**
- Replace with CA-issued certificate
- Ensure certificate CN matches the URL you're accessing
3. **For Internal Network:**
- Add certificate to Trusted Root CA:
```powershell
$cert = Get-ChildItem cert:\LocalMachine\My\<THUMBPRINT>
$store = Get-Item cert:\LocalMachine\Root
$store.Open("ReadWrite")
$store.Add($cert)
$store.Close()
```
### HTTP Not Redirecting to HTTPS
**Symptom:** HTTP URLs still work, no automatic redirect
**Check:**
```powershell
# Verify web.config has redirect rule
Get-Content C:\inetpub\wwwroot\roa2web\frontend\web.config |
Select-String "Force HTTPS"
```
**Fix:**
- Ensure redirect rule is present in web.config
- Verify rule is BEFORE other rewrite rules
- Check rule is not disabled
- Restart IIS site:
```powershell
Restart-Website "Default Web Site"
```
### Mixed Content Warnings
**Symptom:** Console shows "Mixed Content" warnings
**Cause:** Some resources loading over HTTP instead of HTTPS
**Fix:**
1. Check frontend code for hardcoded `http://` URLs
2. Update to use relative URLs or `https://`
3. Update API base URL in frontend config:
```javascript
// src/config.js or similar
const API_BASE_URL = window.location.protocol === 'https:'
? 'https://10.0.20.36/api'
: 'http://10.0.20.36/api';
```
### API Calls Failing After HTTPS
**Symptom:** Frontend loads but API calls fail with CORS or SSL errors
**Check:**
```powershell
# Verify backend is accessible
Invoke-WebRequest http://localhost:8000/health
# Check IIS URL Rewrite is forwarding correctly
Get-WebConfiguration -Filter "system.webServer/rewrite/rules"
```
**Fix:**
- Update CORS settings in FastAPI backend to allow HTTPS origin
- Verify web.config proxy rules are correct
- Check backend logs for errors
---
## 🔒 Security Best Practices
### 1. Use Strong Certificates
```powershell
# For production, use CA-issued certificates
# Minimum key size: 2048 bits (4096 recommended)
# Use SHA-256 or higher
```
### 2. Enable HSTS (Strict Transport Security)
Already configured in `web.config` (lines 115-124):
```xml
<rule name="Add HSTS Header" preCondition="IsHTTPS">
<match serverVariable="RESPONSE_Strict-Transport-Security" pattern=".*" />
<action type="Rewrite" value="max-age=31536000; includeSubDomains" />
</rule>
```
This tells browsers to always use HTTPS for your site.
### 3. Disable Weak SSL/TLS Protocols
```powershell
# Disable SSL 2.0, SSL 3.0, TLS 1.0, TLS 1.1
# Enable only TLS 1.2 and TLS 1.3
# Run as Administrator
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -Force
New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -Name 'Enabled' -Value 1 -PropertyType 'DWord'
New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -Name 'DisabledByDefault' -Value 0 -PropertyType 'DWord'
# Restart required
Restart-Computer
```
### 4. Secure Cookie Settings
Update FastAPI backend cookie settings:
```python
# backend/app/main.py
response.set_cookie(
key="access_token",
value=token,
httponly=True,
secure=True, # Only send over HTTPS
samesite="lax"
)
```
### 5. Regular Certificate Renewal
- CA certificates typically expire in 1-2 years
- Let's Encrypt certificates expire in 90 days
- Set up reminders or automated renewal
```powershell
# Check certificate expiry
$cert = Get-ChildItem cert:\LocalMachine\My |
Where-Object {$_.FriendlyName -eq "ROA2WEB SSL Certificate"}
$cert.NotAfter
# Days until expiry
($cert.NotAfter - (Get-Date)).Days
```
---
## 📚 Additional Resources
### Documentation
- [IIS SSL Configuration](https://docs.microsoft.com/en-us/iis/manage/configuring-security/how-to-set-up-ssl-on-iis)
- [Let's Encrypt](https://letsencrypt.org/)
- [SSL/TLS Best Practices](https://wiki.mozilla.org/Security/Server_Side_TLS)
### Testing Tools
- [SSL Labs Server Test](https://www.ssllabs.com/ssltest/) - Comprehensive SSL/TLS analysis
- [SSL Checker](https://www.sslshopper.com/ssl-checker.html) - Quick certificate validation
- [Why No Padlock?](https://www.whynopadlock.com/) - Find mixed content issues
### Certificate Providers
- **Free:**
- [Let's Encrypt](https://letsencrypt.org/) (Automated, 90-day validity)
- [ZeroSSL](https://zerossl.com/) (Free tier available)
- **Commercial:**
- [DigiCert](https://www.digicert.com/)
- [Sectigo](https://sectigo.com/)
- [GlobalSign](https://www.globalsign.com/)
---
## ✅ Quick Reference
### Essential Commands
```powershell
# View all certificates
Get-ChildItem cert:\LocalMachine\My
# View IIS bindings
Get-WebBinding -Name "Default Web Site"
# View SSL bindings
netsh http show sslcert
# Test HTTPS
Invoke-WebRequest https://localhost -SkipCertificateCheck
# Restart IIS site
Restart-Website "Default Web Site"
# Enable HTTPS (automated script)
.\Enable-HTTPS.ps1
```
### Configuration Files
- **IIS bindings**: IIS Manager → Site → Bindings
- **web.config**: `C:\inetpub\wwwroot\roa2web\frontend\web.config`
- **Certificates**: Certificate Manager (`certmgr.msc`)
- **Backend config**: `C:\inetpub\wwwroot\roa2web\backend\.env`
### Access Points
- **HTTP**: `http://10.0.20.36/roa2web` (redirects to HTTPS)
- **HTTPS**: `https://10.0.20.36/roa2web`
- **API**: `https://10.0.20.36/api/*` (proxied to backend)
- **Health**: `https://10.0.20.36/health`
---
*Last Updated: 2025-01-18*
*ROA2WEB HTTPS Setup Guide v1.0*

View File

@@ -0,0 +1,844 @@
# ROA2WEB Telegram Bot - Windows Server Deployment Guide
**Target Server**: Windows Server (10.0.20.36)
**Deployment Method**: Windows Service (NSSM) - No Docker
**Service Name**: ROA2WEB-TelegramBot
**Internal API Port**: 8002
**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/reports-app/telegram-bot/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

@@ -0,0 +1,917 @@
# ROA2WEB - Windows Server Deployment Guide
Complete deployment guide for ROA2WEB on Windows Server with IIS and Oracle Database.
---
## 📋 Table of Contents
1. [Overview](#overview)
2. [Prerequisites](#prerequisites)
3. [Architecture](#architecture)
4. [Initial Setup](#initial-setup)
5. [Deployment Workflow](#deployment-workflow)
6. [Configuration](#configuration)
7. [Management](#management)
8. [Troubleshooting](#troubleshooting)
9. [Maintenance](#maintenance)
---
## 🎯 Overview
This guide provides step-by-step instructions for deploying ROA2WEB on Windows Server with:
- **Backend**: FastAPI as Windows Service (port 8000)
- **Frontend**: Vue.js static files served by IIS (port 80/443)
- **Database**: Direct connection to local Oracle DB (no SSH tunnel)
- **Reverse Proxy**: IIS with URL Rewrite for API routing
### Key Features
✅ Simple installation with PowerShell scripts
✅ Minimal dependencies (Python + IIS)
✅ Easy replication across multiple servers
✅ Windows Service for backend (auto-start, auto-restart)
✅ Production-ready configuration
---
## 📦 Prerequisites
### Server Requirements
| Component | Requirement | Notes |
|-----------|-------------|-------|
| **OS** | Windows Server 2016+ | Or Windows 10/11 Pro |
| **RAM** | 4GB minimum | 8GB recommended |
| **Disk** | 10GB free space | For application and logs |
| **CPU** | 2 cores minimum | 4 cores recommended |
### Software Requirements
#### Required (will be installed automatically)
- **IIS** (Internet Information Services)
- **Python 3.11+**
- **NSSM** (Non-Sucking Service Manager)
- **IIS URL Rewrite Module**
- **IIS Application Request Routing (ARR)**
#### Pre-installed
- **Oracle Database** (local or network-accessible)
- **Oracle Instant Client** (for Python oracledb)
#### On Development Machine
- **Node.js 16+** (for building frontend)
- **Git** (optional, for cloning repository)
---
## 🏗️ Architecture
### Deployment Structure
```
C:\inetpub\wwwroot\roa2web\
├── backend\ # FastAPI application
│ ├── app\ # Application code
│ ├── requirements.txt # Python dependencies
│ ├── .env # Environment configuration
│ └── logs\ # Application logs
├── frontend\ # Vue.js static files
│ ├── index.html
│ ├── assets\
│ ├── web.config # IIS configuration
│ └── ...
├── logs\ # Service logs
│ ├── backend-stdout.log
│ └── backend-stderr.log
├── temp\ # Temporary files
└── backups\ # Deployment backups
└── backup-YYYYMMDD-HHMMSS\
```
### Network Flow
```
Client Browser
IIS (Port 80/443)
├─→ /api/* ────→ Backend Service (localhost:8000)
│ ↓
│ Oracle Database (localhost:1521)
└─→ /* ─────────→ Frontend Static Files
```
---
## 🚀 Initial Setup
### Step 1: Install IIS
Open PowerShell as Administrator:
```powershell
# Install IIS with required features
Install-WindowsFeature -Name Web-Server -IncludeManagementTools
# Verify installation
Get-WindowsFeature -Name Web-Server
```
### Step 2: Prepare Deployment Package
**On your development machine (WSL/Windows):**
```bash
# Navigate to deployment scripts
cd /mnt/e/proiecte/roa2web/roa2web/deployment/windows/scripts
# Build frontend and create deployment package
./Build-Frontend.ps1
# Output will be in: ./deploy-package
```
This creates a complete deployment package:
```
deploy-package/
├── backend/ # Backend files
├── frontend/ # Built Vue.js files
├── config/ # Configuration templates
└── README.txt # Deployment instructions
```
### Step 3: Transfer to Server
**Option A: Network Share**
```powershell
# On development machine
Copy-Item -Path .\deploy-package -Destination \\SERVER-IP\C$\Temp\roa2web -Recurse
```
**Option B: Manual Transfer**
- Zip the `deploy-package` folder
- Transfer via RDP, FTP, or USB
- Extract on server to `C:\Temp\roa2web`
### Step 4: Run Installation Script
**On Windows Server (PowerShell as Administrator):**
```powershell
# Navigate to deployment scripts
cd C:\path\to\roa2web\deployment\windows\scripts
# Run installation
.\Install-ROA2WEB.ps1
# Installation will:
# - Install Python, NSSM, IIS modules
# - Create directory structure
# - Install Python dependencies
# - Create Windows Service
# - Configure IIS website
```
**Installation Parameters:**
```powershell
# Custom installation path
.\Install-ROA2WEB.ps1 -InstallPath "D:\Apps\roa2web"
# Custom service port
.\Install-ROA2WEB.ps1 -ServicePort 8001
# Skip Python installation (if already installed)
.\Install-ROA2WEB.ps1 -SkipPython
# Skip IIS configuration
.\Install-ROA2WEB.ps1 -SkipIIS
```
### Step 5: Configure Application
**Edit configuration file:**
```powershell
# Copy environment template
Copy-Item C:\inetpub\wwwroot\roa2web\backend\config\.env.production.windows `
C:\inetpub\wwwroot\roa2web\backend\.env
# Edit with your values
notepad C:\inetpub\wwwroot\roa2web\backend\.env
```
**Required configuration:**
```env
# Oracle Database
ORACLE_USER=CONTAFIN_ORACLE
# Database password - configure in .env
ORACLE_HOST=localhost
ORACLE_PORT=1521
ORACLE_SID=ROA
# JWT Secret (generate new one!)
JWT_SECRET_KEY=GENERATE_STRONG_RANDOM_STRING_HERE
```
**Generate JWT Secret:**
```powershell
# PowerShell method
-join ((65..90) + (97..122) + (48..57) | Get-Random -Count 32 | % {[char]$_})
# Or use online tool: https://generate-secret.vercel.app/
```
### Step 6: Start Services
```powershell
# Start backend service
.\Start-ROA2WEB.ps1
# Check service status
Get-Service ROA2WEB-Backend
# Check logs
Get-Content C:\inetpub\wwwroot\roa2web\logs\backend-stdout.log -Tail 50
```
### Step 7: Verify Installation
**Test endpoints:**
```powershell
# Backend health check
Invoke-WebRequest -Uri "http://localhost:8000/health"
# API documentation
Start-Process "http://localhost:8000/docs"
# Frontend application
Start-Process "http://localhost"
```
---
## 🔄 Deployment Workflow
### For Updates and New Deployments
**1. Build on Development Machine:**
```bash
cd /mnt/e/proiecte/roa2web/roa2web/deployment/windows/scripts
./Build-Frontend.ps1 -OutputPath "./deploy-$(date +%Y%m%d)"
```
**2. Transfer to Server:**
```powershell
# Copy deployment package to server
Copy-Item -Path .\deploy-20250118 -Destination C:\Temp\roa2web-deploy -Recurse
```
**3. Deploy on Server:**
```powershell
cd C:\inetpub\wwwroot\roa2web\deployment\windows\scripts
# Run deployment script
.\Deploy-ROA2WEB.ps1 -SourcePath "C:\Temp\roa2web-deploy"
# The script will:
# - Create backup of current deployment
# - Stop backend service
# - Update backend and frontend files
# - Install new Python dependencies (if changed)
# - Restart backend service
# - Validate deployment health
```
**Deployment Options:**
```powershell
# Update only backend
.\Deploy-ROA2WEB.ps1 -UpdateFrontend $false
# Update only frontend
.\Deploy-ROA2WEB.ps1 -UpdateBackend $false
# Skip backup (not recommended)
.\Deploy-ROA2WEB.ps1 -BackupEnabled $false
# Skip service restart
.\Deploy-ROA2WEB.ps1 -RestartService $false
```
---
## ⚙️ Configuration
### Backend Configuration (.env)
**Location:** `C:\inetpub\wwwroot\roa2web\backend\.env`
**Essential settings:**
```env
# Environment
ENVIRONMENT=production
DEBUG=false
# Oracle Database
ORACLE_USER=CONTAFIN_ORACLE
# Database password - configure in .env
ORACLE_HOST=localhost
ORACLE_PORT=1521
ORACLE_SID=ROA
# Connection Pool
ORACLE_MIN_POOL_SIZE=2
ORACLE_MAX_POOL_SIZE=10
# JWT Authentication
JWT_SECRET_KEY=your_strong_secret_key
JWT_ALGORITHM=HS256
JWT_EXPIRE_MINUTES=480
# Server Settings
HOST=127.0.0.1
PORT=8000
WORKERS=4
# Logging
LOG_LEVEL=INFO
LOG_FILE=C:\inetpub\wwwroot\roa2web\backend\logs\app.log
```
### IIS Configuration (web.config)
**Location:** `C:\inetpub\wwwroot\roa2web\frontend\web.config`
This file is automatically created during installation. Key features:
- **SPA Routing**: All non-file requests fallback to `index.html`
- **API Reverse Proxy**: `/api/*` routed to backend service
- **Compression**: Gzip compression enabled
- **Caching**: Static assets cached for 1 year
- **Security Headers**: X-Frame-Options, CSP, HSTS
**No manual configuration needed** - works out of the box!
### Windows Service Configuration
**Service Name:** `ROA2WEB-Backend`
**Startup Type:** Automatic
**Recovery:** Restart on failure (5 second delay)
**View/Edit service:**
```powershell
# Service properties
Get-Service ROA2WEB-Backend | Format-List *
# Service configuration
sc.exe qc ROA2WEB-Backend
# Modify with NSSM GUI
nssm edit ROA2WEB-Backend
```
---
## 🔧 Management
### Service Management
**PowerShell Scripts:**
```powershell
# Start service
.\Start-ROA2WEB.ps1
# Stop service
.\Stop-ROA2WEB.ps1
# Restart service
.\Restart-ROA2WEB.ps1
```
**Manual Service Management:**
```powershell
# Start
Start-Service ROA2WEB-Backend
# Stop
Stop-Service ROA2WEB-Backend
# Restart
Restart-Service ROA2WEB-Backend
# Status
Get-Service ROA2WEB-Backend
```
**Windows Services GUI:**
```powershell
services.msc
# Find: ROA2WEB Backend Service
```
### Log Management
**Log Locations:**
```
C:\inetpub\wwwroot\roa2web\logs\
├── backend-stdout.log # Service output
├── backend-stderr.log # Service errors
└── app.log # Application log
```
**View Logs:**
```powershell
# Real-time monitoring
Get-Content C:\inetpub\wwwroot\roa2web\logs\backend-stdout.log -Tail 50 -Wait
# Last 100 lines
Get-Content C:\inetpub\wwwroot\roa2web\logs\backend-stderr.log -Tail 100
# Search for errors
Select-String -Path "C:\inetpub\wwwroot\roa2web\logs\*.log" -Pattern "ERROR|CRITICAL"
# Filter by date
Get-Content C:\inetpub\wwwroot\roa2web\logs\app.log |
Select-String -Pattern "2025-01-18"
```
**Log Rotation:**
Logs are automatically rotated when they reach 10MB (configured in .env):
```env
LOG_MAX_SIZE=10485760 # 10 MB
LOG_BACKUP_COUNT=5 # Keep 5 old logs
```
### IIS Management
**PowerShell:**
```powershell
# Website status
Get-Website ROA2WEB
# Start/Stop website
Start-Website ROA2WEB
Stop-Website ROA2WEB
# Application pool
Get-WebAppPoolState ROA2WEB-AppPool
Restart-WebAppPool ROA2WEB-AppPool
# View configuration
Get-WebConfiguration -Filter "system.webServer/rewrite/rules"
```
**IIS Manager GUI:**
```powershell
inetmgr
# Navigate to: Sites → ROA2WEB
```
### Backup Management
**Deployment backups are automatic!**
```
C:\inetpub\wwwroot\roa2web\backups\
├── backup-20250118-103045\
├── backup-20250118-154512\
└── backup-20250117-090123\
```
Last 10 backups are kept automatically.
**Manual Backup:**
```powershell
# Create backup
$date = Get-Date -Format "yyyyMMdd-HHmmss"
Copy-Item -Path C:\inetpub\wwwroot\roa2web `
-Destination C:\Backups\roa2web-$date `
-Recurse -Exclude logs,temp,backups
```
**Restore from Backup:**
```powershell
# Stop service
.\Stop-ROA2WEB.ps1
# Restore files
Copy-Item -Path C:\inetpub\wwwroot\roa2web\backups\backup-20250118-103045\* `
-Destination C:\inetpub\wwwroot\roa2web `
-Recurse -Force
# Start service
.\Start-ROA2WEB.ps1
```
---
## 🐛 Troubleshooting
### Service Won't Start
**Symptom:** Backend service fails to start or stops immediately.
**Check:**
```powershell
# View error log
Get-Content C:\inetpub\wwwroot\roa2web\logs\backend-stderr.log -Tail 50
# Test Python manually
cd C:\inetpub\wwwroot\roa2web\backend
python -m uvicorn app.main:app --host 127.0.0.1 --port 8000
```
**Common Issues:**
1. **Python not found:**
```powershell
# Check Python installation
python --version
# Add to PATH if needed
```
2. **Module import errors:**
```powershell
# Reinstall dependencies
cd C:\inetpub\wwwroot\roa2web\backend
pip install -r requirements.txt
```
3. **Oracle connection failed:**
```powershell
# Check Oracle listener
lsnrctl status
# Test connection
sqlplus CONTAFIN_ORACLE/password@localhost:1521/ROA
```
4. **Port already in use:**
```powershell
# Check what's using port 8000
netstat -ano | findstr :8000
# Kill process or change port in .env
```
### Frontend Not Loading
**Symptom:** Blank page or 404 errors.
**Check:**
```powershell
# IIS website running?
Get-Website ROA2WEB
# Files exist?
Test-Path C:\inetpub\wwwroot\roa2web\frontend\index.html
# Check IIS logs
Get-Content C:\inetpub\logs\LogFiles\W3SVC*\*.log -Tail 50
```
**Solutions:**
```powershell
# Restart IIS site
Stop-Website ROA2WEB
Start-Website ROA2WEB
# Restart app pool
Restart-WebAppPool ROA2WEB-AppPool
# Verify web.config
Test-Path C:\inetpub\wwwroot\roa2web\frontend\web.config
```
### API Calls Failing (502/504 errors)
**Symptom:** Frontend loads but API calls fail.
**Check:**
```powershell
# Backend service running?
Get-Service ROA2WEB-Backend
# Backend responding?
Invoke-WebRequest -Uri "http://localhost:8000/health"
# Check ARR proxy
Get-WebConfiguration -Filter "system.webServer/proxy"
```
**Solutions:**
1. **Enable ARR proxy:**
```powershell
Set-WebConfigurationProperty -PSPath "MACHINE/WEBROOT/APPHOST" `
-Filter "system.webServer/proxy" `
-Name "enabled" `
-Value "True"
```
2. **Check backend logs:**
```powershell
Get-Content C:\inetpub\wwwroot\roa2web\logs\backend-stderr.log -Tail 100
```
3. **Test backend directly:**
```powershell
Invoke-WebRequest -Uri "http://localhost:8000/api/health"
```
### Database Connection Issues
**Symptom:** Backend starts but database queries fail.
**Check:**
```powershell
# Oracle client installed?
dir $env:ORACLE_HOME
# TNS names configured?
$env:TNS_ADMIN
Get-Content $env:TNS_ADMIN\tnsnames.ora
# Test connection
sqlplus CONTAFIN_ORACLE/password@localhost:1521/ROA
```
**Solutions:**
1. **Install Oracle Instant Client:**
- Download from: https://www.oracle.com/database/technologies/instant-client/downloads.html
- Extract to C:\oracle\instantclient_19_x
- Add to PATH
2. **Configure .env:**
```env
ORACLE_HOST=localhost
ORACLE_PORT=1521
ORACLE_SID=ROA
```
3. **Check Oracle service:**
```powershell
Get-Service Oracle*
```
### Permission Issues
**Symptom:** Access denied errors.
**Check:**
```powershell
# Check folder permissions
icacls C:\inetpub\wwwroot\roa2web
# Check service account
sc.exe qc ROA2WEB-Backend
```
**Solutions:**
```powershell
# Grant IIS user read access
icacls C:\inetpub\wwwroot\roa2web /grant IIS_IUSRS:(OI)(CI)RX
# Grant service account full access to backend
icacls C:\inetpub\wwwroot\roa2web\backend /grant "NT AUTHORITY\LOCAL SERVICE":(OI)(CI)F
```
### High CPU/Memory Usage
**Check:**
```powershell
# Service resource usage
Get-Process -Name python | Format-Table ProcessName, CPU, WS
# Check worker count
Get-Content C:\inetpub\wwwroot\roa2web\backend\.env | Select-String WORKERS
```
**Solutions:**
```env
# Reduce workers in .env
WORKERS=2
# Reduce pool size
ORACLE_MAX_POOL_SIZE=5
```
---
## 🔄 Maintenance
### Regular Maintenance Tasks
**Daily:**
- Check service status
- Monitor disk space
- Review error logs
```powershell
# Daily check script
Get-Service ROA2WEB-Backend
Get-PSDrive C | Select-Object Used,Free
Get-Content C:\inetpub\wwwroot\roa2web\logs\backend-stderr.log -Tail 20
```
**Weekly:**
- Clean old logs
- Verify backups
- Update dependencies (if needed)
```powershell
# Clean logs older than 30 days
Get-ChildItem C:\inetpub\wwwroot\roa2web\logs\*.log.* |
Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-30)} |
Remove-Item
# List backups
Get-ChildItem C:\inetpub\wwwroot\roa2web\backups
```
**Monthly:**
- Review security updates
- Performance optimization
- Database maintenance
### Updating Python Dependencies
```powershell
cd C:\inetpub\wwwroot\roa2web\backend
# Update all packages
pip install --upgrade -r requirements.txt
# Restart service
Restart-Service ROA2WEB-Backend
```
### Database Maintenance
```sql
-- Connect to Oracle
sqlplus CONTAFIN_ORACLE/password@localhost:1521/ROA
-- Check table statistics
SELECT table_name, num_rows, last_analyzed
FROM user_tables
ORDER BY last_analyzed;
-- Update statistics
EXEC DBMS_STATS.gather_schema_stats('CONTAFIN_ORACLE');
```
### Performance Monitoring
**Built-in health check:**
```powershell
Invoke-WebRequest -Uri "http://localhost:8000/health" |
Select-Object StatusCode, Content
```
**Windows Performance Monitor:**
```powershell
perfmon
# Add counters:
# - Process > % Processor Time > python.exe
# - Process > Private Bytes > python.exe
# - Web Service > Current Connections
```
### Security Updates
**Windows Updates:**
```powershell
# Check for updates
Get-WindowsUpdate
# Install updates
Install-WindowsUpdate -AcceptAll
```
**Python Security Updates:**
```powershell
# Check for vulnerabilities
pip check
# Update specific package
pip install --upgrade fastapi
```
---
## 📚 Additional Resources
### Documentation Files
- `config/.env.production.windows` - Configuration template
- `config/web.config` - IIS configuration
- `scripts/*.ps1` - PowerShell scripts
### PowerShell Scripts Reference
| Script | Purpose | Usage |
|--------|---------|-------|
| `Install-ROA2WEB.ps1` | Initial installation | `.\Install-ROA2WEB.ps1` |
| `Deploy-ROA2WEB.ps1` | Deploy updates | `.\Deploy-ROA2WEB.ps1 -SourcePath <path>` |
| `Build-Frontend.ps1` | Build Vue.js frontend | `.\Build-Frontend.ps1` |
| `Start-ROA2WEB.ps1` | Start backend service | `.\Start-ROA2WEB.ps1` |
| `Stop-ROA2WEB.ps1` | Stop backend service | `.\Stop-ROA2WEB.ps1` |
| `Restart-ROA2WEB.ps1` | Restart backend service | `.\Restart-ROA2WEB.ps1` |
### Support
For issues or questions:
1. Check logs: `C:\inetpub\wwwroot\roa2web\logs\`
2. Review this documentation
3. Contact: development-team@your-company.com
---
## ✅ Quick Reference
### Essential Commands
```powershell
# Service management
.\Start-ROA2WEB.ps1
.\Stop-ROA2WEB.ps1
.\Restart-ROA2WEB.ps1
# Check status
Get-Service ROA2WEB-Backend
Get-Website ROA2WEB
# View logs
Get-Content C:\inetpub\wwwroot\roa2web\logs\backend-stdout.log -Tail 50 -Wait
# Health check
Invoke-WebRequest http://localhost:8000/health
# Deploy update
.\Deploy-ROA2WEB.ps1 -SourcePath "C:\Temp\roa2web-deploy"
```
### Key Locations
- **Application**: `C:\inetpub\wwwroot\roa2web\`
- **Backend**: `C:\inetpub\wwwroot\roa2web\backend\`
- **Frontend**: `C:\inetpub\wwwroot\roa2web\frontend\`
- **Logs**: `C:\inetpub\wwwroot\roa2web\logs\`
- **Config**: `C:\inetpub\wwwroot\roa2web\backend\.env`
- **Backups**: `C:\inetpub\wwwroot\roa2web\backups\`
### Access Points
- **Web App**: http://localhost or http://server-ip
- **API Docs**: http://localhost:8000/docs
- **Health Check**: http://localhost:8000/health
---
*Last Updated: 2025-01-18*
*Version: 2.0.0*
*ROA2WEB Windows Deployment Guide*