# Complete Optimization Problem and Solution: customer_complaints

## 1. Problem Context and Goals

### Context  
The company operates in a customer service environment where handling complaints efficiently is critical to maintaining customer satisfaction and operational cost-effectiveness. The primary business decision revolves around assigning staff members to customer complaints in a way that minimizes the total cost of handling these complaints. The cost is directly influenced by the time each staff member spends on each complaint and their respective hourly wages. 

Each complaint has specific time requirements, defined by a minimum and maximum time needed for resolution. Staff members also have individual maximum working hours, ensuring that no one is overburdened. The goal is to allocate time spent by staff on complaints in a manner that respects these constraints while minimizing the total cost. This problem naturally lends itself to a linear optimization formulation, as the relationships between time spent, wages, and constraints are all proportional and additive.

### Goals  
The optimization goal is to minimize the total cost of handling customer complaints. This cost is calculated as the sum of the time each staff member spends on each complaint multiplied by their hourly wage. Success is measured by achieving the lowest possible total cost while ensuring that all complaints are fully addressed within the specified time bounds and that no staff member exceeds their maximum working hours. The objective is linear, as it involves summing products of time and wage, both of which are fixed parameters in this context.

## 2. Constraints  

The optimization problem must adhere to the following constraints:  
1. **Complaint Assignment Constraint**: Each complaint must be fully assigned to one or more staff members, ensuring that the total time spent on each complaint sums to exactly one unit of time. This ensures that all complaints are fully addressed.  
2. **Time Bounds Constraint**: The time spent by any staff member on a specific complaint must fall within the predefined minimum and maximum time limits for that complaint. This ensures that complaints are neither rushed nor unnecessarily prolonged.  
3. **Staff Working Hours Constraint**: The total time spent by each staff member across all complaints must not exceed their maximum working hours. This ensures that no staff member is overworked.  

These constraints are linear, as they involve summing time spent and comparing it to fixed bounds, without any multiplicative or divisive relationships between variables.

## 3. Available Data  

### Database Schema  
```sql
-- Iteration 2 Database Schema
-- Objective: Schema changes include creating a new table for the missing decision variable 'time_spent[staff_id, complaint_id]'. Configuration logic remains unchanged as no additional scalar parameters or formulas were identified.

CREATE TABLE staff_wages (
  staff_id INTEGER,
  hourly_wage FLOAT
);

CREATE TABLE complaint_time_constraints (
  complaint_id INTEGER,
  min_time FLOAT,
  max_time FLOAT
);

CREATE TABLE staff_working_hours (
  staff_id INTEGER,
  max_hours FLOAT
);

CREATE TABLE time_spent (
  staff_id INTEGER,
  complaint_id INTEGER,
  time_spent FLOAT
);
```

### Data Dictionary  
- **staff_wages**:  
  - **Purpose**: Stores the hourly wage of each staff member.  
  - **Optimization Role**: Provides the coefficients for the objective function, representing the cost per hour for each staff member.  
  - **Columns**:  
    - `staff_id`: Unique identifier for each staff member.  
    - `hourly_wage`: Hourly wage of the staff member, used to calculate the total cost.  

- **complaint_time_constraints**:  
  - **Purpose**: Defines the minimum and maximum time required to handle each complaint.  
  - **Optimization Role**: Provides the bounds for the time spent on each complaint, ensuring resolutions are neither rushed nor prolonged.  
  - **Columns**:  
    - `complaint_id`: Unique identifier for each complaint.  
    - `min_time`: Minimum time required to handle the complaint.  
    - `max_time`: Maximum time allowed to handle the complaint.  

- **staff_working_hours**:  
  - **Purpose**: Specifies the maximum working hours for each staff member.  
  - **Optimization Role**: Provides the upper bound for the total time each staff member can spend on all complaints.  
  - **Columns**:  
    - `staff_id`: Unique identifier for each staff member.  
    - `max_hours`: Maximum working hours for the staff member.  

