# Production Deployment Guide - Version 2.2.0
**Date:** February 15, 2026  
**Feature:** Per-Company Permissions Implementation

---

## 📋 Overview

This deployment implements **per-company permissions**, allowing users to have different permission levels across different companies.

### Example Use Case:
- **User A** with access to Company A and Company B:
  - Company A: Can Add/Edit ✅ | Can Delete ✅
  - Company B: Can Add/Edit ✅ | Can Delete ❌

---

## 🎯 What's New in Version 2.2.0

### 1. **Per-Company Permissions**
- Added `can_add_edit` and `can_delete` columns to `user_companies` table
- Users can now have different permissions for each company they have access to
- Global permissions (`user_permissions` table) are maintained for backward compatibility

### 2. **User List Filtering**
- **Super Admin**: Can see all Admins and Users (not other Super Admins)
- **Admin**: Can see only Users with at least one shared company access
- Improved performance with better SQL queries and indexes

### 3. **Database Optimizations**
- Added composite index `idx_uc_user_company` for faster permission lookups
- Proper NULL handling and default values

---

## ⚠️ Pre-Deployment Checklist

- [ ] **Backup database** (CRITICAL!)
- [ ] Test in staging environment first
- [ ] Schedule maintenance window (< 5 minutes downtime)
- [ ] Notify all users about the maintenance
- [ ] Ensure all users are logged out
- [ ] Have rollback script ready (`rollback_2026_02_15.sql`)
- [ ] Review database credentials and access

---

## 📦 Deployment Files

| File | Purpose |
|------|---------|
| `production_deployment_2026_02_15.sql` | Main deployment script |
| `rollback_2026_02_15.sql` | Rollback script (if needed) |
| `DEPLOYMENT_GUIDE_2026_02_15.md` | This file |

---

## 🚀 Deployment Steps

### Step 1: Backup Database

```bash
# PostgreSQL backup
pg_dump -U your_db_user -d your_database_name -F c -b -v -f backup_before_v2.2.0_$(date +%Y%m%d_%H%M%S).backup

# Or SQL format
pg_dump -U your_db_user -d your_database_name > backup_before_v2.2.0_$(date +%Y%m%d_%H%M%S).sql
```

**Verify backup:**
```bash
# Check file size (should be > 0 bytes)
ls -lh backup_*.backup
```

### Step 2: Run Deployment Script

```bash
# Navigate to SQL directory
cd /path/to/your/project/application/sql/

# Run deployment script
psql -U your_db_user -d your_database_name -f production_deployment_2026_02_15.sql

# Expected output:
# ==============================================
# Starting Production Deployment: 2.2.0
# ==============================================
# ✓ Added can_add_edit column to user_companies
# ✓ Added can_delete column to user_companies
# ✓ Created composite index idx_uc_user_company
# ✓ Per-company permissions schema updated successfully
# ✓ Migrated permissions for X user-company associations
# ✓ All permission columns verified
# ✓ Composite index verified
# ✓ No NULL values in permission columns
# ==============================================
# Deployment completed successfully!
# ==============================================
```

### Step 3: Deploy Application Code

```bash
# Pull latest code from repository
git pull origin main

# Or copy files manually:
# - application/controllers/user.php
# - application/views/users/add_user.php
# - application/views/users/edit_user.php
```

### Step 4: Clear Application Cache

```bash
# Clear CodeIgniter cache (if you have caching enabled)
rm -rf application/cache/*

# Clear opcache (if using PHP opcache)
# Option 1: Restart PHP-FPM
sudo systemctl restart php-fpm

# Option 2: Restart Apache/Nginx
sudo systemctl restart apache2  # or nginx
```

### Step 5: Verify Deployment

1. **Database Verification:**
```sql
-- Check if columns exist
SELECT column_name, data_type, column_default
FROM information_schema.columns
WHERE table_name = 'user_companies'
AND column_name IN ('can_add_edit', 'can_delete');

-- Expected output:
-- can_add_edit | boolean | false
-- can_delete   | boolean | false

-- Check index
SELECT indexname, indexdef
FROM pg_indexes
WHERE tablename = 'user_companies'
AND indexname = 'idx_uc_user_company';

-- Check data migration
SELECT 
    COUNT(*) as total_records,
    COUNT(CASE WHEN can_add_edit = TRUE THEN 1 END) as with_add_edit,
    COUNT(CASE WHEN can_delete = TRUE THEN 1 END) as with_delete
FROM user_companies;
```

2. **Application Testing:**
- [ ] Login as Super Admin → Check user list
- [ ] Login as Admin → Check user list (should see only Users with shared companies)
- [ ] Create a new user with different permissions per company
- [ ] Edit existing user → Verify permissions load correctly
- [ ] Test document upload/delete with different permission levels

### Step 6: Monitor

