# Template Version History

## Overview

The Template Version History feature allows you to track, manage, and restore previous versions of your notification templates. This provides a complete audit trail and the ability to revert changes when needed.

## Features

### 1. Automatic Version Creation
- Every time you update a template, a new version is automatically created
- Version numbers follow a semantic versioning pattern (e.g., 1.0, 1.1, 1.2)
- Each version includes a complete snapshot of the template at that point in time

### 2. Version History View
- Access version history by clicking the "Version History" icon in the template list
- View all versions of a template in chronological order
- See version numbers, change descriptions, and timestamps
- Current version is clearly highlighted

### 3. Version Restoration
- Restore any previous version of a template
- Restoration creates a new version (doesn't overwrite history)
- Automatic backup of current state before restoration

### 4. Version Deletion
- Delete old versions that are no longer needed
- Protection against deleting the current version
- Protection against deleting the only version

## Database Schema

### notification_template_versions Table

| Field | Type | Description |
|-------|------|-------------|
| id | varchar(36) | Primary key (UUID) |
| template_id | varchar(36) | Reference to the main template |
| version | varchar(20) | Version number (e.g., "1.0", "1.1") |
| name | varchar(100) | Template name at this version |
| description | text | Template description |
| subject | varchar(255) | Email subject line |
| email_content | text | Email content/body |
| push_title | varchar(100) | Push notification title |
| push_body | varchar(300) | Push notification body |
| category | varchar(50) | Template category |
| channels | json | Supported channels array |
| status | varchar(20) | Template status (Draft, Active, Archived) |
| change_description | text | Description of what changed |
| is_current | boolean | Whether this is the current version |
| created_by | varchar(36) | User who created this version |
| created_at | timestamp | When this version was created |

## API Endpoints

### Get Version History
```
GET /api/notifications/templates/{id}/versions
```

**Response:**
```json
{
  "success": true,
  "data": {
    "templateId": "template-uuid",
    "templateName": "Template Name",
    "versions": [
      {
        "id": "version-uuid",
        "version": "1.2",
        "name": "Template Name",
        "changeDescription": "Updated welcome message",
        "isCurrent": false,
        "status": "Active",
        "formattedCreatedAt": "03/20/2024, 02:30 PM"
      }
    ],
    "totalCount": 3
  }
}
```

### Restore Version
```
POST /api/notifications/templates/{id}/versions/{versionId}/restore
```

**Response:**
```json
{
  "success": true,
  "data": {
    "message": "Version 1.1 has been restored successfully as version 1.3",
    "templateId": "template-uuid",
    "restoredVersion": "1.1",
    "newVersion": "1.3"
  }
}
```

### Delete Version
```
DELETE /api/notifications/templates/{id}/versions/{versionId}
```

**Response:**
```json
{
  "success": true,
  "data": {
    "message": "Version 1.1 has been deleted successfully",
    "templateId": "template-uuid",
    "deletedVersion": "1.1"
  }
}
```

## How to Use

### 1. Setup Database
Run the migration to create the version history table:

```bash
node scripts/run-migration.js
```

Or manually run the SQL migration file:
```bash
mysql -u your_username -p your_database < database/migrations/003_create_template_version_history.sql
```

### 2. Update Prisma Schema
After running the migration, update your Prisma client:

```bash
npx prisma generate
```

### 3. Using the Frontend

#### View Version History
1. Go to the notification templates page
2. Find the template you want to view history for
3. Click the "Version History" icon in the actions column
4. The version history modal will open showing all versions

#### Restore a Version
1. Open the version history modal
2. Find the version you want to restore
3. Click the "Restore" button for that version
4. Confirm the restoration in the popup dialog
5. The version will be restored as a new version

#### Delete a Version
1. Open the version history modal
2. Find the version you want to delete
3. Click the "Delete" button for that version
4. Confirm the deletion in the popup dialog
5. The version will be permanently deleted

## Best Practices

### 1. Version Naming
- Use semantic versioning (major.minor format)
- Increment minor version for small changes
- Increment major version for significant changes

### 2. Change Descriptions
- Always provide meaningful change descriptions
- Include what was changed and why
- Be specific about the modifications made

### 3. Version Management
- Regularly clean up old versions that are no longer needed
- Keep important milestone versions
- Don't delete versions that might be needed for compliance or audit

### 4. Testing
- Test templates thoroughly before making them active
- Use draft status for work-in-progress templates
- Restore previous versions if issues are found

## Security Considerations

### 1. Access Control
- Only authenticated users can access version history
- Users can only manage versions of templates they have access to
- Audit logs track all version operations

### 2. Data Protection
- All version data is stored securely in the database
- Sensitive information in templates is handled according to your data protection policies
- Regular backups include version history data

### 3. Validation
- All version operations are validated before execution
- Protection against malicious version manipulation
- Proper error handling for failed operations

## Troubleshooting

### Common Issues

1. **Version History Not Loading**
   - Check database connection
   - Verify the template exists
   - Check API endpoint responses

2. **Restore Failing**
   - Ensure you have proper permissions
   - Check if the version exists
   - Verify template is not locked

3. **Delete Failing**
   - Cannot delete current version
   - Cannot delete if it's the only version
   - Check user permissions

### Debug Steps
1. Check browser console for errors
2. Verify API responses
3. Check database logs
4. Confirm user authentication

## Future Enhancements

- Version comparison view
- Bulk version operations
- Version export/import
- Advanced filtering and search
- Version approval workflows
- Automated version cleanup policies 