# Complete Optimization Problem and Solution: customer_complaints

## 1. Problem Context and Goals

### Context  
The business is focused on optimizing the allocation of staff to manage customer complaints effectively. The primary decision involves determining whether a specific complaint is assigned to a staff member, represented by a binary decision variable. The operational objective is to minimize the total time required to resolve all complaints. This is achieved by summing the resolution times for each complaint that is assigned to a staff member. Each staff member has a defined capacity, indicating the maximum number of complaints they can handle, which serves as a constraint in the optimization model. The resolution time for each complaint is calculated based on the difference between the date the complaint was raised and the date it was resolved. This calculation is used to determine the coefficients in the optimization model. The business configuration includes parameters such as the maximum number of complaints a staff member can handle, which is crucial for maintaining workload balance and efficiency. The focus is on precise operational decision-making that aligns with linear optimization formulations, avoiding any nonlinear relationships.

### Goals  
The optimization goal is to minimize the total time taken to resolve all customer complaints. This is achieved by strategically assigning complaints to staff members in a way that reduces the overall resolution time. The success of this optimization is measured by the reduction in total resolution time, which is calculated by summing the resolution times for all assigned complaints. The objective is clearly defined in linear terms, focusing on minimizing the total resolution time without involving any complex mathematical expressions.

## 2. Constraints    

The optimization model includes specific constraints to ensure effective complaint management:

- Each complaint must be assigned to exactly one staff member. This ensures that every complaint is addressed and resolved.
- The number of complaints assigned to each staff member must not exceed their maximum handling capacity. This constraint ensures that no staff member is overloaded, maintaining a balanced workload across the team.

These constraints are expressed in business terms that naturally lead to linear mathematical forms, ensuring clarity and consistency in the optimization process.

## 3. Available Data  

### Database Schema  
```sql
-- Iteration 1 Database Schema
-- Objective: Schema changes include creating a new table for staff capacity and modifying the Complaints table to include resolution time. Configuration logic updates include adding scalar parameters for staff capacity and a formula for resolution time calculation.

CREATE TABLE Complaints (
  complaint_id INTEGER,
  date_complaint_raised DATE,
  date_complaint_closed DATE,
  resolution_time INTEGER
);

CREATE TABLE StaffCapacity (
  staff_id INTEGER,
  max_complaints INTEGER
);
```

### Data Dictionary  
The data dictionary provides a comprehensive mapping of tables and columns to their business purposes and roles in the optimization process:

- **Complaints Table**: This table stores information about customer complaints. Each complaint is uniquely identified by a complaint ID, which serves as a decision variable in the optimization model. The table includes the date the complaint was raised and resolved, which are used to calculate the resolution time. The resolution time acts as an objective coefficient in the optimization model.

- **StaffCapacity Table**: This table records the maximum number of complaints each staff member can handle. Each staff member is uniquely identified by a staff ID. The maximum complaints column serves as a constraint bound in the optimization model, ensuring that staff capacity is not exceeded.

### Current Stored Values  
```sql
-- Iteration 1 Realistic Data
-- Generated by triple expert (business + data + optimization)
-- Values were determined based on typical business operations for handling customer complaints, considering average resolution times and staff capacity in a medium-sized customer service department.

-- Realistic data for Complaints
INSERT INTO Complaints (complaint_id, date_complaint_raised, date_complaint_closed, resolution_time) VALUES (1, 2023-01-01, 2023-01-03, 2);
INSERT INTO Complaints (complaint_id, date_complaint_raised, date_complaint_closed, resolution_time) VALUES (2, 2023-01-02, 2023-01-05, 3);
INSERT INTO Complaints (complaint_id, date_complaint_raised, date_complaint_closed, resolution_time) VALUES (3, 2023-01-03, 2023-01-06, 3);

-- Realistic data for StaffCapacity
INSERT INTO StaffCapacity (staff_id, max_complaints) VALUES (1, 5);
INSERT INTO StaffCapacity (staff_id, max_complaints) VALUES (2, 7);
INSERT INTO StaffCapacity (staff_id, max_complaints) VALUES (3, 6);
```

## 4. Mathematical Optimization Formulation

#### Decision Variables
- Let \( x_{ij} \) be a binary decision variable where \( x_{ij} = 1 \) if complaint \( i \) is assigned to staff member \( j \), and \( x_{ij} = 0 \) otherwise.

#### Objective Function
Minimize the total resolution time for all complaints:
\[ \text{Minimize} \quad \sum_{i} \sum_{j} \text{resolution\_time}_i \times x_{ij} \]

Where:
- \(\text{resolution\_time}_i\) is the resolution time for complaint \( i \) from the `Complaints` table.

#### Constraints
1. Each complaint must be assigned to exactly one staff member:
   \[ \sum_{j} x_{ij} = 1 \quad \forall i \]

2. The number of complaints assigned to each staff member must not exceed their maximum handling capacity:
   \[ \sum_{i} x_{ij} \leq \text{max\_complaints}_j \quad \forall j \]

