arzonstudios / app.py
sebastrh's picture
Update app.py
bed7072 verified
Raw History Blame Contribute Delete
16.8 kB
import streamlit as st
import pandas as pd
from google.oauth2.service_account import Credentials
import gspread
import time
# --- 1. CONFIGURACIÓN ---
st.set_page_config(page_title="ARZON STUDIOS", layout="wide", initial_sidebar_state="collapsed")
# --- 2. CSS "GOD MODE" (Hack agresivo para Móvil) ---
st.markdown("""
<style>
/* FUENTES DE LUJO */
@import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;500;600&family=Inter:wght@300;400;500;600&display=swap');
/* LIMPIEZA TOTAL */
#MainMenu, footer, header, .stDeployButton {display: none;}
.stApp { background-color: #ffffff; color: #000000; font-family: 'Inter', sans-serif; }
/* MARGENES: En móvil los quitamos casi todos */
.block-container {
padding-top: 0rem !important;
padding-bottom: 2rem !important;
padding-left: 0.5rem !important;
padding-right: 0.5rem !important;
max-width: 100% !important;
}
/* =========================================
EL HACK DEL HEADER (PARA QUE NO SE ROMPA EN CELULAR)
========================================= */
/* Forzar contenedor horizontal */
[data-testid="stHorizontalBlock"] {
align-items: center !important;
gap: 0px !important;
}
/* REGLAS MAESTRAS PARA COLUMNAS */
/* En escritorio se ve normal, en móvil forzamos porcentajes */
@media (max-width: 640px) {
/* Forzar que las columnas se queden en línea (Row) */
[data-testid="stHorizontalBlock"] {
display: flex !important;
flex-direction: row !important;
flex-wrap: nowrap !important;
width: 100% !important;
justify-content: space-between !important;
}
/* Ajustar ancho de cada columna para que quepa */
div[data-testid="column"] {
width: auto !important;
flex: 1 !important;
min-width: 0px !important; /* Permite encogerse */
padding: 0px !important;
}
/* El LOGO (Columna 3) recibe más espacio */
div[data-testid="column"]:nth-of-type(2) {
flex: 3 !important; /* Más ancho para el texto ARZON */
}
}
/* =========================================
ESTILO DE LOS ELEMENTOS
========================================= */
/* BOTONES DE TEXTO (MENÚ / BOLSA) */
.nav-btn button {
background: transparent !important;
border: none !important;
color: #000 !important;
font-family: 'Inter', sans-serif !important;
font-size: 11px !important;
font-weight: 600 !important;
letter-spacing: 1px !important;
text-transform: uppercase !important;
padding: 0 !important;
margin: 0 !important;
box-shadow: none !important;
width: 100% !important;
}
/* LOGO (TEXTO GRANDE) */
.logo-btn button {
font-family: 'Playfair Display', serif !important;
font-size: 32px !important;
letter-spacing: 3px !important;
text-align: center !important;
white-space: nowrap !important;
padding: 0 !important;
border: none !important;
background: transparent !important;
color: black !important;
box-shadow: none !important;
width: 100% !important;
}
/* AJUSTE LOGO EN CELULAR */
@media (max-width: 640px) {
.logo-btn button {
font-size: 18px !important; /* Más pequeño para que quepa */
letter-spacing: 1px !important;
margin-top: 5px !important;
}
.nav-btn button {
font-size: 10px !important;
}
}
/* BOTONES DE ACCIÓN (SHOP NOW) */
.stButton button[kind="primary"] {
background-color: #000 !important;
color: #fff !important;
border: 1px solid #000 !important;
border-radius: 0px !important;
padding: 15px !important;
width: 100% !important;
text-transform: uppercase;
font-size: 12px;
letter-spacing: 2px;
}
/* SIDEBAR (MENU LATERAL) */
section[data-testid="stSidebar"] {
width: 85% !important; /* En celular ocupa casi todo */
max-width: 400px !important;
background: white !important;
border-right: 1px solid #eee;
}
/* INPUTS */
div[data-testid="stTextInput"] input {
border: none !important; border-bottom: 1px solid #ccc !important;
border-radius: 0 !important; background: transparent !important;
color: black !important;
}
</style>
""", unsafe_allow_html=True)
# --- 3. CONEXIÓN DATOS ---
secret_dict = {
"type": "service_account",
"project_id": "trhhats",
"private_key_id": "1555421e0c8cd47026bc9907341110db25be89d3",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCpDyDrQBSXf0Bi\nr7KTd4P4c0JszG02wl4Wq0AhMK6VV97dK14WfUXhRVvR86Gg38TC1+nT0RRy1F30\ndN9doT7gOx1khZXSmKTEN9jKGRSC381FiMFA3ziinkm5Kq6dDHS2ldLOYOtmwwbd\n0MTDVLH9/qvnW2siTwJlV0oDJbqqZIoJoh9LEGXq8OHe954G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g06DeihOtlvmfcwn5UAM+Rrx5FRd2IfV/lf6PcxAcCLWSLdi\nB0aZYZOREIq5EUGcdKCNPwsrDYzVFj3IVUbvIx8BcDtdYev3lxtVvZ6xUpILD/wV\nTgpe3VMsRFXU/+Ip2IcKmwvp1GZutOUn3XstuGECgYEAu6wQ1UAhnvTnbav5Yait\nIPm7bPaths/u+wDYGCCdSAZGpXqipWD/vdqfrytZOs43OMkcCEvm5SSK6SDhYfiW\nUBrVj4fBIFUuq6f7hXD2AkH4pkkQZZOV1WpplZYTAAzAcpcBZUNAkcJS7ELkEiyl\nC5Tok5nhOW4UQpu8L15xaWo=\n-----END PRIVATE KEY-----\n",
"client_email": "gestor-rifa@trhhats.iam.gserviceaccount.com",
"client_id": "100715747150949254160",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/gestor-rifa%40trhhats.iam.gserviceaccount.com",
}
WHATSAPP = "522711233984"
SHEET_URL = "https://docs.google.com/spreadsheets/d/1K6Jsg8dZ9ToXQJZuXyn2pLTQTAOFf7Snf7BOA_xS9Rs/edit?usp=sharing"
@st.cache_data(ttl=60)
def cargar_datos():
try:
creds = Credentials.from_service_account_info(secret_dict, scopes=["https://www.googleapis.com/auth/spreadsheets"])
client = gspread.authorize(creds)
try:
sheet = client.open_by_url(SHEET_URL).worksheet("Catalogo")
except:
sheet = client.open_by_url(SHEET_URL).get_worksheet(0)
data = sheet.get_all_records()
if not data: return pd.DataFrame()
df = pd.DataFrame(data)
cols_map = {}
for col in df.columns:
c = col.lower().strip()
if 'producto' in c: cols_map[col] = 'Producto'
elif 'precio' in c: cols_map[col] = 'Precio'
elif 'img' in c: cols_map[col] = 'Imagen'
elif 'talla' in c: cols_map[col] = 'Tallas'
elif 'cat' in c: cols_map[col] = 'Categoria'
elif 'desc' in c: cols_map[col] = 'Descripcion'
elif 'id' in c: cols_map[col] = 'ID'
df.rename(columns=cols_map, inplace=True)
if 'Producto' not in df.columns: return pd.DataFrame()
if 'Precio' in df.columns:
df['Precio'] = df['Precio'].astype(str).str.replace(r'[$,]', '', regex=True).str.strip()
df['Precio'] = pd.to_numeric(df['Precio'], errors='coerce').fillna(0)
return df[df['Producto'].astype(str).str.strip() != '']
except: return pd.DataFrame()
# --- 4. GESTIÓN DE ESTADO ---
if 'active_drawer' not in st.session_state: st.session_state.active_drawer = None
if 'cart' not in st.session_state: st.session_state.cart = []
if 'page' not in st.session_state: st.session_state.page = 'home'
if 'selected_product' not in st.session_state: st.session_state.selected_product = None
if 'filter_cat' not in st.session_state: st.session_state.filter_cat = 'VIEW ALL'
if 'search_query' not in st.session_state: st.session_state.search_query = ""
df = cargar_datos()
# --- 5. HEADER HÍBRIDO (ESTILO APP NATIVA) ---
# Usamos un contenedor vacío arriba para simular el navbar fijo
st.markdown('<div style="height: 10px;"></div>', unsafe_allow_html=True)
# Lógica inteligente: Si es escritorio mostramos todo, si es celular ocultamos Buscar/Favoritos
# para que quepa el logo grande.
col1, col2, col3 = st.columns([1, 2, 1])
with col1:
# Botón Menú
st.markdown('<div class="nav-btn">', unsafe_allow_html=True)
if st.button("☰ MENÚ", key="nav_menu", use_container_width=True):
st.session_state.active_drawer = 'menu' if st.session_state.active_drawer != 'menu' else None
st.rerun()
st.markdown('</div>', unsafe_allow_html=True)
with col2:
# Logo Central
st.markdown('<div class="logo-btn">', unsafe_allow_html=True)
if st.button("ARZON STUDIOS", key="nav_logo", use_container_width=True):
st.session_state.page = 'home'
st.session_state.active_drawer = None
st.rerun()
st.markdown('</div>', unsafe_allow_html=True)
with col3:
# Botón Bolsa
st.markdown('<div class="nav-btn">', unsafe_allow_html=True)
bag_label = f"BOLSA ({len(st.session_state.cart)})"
if st.button(bag_label, key="nav_bag", use_container_width=True):
st.session_state.active_drawer = 'cart' if st.session_state.active_drawer != 'cart' else None
st.rerun()
st.markdown('</div>', unsafe_allow_html=True)
# Botón Buscar debajo del header para celular (opcional, o integrado)
if st.session_state.page == 'home':
st.markdown("<br>", unsafe_allow_html=True)
# Barra de búsqueda limpia
c_s1, c_s2 = st.columns([6, 1])
with c_s1:
query = st.text_input("BUSCAR", placeholder="Buscar producto...", value=st.session_state.search_query, label_visibility="collapsed")
with c_s2:
if st.button("🔍", key="search_go"): pass # Solo visual, el enter funciona
if query != st.session_state.search_query:
st.session_state.search_query = query
st.rerun()
st.markdown("---")
# --- 6. LOGICA DE DRAWERS (MENÚ LATERAL) ---
if st.session_state.active_drawer:
with st.sidebar:
# MENU
if st.session_state.active_drawer == 'menu':
c_close, c_sp = st.columns([1, 4])
with c_close:
if st.button("✕"):
st.session_state.active_drawer = None
st.rerun()
st.markdown("<br>", unsafe_allow_html=True)
cats = ["VIEW ALL"]
if not df.empty and 'Categoria' in df.columns:
cats += sorted(df['Categoria'].dropna().unique().tolist())
for cat in cats:
if st.button(cat.upper(), key=f"c_{cat}", use_container_width=True):
st.session_state.filter_cat = cat
st.session_state.page = 'home'
st.session_state.active_drawer = None
st.rerun()
# BOLSA
elif st.session_state.active_drawer == 'cart':
c_head, c_cl = st.columns([4, 1])
with c_head: st.write("SHOPPING BAG")
with c_cl:
if st.button("✕"):
st.session_state.active_drawer = None
st.rerun()
st.markdown("---")
if not st.session_state.cart:
st.info("Tu bolsa está vacía.")
if st.button("IR A COMPRAR", type="primary"):
st.session_state.active_drawer = None
st.rerun()
else:
total = 0
for i, item in enumerate(st.session_state.cart):
c_img, c_info = st.columns([1, 2])
with c_img: st.image(item['img'], use_container_width=True)
with c_info:
st.write(f"**{item['name']}**")
st.caption(f"${item['price']}")
if st.button("ELIMINAR", key=f"d_{i}"):
st.session_state.cart.pop(i)
st.rerun()
try: total += float(str(item['price']))
except: pass
st.divider()
st.write(f"**TOTAL: ${total:,.2f}**")
msg = f"PEDIDO ARZON: ${total}"
st.link_button("PAGAR WHATSAPP", f"https://wa.me/{WHATSAPP}?text={msg}", type="primary", use_container_width=True)
# --- 7. CONTENIDO (GRID RESPONSIVO) ---
if st.session_state.page == 'home':
if df.empty:
st.warning("Cargando catálogo...")
else:
d_show = df.copy()
if st.session_state.filter_cat != "VIEW ALL" and 'Categoria' in d_show.columns:
d_show = d_show[d_show['Categoria'] == st.session_state.filter_cat]
if st.session_state.search_query:
d_show = d_show[d_show.apply(lambda r: st.session_state.search_query.lower() in str(r).lower(), axis=1)]
if d_show.empty:
st.info("No hay productos.")
else:
# GRID: En Streamlit, las columnas se apilan solas en celular.
# Aquí usamos 3 columnas para PC, que se volverán 1 columna grande en celular automáticamente.
cols = st.columns(3, gap="large")
for idx, row in d_show.iterrows():
with cols[idx % 3]:
# Card Producto
img = row.get('Imagen', '')
if not str(img).startswith('http'): img = "https://via.placeholder.com/600x800"
st.image(img, use_container_width=True)
st.markdown(f"<div style='text-align:center; font-weight:bold; font-size:12px; margin-top:5px;'>{row.get('Producto','').upper()}</div>", unsafe_allow_html=True)
st.markdown(f"<div style='text-align:center; font-size:12px; margin-bottom:10px;'>${row.get('Precio', 0):,.2f}</div>", unsafe_allow_html=True)
if st.button("VER PRODUCTO", key=f"bp_{idx}", type="primary", use_container_width=True):
st.session_state.selected_product = row.to_dict()
st.session_state.page = 'product'
st.rerun()
st.markdown("<br>", unsafe_allow_html=True)
# PÁGINA PRODUCTO
elif st.session_state.page == 'product' and st.session_state.selected_product:
p = st.session_state.selected_product
if st.button("← VOLVER"):
st.session_state.page = 'home'
st.rerun()
st.markdown("<br>", unsafe_allow_html=True)
# En PC 2 columnas, en Celular se apilan (Foto arriba, info abajo)
c1, c2 = st.columns([1, 1], gap="large")
with c1:
st.image(p.get('Imagen', ''), use_container_width=True)
with c2:
st.markdown(f"## {p.get('Producto').upper()}")
st.markdown(f"### ${p.get('Precio', 0):,.2f}")
st.write("")
tallas = str(p.get('Tallas', 'UNICA')).split(',')
size = st.selectbox("TALLA", [t.strip() for t in tallas])
st.markdown("<br>", unsafe_allow_html=True)
if st.button("AÑADIR A LA BOLSA", type="primary", use_container_width=True):
st.session_state.cart.append({
"id": p.get('ID'),
"name": p.get('Producto'),
"price": p.get('Precio'),
"size": size,
"img": p.get('Imagen')
})
st.session_state.active_drawer = 'cart'
st.rerun()
st.markdown("---")
st.write(p.get('Descripcion', ''))