# Conflict Management Department Fix

## Problem

The conflict management system was assigning **ALL lawyers** in the system to review conflicts for **ALL proposals**, regardless of whether those lawyers belonged to the departments assigned to the proposal.

### Example Issue
- **Proposal "Placeat aut ut aut"** only has department **"sapatos"** selected
- **3 lawyers** were assigned to manage conflicts for this proposal
- **But those 3 lawyers might not belong to the "sapatos" department**
- This created unnecessary work and confusion

## Root Cause

The issue was in the `initiateAutomaticConflictManagement()` method in `app/Models/Proposal.php`:

```php
// OLD CODE - Assigns ALL lawyers
$lawyers = User::lawyers()->active()->get();

foreach ($lawyers as $lawyer) {
    ConflictReview::firstOrCreate([
        'proposal_id' => $this->id,
        'lawyer_id' => $lawyer->id,
    ]);
}
```

## Solution

### 1. Added Helper Method
Created `getLawyersForDepartments()` method in `Proposal` model:

```php
/**
 * Get lawyers who belong to the departments associated with this proposal
 */
public function getLawyersForDepartments()
{
    return User::lawyers()->active()->get()->filter(function ($lawyer) {
        // If proposal has no departments, don't assign any lawyers
        if (empty($this->departments)) {
            return false;
        }
        
        // Check if lawyer belongs to any of the proposal's departments
        $lawyerDepartments = $lawyer->department_codes;
        foreach ($this->departments as $proposalDepartment) {
            if (in_array($proposalDepartment, $lawyerDepartments)) {
                return true;
            }
        }
        return false;
    });
}
```

### 2. Updated All Conflict Management Methods

Updated the following methods to use department-based lawyer assignment:

- `initiateAutomaticConflictManagement()` - Automatic conflict management
- `allConflictReviewsCompleted()` - Check if all reviews are done
- `initiateConflictReview()` - Manual conflict review initiation
- `notifyConflictAnalyse()` - Send conflict analysis notifications

### 3. Updated ProposalsManager

Updated `ProposalsManager` to use the same logic:

- `initiateConflictReview()` - Manual conflict review
- `sendConflictReviewNotifications()` - Send notifications

### 4. Added Department Change Handling

**NEW FEATURE**: When departments are added or removed from a proposal, the conflict review system automatically updates:

- **Automatic Updates**: Model events detect department changes and update conflict reviews
- **Manual Updates**: "Update Reviews" button in proposals manager
- **Smart Logic**: Only adds new lawyers, removes pending reviews for removed lawyers
- **Safety**: Preserves completed reviews and handles errors gracefully

## How It Works Now

### Before Fix
```
Proposal (departments: ["sapatos"])
├── Lawyer A (departments: ["tech", "finance"]) ❌
├── Lawyer B (departments: ["marketing"]) ❌
└── Lawyer C (departments: ["sapatos"]) ✅
```

### After Fix
```
Proposal (departments: ["sapatos"])
└── Lawyer C (departments: ["sapatos"]) ✅
```

### Department Changes
```
Proposal (departments: ["sapatos", "finance"]) ← Added "finance"
├── Lawyer C (departments: ["sapatos"]) ✅
└── Lawyer D (departments: ["finance"]) ✅ ← Automatically added
```

## Benefits

1. **Reduced Workload**: Only relevant lawyers are assigned to conflict reviews
2. **Better Organization**: Lawyers only review proposals from their departments
3. **Clearer Notifications**: Users see exactly which departments are involved
4. **Improved Efficiency**: Faster conflict review process
5. **Better Logging**: More detailed logs showing which departments are involved
6. **Automatic Synchronization**: Conflict reviews stay in sync with department changes
7. **User Control**: Manual override option available when needed

## Testing

To test the fix:

1. Create a proposal with specific departments
2. Ensure some lawyers belong to those departments and some don't
3. Approve the proposal or initiate conflict review
4. Verify only lawyers from the proposal's departments are assigned

### Testing Department Changes

1. **Add a department** to an existing proposal
2. **Verify** new lawyers are automatically added to conflict reviews
3. **Remove a department** from a proposal
4. **Verify** lawyers from removed departments are removed from pending reviews
5. **Check logs** for detailed change tracking

## Migration Notes

- **Existing conflict reviews**: Will remain as-is (no automatic cleanup)
- **New proposals**: Will only assign lawyers from relevant departments
- **Notifications**: Will only be sent to lawyers from relevant departments
- **Logs**: Will show which departments are involved in the process
- **Department changes**: Automatically update conflict reviews (NEW)

## Related Files

- `app/Models/Proposal.php` - Main changes
- `app/Livewire/ProposalsManager.php` - UI integration
- `app/Models/User.php` - Department relationship methods
- `app/Models/ConflictReview.php` - Conflict review model
- `docs/DEPARTMENT_CHANGE_CONFLICT_REVIEWS.md` - Detailed department change documentation 