# Windows Server Deployment Guide - Sales Dashboard

Complete guide to deploy your Sales Dashboard on Windows Server as a 24/7 service.

---

## Prerequisites

- ✅ Windows Server (2016, 2019, 2022) or Windows 10/11 Pro
- ✅ Administrator access
- ✅ Python 3.8+ installed
- ✅ Internet connection
- ✅ Company domain: sales.globalerc.pt
- ✅ Server has static IP or accessible from internet

---

## Deployment Overview

**What we'll do:**
1. Copy app to server
2. Install as Windows Service (runs 24/7)
3. Configure IIS as reverse proxy (recommended)
4. Set up SSL certificate
5. Configure DNS
6. Update Google OAuth

⏱️ **Time:** 60-90 minutes

---

## Step 1: Prepare the Server

### 1.1 Copy Application to Server

**On your PC:**
```powershell
# Create deployment package
Compress-Archive -Path "C:\Users\Tiago Rebelo\Desktop\Globale RC\2-Vibe Coding\Sales Dashboard App_VScode\*" `
    -DestinationPath "C:\Users\Tiago Rebelo\Desktop\SalesDashboard-Deploy.zip"
```

**On the server:**
```powershell
# Create application directory
New-Item -ItemType Directory -Path "C:\Sales-Dashboard" -Force

# Extract files
Expand-Archive -Path "C:\path\to\SalesDashboard-Deploy.zip" -DestinationPath "C:\Sales-Dashboard"

cd C:\Sales-Dashboard
```

### 1.2 Install Python (if not installed)

Download and install Python 3.11:
- https://www.python.org/downloads/windows/
- ✅ Check "Add Python to PATH"
- ✅ Install for all users
- ✅ Disable path length limit (at end of installation)

### 1.3 Create Virtual Environment

```powershell
cd C:\Sales-Dashboard

# Create virtual environment
python -m venv venv

# Activate it
.\venv\Scripts\Activate.ps1

# Update pip
python -m pip install --upgrade pip

# Install dependencies
pip install -r requirements.txt

# Install production server
pip install waitress
```

---

## Step 2: Install as Windows Service

### 2.1 Run Installation Script

**Open PowerShell as Administrator:**

```powershell
# Navigate to app directory
cd C:\Sales-Dashboard

# Set execution policy (if needed)
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

# Run installation script
.\install_windows_service.ps1
```

**What this does:**
- ✅ Installs NSSM (service manager)
- ✅ Creates Windows Service "SalesDashboard"
- ✅ Configures auto-start on boot
- ✅ Sets up automatic restart on failure
- ✅ Opens firewall port 5000
- ✅ Creates log files

### 2.2 Verify Service

```powershell
# Check service status
Get-Service -Name SalesDashboard

# Should show: Status = Running

# Test locally
Invoke-WebRequest -Uri http://localhost:5000 -UseBasicParsing