- **time_spent**:  
  - **Purpose**: Tracks the time spent by each staff member on each complaint.  
  - **Optimization Role**: Represents the decision variable in the optimization model, determining how time is allocated.  
  - **Columns**:  
    - `staff_id`: Unique identifier for each staff member.  
    - `complaint_id`: Unique identifier for each complaint.  
    - `time_spent`: Time spent by the staff member on the complaint.  

### Current Stored Values  
```sql
-- Iteration 2 Realistic Data
-- Generated by triple expert (business + data + optimization)
-- Values were determined based on industry standards, realistic business scenarios, and ensuring the optimization problem remains solvable. Hourly wages were set to reflect typical salaries for customer service roles. Time constraints for complaints were based on average handling times, and maximum working hours were set to standard full-time workweeks. Time spent values were generated to fall within the min and max time constraints for each complaint.

-- Realistic data for staff_wages
INSERT INTO staff_wages (staff_id, hourly_wage) VALUES (1, 25.0);
INSERT INTO staff_wages (staff_id, hourly_wage) VALUES (2, 30.0);
INSERT INTO staff_wages (staff_id, hourly_wage) VALUES (3, 35.0);

-- Realistic data for complaint_time_constraints
INSERT INTO complaint_time_constraints (complaint_id, min_time, max_time) VALUES (1, 1.0, 3.0);
INSERT INTO complaint_time_constraints (complaint_id, min_time, max_time) VALUES (2, 1.5, 4.0);
INSERT INTO complaint_time_constraints (complaint_id, min_time, max_time) VALUES (3, 2.0, 5.0);

-- Realistic data for staff_working_hours
INSERT INTO staff_working_hours (staff_id, max_hours) VALUES (1, 40.0);
INSERT INTO staff_working_hours (staff_id, max_hours) VALUES (2, 45.0);
INSERT INTO staff_working_hours (staff_id, max_hours) VALUES (3, 50.0);

-- Realistic data for time_spent
INSERT INTO time_spent (staff_id, complaint_id, time_spent) VALUES (1, 1, 1.5);
INSERT INTO time_spent (staff_id, complaint_id, time_spent) VALUES (2, 2, 2.0);
INSERT INTO time_spent (staff_id, complaint_id, time_spent) VALUES (3, 3, 2.5);
```

## 4. Mathematical Optimization Formulation

#### Decision Variables
- \( x_{i,j} \): Time spent by staff member \( i \) on complaint \( j \).  
  - **Type**: Continuous  
  - **Domain**: \( x_{i,j} \geq 0 \)  

#### Objective Function
Minimize the total cost of handling complaints:  
\[
\text{Minimize } Z = \sum_{i} \sum_{j} (\text{hourly\_wage}_i \times x_{i,j})
\]  
- **Coefficient Source**: `staff_wages.hourly_wage`  

#### Constraints
1. **Complaint Assignment Constraint**: Each complaint must be fully assigned to one or more staff members:  
\[
\sum_{i} x_{i,j} = 1 \quad \forall j
\]  
- **Coefficient Source**: Each complaint must sum to exactly 1 unit of time.  

2. **Time Bounds Constraint**: The time spent by any staff member on a specific complaint must fall within the predefined minimum and maximum time limits for that complaint:  
\[
\text{min\_time}_j \leq x_{i,j} \leq \text{max\_time}_j \quad \forall i, j
\]  
- **Coefficient Source**: `complaint_time_constraints.min_time` and `complaint_time_constraints.max_time`  

3. **Staff Working Hours Constraint**: The total time spent by each staff member across all complaints must not exceed their maximum working hours:  
\[
\sum_{j} x_{i,j} \leq \text{max\_hours}_i \quad \forall i
\]  
- **Coefficient Source**: `staff_working_hours.max_hours`  

