# TEMPLATE: MODIFICAR HORARIOS DE SERVICIO
# Fecha: _____________
# Servicio(s) afectado(s): _____________

## DATOS DEL CAMBIO

### Servicio(s) a modificar:
- [ ] Número: _______________ Alias: _______________
- [ ] Número: _______________ Alias: _______________
- [ ] Número: _______________ Alias: _______________

### Nuevo horario:
- [ ] 24x7 (sin restricciones)
- [ ] Horario específico:
  
  **Lunes a Viernes**:
  - Apertura: ___:___
  - Cierre: ___:___
  
  **Sábados**:
  - [ ] Cerrado
  - [ ] Mismo horario L-V
  - [ ] Horario especial: ___:___ a ___:___
  
  **Domingos y festivos**:
  - [ ] Cerrado
  - [ ] Horario especial: ___:___ a ___:___

### Mensaje fuera de horario:
- [ ] Usar mensaje estándar
- [ ] Mensaje personalizado: _______________

### Comportamiento fuera de horario:
- [ ] Colgar tras mensaje
- [ ] Desviar a buzón
- [ ] Desviar a número: _______________
- [ ] Desviar a servicio 24h: _______________

## IMPLEMENTACIÓN

### OPCIÓN A: MODIFICACIÓN EN PYTHON (Recomendada)

#### 1. BACKUP
```bash
# Ejecutado por: _______________ Fecha/Hora: _______________
cp /var/lib/asterisk/agi-bin/call_system/processors/trunk_processor.py \
   /var/lib/asterisk/agi-bin/call_system/processors/trunk_processor.py.backup_$(date +%Y%m%d_%H%M%S)
```

#### 2. MODIFICAR trunk_processor.py
```python
# Localizar o agregar función check_service_hours()

def check_service_hours(self, service_number):
    """Verifica si el servicio está en horario"""
    from datetime import datetime
    
    now = datetime.now()
    hour = now.hour
    minute = now.minute
    weekday = now.weekday()  # 0=Lunes, 6=Domingo
    
    # Definir horarios por servicio
    service_hours = {
        '_______________': {  # Número servicio
            'weekdays': (_____, _____),      # (hora_inicio, hora_fin)
            'saturday': (_____, _____),      # o None si cerrado
            'sunday': None,                  # o tupla horario
            'holidays': None                 # implementar si necesario
        }
    }
    
    if service_number not in service_hours:
        return True  # Sin restricción = siempre abierto
    
    hours = service_hours[service_number]
    
    # Determinar horario según día
    if weekday < 5:  # Lunes a Viernes
        schedule = hours.get('weekdays')
    elif weekday == 5:  # Sábado
        schedule = hours.get('saturday')
    else:  # Domingo
        schedule = hours.get('sunday')
    
    if schedule is None:
        return False  # Cerrado este día
    
    start_hour, end_hour = schedule
    current_time = hour + (minute / 60.0)
    
    return start_hour <= current_time < end_hour

# En el método process():
if not self.check_service_hours(self.service_number):
    self.log_processor_step("FUERA_HORARIO", 
                           f"Servicio {self.service_number} fuera de horario")
    self.agi.playback("_______________")  # archivo mensaje
    return "hangup"
```

### OPCIÓN B: TABLA EN BASE DE DATOS

#### 1. BACKUP DE BD
```bash
# Ejecutado por: _______________ Fecha/Hora: _______________
mysqldump -u asteriskuser -p asterisk > backup_asterisk_horarios_$(date +%Y%m%d_%H%M%S).sql
```