# Check logs
Get-Content C:\Sales-Dashboard\logs\service-output.log -Tail 20
```

---

## Step 3: Configure IIS as Reverse Proxy (Recommended)

### 3.1 Install IIS and Required Modules

**Server Manager → Add Roles:**
- ✅ Web Server (IIS)
- ✅ Application Development → WebSocket Protocol

**Install URL Rewrite and ARR:**
```powershell
# Download and install these manually:
# 1. URL Rewrite Module: https://www.iis.net/downloads/microsoft/url-rewrite
# 2. Application Request Routing (ARR): https://www.iis.net/downloads/microsoft/application-request-routing
```

### 3.2 Enable ARR Proxy

**IIS Manager:**
1. Click server name (root level)
2. Open "Application Request Routing Cache"
3. Click "Server Proxy Settings" (right panel)
4. ✅ Check "Enable proxy"
5. Apply

### 3.3 Create IIS Website

**In IIS Manager:**

1. **Remove Default Website** (or stop it)

2. **Add New Website:**
   - Name: `SalesDashboard`
   - Physical path: `C:\Sales-Dashboard\static` (or create empty folder)
   - Binding:
     - Type: `http`
     - IP: `All Unassigned`
     - Port: `80`
     - Host name: `sales.globalerc.pt`

3. **Add HTTPS Binding:**
   - Type: `https`
   - Port: `443`
   - Host name: `sales.globalerc.pt`
   - SSL Certificate: (install certificate first - see Step 4)

### 3.4 Configure Reverse Proxy

**Create web.config in site root:**

Create: `C:\Sales-Dashboard\static\web.config`

```xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="ReverseProxyInboundRule" stopProcessing="true">
                    <match url="(.*)" />
                    <action type="Rewrite" url="http://localhost:5000/{R:1}" />
                    <serverVariables>
                        <set name="HTTP_X_FORWARDED_PROTO" value="https" />
                        <set name="HTTP_X_FORWARDED_HOST" value="{HTTP_HOST}" />
                    </serverVariables>
                </rule>
            </rules>
        </rewrite>
        <security>
            <requestFiltering>
                <requestLimits maxAllowedContentLength="52428800" />
            </requestFiltering>
        </security>
    </system.webServer>
</configuration>
```

### 3.5 Test Configuration

```powershell
# Test internal
Invoke-WebRequest -Uri http://localhost:5000 -UseBasicParsing

# Test through IIS (add to hosts file first for testing)
# C:\Windows\System32\drivers\etc\hosts
# Add line: 127.0.0.1  sales.globalerc.pt

Invoke-WebRequest -Uri http://sales.globalerc.pt -UseBasicParsing
```

---

## Step 4: Configure SSL Certificate

### Option A: Let's Encrypt (Free, Recommended)

**Install win-acme:**

1. Download: https://www.win-acme.com/
2. Extract to: `C:\Program Files\win-acme`
3. Run as Administrator: `wacs.exe`
4. Choose: `N` (Create certificate)
5. Choose: `2` (Single binding of IIS site)
6. Select your site: `SalesDashboard`
7. Follow prompts

**Auto-renewal is configured automatically.**

### Option B: Company Certificate

If your company has its own certificate:

1. Import certificate to Windows Certificate Store
2. In IIS, select site → Bindings → HTTPS → Edit
3. Select your certificate

---

## Step 5: Configure DNS

**In your company's DNS or domain registrar:**

### If server has public IP:
```
Type: A
Name: sales
Value: YOUR_SERVER_PUBLIC_IP
TTL: 3600
```

### If behind firewall/NAT:
1. Configure port forwarding: External 443 → Server IP:443
2. Add A record pointing to public IP

**Verify:**
```powershell
nslookup sales.globalerc.pt
# Should return your server IP
```

---

## Step 6: Update Google OAuth

**Google Cloud Console:**

1. Go to: https://console.cloud.google.com/
2. Navigate to: APIs & Services → Credentials
3. Click your OAuth 2.0 Client ID
4. Add to **Authorized redirect URIs**:
   ```
   https://sales.globalerc.pt/oauth2callback
   ```
5. Save

---

## Step 7: Configure Environment Variables

**Edit service configuration:**

```powershell
# Open NSSM GUI
nssm edit SalesDashboard

# In "Environment" tab, add:
FLASK_MODE=production
SECRET_KEY=your-secure-random-key-here
BASE_URL=https://sales.globalerc.pt
DEFAULT_SPREADSHEET_ID=your-spreadsheet-id
```

**Restart service:**
```powershell
Restart-Service -Name SalesDashboard
```

---

## Step 8: Security Hardening

### 8.1 Configure HTTPS Only

**In IIS, add redirect rule to web.config:**

```xml
<rule name="HTTP to HTTPS redirect" stopProcessing="true">
    <match url="(.*)" />
    <conditions>
        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
    </conditions>
    <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
