Descarga con dos botones y totales del Excel como números
Browse files
README.md
CHANGED
|
@@ -75,8 +75,10 @@ Total) y al pie el almacén, el total de unidades, el total, el impuesto, el net
|
|
| 75 |
Un formato guardado con el diseño anterior se migra solo (conserva logo, empresa y nota).
|
| 76 |
- Los datos de cada cliente (dirección, ID fiscal, despacho, teléfono) y el almacén se llenan en «Cliente e
|
| 77 |
instrucciones» y se pueden guardar junto con sus instrucciones (`data/clientes.json`).
|
| 78 |
-
-
|
| 79 |
-
|
|
|
|
|
|
|
| 80 |
|
| 81 |
**Descarga:** el archivo va incrustado en la página. El botón estándar de Streamlit lo pedía aparte al
|
| 82 |
servidor y, en un Space privado, esa petición llegaba sin la sesión de Hugging Face y se descargaba su página de
|
|
|
|
| 75 |
Un formato guardado con el diseño anterior se migra solo (conserva logo, empresa y nota).
|
| 76 |
- Los datos de cada cliente (dirección, ID fiscal, despacho, teléfono) y el almacén se llenan en «Cliente e
|
| 77 |
instrucciones» y se pueden guardar junto con sus instrucciones (`data/clientes.json`).
|
| 78 |
+
- Hay dos botones, «Descargar PDF» y «Descargar Excel» (A4 vertical), cada uno con su archivo ya preparado; el que
|
| 79 |
+
se elige en el formato va primero y resaltado. En el Excel los totales (de cada renglón, total, impuesto, neto y
|
| 80 |
+
total de unidades) van como números y no como fórmulas: así se ven también en la vista previa de Windows, el
|
| 81 |
+
celular o WhatsApp, que no calculan fórmulas.
|
| 82 |
|
| 83 |
**Descarga:** el archivo va incrustado en la página. El botón estándar de Streamlit lo pedía aparte al
|
| 84 |
servidor y, en un Space privado, esa petición llegaba sin la sesión de Hugging Face y se descargaba su página de
|
app.py
CHANGED
|
@@ -350,7 +350,7 @@ def panel_formato():
|
|
| 350 |
|
| 351 |
st.markdown("##### 5 · Descarga")
|
| 352 |
opciones = list(formato.FORMATOS)
|
| 353 |
-
preferido = st.radio("
|
| 354 |
format_func=formato.FORMATOS.get, horizontal=True,
|
| 355 |
index=opciones.index(f["formato_descarga"]))
|
| 356 |
b1, b2 = st.columns(2)
|
|
@@ -380,7 +380,6 @@ def panel_formato():
|
|
| 380 |
mostrar_vista_previa(f, "Así sale hoy (datos de ejemplo)")
|
| 381 |
if nuevo and guardar:
|
| 382 |
formato.guardar(nuevo)
|
| 383 |
-
st.session_state.pop("tipo_descarga", None) # la descarga vuelve al formato por defecto
|
| 384 |
st.toast("Formato guardado.")
|
| 385 |
st.rerun()
|
| 386 |
|
|
@@ -531,11 +530,12 @@ class Trabajo:
|
|
| 531 |
MIME = {"excel": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "pdf": "application/pdf"}
|
| 532 |
|
| 533 |
|
| 534 |
-
def boton_descarga(datos: bytes, nombre: str, tipo: str = "excel"):
|
| 535 |
"""Descarga con el archivo incrustado en la página (data URI). st.download_button lo pide aparte al servidor,
|
| 536 |
y en un Space privado esa petición llega sin la sesión de Hugging Face: se bajaba su página de acceso (HTML)."""
|
| 537 |
b64 = base64.b64encode(datos).decode()
|
| 538 |
-
|
|
|
|
| 539 |
f'href="data:{MIME[tipo]};base64,{b64}">'
|
| 540 |
f'Descargar {formato.FORMATOS[tipo]}</a>', unsafe_allow_html=True)
|
| 541 |
|
|
@@ -1186,24 +1186,26 @@ elif "cotizacion" in st.session_state:
|
|
| 1186 |
st.warning(f"{len(pendientes)} renglón(es) pendientes de revisión no saldrán en la cotización: "
|
| 1187 |
+ ", ".join(f"{l.n}. {l.principio_activo}" for l in pendientes)
|
| 1188 |
+ ". Confírmalos y vuelve a preparar la cotización.")
|
|
|
|
|
|
|
| 1189 |
formato_actual = formato.leer()
|
| 1190 |
-
opciones = list(formato.FORMATOS)
|
| 1191 |
-
tipo = st.radio("Descargar en", opciones, format_func=formato.FORMATOS.get, horizontal=True,
|
| 1192 |
-
index=opciones.index(formato_actual["formato_descarga"]), key="tipo_descarga",
|
| 1193 |
-
help="El formato (logo, columnas, impuesto...) se cambia en «Formato del presupuesto», arriba.")
|
| 1194 |
incluir_todo = st.checkbox("Incluir también los renglones no ofertados (uso interno)")
|
| 1195 |
-
|
| 1196 |
-
|
| 1197 |
-
|
| 1198 |
-
|
| 1199 |
-
|
| 1200 |
-
|
| 1201 |
-
|
| 1202 |
-
|
| 1203 |
-
|
| 1204 |
-
|
| 1205 |
-
|
| 1206 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1207 |
|
| 1208 |
atender_orden()
|
| 1209 |
pintar() # deja el panel con los últimos mensajes de esta pasada
|
|
|
|
| 350 |
|
| 351 |
st.markdown("##### 5 · Descarga")
|
| 352 |
opciones = list(formato.FORMATOS)
|
| 353 |
+
preferido = st.radio("Botón de descarga que va primero (resaltado)", opciones,
|
| 354 |
format_func=formato.FORMATOS.get, horizontal=True,
|
| 355 |
index=opciones.index(f["formato_descarga"]))
|
| 356 |
b1, b2 = st.columns(2)
|
|
|
|
| 380 |
mostrar_vista_previa(f, "Así sale hoy (datos de ejemplo)")
|
| 381 |
if nuevo and guardar:
|
| 382 |
formato.guardar(nuevo)
|
|
|
|
| 383 |
st.toast("Formato guardado.")
|
| 384 |
st.rerun()
|
| 385 |
|
|
|
|
| 530 |
MIME = {"excel": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "pdf": "application/pdf"}
|
| 531 |
|
| 532 |
|
| 533 |
+
def boton_descarga(datos: bytes, nombre: str, tipo: str = "excel", secundario: bool = False):
|
| 534 |
"""Descarga con el archivo incrustado en la página (data URI). st.download_button lo pide aparte al servidor,
|
| 535 |
y en un Space privado esa petición llega sin la sesión de Hugging Face: se bajaba su página de acceso (HTML)."""
|
| 536 |
b64 = base64.b64encode(datos).decode()
|
| 537 |
+
clase = "boton-descarga" + (" boton-secundario" if secundario else "")
|
| 538 |
+
st.markdown(f'<a class="{clase}" download="{html.escape(nombre)}" '
|
| 539 |
f'href="data:{MIME[tipo]};base64,{b64}">'
|
| 540 |
f'Descargar {formato.FORMATOS[tipo]}</a>', unsafe_allow_html=True)
|
| 541 |
|
|
|
|
| 1186 |
st.warning(f"{len(pendientes)} renglón(es) pendientes de revisión no saldrán en la cotización: "
|
| 1187 |
+ ", ".join(f"{l.n}. {l.principio_activo}" for l in pendientes)
|
| 1188 |
+ ". Confírmalos y vuelve a preparar la cotización.")
|
| 1189 |
+
# Los dos archivos se preparan juntos y cada uno tiene su botón: con un selector, mientras la página se
|
| 1190 |
+
# regeneraba seguía visible el botón anterior y se bajaba el formato equivocado.
|
| 1191 |
formato_actual = formato.leer()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1192 |
incluir_todo = st.checkbox("Incluir también los renglones no ofertados (uso interno)")
|
| 1193 |
+
datos_doc = {"cliente": sol_final.cliente, "almacen": st.session_state.get("cli_almacen", "").strip(),
|
| 1194 |
+
**{c: st.session_state.get(f"cli_{c}", "").strip() for c in CAMPOS_CLIENTE}}
|
| 1195 |
+
base = f"PRESUPUESTO_{Path(st.session_state.get('archivo', 'solicitud')).stem}"
|
| 1196 |
+
tipos_descarga = sorted(formato.FORMATOS, key=lambda t: t != formato_actual["formato_descarga"]) # preferido 1.º
|
| 1197 |
+
columnas_descarga = st.columns(len(tipos_descarga) + 2)
|
| 1198 |
+
for col, tipo in zip(columnas_descarga, tipos_descarga):
|
| 1199 |
+
try:
|
| 1200 |
+
datos_salida = generar_cotizacion(cot, tipo, solo_ofertados=not incluir_todo, f=formato_actual,
|
| 1201 |
+
doc=datos_doc)
|
| 1202 |
+
except Exception: # noqa: BLE001
|
| 1203 |
+
fallo_inesperado(f"preparar el {formato.FORMATOS[tipo]} del presupuesto")
|
| 1204 |
+
continue
|
| 1205 |
+
with col:
|
| 1206 |
+
boton_descarga(datos_salida, f"{base}.{'pdf' if tipo == 'pdf' else 'xlsx'}", tipo,
|
| 1207 |
+
secundario=tipo != tipos_descarga[0])
|
| 1208 |
+
st.caption("El formato (logo, columnas, impuesto...) se cambia en «Formato del presupuesto», arriba.")
|
| 1209 |
|
| 1210 |
atender_orden()
|
| 1211 |
pintar() # deja el panel con los últimos mensajes de esta pasada
|
estilo.py
CHANGED
|
@@ -337,6 +337,15 @@ a.boton-descarga:hover {
|
|
| 337 |
background: linear-gradient(180deg, #b5ddfc 0%, #65b3f2 47%, #2d84df 53%, #4ea2ee 100%);
|
| 338 |
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .7), 0 0 10px rgba(120, 205, 255, .95);
|
| 339 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 340 |
|
| 341 |
/* ---------- pestañas del registro ---------- */
|
| 342 |
[data-baseweb="tab-list"] { gap: 2px; border-bottom: 1px solid #a5bdd8; }
|
|
|
|
| 337 |
background: linear-gradient(180deg, #b5ddfc 0%, #65b3f2 47%, #2d84df 53%, #4ea2ee 100%);
|
| 338 |
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .7), 0 0 10px rgba(120, 205, 255, .95);
|
| 339 |
}
|
| 340 |
+
/* el segundo formato de descarga, con el aspecto de un botón normal */
|
| 341 |
+
a.boton-descarga.boton-secundario {
|
| 342 |
+
color: #1f2937 !important; text-shadow: none;
|
| 343 |
+
background: linear-gradient(180deg, #fbfcfe 0%, #eef2f7 47%, #e1e8f0 53%, #eaf0f6 100%);
|
| 344 |
+
border: 1px solid #8fa6c0;
|
| 345 |
+
}
|
| 346 |
+
a.boton-descarga.boton-secundario:hover {
|
| 347 |
+
background: linear-gradient(180deg, #ffffff 0%, #f3f7fb 47%, #e8eff7 53%, #f1f6fb 100%);
|
| 348 |
+
}
|
| 349 |
|
| 350 |
/* ---------- pestañas del registro ---------- */
|
| 351 |
[data-baseweb="tab-list"] { gap: 2px; border-bottom: 1px solid #a5bdd8; }
|
excel_salida.py
CHANGED
|
@@ -149,16 +149,12 @@ def generar_excel(cot: Cotizacion, solo_ofertados: bool = True, f: dict | None =
|
|
| 149 |
celda.font = Font(bold=True, size=9, color=TEXTO)
|
| 150 |
celda.alignment = Alignment(horizontal="right" if c["clave"] in NUMERICAS else "left", vertical="center")
|
| 151 |
celda.border = Border(top=fina, bottom=gruesa)
|
| 152 |
-
|
| 153 |
-
|
| 154 |
for l in lineas:
|
| 155 |
r += 1
|
| 156 |
for col, clave in enumerate(claves, 1):
|
| 157 |
-
|
| 158 |
-
if clave == "total" and con_formula:
|
| 159 |
-
q, p = letra["cantidad"], letra["precio"]
|
| 160 |
-
v = f'=IF(AND({q}{r}<>"",{p}{r}<>""),ROUND({q}{r}*{p}{r},2),"")'
|
| 161 |
-
c = ws.cell(r, col, v)
|
| 162 |
c.font = Font(size=9, color=TEXTO)
|
| 163 |
c.border = Border(bottom=suave)
|
| 164 |
c.alignment = Alignment(horizontal="right" if clave in NUMERICAS else "left", vertical="center",
|
|
@@ -180,18 +176,17 @@ def generar_excel(cot: Cotizacion, solo_ofertados: bool = True, f: dict | None =
|
|
| 180 |
poner(f"A{r}", f"ALMACEN: {doc['almacen']}".rstrip(), negrita)
|
| 181 |
col_u = min(n, max(2, k))
|
| 182 |
poner(f"{get_column_letter(col_u)}{r}", "TOTAL UNIDADES:", negrita)
|
| 183 |
-
|
| 184 |
-
celda_u = ws.cell(r + 1, col_u, f"=SUM({rango_q})" if rango_q and lineas else unidades)
|
| 185 |
celda_u.number_format = "#,##0.00"
|
| 186 |
celda_u.font = Font(size=9, color=TEXTO)
|
| 187 |
celda_u.alignment = Alignment(horizontal="left")
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
|
|
|
| 192 |
for i, (etiqueta, valor) in enumerate((("TOTAL....:", total), ("IMPUESTO:", impuesto), ("NETO:", neto))):
|
| 193 |
fila = r + i
|
| 194 |
-
filas_monto[etiqueta] = fila
|
| 195 |
e = ws.cell(fila, col_e, etiqueta)
|
| 196 |
e.font = negrita
|
| 197 |
e.alignment = Alignment(horizontal="right")
|
|
@@ -201,12 +196,6 @@ def generar_excel(cot: Cotizacion, solo_ofertados: bool = True, f: dict | None =
|
|
| 201 |
m.alignment = Alignment(horizontal="right")
|
| 202 |
if i:
|
| 203 |
m.border = Border(top=fina)
|
| 204 |
-
if rango_t and lineas:
|
| 205 |
-
t, im = filas_monto["TOTAL....:"], filas_monto["IMPUESTO:"]
|
| 206 |
-
tc = get_column_letter(col_t)
|
| 207 |
-
ws.cell(t, col_t, f"=SUM({rango_t})")
|
| 208 |
-
ws.cell(im, col_t, f"=ROUND({tc}{t}*{f['impuesto_pct'] / 100},2)")
|
| 209 |
-
ws.cell(filas_monto["NETO:"], col_t, f"={tc}{t}+{tc}{im}")
|
| 210 |
r += 4
|
| 211 |
|
| 212 |
# ---- nota, texto legal y datos de la empresa ----
|
|
|
|
| 149 |
celda.font = Font(bold=True, size=9, color=TEXTO)
|
| 150 |
celda.alignment = Alignment(horizontal="right" if c["clave"] in NUMERICAS else "left", vertical="center")
|
| 151 |
celda.border = Border(top=fina, bottom=gruesa)
|
| 152 |
+
# Los totales se escriben como números (no fórmulas): una fórmula sin su valor calculado se ve vacía en la vista
|
| 153 |
+
# previa de Windows, el celular, WhatsApp o los visores web, que no la calculan.
|
| 154 |
for l in lineas:
|
| 155 |
r += 1
|
| 156 |
for col, clave in enumerate(claves, 1):
|
| 157 |
+
c = ws.cell(r, col, _valor(l, clave))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
c.font = Font(size=9, color=TEXTO)
|
| 159 |
c.border = Border(bottom=suave)
|
| 160 |
c.alignment = Alignment(horizontal="right" if clave in NUMERICAS else "left", vertical="center",
|
|
|
|
| 176 |
poner(f"A{r}", f"ALMACEN: {doc['almacen']}".rstrip(), negrita)
|
| 177 |
col_u = min(n, max(2, k))
|
| 178 |
poner(f"{get_column_letter(col_u)}{r}", "TOTAL UNIDADES:", negrita)
|
| 179 |
+
celda_u = ws.cell(r + 1, col_u, unidades)
|
|
|
|
| 180 |
celda_u.number_format = "#,##0.00"
|
| 181 |
celda_u.font = Font(size=9, color=TEXTO)
|
| 182 |
celda_u.alignment = Alignment(horizontal="left")
|
| 183 |
+
# Los montos van debajo de la columna Total (o en la última si está oculta) y las etiquetas a su izquierda
|
| 184 |
+
col_t = claves.index("total") + 1 if "total" in claves else n
|
| 185 |
+
col_e = col_t - 1
|
| 186 |
+
if col_e < 1:
|
| 187 |
+
col_e, col_t = 1, min(n, 2)
|
| 188 |
for i, (etiqueta, valor) in enumerate((("TOTAL....:", total), ("IMPUESTO:", impuesto), ("NETO:", neto))):
|
| 189 |
fila = r + i
|
|
|
|
| 190 |
e = ws.cell(fila, col_e, etiqueta)
|
| 191 |
e.font = negrita
|
| 192 |
e.alignment = Alignment(horizontal="right")
|
|
|
|
| 196 |
m.alignment = Alignment(horizontal="right")
|
| 197 |
if i:
|
| 198 |
m.border = Border(top=fina)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
r += 4
|
| 200 |
|
| 201 |
# ---- nota, texto legal y datos de la empresa ----
|