#### 2. CREAR/MODIFICAR TABLA
```sql
-- Si no existe la tabla
CREATE TABLE IF NOT EXISTS service_hours (
    id INT AUTO_INCREMENT PRIMARY KEY,
    service_number VARCHAR(50) NOT NULL,
    day_of_week TINYINT NOT NULL COMMENT '0=Dom, 1=Lun...6=Sab',
    start_time TIME,
    end_time TIME,
    active TINYINT DEFAULT 1,
    out_of_hours_action VARCHAR(50) DEFAULT 'hangup',
    out_of_hours_destination VARCHAR(50),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_service_day (service_number, day_of_week),
    INDEX idx_active (active)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Limpiar horarios anteriores del servicio
DELETE FROM service_hours WHERE service_number = '_______________';

-- Insertar nuevos horarios
-- Lunes a Viernes
INSERT INTO service_hours (service_number, day_of_week, start_time, end_time)
VALUES 
    ('_______________', 1, '___:___:00', '___:___:00'),  -- Lunes
    ('_______________', 2, '___:___:00', '___:___:00'),  -- Martes
    ('_______________', 3, '___:___:00', '___:___:00'),  -- Miércoles
    ('_______________', 4, '___:___:00', '___:___:00'),  -- Jueves
    ('_______________', 5, '___:___:00', '___:___:00');  -- Viernes

-- Sábados (si aplica)
INSERT INTO service_hours (service_number, day_of_week, start_time, end_time)
VALUES ('_______________', 6, '___:___:00', '___:___:00');

-- Domingos (si aplica)
INSERT INTO service_hours (service_number, day_of_week, start_time, end_time)
VALUES ('_______________', 0, '___:___:00', '___:___:00');
```

#### 3. MODIFICAR PYTHON PARA USAR BD
```python
def check_service_hours_db(self, service_number):
    """Verifica horario desde base de datos"""
    sql = """
    SELECT COUNT(*) as is_open
    FROM service_hours
    WHERE service_number = %s
    AND day_of_week = DAYOFWEEK(NOW()) - 1
    AND NOW() BETWEEN CONCAT(CURDATE(), ' ', start_time) 
                  AND CONCAT(CURDATE(), ' ', end_time)
    AND active = 1
    """
    
    result = self.execute_db_query(sql, (service_number,), fetch_one=True)
    
    if result and result['is_open'] > 0:
        return True
    
    # Verificar acción fuera de horario
    sql_action = """
    SELECT DISTINCT out_of_hours_action, out_of_hours_destination
    FROM service_hours
    WHERE service_number = %s
    LIMIT 1
    """
    action_result = self.execute_db_query(sql_action, (service_number,), fetch_one=True)
    
    if action_result:
        self.out_of_hours_action = action_result['out_of_hours_action']
        self.out_of_hours_destination = action_result['out_of_hours_destination']
    
    return False
```

### OPCIÓN C: ARCHIVO DE CONFIGURACIÓN

#### 1. CREAR ARCHIVO JSON
```bash
# /etc/centralita-tarot/service_hours.json
{
    "_______________": {
        "name": "_______________",
        "schedule": {
            "monday": {"start": "___:___", "end": "___:___"},
            "tuesday": {"start": "___:___", "end": "___:___"},
            "wednesday": {"start": "___:___", "end": "___:___"},
            "thursday": {"start": "___:___", "end": "___:___"},
            "friday": {"start": "___:___", "end": "___:___"},
            "saturday": null,
            "sunday": null
        },
        "out_of_hours": {
            "message": "fuera-de-horario",
            "action": "hangup"
        }
    }
}
```

#### 2. MODIFICAR PYTHON
```python
import json
from datetime import datetime

def load_service_hours(self):
    """Carga configuración de horarios desde JSON"""
    try:
        with open('/etc/centralita-tarot/service_hours.json', 'r') as f:
            return json.load(f)
    except:
        self.logger.error("No se pudo cargar service_hours.json")
        return {}
```

## PRUEBAS

### Test 1: Verificar horario actual
```sql
-- Ver qué servicios deberían estar abiertos ahora
SELECT 
    service_number,
    day_of_week,
    start_time,
    end_time,
    CASE 
        WHEN NOW() BETWEEN CONCAT(CURDATE(), ' ', start_time) 
                      AND CONCAT(CURDATE(), ' ', end_time)
             AND day_of_week = DAYOFWEEK(NOW()) - 1
        THEN 'ABIERTO'
        ELSE 'CERRADO'
    END as estado_actual
FROM service_hours
WHERE service_number = '_______________'
AND active = 1;
```

### Test 2: Simular llamada en horario
```bash
# Durante horario de servicio
asterisk -rx "originate PJSIP/200 extension _______________@from-trunk"

# Verificar en log
tail -f /var/log/asterisk/python_call_system.log | grep "_______________"
```

