# Contact Messages Management System - Complete Guide

## Overview
A complete Contact Messages management system for the Brand Master e-commerce platform that allows customers to submit contact forms and admins to manage messages from a dedicated dashboard.

## Features

### Public Contact Form
- Full name, email, phone (optional), subject, and message fields
- Frontend validation with error messages
- Required field indicators (red asterisks)
- Success confirmation after submission
- Enhanced user experience with placeholders and helpful hints

### Admin Dashboard
- Dedicated "Contact Messages" tab in Admin panel
- Unread message counter badge
- Message listing table with:
  - Visual unread indicator (yellow highlight)
  - Status badges (New/Read/Replied)
  - Sortable by date
  - Filter by status
- Message details modal with:
  - Full message content display
  - Status update dropdown
  - Admin notes textarea
  - Delete functionality

### Backend Features
- Full REST API for message management
- Admin-only endpoints with JWT authentication
- PostgreSQL database persistence
- Enhanced data model with:
  - Phone number support
  - Read/unread tracking
  - Status management (new/read/replied)
  - Admin notes capability

## Database Schema

```sql
Table: contact_message
- id: INTEGER (Primary Key)
- full_name: VARCHAR (Customer name)
- email: VARCHAR (Customer email)
- phone: VARCHAR (Optional phone number)
- subject: VARCHAR (Message subject)
- message: TEXT (Message content)
- created_at: TIMESTAMP (Submission time)
- is_read: BOOLEAN (Read status, default: false)
- status: VARCHAR (new/read/replied, default: 'new')
- admin_notes: TEXT (Internal admin notes, nullable)
```

## API Endpoints

### Public Endpoint
```
POST /api/contact
Body: {
  "full_name": "John Doe",
  "email": "john@example.com",
  "phone": "+972 XX-XXX-XXXX",  // Optional
  "subject": "Product Inquiry",
  "message": "I have a question..."
}
```

### Admin Endpoints (Requires Authentication)
```
GET /api/admin/contact-messages
Query Parameters:
  - status: (optional) Filter by status (new/read/replied)
  - is_read: (optional) Filter by read status (true/false)
  - skip: (optional) Pagination offset (default: 0)
  - limit: (optional) Page size (default: 100)

GET /api/admin/contact-messages/unread-count
Returns: { "unread_count": 5 }

GET /api/admin/contact-messages/{message_id}
Returns: Full message details

PUT /api/admin/contact-messages/{message_id}
Body: {
  "is_read": true,
  "status": "replied",
  "admin_notes": "Called customer and resolved issue"
}

DELETE /api/admin/contact-messages/{message_id}
Returns: { "message": "Contact message deleted successfully" }
```

## Modified Files

### Backend
1. **backend/app/models/contact_message.py** - Enhanced database model
2. **backend/app/schemas/contact.py** - Updated Pydantic schemas
3. **backend/app/routers/contact.py** - Added admin endpoints
4. **backend/app/main.py** - Registered admin router
5. **backend/migrations/007_enhance_contact_messages.sql** - Database migration

### Frontend
1. **frontend/src/pages/Contact.jsx** - Enhanced form with validation
2. **frontend/src/pages/Admin.jsx** - Added Contact Messages management tab

## Deployment Steps

### Step 1: Apply Database Migration
```bash
# On Windows
cd c:\Users\dvirl\OneDrive\Desktop\gitea\brand-master
apply-migration.bat 007_enhance_contact_messages.sql

# Or on Linux/Mac
./apply-migration.sh 007_enhance_contact_messages.sql
```

### Step 2: Build and Push Docker Images
```bash
# Build backend
cd backend
docker build -t harbor.dvirlabs.com/my-apps/brand-master-backend:latest .

# Build frontend
cd ../frontend
docker build -t harbor.dvirlabs.com/my-apps/brand-master-frontend:latest .

# Push to Harbor
docker push harbor.dvirlabs.com/my-apps/brand-master-backend:latest
docker push harbor.dvirlabs.com/my-apps/brand-master-frontend:latest
```

### Step 3: Deploy to Kubernetes
```bash
cd brand-master-chart

# Upgrade Helm deployment
helm upgrade brand-master . \
  --namespace my-apps \
  --set backend.image.tag=latest \
  --set frontend.image.tag=latest \
  --wait
```

### Step 4: Verify Deployment
```bash
# Check pods are running
kubectl get pods -n my-apps | grep brand-master

# Check backend logs
kubectl logs -n my-apps deployment/brand-master-backend --tail=50

# Check frontend logs
kubectl logs -n my-apps deployment/brand-master-frontend --tail=50
```

## Testing

### Test Public Contact Form
1. Navigate to https://brand-master.dvirlabs.com/contact
2. Fill in the form:
   - Full Name: Test User
   - Email: test@example.com
   - Phone: +972 50-123-4567 (optional)
   - Subject: Test Message
   - Message: This is a test message
3. Submit and verify success message

### Test Admin Dashboard
1. Login as admin at https://brand-master.dvirlabs.com/login
2. Navigate to Admin Dashboard
3. Click "Contact Messages" tab
4. Verify:
   - ✅ Test message appears in list
   - ✅ Unread counter shows correct count
   - ✅ Message has yellow highlight (unread)
   - ✅ Status shows "NEW"
5. Click on message row to open details modal
6. Test actions:
   - Change status to "Read"
   - Add admin notes
   - Save changes
   - Verify message updated
   - Test delete functionality

### Test Filters
1. Create messages with different statuses
2. Test status filter dropdown:
   - All Messages
   - New
   - Read
   - Replied
3. Verify filtering works correctly

## Security Features
- Admin endpoints protected by JWT authentication
- Only users with `is_admin=true` can access admin endpoints
- Email validation on both frontend and backend
- SQL injection protection via SQLAlchemy ORM
- XSS protection via React's built-in escaping

## Future Enhancements
- Email notifications for new messages
- Reply functionality from admin panel
- Attachment support
- Search functionality for messages
- Export messages to CSV
- Message templates for common responses
- Bulk actions (mark multiple as read, delete multiple)

## Troubleshooting

### Backend Issues
```bash
# Check backend logs
kubectl logs -n my-apps deployment/brand-master-backend --tail=100

# Common issues:
# 1. Migration not applied - Run migration script
# 2. Auth errors - Check JWT token and admin role
# 3. Database connection - Verify PostgreSQL is running
```

### Frontend Issues
```bash
# Check frontend logs
kubectl logs -n my-apps deployment/brand-master-frontend --tail=100

# Common issues:
# 1. API calls failing - Check VITE_API_URL environment variable
# 2. Auth errors - Clear browser storage and re-login
# 3. Component errors - Check browser console
```

### Database Issues
```bash
# Connect to PostgreSQL pod
kubectl exec -it -n my-apps deployment/brand-master-postgres -- psql -U brand_master -d brand_master_db

# Check if migration applied
\d contact_message

# View messages
SELECT id, full_name, email, subject, status, is_read, created_at FROM contact_message;

# Count unread messages
SELECT COUNT(*) FROM contact_message WHERE is_read = false;
```

## Performance Considerations
- Messages are fetched only when admin clicks the "Contact Messages" tab
- Unread count is fetched once on admin dashboard load
- Table supports pagination (limit parameter)
- Indexes on status, is_read, and created_at for fast filtering
- Modal opens client-side without additional API calls

## Maintenance
- Periodically review and archive old messages
- Monitor unread message count
- Review admin notes for customer service insights
- Consider data retention policies for GDPR compliance

---

**Status:** Ready for deployment
**Last Updated:** 2026-05-08
**Version:** 1.0.0