```bash
# Monitor application logs
tail -f application/logs/log-$(date +%Y-%m-%d).php

# Monitor PostgreSQL logs
tail -f /var/log/postgresql/postgresql-*.log

# Monitor web server logs
tail -f /var/log/apache2/error.log  # or nginx
```

---

## 🔄 Rollback Procedure

**If deployment fails or you encounter critical issues:**

### Step 1: Run Rollback Script

```bash
psql -U your_db_user -d your_database_name -f rollback_2026_02_15.sql

# The script will:
# 1. Wait 5 seconds (allowing you to cancel)
# 2. Remove can_add_edit and can_delete columns
# 3. Remove idx_uc_user_company index
# 4. Verify rollback success
```

### Step 2: Restore Previous Code

```bash
# Revert to previous version
git revert HEAD

# Or restore from backup
# (restore your backed up files)
```

### Step 3: Clear Cache

```bash
rm -rf application/cache/*
sudo systemctl restart php-fpm
sudo systemctl restart apache2  # or nginx
```

### Step 4: Restore Database (If Needed)

**Only if rollback script fails:**

```bash
# Restore from backup
pg_restore -U your_db_user -d your_database_name -c backup_before_v2.2.0_*.backup

# Or from SQL dump
psql -U your_db_user -d your_database_name < backup_before_v2.2.0_*.sql
```

---

## 📊 Expected Changes

### Database Schema

**Table: `user_companies`**
```sql
-- Before:
user_companies (id, user_id, company_id, created_at)

-- After:
user_companies (id, user_id, company_id, can_add_edit, can_delete, created_at)
```

### Application Behavior

| User Role | Before | After |
|-----------|--------|-------|
| **Super Admin** | See all users including Super Admins | See only Admins + Users |
| **Admin (Company A)** | See Admins + Users in Company A | See only Users in Company A |
| **User Permissions** | Global (same for all companies) | Per-company (can vary) |

---

## 🐛 Troubleshooting

### Issue 1: "column can_add_edit already exists"
**Cause:** Script was run multiple times  
**Solution:** This is safe to ignore - script uses `IF NOT EXISTS` checks

### Issue 2: Users can't access certain features
**Cause:** Permissions defaulted to FALSE during migration  
**Solution:** Edit users and set appropriate per-company permissions

### Issue 3: "permission denied" errors
**Cause:** Database user lacks ALTER TABLE privileges  
**Solution:** Run as superuser or grant privileges:
```sql
GRANT ALL PRIVILEGES ON DATABASE your_database_name TO your_db_user;
GRANT ALL ON ALL TABLES IN SCHEMA public TO your_db_user;
```

### Issue 4: Performance degradation
**Cause:** Index not created  
**Solution:** Verify and create index:
```sql
CREATE INDEX IF NOT EXISTS idx_uc_user_company ON user_companies(user_id, company_id);
ANALYZE user_companies;
```

---

## 📝 Post-Deployment Tasks

### Immediate (Within 1 hour)
- [ ] Monitor error logs for any issues
- [ ] Test all critical user flows
- [ ] Verify permissions work correctly per company
- [ ] Check performance metrics

### Within 24 hours
- [ ] Review all existing users and set per-company permissions as needed
- [ ] Update user documentation/training materials
- [ ] Communicate changes to admin users

### Within 1 week
- [ ] Gather user feedback
- [ ] Monitor database performance
- [ ] Review and optimize queries if needed

---

## 📞 Support

If you encounter issues:

1. Check application logs: `application/logs/log-YYYY-MM-DD.php`
2. Check PostgreSQL logs
3. Review this guide's troubleshooting section
4. Contact development team with:
   - Error messages
   - Steps to reproduce
   - Database version
   - PHP version
   - Server environment details

---

## 📄 Change Log

### Version 2.2.0 (2026-02-15)
- ✅ Added per-company permissions (can_add_edit, can_delete)
- ✅ User list filtering by role and company access
- ✅ Database migration for existing users
- ✅ Performance optimization with composite index
- ✅ Backward compatibility with global permissions

### Version 2.1.0 (2026-02-14)
- Multi-company support
- Document head deactivation tracking
- User permissions system

---

## ✅ Deployment Checklist

Print this and check off each step:

- [ ] Database backed up
- [ ] Staging environment tested
- [ ] Maintenance window scheduled
- [ ] Users notified
- [ ] Deployment script reviewed
- [ ] Rollback script ready
- [ ] Database credentials verified
- [ ] Deployment script executed successfully
- [ ] Application code deployed
- [ ] Cache cleared
- [ ] Database verification completed
- [ ] Application testing completed
- [ ] Logs monitored (no errors)
- [ ] Users can login and work normally
- [ ] Post-deployment tasks scheduled
- [ ] Documentation updated

---

**Deployment prepared by:** Development Team  
**Review date:** February 15, 2026  
**Approved by:** _________________  
**Deployment date:** _________________  
**Deployment time:** _________________  
**Deployed by:** _________________