Where:
- \(\text{max\_complaints}_j\) is the maximum number of complaints staff member \( j \) can handle from the `StaffCapacity` table.

3. Binary constraint for decision variables:
   \[ x_{ij} \in \{0, 1\} \quad \forall i, j \]

Data Source Verification:
- \(\text{resolution\_time}_i\) is sourced from `Complaints.resolution_time`.
- \(\text{max\_complaints}_j\) is sourced from `StaffCapacity.max_complaints`. 

This linear model is designed to be immediately solvable using linear programming or mixed-integer programming techniques, ensuring that all constraints and the objective function are expressed in linear terms.

## 5. Gurobipy Implementation

```python
# Complete GUROBIPY implementation

import gurobipy as gp
from gurobipy import GRB

def optimize_customer_complaints():
    """Optimize the allocation of staff to manage customer complaints."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("customer_complaints")
    
    # Data from the database
    complaints = [
        {"complaint_id": 1, "resolution_time": 2},
        {"complaint_id": 2, "resolution_time": 3},
        {"complaint_id": 3, "resolution_time": 3}
    ]
    
    staff_capacity = [
        {"staff_id": 1, "max_complaints": 5},
        {"staff_id": 2, "max_complaints": 7},
        {"staff_id": 3, "max_complaints": 6}
    ]
    
    num_complaints = len(complaints)
    num_staff = len(staff_capacity)
    
    # CRITICAL: Validate array lengths before loops
    assert num_complaints > 0 and num_staff > 0, "No data available for complaints or staff"
    
    # 2. VARIABLES
    # Binary decision variables for complaint assignment
    x = model.addVars(num_complaints, num_staff, vtype=GRB.BINARY, name="x")
    
    # 3. OBJECTIVE FUNCTION
    # Minimize total resolution time
    model.setObjective(
        gp.quicksum(complaints[i]["resolution_time"] * x[i, j] for i in range(num_complaints) for j in range(num_staff)),
        GRB.MINIMIZE
    )
    
    # 4. CONSTRAINTS
    
    # Each complaint must be assigned to exactly one staff member
    model.addConstrs(
        (gp.quicksum(x[i, j] for j in range(num_staff)) == 1 for i in range(num_complaints)),
        name="assign_complaint"
    )
    
    # The number of complaints assigned to each staff member must not exceed their capacity
    model.addConstrs(
        (gp.quicksum(x[i, j] for i in range(num_complaints)) <= staff_capacity[j]["max_complaints"] for j in range(num_staff)),
        name="staff_capacity"
    )
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in range(num_complaints):
            for j in range(num_staff):
                if x[i, j].x > 1e-6:
                    print(f"Complaint {complaints[i]['complaint_id']} assigned to Staff {staff_capacity[j]['staff_id']}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

# Run the optimization
optimize_customer_complaints()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 8.0
**Execution Time**: 1.06 seconds
**Reliability**: high
**Analysis**: Gurobipy successfully found an optimal solution with the lowest execution time among the solvers, indicating efficient performance.

## 6. DOCplex Implementation

```python
# Complete DOCPLEX implementation

from docplex.mp.model import Model

