# Production Deployment Guide

**Project:** B2B Flight Ticketing UI  
**Version:** 1.0.0-MVP  
**Last Updated:** January 26, 2026

---

## Table of Contents

1. [Prerequisites](#prerequisites)
2. [Pre-Deployment Checklist](#pre-deployment-checklist)
3. [Build Process](#build-process)
4. [Environment Configuration](#environment-configuration)
5. [Deployment Steps](#deployment-steps)
6. [Post-Deployment Verification](#post-deployment-verification)
7. [Rollback Procedure](#rollback-procedure)
8. [Monitoring and Alerts](#monitoring-and-alerts)
9. [Troubleshooting](#troubleshooting)
10. [Support Contacts](#support-contacts)

---

## Prerequisites

### Required Software

- Node.js 16.x or higher
- npm 8.x or higher
- Angular CLI 16.x
- Git

### Required Access

- Production server SSH access
- Production backend API access
- SSL/TLS certificates
- Environment variables and secrets
- Monitoring dashboard access
- Error tracking service access

### Required Approvals

- [ ] Security audit completed and approved
- [ ] QA testing completed and signed off
- [ ] User acceptance testing completed
- [ ] Product owner approval
- [ ] Change management approval (if required)

---

## Pre-Deployment Checklist

### Code Quality

- [ ] All tests passing (749/749)
- [ ] Code coverage ≥80%
- [ ] No critical or high-severity bugs
- [ ] Code review completed
- [ ] Security scan passed

### Testing

- [ ] Unit tests: 100% pass rate
- [ ] Integration tests: All passing
- [ ] E2E tests: All critical paths passing
- [ ] Cross-browser testing completed
- [ ] Mobile device testing completed
- [ ] Performance testing completed
- [ ] Load testing completed
- [ ] Accessibility testing completed

### Documentation

- [ ] README updated
- [ ] API documentation current
- [ ] Deployment guide reviewed
- [ ] Troubleshooting guide available
- [ ] User documentation complete

### Infrastructure

- [ ] Production environment configured
- [ ] SSL/TLS certificates valid
- [ ] CDN configured (if applicable)
- [ ] Monitoring configured
- [ ] Error tracking configured
- [ ] Backup strategy in place
- [ ] Rollback plan documented

---

## Build Process

### 1. Prepare Release Branch

```bash
# Create release branch from main
git checkout main
git pull origin main
git checkout -b release/v1.0.0

# Update version in package.json
npm version 1.0.0 --no-git-tag-version

# Commit version bump
git add package.json package-lock.json
git commit -m "chore: bump version to 1.0.0"
git push origin release/v1.0.0
```

### 2. Run Pre-Build Checks

```bash
# Install dependencies
npm ci

# Run linter (if configured)
npm run lint

# Run tests
npm test -- --watch=false --code-coverage --browsers=ChromeHeadless

# Verify coverage
# Check coverage/index.html for ≥80% coverage
```

### 3. Build Production Bundle

```bash
# Build for production
npm run build -- --configuration=production

# Verify build output
ls -lh dist/frontend/

# Expected output:
# - index.html
# - main.[hash].js
# - polyfills.[hash].js
# - runtime.[hash].js
# - styles.[hash].css
# - assets/
```

### 4. Optimize Build (Optional)

```bash
# Analyze bundle size
npm install -g webpack-bundle-analyzer
webpack-bundle-analyzer dist/frontend/stats.json

# Review and optimize large dependencies
# Consider lazy loading or code splitting
```

### 5. Security Scan

```bash
# Run npm audit
npm audit --production

# Fix critical vulnerabilities
npm audit fix

# Run security scan (if tool available)
# Example: Snyk, OWASP Dependency Check
```

---

## Environment Configuration

### Production Environment Variables

Create `src/environments/environment.prod.ts`:

```typescript
export const environment = {
  production: true,
  apiUrl: 'https://api.production.example.com/api/v1',
  keycloakUrl: 'https://auth.production.example.com',
  keycloakRealm: 'b2b-flight-platform',
  keycloakClientId: 'b2b-flight-ui',
  wsUrl: 'wss://api.production.example.com/ws',
  enableLogging: false,
  enableDebug: false,
  cacheTimeout: 300000, // 5 minutes
  apiTimeout: 30000, // 30 seconds
  retryAttempts: 3,
  retryDelay: 1000
};
```

### Server Configuration

#### Nginx Configuration

Create `/etc/nginx/sites-available/b2b-flight-ui`:

```nginx
server {
    listen 80;
    server_name app.production.example.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name app.production.example.com;

    # SSL Configuration
    ssl_certificate /etc/ssl/certs/app.production.example.com.crt;
    ssl_certificate_key /etc/ssl/private/app.production.example.com.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

    # Security Headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "no-referrer-when-downgrade" always;
    add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:; connect-src 'self' https://api.production.example.com wss://api.production.example.com;" always;

    # Root directory
    root /var/www/b2b-flight-ui;
    index index.html;

    # Gzip compression
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml+rss application/javascript application/json;

    # Cache static assets
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    # Angular routing
    location / {
        try_files $uri $uri/ /index.html;
    }

    # API proxy (optional)
    location /api/ {
        proxy_pass https://api.production.example.com/api/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    # WebSocket proxy (optional)
    location /ws/ {
        proxy_pass https://api.production.example.com/ws/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
```

Enable the site:

```bash
sudo ln -s /etc/nginx/sites-available/b2b-flight-ui /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
```

---

## Deployment Steps

### Option 1: Manual Deployment

#### Step 1: Backup Current Version

```bash
# SSH to production server
ssh user@production-server

# Backup current deployment
cd /var/www
sudo tar -czf b2b-flight-ui-backup-$(date +%Y%m%d-%H%M%S).tar.gz b2b-flight-ui/
sudo mv b2b-flight-ui-backup-*.tar.gz /var/backups/
```

#### Step 2: Deploy New Version

```bash
# On local machine, create deployment package
cd frontend
tar -czf b2b-flight-ui-v1.0.0.tar.gz -C dist/frontend .

# Transfer to production server
scp b2b-flight-ui-v1.0.0.tar.gz user@production-server:/tmp/

# On production server, extract and deploy
ssh user@production-server
cd /var/www/b2b-flight-ui
sudo tar -xzf /tmp/b2b-flight-ui-v1.0.0.tar.gz
sudo chown -R www-data:www-data /var/www/b2b-flight-ui
sudo chmod -R 755 /var/www/b2b-flight-ui
```

#### Step 3: Verify Deployment

```bash
# Check files deployed
ls -la /var/www/b2b-flight-ui

# Check Nginx configuration
sudo nginx -t

# Reload Nginx
sudo systemctl reload nginx

# Check Nginx status
sudo systemctl status nginx
```

---

### Option 2: CI/CD Deployment

#### GitHub Actions Example

Create `.github/workflows/deploy-production.yml`:

```yaml
name: Deploy to Production

on:
  push:
    tags:
      - 'v*'

jobs:
  deploy:
    runs-on: ubuntu-latest
    
    steps:
      - name: Checkout code
        uses: actions/checkout@v3
      
      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '16'
          cache: 'npm'
          cache-dependency-path: frontend/package-lock.json
      
      - name: Install dependencies
        working-directory: frontend
        run: npm ci
      
      - name: Run tests
        working-directory: frontend
        run: npm test -- --watch=false --code-coverage --browsers=ChromeHeadless
      
      - name: Build production bundle
        working-directory: frontend
        run: npm run build -- --configuration=production
      
      - name: Deploy to production
        uses: appleboy/scp-action@master
        with:
          host: ${{ secrets.PROD_HOST }}
          username: ${{ secrets.PROD_USER }}
          key: ${{ secrets.PROD_SSH_KEY }}
          source: "frontend/dist/frontend/*"
          target: "/var/www/b2b-flight-ui"
          strip_components: 3
      
      - name: Reload Nginx
        uses: appleboy/ssh-action@master
        with:
          host: ${{ secrets.PROD_HOST }}
          username: ${{ secrets.PROD_USER }}
          key: ${{ secrets.PROD_SSH_KEY }}
          script: |
            sudo chown -R www-data:www-data /var/www/b2b-flight-ui
            sudo chmod -R 755 /var/www/b2b-flight-ui
            sudo nginx -t
            sudo systemctl reload nginx
      
      - name: Notify deployment
        uses: 8398a7/action-slack@v3
        with:
          status: ${{ job.status }}
          text: 'Production deployment completed'
          webhook_url: ${{ secrets.SLACK_WEBHOOK }}
        if: always()
```

---

## Post-Deployment Verification

### 1. Smoke Tests

```bash
# Test application loads
curl -I https://app.production.example.com

# Expected: HTTP/2 200

# Test static assets
curl -I https://app.production.example.com/main.[hash].js

# Expected: HTTP/2 200
```

### 2. Functional Tests

**Manual Verification:**

1. **Login**
   - Navigate to https://app.production.example.com
   - Enter valid credentials
   - Verify successful login
   - Verify dashboard loads

2. **Flight Search**
   - Navigate to booking/search
   - Enter search criteria
   - Submit search
   - Verify results display

3. **Passenger Details**
   - Select a flight
   - Enter passenger details
   - Verify validation works
   - Proceed to payment

4. **Payment**
   - Verify booking summary
   - Verify wallet balance
   - Confirm booking
   - Verify success message

5. **Other Features**
   - Test wallet management
   - Test reports
   - Test admin features (if applicable)
   - Test support center

### 3. Performance Checks

```bash
# Run Lighthouse audit
lighthouse https://app.production.example.com --output=html --output-path=./lighthouse-report.html

# Check key metrics:
# - Performance score ≥90
# - Accessibility score ≥90
# - Best Practices score ≥90
# - SEO score ≥90
```

### 4. Monitoring Checks

- [ ] Application monitoring active (Sentry, etc.)
- [ ] Error tracking receiving data
- [ ] Performance monitoring active
- [ ] Alerts configured and working
- [ ] Dashboard accessible

---

## Rollback Procedure

### When to Rollback

Rollback immediately if:
- Critical functionality broken
- Security vulnerability discovered
- Data corruption detected
- Performance degradation >50%
- Error rate >5%

### Rollback Steps

#### Option 1: Restore from Backup

```bash
# SSH to production server
ssh user@production-server

# Stop Nginx (optional, for zero-downtime use symlink method)
sudo systemctl stop nginx

# Remove current deployment
cd /var/www
sudo rm -rf b2b-flight-ui/

# Restore from backup
sudo tar -xzf /var/backups/b2b-flight-ui-backup-YYYYMMDD-HHMMSS.tar.gz

# Verify restoration
ls -la b2b-flight-ui/

# Start Nginx
sudo systemctl start nginx

# Verify application
curl -I https://app.production.example.com
```

#### Option 2: Redeploy Previous Version

```bash
# On local machine, checkout previous version
git checkout v0.9.0

# Build and deploy
npm run build -- --configuration=production
# Follow deployment steps above
```

### Post-Rollback

1. Notify stakeholders of rollback
2. Document rollback reason
3. Create incident report
4. Plan fix and redeployment

---

## Monitoring and Alerts

### Application Monitoring

**Sentry Configuration:**

```typescript
// src/main.ts
import * as Sentry from "@sentry/angular";

if (environment.production) {
  Sentry.init({
    dsn: "https://your-sentry-dsn@sentry.io/project-id",
    environment: "production",
    release: "b2b-flight-ui@1.0.0",
    tracesSampleRate: 0.1,
    integrations: [
      new Sentry.BrowserTracing({
        tracingOrigins: ["https://api.production.example.com"],
        routingInstrumentation: Sentry.routingInstrumentation,
      }),
    ],
  });
}
```

### Key Metrics to Monitor

1. **Error Rate**
   - Target: <1%
   - Alert: >5%

2. **Response Time**
   - Target: <2s
   - Alert: >5s

3. **Availability**
   - Target: 99.9%
   - Alert: <99%

4. **User Sessions**
   - Monitor active users
   - Track session duration

5. **API Errors**
   - Monitor 4xx and 5xx errors
   - Track error patterns

### Alert Configuration

**Critical Alerts (Immediate Response):**
- Application down
- Error rate >10%
- Security breach detected

**High Priority Alerts (Response within 1 hour):**
- Error rate >5%
- Response time >10s
- Availability <99%

**Medium Priority Alerts (Response within 4 hours):**
- Error rate >2%
- Response time >5s
- Unusual traffic patterns

---

## Troubleshooting

### Common Issues

#### Issue 1: Application Not Loading

**Symptoms:**
- Blank page
- 404 errors
- Console errors

**Diagnosis:**
```bash
# Check Nginx status
sudo systemctl status nginx

# Check Nginx error log
sudo tail -f /var/log/nginx/error.log

# Check file permissions
ls -la /var/www/b2b-flight-ui
```

**Solution:**
```bash
# Verify files deployed
ls -la /var/www/b2b-flight-ui

# Fix permissions
sudo chown -R www-data:www-data /var/www/b2b-flight-ui
sudo chmod -R 755 /var/www/b2b-flight-ui

# Reload Nginx
sudo systemctl reload nginx
```

---

#### Issue 2: API Connection Errors

**Symptoms:**
- "Network error" messages
- Failed API calls
- CORS errors

**Diagnosis:**
```bash
# Test API connectivity
curl -I https://api.production.example.com/api/v1/health

# Check browser console for CORS errors
# Check Network tab for failed requests
```

**Solution:**
- Verify API URL in environment.prod.ts
- Check API server status
- Verify CORS configuration on backend
- Check SSL certificates

---

#### Issue 3: Authentication Failures

**Symptoms:**
- Cannot log in
- Token errors
- Redirect loops

**Diagnosis:**
```bash
# Check Keycloak status
curl -I https://auth.production.example.com

# Check browser console for auth errors
# Verify token in browser DevTools > Application > Cookies
```

**Solution:**
- Verify Keycloak URL in environment.prod.ts
- Check Keycloak realm and client configuration
- Verify redirect URIs configured
- Clear browser cache and cookies

---

#### Issue 4: Performance Issues

**Symptoms:**
- Slow page loads
- High response times
- Browser freezing

**Diagnosis:**
```bash
# Run Lighthouse audit
lighthouse https://app.production.example.com

# Check bundle size
ls -lh /var/www/b2b-flight-ui/*.js

# Check server resources
top
free -h
df -h
```

**Solution:**
- Enable gzip compression
- Configure CDN for static assets
- Optimize bundle size
- Increase server resources
- Enable caching

---

## Support Contacts

### Development Team

- **Lead Developer:** [Name] - [email] - [phone]
- **Frontend Team:** [email]
- **On-Call:** [phone/pager]

### Operations Team

- **DevOps Lead:** [Name] - [email] - [phone]
- **Infrastructure Team:** [email]
- **On-Call:** [phone/pager]

### Business Contacts

- **Product Owner:** [Name] - [email] - [phone]
- **Project Manager:** [Name] - [email] - [phone]

### Escalation Path

1. **Level 1:** Development Team (Response: 1 hour)
2. **Level 2:** DevOps Lead (Response: 30 minutes)
3. **Level 3:** CTO (Response: 15 minutes)

---

## Appendix

### A. Environment Variables Reference

| Variable | Description | Example |
|----------|-------------|---------|
| `apiUrl` | Backend API base URL | `https://api.production.example.com/api/v1` |
| `keycloakUrl` | Keycloak authentication URL | `https://auth.production.example.com` |
| `keycloakRealm` | Keycloak realm name | `b2b-flight-platform` |
| `keycloakClientId` | Keycloak client ID | `b2b-flight-ui` |
| `wsUrl` | WebSocket URL | `wss://api.production.example.com/ws` |
| `enableLogging` | Enable console logging | `false` (production) |
| `cacheTimeout` | API cache timeout (ms) | `300000` (5 minutes) |

### B. Build Artifacts

| File | Description | Size (approx) |
|------|-------------|---------------|
| `index.html` | Main HTML file | 1 KB |
| `main.[hash].js` | Main application bundle | 500-800 KB |
| `polyfills.[hash].js` | Browser polyfills | 100-150 KB |
| `runtime.[hash].js` | Webpack runtime | 5-10 KB |
| `styles.[hash].css` | Application styles | 50-100 KB |
| `assets/` | Static assets (images, fonts) | Varies |

### C. SSL/TLS Certificate Renewal

```bash
# Check certificate expiry
openssl x509 -in /etc/ssl/certs/app.production.example.com.crt -noout -dates

# Renew certificate (Let's Encrypt example)
sudo certbot renew

# Reload Nginx
sudo systemctl reload nginx
```

---

**Document Version:** 1.0  
**Last Updated:** January 26, 2026  
**Next Review:** After first production deployment
