excel-planner/export/google_sheet_sync.py
juan.pelaez 27d759ace8 Agregar integracion Excel-Planner con tablero RTC Sapian.
Puente Power Automate, servidor local del tablero HTML v7 y exportacion a Excel/TSV para monitoreo de proyectos en Microsoft Planner.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-10 13:44:38 -05:00

61 lines
1.8 KiB
Python

"""
Sincroniza filas del tablero RTC con Google Sheets.
Requiere una cuenta de servicio con acceso de edicion a la hoja que publica el HTML.
"""
from __future__ import annotations
from pathlib import Path
from config import GOOGLE_CREDENTIALS_PATH, GOOGLE_SHEET_NAME, GOOGLE_SPREADSHEET_ID
class GoogleSheetSyncError(Exception):
pass
def validate_google_config() -> list[str]:
missing = []
if not GOOGLE_SPREADSHEET_ID:
missing.append("GOOGLE_SPREADSHEET_ID")
if not GOOGLE_CREDENTIALS_PATH:
missing.append("GOOGLE_CREDENTIALS_PATH")
elif not Path(GOOGLE_CREDENTIALS_PATH).is_file():
missing.append("GOOGLE_CREDENTIALS_PATH (archivo no encontrado)")
return missing
def sync_rows_to_google_sheet(rows: list[list[str]]) -> int:
"""
Reemplaza el contenido de la hoja configurada con las filas dadas.
Devuelve la cantidad de filas escritas (sin contar encabezado).
"""
missing = validate_google_config()
if missing:
raise GoogleSheetSyncError(
"Faltan variables para sincronizar Google Sheets: " + ", ".join(missing)
)
try:
import gspread
from google.oauth2.service_account import Credentials
except ImportError as exc:
raise GoogleSheetSyncError(
"Instala dependencias: pip install gspread google-auth"
) from exc
scopes = ["https://www.googleapis.com/auth/spreadsheets"]
credentials = Credentials.from_service_account_file(
GOOGLE_CREDENTIALS_PATH,
scopes=scopes,
)
client = gspread.authorize(credentials)
spreadsheet = client.open_by_key(GOOGLE_SPREADSHEET_ID)
worksheet = spreadsheet.worksheet(GOOGLE_SHEET_NAME)
worksheet.clear()
worksheet.update(rows, value_input_option="RAW")
data_rows = max(len(rows) - 1, 0)
return data_rows