# Department Change Conflict Review Updates

## Overview

When departments are added or removed from a proposal after it has been saved, the conflict review system now automatically updates to include or remove lawyers accordingly.

## How It Works

### Automatic Updates

When a proposal's departments are modified, the system automatically:

1. **Detects Department Changes**: Uses Laravel's model events to detect when the `departments` field changes
2. **Identifies New Lawyers**: Finds lawyers who belong to the newly added departments
3. **Identifies Removed Lawyers**: Finds lawyers who are no longer in the proposal's departments
4. **Adds New Reviews**: Creates conflict reviews for new lawyers from the added departments
5. **Removes Old Reviews**: Removes pending conflict reviews for lawyers no longer in the departments
6. **Sends Notifications**: Notifies new lawyers about their conflict review assignment

### Manual Updates

Users can also manually trigger the update process using the "Update Reviews" button in the proposals manager.

## Implementation Details

### 1. Model Event Listener

```php
protected static function booted()
{
    static::saved(function ($proposal) {
        if ($proposal->wasChanged('status') && $proposal->status === 'conflict_analyse') {
            $proposal->notifyConflictAnalyse();
        }
        
        // Update conflict reviews when departments change
        if ($proposal->wasChanged('departments')) {
            $proposal->updateConflictReviewsForDepartments();
        }
    });
}
```

### 2. Update Method

```php
public function updateConflictReviewsForDepartments(): void
{
    // Only update if proposal is in a state that requires conflict review
    if (!$this->requiresConflictReview()) {
        return;
    }

    // Get current lawyers for the proposal's departments
    $currentLawyers = $this->getLawyersForDepartments();
    $currentLawyerIds = $currentLawyers->pluck('id')->toArray();

    // Get existing conflict reviews
    $existingReviews = $this->conflictReviews;
    $existingLawyerIds = $existingReviews->pluck('lawyer_id')->toArray();

    // Find lawyers to add (new lawyers in departments)
    $lawyersToAdd = $currentLawyers->whereNotIn('id', $existingLawyerIds);

    // Find lawyers to remove (lawyers no longer in departments)
    $lawyersToRemove = $existingReviews->whereNotIn('lawyer_id', $currentLawyerIds);

    // Add new lawyers
    foreach ($lawyersToAdd as $lawyer) {
        ConflictReview::create([
            'proposal_id' => $this->id,
            'lawyer_id' => $lawyer->id,
            'status' => ConflictReview::STATUS_PENDING,
            'notes' => 'Added due to department change',
        ]);

        // Send notification to new lawyer
        \Mail::to($lawyer->email)->send(new \App\Mail\ConflictReviewNotification($this, $lawyer));
    }

    // Remove lawyers no longer in departments (only if review is pending)
    foreach ($lawyersToRemove as $review) {
        if ($review->status === ConflictReview::STATUS_PENDING) {
            $review->delete();
        }
    }
}
```

### 3. UI Integration

Added a "Update Reviews" button in the proposals manager that:

- Only shows for proposals in `draft` or `pending_review` status
- Requires `conflicts.manage` permission
- Manually triggers the update process
- Shows success notification with updated lawyer count

## Scenarios

### Scenario 1: Adding a Department

**Before:**
```
Proposal: "Tech Project" (departments: ["tech"])
Lawyers Assigned: 2 (from tech department)
```

**After adding "finance" department:**
```
Proposal: "Tech Project" (departments: ["tech", "finance"])
Lawyers Assigned: 4 (2 from tech + 2 from finance)
```

**What happens:**
1. System detects department change
2. Finds 2 new lawyers from finance department
3. Creates conflict reviews for new lawyers
4. Sends notifications to new lawyers
5. Logs the changes

### Scenario 2: Removing a Department

**Before:**
```
Proposal: "Tech Project" (departments: ["tech", "finance"])
Lawyers Assigned: 4 (2 from tech + 2 from finance)
```

**After removing "finance" department:**
```
Proposal: "Tech Project" (departments: ["tech"])
Lawyers Assigned: 2 (only from tech department)
```

**What happens:**
1. System detects department change
2. Identifies 2 lawyers no longer in departments
3. Removes pending conflict reviews for those lawyers
4. Keeps completed reviews (doesn't delete them)
5. Logs the changes

### Scenario 3: Replacing Departments

**Before:**
```
Proposal: "Tech Project" (departments: ["tech"])
Lawyers Assigned: 2 (from tech department)
```

**After changing to ["marketing", "sales"]:**
```
Proposal: "Tech Project" (departments: ["marketing", "sales"])
Lawyers Assigned: 3 (from marketing and sales departments)
```

**What happens:**
1. System detects department change
2. Removes all existing conflict reviews (since no departments overlap)
3. Creates new conflict reviews for lawyers in marketing and sales
4. Sends notifications to new lawyers
5. Logs the changes

## Safety Features

### 1. Status Protection
- Only updates proposals in `draft` or `pending_review` status
- Won't modify completed conflict reviews

### 2. Review Protection
- Only removes conflict reviews that are still `pending`
- Preserves completed reviews (`no_conflict` or `conflict_exists`)

### 3. Logging
- Comprehensive logging of all changes
- Tracks added/removed lawyers
- Records notification attempts

### 4. Error Handling
- Graceful handling of email failures
- Continues process even if some notifications fail

## User Interface

### Automatic Updates
- Happens transparently when departments are changed
- No user action required
- Logs available for audit

### Manual Updates
- "Update Reviews" button in proposals manager
- Shows only for relevant proposals and users
- Provides immediate feedback

## Benefits

1. **Automatic Synchronization**: Conflict reviews stay in sync with departments
2. **Reduced Manual Work**: No need to manually reassign lawyers
3. **Better Accuracy**: Ensures only relevant lawyers review proposals
4. **Audit Trail**: Complete logging of all changes
5. **User Control**: Manual override option available
6. **Safety**: Protects completed reviews and handles errors gracefully

## Testing

To test the feature:

1. **Create a proposal** with specific departments
2. **Add lawyers** to those departments
3. **Initiate conflict review** or approve the proposal
4. **Modify departments** (add/remove/replace)
5. **Verify** that conflict reviews update accordingly
6. **Check logs** for detailed change tracking

## Related Files

- `app/Models/Proposal.php` - Main implementation
- `app/Livewire/ProposalsManager.php` - UI integration
- `resources/views/livewire/proposals-manager.blade.php` - Button UI
- `app/Models/ConflictReview.php` - Review model
- `app/Mail/ConflictReviewNotification.php` - Email notifications 