Person / pages /visitas.py
Yofran23's picture
Update pages/visitas.py
8c1f43c verified
Raw
History Blame Contribute Delete
4.31 kB
import streamlit as st
import pandas as pd
from datetime import datetime
import os
import json
import gspread
from google.oauth2.service_account import Credentials
# --- CONFIGURACIÓN DE PÁGINA ---
st.set_page_config(page_title="Registro de Visitas", page_icon="🚗", layout="centered")
st.title("🚗 Registro de Visitas y Traslados")
st.markdown("Completa los datos para registrar el movimiento del personal.")
# --- CARGA DE DATOS (Estados y Municipios) ---
@st.cache_data # Usamos cache para que cargue súper rápido y no lea el excel en cada clic
def cargar_datos_ubicacion():
look = pd.read_csv("Informacion - Estados.csv")
look = look.rename(columns={'Estado': 'ESTADO'})
df_ubicaciones = pd.read_excel('Municipios (1).xlsx', engine='openpyxl')
estados_list = look['ESTADO'].unique().tolist()
return df_ubicaciones, estados_list
df_ubicaciones, estados = cargar_datos_ubicacion()
# --- CONEXIÓN A GOOGLE SHEETS ---
try:
SCOPE = ["https://www.googleapis.com/auth/spreadsheets"]
credenciales_secretas = os.environ.get("GOOGLE_SHEETS_JSON")
creds_dict = json.loads(credenciales_secretas)
CREDS = Credentials.from_service_account_info(creds_dict, scopes=SCOPE)
client = gspread.authorize(CREDS)
sheet_id = "1dDgUALSVyqgMQJTkCxs2kjI3S5IVoggxxias4dEcqb8" # TU ID ACTUAL
workbook = client.open_by_key(sheet_id)
# IMPORTANTE: Crea una pestaña llamada "Visitas" en tu Google Sheets
worksheet = workbook.worksheet("Visitas")
except Exception as e:
worksheet = None
st.sidebar.warning("No hay conexión con Google Sheets.")
# --- INTERFAZ DEL FORMULARIO ---
st.markdown("### 📋 Detalles del Motivo")
motivo = st.radio(
"Selecciona el motivo de la visita*",
["Desarrollo", "Competiciones", "Selecciones"],
horizontal=True,
index=None
)
descripcion = st.text_area("Descripción de la visita (Opcional pero recomendada):",
placeholder="Escribe aquí los detalles, actividades a realizar, personas a contactar, etc.")
st.markdown("---")
# --- SECCIÓN DE ORIGEN Y DESTINO ---
# Usamos columnas para que se vea ordenado en pantallas grandes
col1, col2 = st.columns(2)
with col1:
st.markdown("### 📍 Origen (Salida)")
estado_origen = st.selectbox("Estado de salida:", options=[''] + estados, key="estado_origen")
municipio_origen = None
if estado_origen:
muni_origen_list = df_ubicaciones[df_ubicaciones['ESTADO'] == estado_origen]['MUNICIPIO'].unique().tolist()
municipio_origen = st.selectbox("Municipio de salida:", options=[''] + muni_origen_list, key="muni_origen")
with col2:
st.markdown("### 🏁 Destino (Llegada)")
estado_destino = st.selectbox("Estado de llegada:", options=[''] + estados, key="estado_destino")
municipio_destino = None
if estado_destino:
muni_destino_list = df_ubicaciones[df_ubicaciones['ESTADO'] == estado_destino]['MUNICIPIO'].unique().tolist()
municipio_destino = st.selectbox("Municipio de llegada:", options=[''] + muni_destino_list, key="muni_destino")
st.markdown("---")
# --- BOTÓN DE GUARDADO ---
if st.button("💾 Guardar Registro de Visita", use_container_width=True):
# Validaciones básicas antes de guardar
if not motivo:
st.error("⚠️ Por favor, selecciona un motivo de visita.")
elif not municipio_origen or not municipio_destino:
st.error("⚠️ Por favor, completa los estados y municipios tanto de origen como de destino.")
else:
# Preparamos los datos
fecha_registro = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
fila_visita = [
fecha_registro,
motivo,
descripcion,
estado_origen,
municipio_origen,
estado_destino,
municipio_destino
]
if worksheet:
try:
with st.spinner("Guardando en la base de datos..."):
worksheet.append_row(fila_visita)
st.success("✅ ¡Visita registrada exitosamente!")
st.balloons()
except Exception as e:
st.error(f"Error al guardar en Google Sheets: {str(e)}")
else:
st.error("No se pudo guardar: Revisa la conexión con Google Sheets.")