#### Data Source Verification
- **Objective Function Coefficients**: `staff_wages.hourly_wage`  
- **Complaint Assignment Constraint**: Each complaint must sum to exactly 1 unit of time.  
- **Time Bounds Constraint**: `complaint_time_constraints.min_time` and `complaint_time_constraints.max_time`  
- **Staff Working Hours Constraint**: `staff_working_hours.max_hours`  

This formulation provides a complete, immediately solvable LINEAR mathematical model with all numerical coefficients derived from the provided data.

## 5. Gurobipy Implementation

```python
# Complete GUROBIPY implementation - Retry Attempt 4

import gurobipy as gp
from gurobipy import GRB

def optimize_customer_complaints():
    # 1. MODEL & DATA SETUP
    model = gp.Model("customer_complaints")
    
    # Data from the database
    staff_wages = {1: 25.0, 2: 30.0, 3: 35.0}
    complaint_time_constraints = {
        1: {'min_time': 1.0, 'max_time': 3.0},
        2: {'min_time': 1.5, 'max_time': 4.0},
        3: {'min_time': 2.0, 'max_time': 5.0}
    }
    staff_working_hours = {1: 40.0, 2: 45.0, 3: 50.0}
    
    # Extract staff and complaint IDs
    staff_ids = list(staff_wages.keys())
    complaint_ids = list(complaint_time_constraints.keys())
    
    # CRITICAL: Validate array lengths before loops
    assert len(staff_ids) > 0, "No staff members found"
    assert len(complaint_ids) > 0, "No complaints found"
    
    # 2. VARIABLES
    # Decision variable: time spent by staff member i on complaint j
    x = model.addVars(staff_ids, complaint_ids, vtype=GRB.CONTINUOUS, name="x", lb=0)
    
    # 3. OBJECTIVE FUNCTION
    # Minimize the total cost of handling complaints
    model.setObjective(
        gp.quicksum(staff_wages[i] * x[i, j] for i in staff_ids for j in complaint_ids),
        GRB.MINIMIZE
    )
    
    # 4. CONSTRAINTS
    
    # Complaint Assignment Constraint: Each complaint must be fully assigned
    for j in complaint_ids:
        model.addConstr(
            gp.quicksum(x[i, j] for i in staff_ids) == 1,
            name=f"complaint_assignment_{j}"
        )
    
    # Time Bounds Constraint: Time spent must be within min and max time for each complaint
    for i in staff_ids:
        for j in complaint_ids:
            model.addConstr(
                x[i, j] >= complaint_time_constraints[j]['min_time'],
                name=f"min_time_{i}_{j}"
            )
            model.addConstr(
                x[i, j] <= complaint_time_constraints[j]['max_time'],
                name=f"max_time_{i}_{j}"
            )
    
    # Staff Working Hours Constraint: Total time spent by each staff member must not exceed max hours
    for i in staff_ids:
        model.addConstr(
            gp.quicksum(x[i, j] for j in complaint_ids) <= staff_working_hours[i],
            name=f"staff_hours_{i}"
        )
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in staff_ids:
            for j in complaint_ids:
                if x[i, j].x > 1e-6:
                    print(f"x[{i},{j}] = {x[i, j].x:.3f}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

# Execute the optimization
optimize_customer_complaints()
```

### Execution Results
**Status**: INFEASIBLE
**Error**: Problem is infeasible
**Analysis**: Gurobipy identified the problem as infeasible, indicating that the constraints cannot be satisfied simultaneously. This is a reliable result given Gurobipy's robust algorithms.

## 6. DOCplex Implementation

