Metadata-Version: 2.4
Name: soxlib
Version: 0.1.2
Summary: Utilidades para Google Sheets, Drive y webhooks de Google Chat.
Author-email: Miguel Gallegos Gracia <mgallegos.gracia@gmail.com>
License-Expression: GPL-3.0-or-later
Project-URL: Homepage, https://github.com/your-user/soxlib
Project-URL: Repository, https://github.com/your-user/soxlib.git
Project-URL: Issues, https://github.com/your-user/soxlib/issues
Keywords: google-sheets,google-drive,google-chat,pandas,webhooks
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.8
Classifier: Operating System :: OS Independent
Classifier: Intended Audience :: Developers
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: google-api-python-client>=2.0.0
Requires-Dist: google-auth>=2.0.0
Requires-Dist: google-auth-oauthlib>=1.0.0
Requires-Dist: pydrive>=1.3.1
Requires-Dist: pandas>=1.5.0
Requires-Dist: pandasql>=0.7.3
Requires-Dist: requests>=2.31.0
Requires-Dist: tabulate>=0.9.0
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Requires-Dist: build>=1; extra == "dev"
Requires-Dist: twine>=5; extra == "dev"
Dynamic: license-file

# soxlib

Utilidades para **Google Sheets**, **Google Drive**, **webhooks de Google Chat** y **calendario de operaciones** con soporte para `pandas` y `pandasql`.

Incluye helpers para leer/escribir hojas, subir archivos a Drive, enviar resultados a Chat y actualizar calendarios históricos de forma incremental.

## Instalación

```bash
pip install soxlib
```

Para desarrollo local:

```bash
pip install -e ".[dev]"
```

## Requisitos previos

- **Python ≥ 3.8**
- **Credenciales OAuth**: coloca `client_secret.json` y `credentials.json` en `scripts/utils/` (o pasa una ruta distinta a `create_login`). El flujo generará `token.pickle` al primer uso.
- **Archivo `scripts/utils/directorio.json`** con la configuración de IDs de Sheets y webhooks. Ejemplo mínimo:

```json
{
  "mi_tabla": {
    "GOOGLE_SHEET_ID_FUNCIONAL": "1AbcDEFghi...",
    "GOOGLE_SHEET_ID_VISTA_0": "",
    "FILTRO_VISTA_0": "",
    "ARCHIVO": "mi_archivo.csv"
  },
  "mi_webhook": {
    "GOOGLE_SHEET_ID_FUNCIONAL": "https://chat.googleapis.com/v1/spaces/.../messages?key=...&token=..."
  }
}
```

## Módulos

### Google Sheets / Drive / Chat (`soxlib.gsu`)

| Función | Descripción |
|---|---|
| `lee_hoja_datos(nombre, cloud=True)` | Lee una hoja (Google Sheets o CSV local) a DataFrame. |
| `actualiza_hoja_datos(df, nombre, overwrite=True, cloud=True)` | Escribe un DataFrame en Sheets y vista opcional. |
| `enviar_dataframe_a_google_chat(df, webhook_name)` | Envía un DataFrame tabulado a un webhook de Google Chat. |
| `enviar_mensaje_simple_a_google_chat(msg, webhook_name)` | Envía un mensaje de texto plano al webhook. |
| `sube_archivo(path, mime_type="image/png")` | Sube archivos a Drive y devuelve el ID. |
| `sox_enviar_imagen_a_google_chat(path, webhook_name)` | Sube imagen a Drive y envía enlace al webhook. |
| `create_login(client_secret_path=...)` | Crea un cliente de Sheets autenticado. |
| `gsheets_to_dataframe(...)` | Convierte hojas de Google Sheets a DataFrame. |
| `get_all_sheets_data(...)` | Obtiene datos de todas las hojas de un Spreadsheet. |
| `filtrar_dataframe(df, filtros)` | Filtra un DataFrame con condiciones dinámicas. |
| `guardar_y_subir_gs(df, nombre)` | Guarda como CSV local y sube a Google Sheets. |
| `imprimir_tabla(df)` | Imprime un DataFrame como tabla formateada. |
| `estrella_5_picos_ascii()` | Devuelve arte ASCII decorativo. |

### Calendario (`soxlib.calendar`)

| Función | Descripción |
|---|---|
| `cal_update(table_1, table_2, table_3, ...)` | Actualiza un calendario histórico a partir de datos nuevos, respetando excepciones. |

### Core (`soxlib.core`)

| Función | Descripción |
|---|---|
| `add(a, b)` | Suma dos números (función base de la biblioteca). |

## Ejemplos rápidos

### Google Sheets y Chat

```python
from soxlib import (
    lee_hoja_datos,
    actualiza_hoja_datos,
    enviar_dataframe_a_google_chat,
    sox_enviar_imagen_a_google_chat,
)

df = lee_hoja_datos("mi_tabla")
df_filtrado = df[df["status"] == "OK"]
actualiza_hoja_datos(df_filtrado, "mi_tabla")
enviar_dataframe_a_google_chat(df_filtrado, "mi_webhook")
sox_enviar_imagen_a_google_chat("imagen.png", "mi_webhook")
```

### Calendario

```python
from soxlib import cal_update

resultado = cal_update(
    datos,              # DataFrame con ejecuciones (key, fecha, status)
    calendario,         # DataFrame histórico con columnas de fecha
    especialidad,       # DataFrame auxiliar (o None)
    col_key="JOBNAME",
    col_date="RUN DATE",
    col_info="STATUS",
    month_window=6,
    exceptions=["FORK", "RECUP", "INC"],
)
```

## Estructura del proyecto

```
soxlib/
├── src/soxlib/
│   ├── __init__.py      # Exports públicos y versión
│   ├── core.py          # Función base (add)
│   ├── gsu.py           # Google Sheets, Drive y Chat
│   └── calendar.py      # Actualización de calendarios
├── tests/
│   ├── test_core.py     # Tests de core
│   ├── test_gsu.py      # Tests de gsu
│   └── test_calendar.py # Tests de calendar
├── pyproject.toml
├── README.md
└── LICENSE
```

## Desarrollo

1. Crear y activar un entorno virtual.
2. Instalar dependencias de desarrollo:
   ```bash
   pip install -e ".[dev]"
   ```
3. Ejecutar pruebas:
   ```bash
   pytest
   ```
4. Construir el paquete:
   ```bash
   python -m build
   ```
5. Publicar en TestPyPI/PyPI:
   ```bash
   twine upload dist/*
   ```

## Licencia

GPLv3+. Ver [LICENSE](LICENSE).
