# Contacts Module Deployment Guide

## Quick Start

This guide will help you deploy and test the newly implemented Contacts module features.

---

## Prerequisites

- Docker and Docker Compose installed
- Node.js 18+ (for local development)
- Access to production server (37.60.249.71)

---

## Local Development Testing

### 1. Install Dependencies

```bash
# Backend
cd backend
npm install

# Frontend
cd ../frontend
npm install
```

### 2. Build and Start

```bash
# From project root
docker-compose down
docker-compose build
docker-compose up -d
```

### 3. Verify Services

```bash
# Check all services are running
docker-compose ps

# Check backend logs
docker-compose logs backend -f

# Check frontend logs
docker-compose logs frontend -f
```

### 4. Access the Application

- **Frontend**: http://localhost:3000
- **Backend API**: http://localhost:5001
- **Login**: admin@example.com / Admin@123

---

## Testing New Features

### 1. Contact Detail Page

**Test Steps**:
1. Navigate to Contacts page
2. Click the "Eye" icon on any contact
3. Verify all tabs load correctly:
   - Info tab shows all contact fields
   - Company tab shows company info
   - Address tab shows location details
   - Categories tab shows assigned categories
   - History tab shows audit trail
4. Test copy-to-clipboard for email/phone
5. Click "Edit" to open the enhanced form
6. Click "History" to view audit trail

**Expected Result**: All tabs display data correctly, no console errors

---

### 2. Enhanced Contact Form

**Test Steps**:
1. Click "Add Contact" button
2. Verify all fields are present:
   - Contact Type & Source (dropdowns)
   - Name & Arabic Name
   - Rating (star selector)
   - Email, Phone, Mobile, Website
   - Company Name & Arabic Company Name (for Company types)
   - Tax Number & Commercial Register (for Company types)
   - Full address fields including Postal Code
   - Categories (hierarchical selector)
   - Tags (multi-input)
3. Fill in all fields
4. Submit form
5. Verify contact is created with all data

**Expected Result**: All fields save correctly, no validation errors

---

### 3. Category Management

**Test Steps**:
1. Open contact create/edit form
2. Scroll to Categories section
3. Click "+" button to add new category
4. Create a root category (e.g., "Customer")
5. Create a child category with "Customer" as parent (e.g., "VIP Customer")
6. Select both categories
7. Save contact
8. Verify categories appear on contact detail page

**Expected Result**: Hierarchical categories work, display correctly

---

### 4. Export Functionality

**Test Steps**:
1. On Contacts page, apply some filters (e.g., Type=Company)
2. Click "Export" button
3. Verify export modal shows filtered count
4. Click "Export"
5. Verify Excel file downloads
6. Open file and verify data matches filters

**Expected Result**: Excel file downloads with correct filtered data

---

### 5. Advanced Filters

**Test Steps**:
1. On Contacts page, click "Advanced" button
2. Verify additional filters appear:
   - Source dropdown
   - Rating dropdown
3. Apply Source filter (e.g., "WEBSITE")
4. Apply Rating filter (e.g., "5 Stars")
5. Verify contacts list updates
6. Click "Clear All Filters"
7. Verify all filters reset

**Expected Result**: Filters work correctly, results update

---

### 6. Contact History

**Test Steps**:
1. Open a contact detail page
2. Click "History" tab
3. Verify timeline displays all actions:
   - Create event with user and timestamp
   - Any update events with changed fields
4. Edit the contact
5. Return to History tab
6. Verify new update event appears with field changes

**Expected Result**: Timeline shows all events with before/after values

---

### 7. Bulk Selection

**Test Steps**:
1. On Contacts page, click checkbox in table header
2. Verify all contacts on current page are selected
3. Verify selection counter appears in header
4. Click individual checkboxes
5. Verify selection count updates
6. Click "X" to clear selection
7. Verify all checkboxes uncheck

**Expected Result**: Bulk selection works smoothly, visual feedback clear

---

## Production Deployment

### Option A: Build and Deploy via SSH (Recommended)

```bash
# 1. Build frontend and backend locally
cd frontend
npm run build

cd ../backend
npm run build

# 2. Sync files to server
sshpass -p 'H191G9gD0GnOy' rsync -avz --delete \
  --exclude 'node_modules' \
  --exclude '.git' \
  . root@37.60.249.71:/root/z_crm/

# 3. SSH into server and rebuild
sshpass -p 'H191G9gD0GnOy' ssh root@37.60.249.71 << 'EOF'
cd /root/z_crm
docker-compose down
docker-compose build --no-cache
docker-compose up -d
docker-compose logs -f
EOF
```