```python
# Complete DOCPLEX implementation - Retry Attempt 4

from docplex.mp.model import Model

def optimize_customer_complaints():
    # 1. MODEL & DATA SETUP
    mdl = Model(name="customer_complaints_optimization")
    
    # Data from the database
    staff_wages = [
        (1, 25.0),
        (2, 30.0),
        (3, 35.0)
    ]
    
    complaint_time_constraints = [
        (1, 1.0, 3.0),
        (2, 1.5, 4.0),
        (3, 2.0, 5.0)
    ]
    
    staff_working_hours = [
        (1, 40.0),
        (2, 45.0),
        (3, 50.0)
    ]
    
    # Extract unique staff and complaint IDs
    staff_ids = sorted({sw[0] for sw in staff_wages})
    complaint_ids = sorted({ctc[0] for ctc in complaint_time_constraints})
    
    # Create dictionaries for easy access
    hourly_wage = {sw[0]: sw[1] for sw in staff_wages}
    min_time = {ctc[0]: ctc[1] for ctc in complaint_time_constraints}
    max_time = {ctc[0]: ctc[2] for ctc in complaint_time_constraints}
    max_hours = {swh[0]: swh[1] for swh in staff_working_hours}
    
    # 2. VARIABLES
    # Decision variable: time spent by staff member i on complaint j
    x = {(i, j): mdl.continuous_var(name=f"x_{i}_{j}", lb=0) for i in staff_ids for j in complaint_ids}
    
    # 3. OBJECTIVE FUNCTION
    # Minimize the total cost of handling complaints
    total_cost = mdl.sum(hourly_wage[i] * x[i, j] for i in staff_ids for j in complaint_ids)
    mdl.minimize(total_cost)
    
    # 4. CONSTRAINTS
    
    # Complaint Assignment Constraint: Each complaint must be fully assigned
    for j in complaint_ids:
        mdl.add_constraint(mdl.sum(x[i, j] for i in staff_ids) == 1, ctname=f"complaint_assignment_{j}")
    
    # Time Bounds Constraint: Time spent must be within min and max time for each complaint
    for i in staff_ids:
        for j in complaint_ids:
            mdl.add_constraint(x[i, j] >= min_time[j], ctname=f"min_time_{i}_{j}")
            mdl.add_constraint(x[i, j] <= max_time[j], ctname=f"max_time_{i}_{j}")
    
    # Staff Working Hours Constraint: Total time spent by each staff member must not exceed max hours
    for i in staff_ids:
        mdl.add_constraint(mdl.sum(x[i, j] for j in complaint_ids) <= max_hours[i], ctname=f"max_hours_{i}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in staff_ids:
            for j in complaint_ids:
                value = solution.get_value(x[i, j])
                if value > 1e-6:
                    print(f"Time spent by staff {i} on complaint {j}: {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
        if mdl.solve_details.status == "infeasible":
            print("The problem is infeasible. Please check the constraints.")
        elif mdl.solve_details.status == "unbounded":
            print("The problem is unbounded. Please check the objective function.")
    
    return mdl

# Run the optimization
optimize_customer_complaints()
```

### Execution Results
**Status**: INFEASIBLE
**Error**: Problem is infeasible
**Analysis**: DOCplex also concluded that the problem is infeasible, aligning with Gurobipy's result. This consistency reinforces the reliability of the infeasibility diagnosis.

## 7. Pyomo Implementation

