# GUÍA DE INSTALACIÓN Y CONFIGURACIÓN - SIIGO Importer

## 1. INSTALACIÓN INICIAL

### Paso 1: Copiar Archivos

La carpeta `siigo-importer` ya está en:
```
c:\Users\Asus\Downloads\SIIGO\wp-content\plugins\siigo-importer\
```

Si tienes WordPress en otra ubicación, copia esta carpeta a:
```
[ruta-wordpress]\wp-content\plugins\siigo-importer\
```

### Paso 2: Verificar Dependencias Python

Abre terminal/cmd y ejecuta:
```bash
python -m pip install pandas openpyxl
```

O:
```bash
pip install pandas openpyxl
```

### Paso 3: Verificar Permisos de Carpetas

Asegúrate que las siguientes carpetas son escribibles:
- `wp-content/uploads/` (para archivos temporales)
- `wp-content/plugins/siigo-importer/configs/` (para guardar mapeos)

**En Linux/Mac:**
```bash
chmod 755 wp-content/uploads/
chmod 755 wp-content/plugins/siigo-importer/configs/
```

### Paso 4: Activar Plugin en WordPress

1. Login en Panel de Admin
2. Ve a **Plugins**
3. Busca "SIIGO Importer"
4. Haz clic en **Activar**

## 2. CONFIGURACIÓN IMPORTANTE

### Detectar Python Automáticamente ✅

El plugin intenta detectar Python automáticamente. Para verificar que funciona:

1. Ve a **SIIGO Importer → Historial**
2. Sube un archivo Excel pequeño
3. Si ves "Procesando...", está funcionando
4. Si ves error, sigue el siguiente paso

### Si Python No Se Detecta (Solución Manual)

Edita: `wp-content/plugins/siigo-importer/controllers/SiigoExcelController.php`

Busca esta línea (línea ~30):
```php
private $python_path = 'python';
```

Y reemplázala con la ruta completa de tu Python:

**En Windows:**
```php
private $python_path = 'C:\\Program Files\\Python39\\python.exe';
// O donde esté instalado tu Python
```

**En Linux/Mac:**
```php
private $python_path = '/usr/bin/python3';
// O /usr/local/bin/python3, etc.
```

Para encontrar la ruta, ejecuta en terminal:
```bash
which python3  # Linux/Mac
where python   # Windows
```

## 3. PRUEBA DEL PLUGIN

### Test 1: Con Archivo DIAN

1. Ve a **SIIGO Importer → Cargar Excel**
2. Sube el archivo: `EMPRESA 13/e6805911-98f4-4649-b685-8d2b922c722a.xlsx`
3. Haz clic en **Procesar Archivo**
4. Debería:
   - ✓ Detectar formato: DIAN
   - ✓ Validar columnas: OK
   - ✓ Mostrar éxito
   - ✓ Permitir descargar plano

### Test 2: Con Archivo SIIGO

1. Ve a **SIIGO Importer → Cargar Excel**
2. Sube: `COMPRAS ABRIL CORTE 14.xlsx`
3. Debería:
   - ✓ Detectar formato: SIIGO
   - ✓ Validar columnas: OK
   - ✓ Mostrar éxito

### Test 3: Ver Historial

1. Ve a **SIIGO Importer → Historial**
2. Deberías ver logs de ambos procesamientos

## 4. ESTRUCTURA FINAL CREADA

```
wp-content/plugins/siigo-importer/
│
├── plugin.php                              [Plugin principal]
│
├── controllers/
│   └── SiigoExcelController.php           [Controlador principal]
│
├── admin/
│   ├── page.php                           [Página de admin con UI]
│   └── assets/
│       ├── style.css                      [Estilos]
│       └── script.js                      [JavaScript AJAX]
│
├── python/
│   ├── config.py                          [Configuraciones]
│   ├── utils.py                           [Funciones auxiliares]
│   ├── detectar_formato.py                [Detecta DIAN/SIIGO]
│   ├── mapeo_dinamico.py                  [Mapea columnas]
│   ├── validar_columnas.py                [Valida críticas]
│   └── generar_plano.py                   [Genera plano final]
│
├── includes/
│   └── Logger.php                         [Sistema de logging]
│
├── configs/
│   └── mapeos_cliente.json                [Mapeos guardados]
│
└── README.md                              [Documentación]
```

## 5. FLUJO OPERATIVO

Cuando el usuario sube un Excel:

```
Usuario sube archivo
    ↓ (AJAX)
PHP Controller recibe
    ↓
Valida tipo MIME
    ↓
Ejecuta: python detectar_formato.py
    ↓ (Identifica DIAN/SIIGO)
Ejecuta: python validar_columnas.py
    ↓ (Verifica 18 críticas)
Ejecuta: python mapeo_dinamico.py
    ↓ (Mapea columnas automáticamente)
¿Todas las críticas presentes?
    ├─→ SÍ: Genera plano SIIGO
    ├─→ NO: Muestra interface mapeo manual
         ↓ (Usuario mapea)
         ↓ (Vuelve a generar)
    ↓
Descarga archivo
```

## 6. AJUSTES PARA PRODUCCIÓN

### 6.1 Cambiar Timeout AJAX

Si los archivos son muy grandes y tardan, aumenta el timeout en:
`admin/assets/script.js`, línea ~80:

```javascript
timeout: 120000, // 2 minutos - cambiar a 300000 (5 min) si es necesario
```

### 6.2 Limitar Tamaño de Archivo

En `controllers/SiigoExcelController.php`, agregar validación:

```php
// En método procesar_archivo()
if ($archivo['size'] > 50 * 1024 * 1024) { // 50MB
    throw new Exception('Archivo demasiado grande. Máximo 50MB.');
}
```

### 6.3 Backup de Configuraciones

Haz backup periódico de:
```
wp-content/plugins/siigo-importer/configs/mapeos_cliente.json
```

## 7. PRÓXIMOS PASOS (Opcional)

### Agregar Generación de Egresos

El plugin está preparado para:
```php
// En SiigoExcelController.php, método ejecutar_generacion()
// Se puede extender para llamar a generar_egresos_siigo.py
```

### Integrar Base de Datos

Reemplazar JSON con tabla WP:
```php
// En Logger.php, agregar:
// 1. Tabla de configuraciones
// 2. Tabla de historial
// 3. Tabla de mapeos por cliente
```

## 8. SOPORTE Y DEBUGGING

### Ver Logs en Tiempo Real

```bash
# Linux/Mac
tail -f wp-content/uploads/siigo_logs/siigo_*.log

# Windows (PowerShell)
Get-Content wp-content/uploads/siigo_logs/siigo_*.log -Wait
```

### Probar Scripts Python Manualmente

```bash
cd wp-content/plugins/siigo-importer/python

# Test detectar formato
python detectar_formato.py /ruta/archivo.xlsx

# Test validar columnas
python validar_columnas.py /ruta/archivo.xlsx

# Test mapeo
python mapeo_dinamico.py /ruta/archivo.xlsx DIAN
```

### Debug Mode

Edita `includes/Logger.php` y cambia:
```php
private $debug = false;
// a
private $debug = true;
```

## 9. CONTACTO Y SOPORTE

Si encuentras problemas:

1. Revisa **SIIGO Importer → Historial**
2. Busca el error en los logs
3. Intenta probar el script Python manualmente
4. Verifica que Python esté correctamente configurado

---

**Versión**: 1.0.0  
**Creado**: 2026-05-02  
**Estado**: ✅ Listo para instalar