### Option B: Direct Server Build

```bash
# 1. SSH into server
ssh root@37.60.249.71

# 2. Pull latest code (if using git)
cd /root/z_crm
git pull

# 3. Rebuild and restart
docker-compose down
docker-compose build --no-cache
docker-compose up -d

# 4. Monitor logs
docker-compose logs backend frontend -f
```

---

## Post-Deployment Verification

### 1. Health Checks

```bash
# Check all services are running
docker-compose ps

# Verify backend is responding
curl http://localhost:5001/api/v1/health

# Verify frontend is accessible
curl http://localhost:3000
```

### 2. API Testing

```bash
# Test categories endpoint
curl -H "Authorization: Bearer YOUR_TOKEN" \
  http://localhost:5001/api/v1/contacts/categories

# Test contacts with filters
curl -H "Authorization: Bearer YOUR_TOKEN" \
  http://localhost:5001/api/v1/contacts?source=WEBSITE&rating=5
```

### 3. Frontend Testing

1. Open https://zerp.atmata-group.com
2. Login with admin credentials
3. Test each new feature (see Testing New Features section)
4. Check browser console for errors
5. Test on mobile device

---

## Rollback Procedure

If issues are discovered:

```bash
# 1. SSH into server
ssh root@37.60.249.71

# 2. Stop containers
cd /root/z_crm
docker-compose down

# 3. Checkout previous version (if using git)
git checkout <previous-commit-hash>

# 4. Rebuild
docker-compose build
docker-compose up -d

# 5. Verify
docker-compose logs -f
```

---

## Troubleshooting

### Issue: Categories not loading

**Solution**:
```bash
# Check backend logs
docker-compose logs backend | grep category

# Verify database
docker-compose exec postgres psql -U zerp_user -d zerp_db -c "SELECT COUNT(*) FROM contact_categories;"
```

### Issue: Form not saving all fields

**Solution**:
```bash
# Check network tab in browser DevTools
# Verify request payload includes all fields
# Check backend validation logs
docker-compose logs backend | grep "Validation"
```

### Issue: Export not working

**Solution**:
```bash
# Verify backend endpoint
docker-compose logs backend | grep export

# Check if export route is registered
docker-compose exec backend cat src/modules/contacts/contacts.routes.ts | grep export
```

### Issue: Permission errors on categories

**Solution**:
```bash
# Verify user has correct permissions
# Check database: permissions table
docker-compose exec postgres psql -U zerp_user -d zerp_db -c "SELECT * FROM permissions WHERE resource = 'contacts';"
```

---

## Database Seeding (If Needed)

If you need to seed sample categories:

```bash
# 1. SSH into server
ssh root@37.60.249.71

# 2. Connect to database
docker-compose exec postgres psql -U zerp_user -d zerp_db

# 3. Insert sample categories
INSERT INTO contact_categories (id, name, "nameAr", "isActive", "createdAt", "updatedAt")
VALUES 
  (gen_random_uuid(), 'Customer', 'عميل', true, NOW(), NOW()),
  (gen_random_uuid(), 'Supplier', 'مورد', true, NOW(), NOW()),
  (gen_random_uuid(), 'Partner', 'شريك', true, NOW(), NOW());
```

---

## Monitoring

### Key Metrics to Watch

1. **Response Times**
   - Category API: < 200ms
   - Contact List: < 500ms
   - Contact Detail: < 300ms

2. **Error Rates**
   - Monitor 4xx/5xx errors in logs
   - Check for validation failures

3. **Database Performance**
   - Monitor query times for contacts with categories
   - Check for N+1 query issues

### Logging

```bash
# Tail all logs
docker-compose logs -f

# Backend only
docker-compose logs backend -f

# Frontend only
docker-compose logs frontend -f

# Postgres only
docker-compose logs postgres -f
```

---

## Support

For issues or questions:
1. Check `CONTACTS_IMPLEMENTATION_STATUS.md` for feature status
2. Review `PRODUCTION_IMPLEMENTATION_GUIDE.md` for general deployment
3. Check Docker logs for errors
4. Verify database connectivity

---

**Last Updated**: February 9, 2026