```python
# Complete PYOMO implementation - Retry Attempt 4

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

def customer_complaints_optimization():
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Staff data
    staff_ids = [1, 2, 3]
    hourly_wages = {1: 25.0, 2: 30.0, 3: 35.0}
    max_hours = {1: 40.0, 2: 45.0, 3: 50.0}
    
    # Complaint data
    complaint_ids = [1, 2, 3]
    min_time = {1: 1.0, 2: 1.5, 3: 2.0}
    max_time = {1: 3.0, 2: 4.0, 3: 5.0}
    
    # Validate array lengths
    assert len(staff_ids) == len(hourly_wages) == len(max_hours), "Staff data length mismatch"
    assert len(complaint_ids) == len(min_time) == len(max_time), "Complaint data length mismatch"
    
    # 3. SETS
    model.staff = pyo.Set(initialize=staff_ids)
    model.complaints = pyo.Set(initialize=complaint_ids)
    
    # 4. PARAMETERS
    model.hourly_wage = pyo.Param(model.staff, initialize=hourly_wages)
    model.max_hours = pyo.Param(model.staff, initialize=max_hours)
    model.min_time = pyo.Param(model.complaints, initialize=min_time)
    model.max_time = pyo.Param(model.complaints, initialize=max_time)
    
    # 5. VARIABLES
    model.time_spent = pyo.Var(model.staff, model.complaints, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.hourly_wage[i] * model.time_spent[i, j] for i in model.staff for j in model.complaints)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    # Complaint Assignment Constraint
    def complaint_assignment_rule(model, j):
        return sum(model.time_spent[i, j] for i in model.staff) == 1
    model.complaint_assignment = pyo.Constraint(model.complaints, rule=complaint_assignment_rule)
    
    # Time Bounds Constraint
    def time_bounds_rule(model, i, j):
        return (model.min_time[j], model.time_spent[i, j], model.max_time[j])
    model.time_bounds = pyo.Constraint(model.staff, model.complaints, rule=time_bounds_rule)
    
    # Staff Working Hours Constraint
    def staff_hours_rule(model, i):
        return sum(model.time_spent[i, j] for j in model.complaints) <= model.max_hours[i]
    model.staff_hours = pyo.Constraint(model.staff, rule=staff_hours_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)  # tee=True shows solver output
    
    # 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("\nTime spent by staff on complaints:")
        for i in model.staff:
            for j in model.complaints:
                time_val = pyo.value(model.time_spent[i, j])
                if time_val > 1e-6:  # Only print non-zero values
                    print(f"Staff {i} spent {time_val:.3f} hours on complaint {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

# Execute the optimization
if __name__ == "__main__":
    customer_complaints_optimization()
```

### Execution Results
**Status**: INFEASIBLE
**Error**: Problem is infeasible
**Analysis**: Pyomo also reported infeasibility, but its execution time was slightly longer. While the result is consistent with the other solvers, Pyomo's performance is less efficient.

## 8. Cross-Solver Analysis and Final Recommendation

### Solver Results Comparison

| Solver | Status | Optimal Value | Execution Time | Decision Variables | Retry Attempt |
|--------|--------|---------------|----------------|-------------------|---------------|
| Gurobipy | INFEASIBLE | N/A | 0.39s | N/A | 4 |
| Docplex | INFEASIBLE | N/A | 1.34s | N/A | 4 |
| Pyomo | INFEASIBLE | N/A | 1.37s | N/A | 4 |

### Solver Consistency Analysis
**Result**: All solvers produced consistent results ✓
**Consistent Solvers**: gurobipy, docplex, pyomo
**Solver Retry Summary**: gurobipy: 4 attempts, docplex: 4 attempts, pyomo: 4 attempts

### Final Recommendation
**Confidence Level**: HIGH
**Preferred Solver(s)**: gurobipy
**Reasoning**: Gurobipy provided the fastest and most reliable infeasibility diagnosis. Its efficiency and robustness make it the preferred solver for this analysis.

### Business Interpretation
**Overall Strategy**: The problem is infeasible, meaning the current constraints and data inputs do not allow for a valid solution. This suggests that the staffing or time allocation requirements are unrealistic or conflicting.
**Objective Value Meaning**: The objective value represents the total cost of handling complaints. Since the problem is infeasible, no cost can be calculated.
**Resource Allocation Summary**: No valid resource allocation is possible under the current constraints. Re-evaluate the constraints or data inputs to identify feasible adjustments.
**Implementation Recommendations**: 1. Review and relax constraints (e.g., min_time, max_time, max_hours) to make the problem feasible. 2. Verify data inputs for consistency and realism. 3. Consider revising the model formulation to address potential logical errors.