# Production Deployment Checklist & CI/CD Pipeline

**Project**: Maternal App (ParentFlow)
**Last Updated**: October 9, 2025
**Environment**: Development → Production

---

## Table of Contents
1. [Pre-Deployment Checklist](#pre-deployment-checklist)
2. [Development Server Steps](#development-server-steps)
3. [Production Server Steps](#production-server-steps)
4. [Database Sync Strategy](#database-sync-strategy)
5. [Deployment Automation Scripts](#deployment-automation-scripts)
6. [Rollback Procedure](#rollback-procedure)
7. [Post-Deployment Verification](#post-deployment-verification)

---

## Pre-Deployment Checklist

### ✅ Code Quality & Testing

- [ ] All TypeScript compilation errors resolved
- [ ] All ESLint warnings resolved
- [ ] Frontend production build succeeds (`npm run build` in maternal-web)
- [ ] Backend production build succeeds (`npm run build` in maternal-app-backend)
- [ ] Admin panel production build succeeds (`npm run build` in parentflow-admin)
- [ ] All unit tests pass
- [ ] Critical user flows manually tested
- [ ] No console errors in browser
- [ ] API endpoints tested with Postman/curl

### ✅ Database

- [ ] All migrations created and tested locally
- [ ] Database schema documented
- [ ] Backup of production database created
- [ ] Migration rollback scripts ready
- [ ] Seed data scripts updated (if needed)

### ✅ Configuration

- [ ] Environment variables reviewed (`.env.production`)
- [ ] API URLs point to production endpoints
- [ ] Database connection strings verified
- [ ] Redis/cache configuration verified
- [ ] Email service configuration verified
- [ ] File upload paths/S3 buckets verified
- [ ] SSL certificates valid and not expiring soon

### ✅ Security

- [ ] No sensitive data in git history
- [ ] No API keys in source code
- [ ] Rate limiting configured
- [ ] CORS settings reviewed
- [ ] CSP headers configured
- [ ] Authentication flows tested
- [ ] Permission checks verified

### ✅ Performance

- [ ] Images optimized
- [ ] Code splitting implemented
- [ ] Lazy loading configured
- [ ] Database indexes reviewed
- [ ] Cache strategy implemented
- [ ] CDN configured (if applicable)

---

## Development Server Steps

**Location**: `/root/maternal-app/` on development server

### Step 1: Clean Production Build (Frontend)

```bash
cd /root/maternal-app/maternal-web

# Clean previous builds
rm -rf .next
rm -rf node_modules/.cache

# Production build
npm run build

# Check for errors
# Expected: "✓ Compiled successfully" message
# Expected: No TypeScript or ESLint errors
```

**Expected Output**:
```
✓ Compiled successfully
✓ Generating static pages (39/39)
Route (app)                                 Size  First Load JS
...
```

### Step 2: Production Build (Backend)

```bash
cd /root/maternal-app/maternal-app/maternal-app-backend

# Clean build directory
rm -rf dist

# Production build
npm run build

# Check for errors
# Expected: "Successfully compiled X files" message
```

**Expected Output**:
```
Successfully compiled XX files with swc
```

### Step 2.5: Production Build (Admin Panel)

```bash
cd /root/maternal-app/parentflow-admin

# Clean previous builds
rm -rf .next
rm -rf node_modules/.cache

# Production build
npm run build

# Check for errors
# Expected: "✓ Compiled successfully" message
```

**Expected Output**:
```
✓ Compiled successfully
✓ Generating static pages (13/13)
Route (app)                                 Size  First Load JS
...
```

### Step 3: Fix Any Build Errors

If errors occur:
1. **TypeScript errors**: Fix type issues, missing imports
2. **Dependency errors**: Run `npm install`
3. **Environment errors**: Check `.env` files

**Common Issues**:
- Missing `@types/*` packages
- Incorrect import paths
- Environment variable references
- Missing database entities/columns

### Step 4: Database Migration Dry Run

```bash
cd /root/maternal-app/maternal-app/maternal-app-backend

# Check pending migrations
npm run migration:show

# Generate SQL for review (don't run yet)
npm run migration:generate -- -n ReviewChanges

# Review generated migration file in src/database/migrations/
```

### Step 5: Commit to Git

```bash
cd /root/maternal-app

# Review changes
git status
git diff

# Stage changes
git add .

# Commit with descriptive message
git commit -m "feat: [Description of features/fixes]

- Feature 1 description
- Feature 2 description
- Bug fixes
- Database migrations: [List migration files]

Deployment: Ready for production"

# Push to repository
git push origin main
```

### Step 6: Tag Release

```bash
# Create version tag
git tag -a v1.x.x -m "Release v1.x.x - [Brief description]"
git push origin v1.x.x
```

---

## Production Server Steps

**Location**: Production server

### Step 1: Backup Current State

```bash
# Backup database
pg_dump -U postgres -d parentflowprod -F c -f /backup/parentflowprod_$(date +%Y%m%d_%H%M%S).dump

# Backup application directory
tar -czf /backup/maternal-app_$(date +%Y%m%d_%H%M%S).tar.gz /var/www/maternal-app

# Verify backups
ls -lh /backup/
```

### Step 2: Pull Latest Code

```bash
cd /var/www/maternal-app

# Stash any local changes (shouldn't be any)
git stash

# Pull latest code
git fetch origin
git pull origin main

# Or checkout specific tag
# git checkout v1.x.x

# Verify correct version
git log -1 --oneline
```

### Step 3: Install Dependencies

```bash
# Frontend
cd /var/www/maternal-app/maternal-web
npm ci --production

# Backend
cd /var/www/maternal-app/maternal-app/maternal-app-backend
npm ci --production
```

### Step 4: Run Database Migrations

```bash
cd /var/www/maternal-app/maternal-app/maternal-app-backend

# Check pending migrations
npm run migration:show

# Run migrations
npm run migration:run

# Verify migrations applied
npm run migration:show
```

### Step 5: Build Applications

```bash
# Build frontend
cd /var/www/maternal-app/maternal-web
npm run build

# Build backend
cd /var/www/maternal-app/maternal-app/maternal-app-backend
npm run build
```

### Step 6: Restart Services

```bash
# Restart backend (PM2)
pm2 restart maternal-app-backend

# Restart frontend (PM2)
pm2 restart maternal-web

# Or restart all
pm2 restart all

# Check status
pm2 status
pm2 logs --lines 50
```

### Step 7: Clear Caches

```bash
# Clear Redis cache
redis-cli FLUSHDB

# Clear Next.js cache (if needed)
cd /var/www/maternal-app/maternal-web
rm -rf .next/cache
```

---

## Database Sync Strategy

### Database Comparison Script

```bash
#!/bin/bash
# File: scripts/compare-databases.sh

DEV_DB="parentflowdev"
PROD_DB="parentflowprod"
DEV_HOST="10.0.0.207"
PROD_HOST="production-db-host"

echo "Comparing database schemas..."

# Export schemas
pg_dump -h $DEV_HOST -U postgres -d $DEV_DB --schema-only > /tmp/dev_schema.sql
pg_dump -h $PROD_HOST -U postgres -d $PROD_DB --schema-only > /tmp/prod_schema.sql

# Compare
diff /tmp/dev_schema.sql /tmp/prod_schema.sql > /tmp/schema_diff.txt

if [ -s /tmp/schema_diff.txt ]; then
  echo "⚠️  Schemas differ! Review /tmp/schema_diff.txt"
  cat /tmp/schema_diff.txt
else
  echo "✅ Schemas are identical"
fi
```

### Migration Workflow

**Development → Production**:

1. **Create Migration** (Dev):
   ```bash
   npm run migration:generate -- -n DescriptiveName
   ```

2. **Test Migration** (Dev):
   ```bash
   npm run migration:run
   npm run migration:revert  # Test rollback
   npm run migration:run     # Re-apply
   ```

3. **Commit Migration** (Dev):
   ```bash
   git add src/database/migrations/*
   git commit -m "feat: Add [description] migration"
   ```

4. **Apply to Production** (Prod):
   ```bash
   git pull origin main
   npm run migration:run
   ```

### Manual Database Sync

If migrations are out of sync:

```sql
-- Check migration history
SELECT * FROM migrations ORDER BY executed_at DESC LIMIT 10;

-- Compare tables
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public'
ORDER BY table_name;

-- Compare columns for specific table
SELECT column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_name = 'users'
ORDER BY ordinal_position;
```

---

## Deployment Automation Scripts

### Auto-Deploy Script (Production Server)

Create: `/var/www/maternal-app/deploy.sh`

```bash
#!/bin/bash
set -e  # Exit on error

echo "======================================"
echo "🚀 Starting Production Deployment"
echo "======================================"

# Configuration
APP_DIR="/var/www/maternal-app"
BACKUP_DIR="/backup"
BRANCH="main"
LOG_FILE="/var/log/maternal-app-deploy-$(date +%Y%m%d_%H%M%S).log"

# Redirect output to log
exec 1> >(tee -a "$LOG_FILE")
exec 2>&1

echo "[$(date)] Deployment started"

# Step 1: Backup
echo "📦 Creating backup..."
pg_dump -U postgres -d parentflowprod -F c -f "$BACKUP_DIR/parentflowprod_$(date +%Y%m%d_%H%M%S).dump"
tar -czf "$BACKUP_DIR/maternal-app_$(date +%Y%m%d_%H%M%S).tar.gz" "$APP_DIR" --exclude node_modules --exclude .next --exclude dist
echo "✅ Backup complete"

# Step 2: Pull code
echo "📥 Pulling latest code..."
cd "$APP_DIR"
git stash
git fetch origin
git pull origin "$BRANCH"
COMMIT=$(git log -1 --oneline)
echo "✅ Updated to: $COMMIT"

# Step 3: Install dependencies
echo "📦 Installing dependencies..."
cd "$APP_DIR/maternal-web"
npm ci --production
cd "$APP_DIR/maternal-app/maternal-app-backend"
npm ci --production
echo "✅ Dependencies installed"

# Step 4: Run migrations
echo "🗄️  Running database migrations..."
cd "$APP_DIR/maternal-app/maternal-app-backend"
npm run migration:run
echo "✅ Migrations complete"

# Step 5: Build applications
echo "🔨 Building applications..."
cd "$APP_DIR/maternal-web"
npm run build
cd "$APP_DIR/maternal-app/maternal-app-backend"
npm run build
echo "✅ Build complete"

# Step 6: Restart services
echo "🔄 Restarting services..."
pm2 restart all
pm2 save
echo "✅ Services restarted"

# Step 7: Health check
echo "🏥 Running health checks..."
sleep 5
BACKEND_STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:3020/api/v1/health || echo "000")
FRONTEND_STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:3030 || echo "000")

if [ "$BACKEND_STATUS" = "200" ] && [ "$FRONTEND_STATUS" = "200" ]; then
  echo "✅ Health checks passed"
  echo "[$(date)] Deployment successful!"
  echo "======================================"
  echo "🎉 Deployment Complete"
  echo "======================================"
else
  echo "❌ Health checks failed! Backend: $BACKEND_STATUS, Frontend: $FRONTEND_STATUS"
  echo "⚠️  Consider rollback if issues persist"
fi

# Send notification (optional)
# curl -X POST https://your-webhook-url -d "Deployment complete: $COMMIT"
```

Make executable:
```bash
chmod +x /var/www/maternal-app/deploy.sh
```

Usage:
```bash
/var/www/maternal-app/deploy.sh
```

### Pre-Deploy Check Script (Development Server)

Create: `/root/maternal-app/pre-deploy-check.sh`

```bash
#!/bin/bash
set -e

echo "======================================"
echo "🔍 Pre-Deployment Checks"
echo "======================================"

ERRORS=0

# Check 1: Frontend build
echo "Checking frontend build..."
cd /root/maternal-app/maternal-web
if npm run build; then
  echo "✅ Frontend build successful"
else
  echo "❌ Frontend build failed"
  ERRORS=$((ERRORS + 1))
fi

# Check 2: Backend build
echo "Checking backend build..."
cd /root/maternal-app/maternal-app/maternal-app-backend
if npm run build; then
  echo "✅ Backend build successful"
else
  echo "❌ Backend build failed"
  ERRORS=$((ERRORS + 1))
fi

# Check 3: Uncommitted changes
echo "Checking for uncommitted changes..."
cd /root/maternal-app
if [ -z "$(git status --porcelain)" ]; then
  echo "✅ No uncommitted changes"
else
  echo "⚠️  Uncommitted changes detected:"
  git status --short
fi

# Check 4: Pending migrations
echo "Checking for pending migrations..."
cd /root/maternal-app/maternal-app/maternal-app-backend
PENDING=$(npm run migration:show 2>&1 | grep "pending" | wc -l)
if [ "$PENDING" -gt 0 ]; then
  echo "⚠️  $PENDING pending migrations found"
else
  echo "✅ No pending migrations"
fi

# Summary
echo "======================================"
if [ $ERRORS -eq 0 ]; then
  echo "✅ All checks passed! Ready to deploy."
  echo "Next steps:"
  echo "  1. git add ."
  echo "  2. git commit -m 'your message'"
  echo "  3. git push origin main"
  echo "  4. Run deploy.sh on production server"
else
  echo "❌ $ERRORS check(s) failed. Fix issues before deploying."
  exit 1
fi
echo "======================================"
```

Make executable:
```bash
chmod +x /root/maternal-app/pre-deploy-check.sh
```

Usage:
```bash
cd /root/maternal-app
./pre-deploy-check.sh
```

---

## Rollback Procedure

### Quick Rollback (if deployment fails)

```bash
# 1. Restore previous code
cd /var/www/maternal-app
git log -5 --oneline  # Find previous commit
git reset --hard <previous-commit-hash>

# 2. Restore database (if migrations ran)
pg_restore -U postgres -d parentflowprod -c /backup/parentflowprod_YYYYMMDD_HHMMSS.dump

# 3. Rebuild
cd /var/www/maternal-app/maternal-web && npm run build
cd /var/www/maternal-app/maternal-app/maternal-app-backend && npm run build

# 4. Restart services
pm2 restart all
```

### Migration Rollback

```bash
cd /var/www/maternal-app/maternal-app/maternal-app-backend

# Rollback last migration
npm run migration:revert

# Rollback multiple migrations
npm run migration:revert  # Repeat N times
```

---

## Post-Deployment Verification

### Checklist

- [ ] Application accessible at production URL
- [ ] Login functionality works
- [ ] API endpoints responding
- [ ] Database queries working
- [ ] File uploads working
- [ ] Email sending working
- [ ] WebSocket connections working
- [ ] No JavaScript errors in console
- [ ] PM2 processes healthy (`pm2 status`)
- [ ] Database connections stable
- [ ] SSL certificate valid
- [ ] Logs clean (no critical errors)

### Health Check Commands

```bash
# Backend health
curl https://api.maternal.noru1.ro/api/v1/health

# Frontend accessibility
curl https://maternal.noru1.ro

# Check PM2 status
pm2 status
pm2 logs --lines 100

# Check database connections
psql -U postgres -d parentflowprod -c "SELECT COUNT(*) FROM users;"

# Monitor logs
tail -f /var/log/maternal-app/*.log
pm2 logs --lines 100 --raw
```

### Monitoring

```bash
# CPU/Memory usage
pm2 monit

# Database size
psql -U postgres -c "SELECT pg_size_pretty(pg_database_size('parentflowprod'));"

# Active connections
psql -U postgres -d parentflowprod -c "SELECT count(*) FROM pg_stat_activity;"
```

---

## Deployment Frequency

**Recommended Schedule**:
- **Hotfixes**: As needed (critical bugs)
- **Minor Updates**: Weekly (Friday afternoons)
- **Major Releases**: Bi-weekly or monthly
- **Database Migrations**: Bundle with releases

**Best Practices**:
- Deploy during low-traffic hours
- Have team member available for 1 hour post-deployment
- Test in staging environment first (if available)
- Communicate deployment to users (if user-facing changes)

---

## Environment Variables

### Development (.env.local)
```env
DATABASE_HOST=10.0.0.207
DATABASE_NAME=parentflowdev
NODE_ENV=development
API_URL=http://localhost:3020
```

### Production (.env.production)
```env
DATABASE_HOST=production-db-host
DATABASE_NAME=parentflowprod
NODE_ENV=production
API_URL=https://api.maternal.noru1.ro
```

**Security Note**: Never commit `.env` files to git!

---

## Emergency Contacts

- **Developer**: [Your contact]
- **DevOps**: [DevOps contact]
- **Database Admin**: [DBA contact]
- **Server Access**: [Server details]

---

## Changelog Template

```markdown
# Release v1.x.x - YYYY-MM-DD

## New Features
- Feature 1
- Feature 2

## Improvements
- Improvement 1
- Improvement 2

## Bug Fixes
- Fix 1
- Fix 2

## Database Changes
- Migration 1: Description
- Migration 2: Description

## Breaking Changes
- None / List breaking changes

## Deployment Notes
- Special instructions if any
```

---

**Last Updated**: October 9, 2025
**Version**: 1.0
**Maintained By**: Development Team