</rule>
```

### 8.2 Restrict Access (Optional)

**If sales team has static IPs:**

IIS → Site → IP Address and Domain Restrictions:
- Add allowed IPs
- Deny all others

### 8.3 Configure Credentials Security

```powershell
# Set strict permissions on credentials.json
$acl = Get-Acl "C:\Sales-Dashboard\credentials.json"
$acl.SetAccessRuleProtection($true, $false)
$adminRule = New-Object System.Security.AccessControl.FileSystemAccessRule("Administrators","FullControl","Allow")
$acl.AddAccessRule($adminRule)
Set-Acl "C:\Sales-Dashboard\credentials.json" $acl
```

---

## Monitoring and Maintenance

### Check Service Status

```powershell
# Service status
Get-Service -Name SalesDashboard

# View logs
Get-Content C:\Sales-Dashboard\logs\service-output.log -Tail 50 -Wait

# Check errors
Get-Content C:\Sales-Dashboard\logs\service-error.log -Tail 50
```

### Restart Service

```powershell
Restart-Service -Name SalesDashboard
```

### Update Application

```powershell
# Stop service
Stop-Service -Name SalesDashboard

# Update files (replace in C:\Sales-Dashboard)

# Restart service
Start-Service -Name SalesDashboard
```

### Monitor Performance

**Task Manager:**
- Look for `python.exe` process
- Check CPU/Memory usage

**IIS Logs:**
- Located in: `C:\inetpub\logs\LogFiles\`

---

## Troubleshooting

### Service won't start

```powershell
# Check logs
Get-Content C:\Sales-Dashboard\logs\service-error.log

# Common issues:
# - Python path incorrect
# - Missing dependencies
# - Port already in use
# - Permissions issues
```

**Fix port conflict:**
```powershell
# Find process using port 5000
netstat -ano | findstr :5000

# Kill process (replace PID)
taskkill /PID 1234 /F
```

### Can't access from outside

1. Check Windows Firewall:
   ```powershell
   Get-NetFirewallRule -DisplayName "Sales Dashboard*"
   ```

2. Check IIS is running:
   ```powershell
   Get-Service -Name W3SVC
   ```

3. Test locally first:
   ```powershell
   Invoke-WebRequest -Uri http://localhost:5000
   ```

4. Check DNS propagation:
   ```powershell
   nslookup sales.globalerc.pt
   ```

### SSL certificate issues

```powershell
# Re-run win-acme
cd "C:\Program Files\win-acme"
.\wacs.exe --renew --force

# Check certificate in IIS
# Site → Bindings → HTTPS → View certificate
```

### Application errors

```powershell
# View Flask logs
Get-Content C:\Sales-Dashboard\logs\service-output.log -Tail 100

# Check Python environment
C:\Sales-Dashboard\venv\Scripts\python.exe --version
C:\Sales-Dashboard\venv\Scripts\pip.exe list
```

---

## Production Checklist

- [ ] Service installed and running
- [ ] Auto-start on boot configured
- [ ] IIS reverse proxy configured
- [ ] SSL certificate installed and working
- [ ] DNS pointing to server
- [ ] Google OAuth redirect URI updated
- [ ] Firewall rules configured
- [ ] credentials.json secured
- [ ] Environment variables set
- [ ] HTTPS redirect enabled
- [ ] Tested from external network
- [ ] Logs rotation configured
- [ ] Backup strategy in place
- [ ] Team trained on access URL

---

## Support

### View Service Configuration
```powershell
nssm dump SalesDashboard
```

### Uninstall Service
```powershell
nssm stop SalesDashboard
nssm remove SalesDashboard confirm
```

### Professional Support
- Windows Server Admin documentation
- IIS documentation: https://docs.microsoft.com/iis
- win-acme support: https://www.win-acme.com/

---

## Next Steps

1. ✅ Complete deployment following this guide
2. ✅ Test with 1-2 users first
3. ✅ Monitor logs for 24-48 hours
4. ✅ Roll out to all 6 users
5. ✅ Schedule regular maintenance windows
6. ✅ Set up automated backups

---

**Your URL:** `https://sales.globalerc.pt`

**Service is now 24/7, independent of your PC!** 🎉