def optimize_customer_complaints():
    """Optimize the allocation of staff to manage customer complaints."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="customer_complaints")
    
    # Data from the database
    resolution_times = [2, 3, 3]  # From Complaints table
    max_complaints = [5, 7, 6]    # From StaffCapacity table
    
    n_complaints = len(resolution_times)
    n_staff = len(max_complaints)
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(resolution_times) == n_complaints, "Resolution times length mismatch"
    assert len(max_complaints) == n_staff, "Max complaints length mismatch"
    
    # Safe range for indexing
    safe_complaints_range = range(n_complaints)
    safe_staff_range = range(n_staff)
    
    # 2. VARIABLES
    # Binary decision variables: x[i][j] = 1 if complaint i is assigned to staff j
    x = {(i, j): mdl.binary_var(name=f"x_{i}_{j}") for i in safe_complaints_range for j in safe_staff_range}
    
    # 3. OBJECTIVE FUNCTION
    # Minimize the total resolution time
    objective = mdl.sum(resolution_times[i] * x[i, j] for i in safe_complaints_range for j in safe_staff_range)
    mdl.minimize(objective)
    
    # 4. CONSTRAINTS
    
    # Each complaint must be assigned to exactly one staff member
    for i in safe_complaints_range:
        mdl.add_constraint(mdl.sum(x[i, j] for j in safe_staff_range) == 1, ctname=f"assign_complaint_{i}")
    
    # The number of complaints assigned to each staff member must not exceed their capacity
    for j in safe_staff_range:
        mdl.add_constraint(mdl.sum(x[i, j] for i in safe_complaints_range) <= max_complaints[j], ctname=f"staff_capacity_{j}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_complaints_range:
            for j in safe_staff_range:
                if solution.get_value(x[i, j]) > 1e-6:
                    print(f"Complaint {i} assigned to Staff {j}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")

    return mdl

# Run the optimization
optimize_customer_complaints()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 8.0
**Execution Time**: 1.11 seconds
**Reliability**: high
**Analysis**: DOCplex also found an optimal solution with a slightly higher execution time than Gurobipy, but still within an acceptable range.

## 7. Pyomo Implementation

```python
# Complete PYOMO implementation

import pyomo.environ as pyo
from pyomo.opt import SolverFactory

def optimize_customer_complaints():
    """Optimize the allocation of staff to manage customer complaints"""

    # 1. MODEL CREATION
    model = pyo.ConcreteModel()

    # 2. DATA SETUP
    # Example data based on the provided database schema and stored values
    complaints = [1, 2, 3]
    staff_members = [1, 2, 3]
    resolution_times = {1: 2, 2: 3, 3: 3}
    max_complaints = {1: 5, 2: 7, 3: 6}

    # CRITICAL: Validate array lengths before indexing
    assert len(complaints) == len(resolution_times), "Array length mismatch for complaints and resolution times"
    assert len(staff_members) == len(max_complaints), "Array length mismatch for staff members and max complaints"

    # 3. SETS
    model.I = pyo.Set(initialize=complaints)
    model.J = pyo.Set(initialize=staff_members)

    # 4. PARAMETERS
    model.resolution_time = pyo.Param(model.I, initialize=resolution_times)
    model.max_complaints = pyo.Param(model.J, initialize=max_complaints)

    # 5. VARIABLES
    model.x = pyo.Var(model.I, model.J, within=pyo.Binary)

    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.resolution_time[i] * model.x[i, j] for i in model.I for j in model.J)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)

    # 7. CONSTRAINTS
    # Each complaint must be assigned to exactly one staff member
    def assignment_rule(model, i):
        return sum(model.x[i, j] for j in model.J) == 1
    model.assignment_constraint = pyo.Constraint(model.I, rule=assignment_rule)

    # The number of complaints assigned to each staff member must not exceed their maximum handling capacity
    def capacity_rule(model, j):
        return sum(model.x[i, j] for i in model.I) <= model.max_complaints[j]
    model.capacity_constraint = pyo.Constraint(model.J, rule=capacity_rule)

    # 8. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')

    # Optional: Set solver options
    solver.options['TimeLimit'] = 300  # 5 minutes
    solver.options['MIPGap'] = 0.01    # 1% gap

    # Solve the model
    results = solver.solve(model, tee=True)

    # 9. RESULT PROCESSING
    # Check solver status
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective)}")

        # Extract variable values
        print("\nAssignment of complaints to staff members:")
        for i in model.I:
            for j in model.J:
                if pyo.value(model.x[i, j]) > 0.5:  # Binary variable, check if assigned
                    print(f"Complaint {i} assigned to Staff {j}")

    elif results.solver.termination_condition == pyo.TerminationCondition.infeasible:
        print("Problem is infeasible")
    elif results.solver.termination_condition == pyo.TerminationCondition.unbounded:
        print("Problem is unbounded")
    else:
        print(f"Solver terminated with condition: {results.solver.termination_condition}")

    return model

# Run the optimization
optimize_customer_complaints()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 8.0
**Execution Time**: 1.93 seconds
**Reliability**: high
**Analysis**: Pyomo achieved an optimal solution, albeit with the highest execution time. This suggests it is less efficient but still reliable.

## 8. Cross-Solver Analysis and Final Recommendation

### Solver Results Comparison

| Solver | Status | Optimal Value | Execution Time | Decision Variables | Retry Attempt |
|--------|--------|---------------|----------------|-------------------|---------------|
| Gurobipy | OPTIMAL | 8.00 | 1.06s | N/A | N/A |
| Docplex | OPTIMAL | 8.00 | 1.11s | N/A | N/A |
| Pyomo | OPTIMAL | 8.00 | 1.93s | N/A | N/A |

### Solver Consistency Analysis
**Result**: All solvers produced consistent results ✓
**Consistent Solvers**: gurobipy, docplex, pyomo
**Majority Vote Optimal Value**: 8.0

### Final Recommendation
**Recommended Optimal Value**: 8.0
**Confidence Level**: HIGH
**Preferred Solver(s)**: gurobipy
**Reasoning**: Gurobipy is recommended due to its optimal solution and the fastest execution time, making it the most efficient choice for this problem.

### Business Interpretation
**Overall Strategy**: The optimal resolution time of 8.0 indicates efficient allocation of complaints to staff, minimizing total resolution time.
**Objective Value Meaning**: The optimal objective value of 8.0 represents the minimized total resolution time for all complaints, indicating efficient resource allocation.
**Resource Allocation Summary**: Each complaint is assigned to a staff member in a way that minimizes total resolution time while respecting capacity constraints.
**Implementation Recommendations**: Implement the solution by assigning complaints to staff as per the decision variables, ensuring adherence to capacity constraints and monitoring resolution times for continuous improvement.