### Test 3: Simular llamada fuera de horario
```bash
# Cambiar hora del sistema temporalmente (CUIDADO en producción)
# O modificar el código para forzar prueba

# Verificar que:
# - Se reproduce mensaje fuera de horario
# - La llamada se corta o desvía según configuración
```

### Test 4: Verificar cambio de día
```bash
# Verificar que el cambio L-V a Sábado funcione
# Programar prueba automática o revisar logs del día siguiente
```

## VERIFICACIÓN POST-IMPLEMENTACIÓN

### Inmediata:
- [ ] Llamadas en horario entran normal
- [ ] Llamadas fuera de horario reciben mensaje
- [ ] No hay errores en logs
- [ ] Otros servicios no afectados

### Primer día completo:
- [ ] Apertura correcta en la mañana
- [ ] Cierre correcto en la noche
- [ ] Comportamiento correcto fin de semana

### Primera semana:
- [ ] Estadísticas de llamadas rechazadas por horario
- [ ] Feedback de usuarios/clientes
- [ ] Ajustes necesarios

## ROLLBACK

### Si hay problemas:

#### 1. Restaurar código Python
```bash
cp /var/lib/asterisk/agi-bin/call_system/processors/trunk_processor.py.backup_[FECHA] \
   /var/lib/asterisk/agi-bin/call_system/processors/trunk_processor.py
```

#### 2. O desactivar en BD
```sql
-- Desactivar temporalmente todos los horarios
UPDATE service_hours SET active = 0 WHERE service_number = '_______________';

-- O eliminar completamente
DELETE FROM service_hours WHERE service_number = '_______________';
```

#### 3. Verificar funcionamiento
```bash
# Hacer llamada de prueba
asterisk -rx "originate PJSIP/200 extension _______________@from-trunk"
```

## COMUNICACIÓN

### A usuarios internos:
```
Asunto: Cambio de horario - Servicio _______________

A partir del ___/___/___, el servicio _______________ 
tendrá el siguiente horario:

Lunes a Viernes: ___:___ a ___:___
Sábados: _______________
Domingos: _______________

Fuera de este horario, los clientes escucharán:
_______________

Por favor, informar a los agentes asignados.
```

### A clientes (si aplica):
- [ ] Actualizar web con nuevos horarios
- [ ] Email informativo
- [ ] SMS si hay base de clientes

## DOCUMENTACIÓN

### Actualizar:
- [ ] Wiki interna con horarios de todos los servicios
- [ ] Manual de operaciones
- [ ] Guía de agentes

### CHANGELOG
```bash
echo "## [$(date +%Y-%m-%d)] - Modificación horarios
- Servicio: _______________
- Horario anterior: _______________
- Horario nuevo: _______________
- Mensaje fuera horario: _______________
- Implementado por: _______________" >> /var/www/html/CHANGELOG.md
```

## CONSIDERACIONES ESPECIALES

### Festivos:
- [ ] Definir calendario de festivos
- [ ] Implementar lógica especial para festivos
- [ ] Considerar festivos locales/nacionales

### Cambios de hora (verano/invierno):
- [ ] Verificar que el sistema use hora local correcta
- [ ] Probar comportamiento en cambio de hora

### Mensajes especiales:
- [ ] Mensaje de "cerraremos en X minutos"
- [ ] Mensaje especial para festivos
- [ ] Mensaje de emergencia/mantenimiento

## MONITOREO POST-CAMBIO

```bash
# Script para monitorear rechazos por horario
cat > /tmp/monitor_horario.sh << 'EOF'
#!/bin/bash
echo "=== Llamadas rechazadas por horario - $(date) ==="
grep "FUERA_HORARIO" /var/log/asterisk/python_call_system.log | \
grep "$(date +%Y-%m-%d)" | wc -l
EOF

chmod +x /tmp/monitor_horario.sh
```

## NOTAS/OBSERVACIONES

_________________________________
_________________________________
_________________________________

## FIRMAS

Solicitado por: _______________ Fecha: _______________
Implementado por: _______________ Fecha: _______________
Verificado por: _______________ Fecha: _______________
Comunicado a agentes: _______________ Fecha: _______________