# 🚀 Production Deployment Guide v2.1.0
**Date:** February 14, 2026  
**Version:** 2.1.0  
**Environment:** Production

---

## 📋 Pre-Deployment Checklist

### ⚠️ CRITICAL - Must Complete Before Deployment

- [ ] **Database Backup Created**
  ```bash
  pg_dump -U postgres -d your_database_name > backup_before_v2.1.0_$(date +%Y%m%d_%H%M%S).sql
  ```

- [ ] **Application Tested in Staging**
  - [ ] All test cases passed
  - [ ] User permissions working correctly
  - [ ] Document head deactivation workflow tested
  - [ ] Dashboard tiles displaying properly

- [ ] **Maintenance Window Scheduled**
  - [ ] All users notified
  - [ ] Estimated downtime: 10-15 minutes
  - [ ] Rollback plan prepared

- [ ] **Code Deployed to Server**
  ```bash
  cd /path/to/dmsnew
  git pull origin master
  # Verify commit: 09c1eb8
  ```

---

## 🗄️ Database Migration

### Step 1: Connect to Database
```bash
psql -U postgres -d your_database_name
```

### Step 2: Run Production SQL Script
```bash
\i /path/to/dmsnew/application/sql/production_deployment_2026_02_14.sql
```

**Expected Output:**
```
============================================
Starting Production Deployment: 2.1.0
Date: February 14, 2026
============================================

SECTION 1: Adding company_id to master tables...
✓ Added company_id to sub_type
✓ Added is_enabled to sub_type
✓ Added company_id to authority
...
✓ DEPLOYMENT COMPLETED SUCCESSFULLY
```

### Step 3: Verify Migration Success
```sql
-- Check all new columns exist
SELECT table_name, column_name, data_type
FROM information_schema.columns
WHERE table_schema = 'public'
AND column_name IN ('company_id', 'is_enabled', 'deactivation_date', 'deactivation_remarks')
ORDER BY table_name, column_name;

-- Should return at least 15 rows
```

---

## 🎯 What Changed

### 1. Multi-Company Master Data (Company-Wise Separation)
**Impact:** Each company now has separate masters  
**Tables Modified:**
- `sub_type` (document heads) - Added `company_id`, `is_enabled`
- `authority` - Added `company_id`
- `documents` - Added `company_id`
- `mandatory_documents` - Added `company_id`, `is_enabled`
- `sub_type_reminders` - Added `company_id`, `is_enabled`
- `document_groups` - Added `company_id`
- `holidays` - Added `company_id`

**User Impact:** 
- ✅ Users only see data for their assigned companies
- ✅ Different companies can have same-named authorities/documents
- ✅ No data conflicts between companies

---

### 2. Granular User Permissions
**Impact:** Per-user access control instead of role-only  
**New Table:** `user_permissions`
- `can_view` (Boolean) - View access
- `can_add_edit` (Boolean) - Create/modify access
- `can_delete` (Boolean) - Delete access

**Migration Notes:**
- Existing users automatically migrated based on role
- Super Admin (role_id=1): Full access
- Admin (role_id=2): View + Add/Edit + Delete
- User (role_id=3): View only (default)

**User Impact:**
- ✅ Admins can grant custom permissions per user
- ✅ More flexible access control
- ✅ Existing behavior preserved

---

### 3. Document Head Deactivation Tracking
**Impact:** Audit trail for deactivated document heads  
**Tables Modified:**
- `sub_type` - Added `deactivation_date`, `deactivation_remarks`

**Business Rules:**
- ✅ Deactivation requires date + remarks (min 10 chars)
- ✅ Remarks capture reason for deactivation
- ✅ Reactivation clears deactivation fields

**User Impact:**
- ✅ Better compliance and audit trail
- ✅ Clear documentation why doc heads were disabled
- ✅ Historical tracking of changes

---

### 4. Critical Bug Fixes

#### 🐛 Bug #1: Yearly Document Due Date Calculation
**Issue:** Yearly documents showing wrong "Next Due" date  
**Example:** Document with start date 01-Jan-2026 showed "Next Due: June 2026" instead of "Jan 2027"  
**Root Cause:** Logic using fiscal year end instead of document start month  
**Fix:** Modified `Upload_Model.php` to use `document_start_date` month  
**Impact:** ✅ Yearly documents now calculate correctly

#### 🐛 Bug #2: Dashboard Pending/Upcoming Tiles
**Issue:** Newly added monthly documents not appearing in Current or Upcoming tiles  
**Example:** "Value Added Tax" appearing only in Overdue, not in Current/Upcoming  
**Root Cause:** PHP by-reference loop bug - missing `unset($group)` causing iteration malfunction  
**Fix:** Added `unset($group)` in `Dashboard_model.php` after by-reference foreach  
**Impact:** ✅ All documents now appear in correct tiles

---

## 🧪 Post-Deployment Testing

### Test Case 1: User Permissions
1. Login as Admin
2. Go to Users → Edit User
3. Verify permission checkboxes appear
4. Change permissions and save
5. Login as that user and verify access reflects changes

### Test Case 2: Document Head Deactivation
1. Go to Document Heads list
2. Click "Deactivate" on any active document head
3. Verify modal appears requesting date + remarks
4. Try saving without remarks → Should fail
5. Add remarks (10+ chars) → Should save successfully
6. Reactivate → Deactivation fields should clear

### Test Case 3: Dashboard Tiles
1. Create a new monthly document head
2. Set start date = 07-Jan-2026, Due Day = 20
3. Check dashboard (assuming today is Feb 14, 2026):
   - ✅ Should appear in **Overdue** (Jan 20 passed)
   - ✅ Should appear in **Current** (Feb 20 not passed)
   - ✅ Should appear in **Upcoming** (March period)

### Test Case 4: Yearly Documents
1. Create a yearly document with start date = 01-Jan-2026
2. Upload for period January 2026
3. Check "Next Due" → Should show **January 2027** (not June 2026)

---

## 📊 Database Schema Summary

```sql
-- Key Changes:
ALTER TABLE sub_type ADD COLUMN company_id INTEGER;
ALTER TABLE sub_type ADD COLUMN is_enabled BOOLEAN DEFAULT TRUE;
ALTER TABLE sub_type ADD COLUMN deactivation_date DATE;
ALTER TABLE sub_type ADD COLUMN deactivation_remarks TEXT;

CREATE TABLE user_permissions (
    id SERIAL PRIMARY KEY,
    user_id INT NOT NULL UNIQUE,
    can_view BOOLEAN DEFAULT TRUE,
    can_add_edit BOOLEAN DEFAULT FALSE,
    can_delete BOOLEAN DEFAULT FALSE
);

-- Plus 8 more tables with company_id columns
-- Plus 12 new indexes for performance
```

---

## 🔄 Rollback Plan (If Needed)

### If Issues Arise Within 1 Hour of Deployment:

1. **Stop Application**
   ```bash
   # Stop web server
   sudo systemctl stop apache2  # or nginx
   ```

2. **Restore Database Backup**
   ```bash
   psql -U postgres -d your_database_name < backup_before_v2.1.0_*.sql
   ```

3. **Revert Code**
   ```bash
   cd /path/to/dmsnew
   git revert 09c1eb8
   git push origin master
   ```

4. **Restart Application**
   ```bash
   sudo systemctl start apache2
   ```

---

## 📞 Support Contacts

**Technical Lead:** [Your Name]  
**Database Admin:** [DBA Name]  
**Emergency Hotline:** [Phone]

---

## 📝 Post-Deployment Monitoring

### For First 24 Hours, Monitor:

1. **Error Logs**
   ```bash
   tail -f /path/to/dmsnew/application/logs/log-$(date +%Y-%m-%d).php
   ```

2. **Database Performance**
   ```sql
   -- Check for slow queries
   SELECT query, calls, mean_exec_time, total_exec_time
   FROM pg_stat_statements
   WHERE mean_exec_time > 100
   ORDER BY mean_exec_time DESC
   LIMIT 10;
   ```

3. **User Feedback**
   - Dashboard loading times
   - Permission access issues
   - Data visibility concerns

---

## ✅ Deployment Sign-Off

- [ ] Database migration completed successfully
- [ ] All test cases passed
- [ ] Error logs reviewed (no critical errors)
- [ ] Users can login and access their data
- [ ] Dashboard displays correctly
- [ ] Document upload/download working
- [ ] Performance acceptable

**Deployed By:** _________________  
**Date/Time:** _________________  
**Verified By:** _________________  

---

## 📚 Additional Resources

- **Full SQL Script:** `application/sql/production_deployment_2026_02_14.sql`
- **Bug Fix Details:** `BUGFIX_DASHBOARD_PENDING_2026-02-14.md`
- **Change Log:** `CHANGES_2026-02-14.md`
- **Git Commit:** `09c1eb8`

---

**Version:** 2.1.0  
**Last Updated:** February 14, 2026  
**Status:** Ready for Production ✅

