Formato de la cotización editable y descarga en Excel o PDF
Browse files- README.md +12 -3
- app.py +101 -7
- excel_salida.py +299 -70
- formato.py +157 -0
- requirements.txt +1 -0
README.md
CHANGED
|
@@ -57,7 +57,14 @@ solicitud anterior. También avisa si es la misma solicitud que ya tiene leída
|
|
| 57 |
si persiste, comunicarse con `CONTACTO_SOPORTE`. El detalle técnico queda en los logs del
|
| 58 |
servidor (en el Space: *Logs*), en las líneas que empiezan por `[llm]` y `[app]`.
|
| 59 |
|
| 60 |
-
**
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
servidor y, en un Space privado, esa petición llegaba sin la sesión de Hugging Face y se descargaba su página de
|
| 62 |
acceso (un HTML) en lugar del Excel.
|
| 63 |
|
|
@@ -124,7 +131,9 @@ nueva. Si un producto deja de existir en los Excel, sus decisiones se ignoran si
|
|
| 124 |
| `llm.py` | Cliente del modelo (SDK de OpenAI, sirve para Gemini/Groq/OpenAI) con reintentos |
|
| 125 |
| `modelos.py` | Esquemas (Pydantic) que el modelo está obligado a llenar |
|
| 126 |
| `cotizacion.py` | Cálculo determinístico de la cotización |
|
| 127 |
-
| `excel_salida.py` | Genera
|
|
|
|
|
|
|
| 128 |
| `cotizar_cli.py` | Lo mismo desde la terminal, para probar prompts rápido |
|
| 129 |
| `herramientas/publicar_space.py` | Publica en el Space sin subir el historial de git |
|
| 130 |
|
|
@@ -217,7 +226,7 @@ Variables disponibles (las mismas de `.env.example`):
|
|
| 217 |
| `FRASE_ACCESO` | secreto | Frase de acceso (mínimo 12 caracteres). Sin ella nadie entra |
|
| 218 |
| `ACCESO_HORAS` | variable | Horas que dura una sesión (12) |
|
| 219 |
| `LLM_BASE_URL`, `LLM_MODEL` | variable | Proveedor y modelo (por defecto Gemini) |
|
| 220 |
-
| `EMPRESA_NOMBRE`, `EMPRESA_RIF`, `EMPRESA_DATOS` | variable | Encabezado
|
| 221 |
| `VENCIMIENTO_MINIMO_MESES`, `DECIMALES_PRECIO` | variable | Reglas por defecto |
|
| 222 |
| `AGENTE_NOMBRE`, `AGENTE_LEMA` | variable | Nombre del agente y lema bajo su nombre (Agosto, «tu agente y asistente ;)») |
|
| 223 |
| `CONTACTO_SOPORTE` | variable | A quién acudir si la IA falla de forma persistente (por defecto, «el ingeniero encargado») |
|
|
|
|
| 57 |
si persiste, comunicarse con `CONTACTO_SOPORTE`. El detalle técnico queda en los logs del
|
| 58 |
servidor (en el Space: *Logs*), en las líneas que empiezan por `[llm]` y `[app]`.
|
| 59 |
|
| 60 |
+
**Formato de salida (Excel o PDF):** en «Formato de la cotización» el departamento edita cómo sale lo que recibe el
|
| 61 |
+
cliente: nombre, RIF y datos de la empresa, título, color, logo, una nota al pie (validez de la oferta, IVA, forma de
|
| 62 |
+
pago...), si se muestran las condiciones, y las columnas (mostrar u ocultar, renombrar, ancho y orden). Se guarda en
|
| 63 |
+
`data/formato.json` y `data/logo.png` (en el Space, en el bucket) y vale para todos. Al descargar se elige Excel o PDF;
|
| 64 |
+
el formato por defecto también se configura ahí. El Excel conserva la fórmula del total cuando están visibles la
|
| 65 |
+
cantidad ofertada y el precio.
|
| 66 |
+
|
| 67 |
+
**Descarga:** el archivo va incrustado en la página. El botón estándar de Streamlit lo pedía aparte al
|
| 68 |
servidor y, en un Space privado, esa petición llegaba sin la sesión de Hugging Face y se descargaba su página de
|
| 69 |
acceso (un HTML) en lugar del Excel.
|
| 70 |
|
|
|
|
| 131 |
| `llm.py` | Cliente del modelo (SDK de OpenAI, sirve para Gemini/Groq/OpenAI) con reintentos |
|
| 132 |
| `modelos.py` | Esquemas (Pydantic) que el modelo está obligado a llenar |
|
| 133 |
| `cotizacion.py` | Cálculo determinístico de la cotización |
|
| 134 |
+
| `excel_salida.py` | Genera la cotización en Excel o PDF con el formato del departamento |
|
| 135 |
+
| `formato.py` | Formato editable de la cotización (empresa, logo, columnas, nota) |
|
| 136 |
+
| `documentos.py` | Revisa los archivos subidos y recuerda qué se subió y cuándo |
|
| 137 |
| `cotizar_cli.py` | Lo mismo desde la terminal, para probar prompts rápido |
|
| 138 |
| `herramientas/publicar_space.py` | Publica en el Space sin subir el historial de git |
|
| 139 |
|
|
|
|
| 226 |
| `FRASE_ACCESO` | secreto | Frase de acceso (mínimo 12 caracteres). Sin ella nadie entra |
|
| 227 |
| `ACCESO_HORAS` | variable | Horas que dura una sesión (12) |
|
| 228 |
| `LLM_BASE_URL`, `LLM_MODEL` | variable | Proveedor y modelo (por defecto Gemini) |
|
| 229 |
+
| `EMPRESA_NOMBRE`, `EMPRESA_RIF`, `EMPRESA_DATOS` | variable | Encabezado de la cotización hasta que se edite el formato en la app |
|
| 230 |
| `VENCIMIENTO_MINIMO_MESES`, `DECIMALES_PRECIO` | variable | Reglas por defecto |
|
| 231 |
| `AGENTE_NOMBRE`, `AGENTE_LEMA` | variable | Nombre del agente y lema bajo su nombre (Agosto, «tu agente y asistente ;)») |
|
| 232 |
| `CONTACTO_SOPORTE` | variable | A quién acudir si la IA falla de forma persistente (por defecto, «el ingeniero encargado») |
|
app.py
CHANGED
|
@@ -21,7 +21,8 @@ import documentos
|
|
| 21 |
from catalogo import construir_catalogo, Catalogo
|
| 22 |
from cotizacion import cotizar
|
| 23 |
from estilo import aplicar_estilo
|
| 24 |
-
|
|
|
|
| 25 |
from ia import (extraer_solicitud, emparejar, interpretar_instrucciones, aplicar_respuestas, resolver_catalogo,
|
| 26 |
SUGERIR_UNIONES, contexto_agente, interpretar_orden)
|
| 27 |
from llm import LLM, ErrorIA
|
|
@@ -154,6 +155,83 @@ def panel_registro():
|
|
| 154 |
st.rerun()
|
| 155 |
|
| 156 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
# ---------------- barra lateral ----------------
|
| 158 |
RUTAS_CATALOGO = {"existencias": RUTA_EXIST, "precios": RUTA_PRECIOS}
|
| 159 |
|
|
@@ -295,13 +373,16 @@ class Trabajo:
|
|
| 295 |
pintar(pasos=self.pasos)
|
| 296 |
|
| 297 |
|
| 298 |
-
|
|
|
|
|
|
|
|
|
|
| 299 |
"""Descarga con el archivo incrustado en la página (data URI). st.download_button lo pide aparte al servidor,
|
| 300 |
y en un Space privado esa petición llega sin la sesión de Hugging Face: se bajaba su página de acceso (HTML)."""
|
| 301 |
b64 = base64.b64encode(datos).decode()
|
| 302 |
st.markdown(f'<a class="boton-descarga" download="{html.escape(nombre)}" '
|
| 303 |
-
f'href="data:
|
| 304 |
-
f'Descargar
|
| 305 |
|
| 306 |
|
| 307 |
def fallo_inesperado(que_hacia: str):
|
|
@@ -452,6 +533,7 @@ def detener():
|
|
| 452 |
pintar()
|
| 453 |
agente.conversacion_completa()
|
| 454 |
panel_registro()
|
|
|
|
| 455 |
|
| 456 |
if not catalogo:
|
| 457 |
detener()
|
|
@@ -765,12 +847,24 @@ if "cotizacion" in st.session_state:
|
|
| 765 |
|
| 766 |
pendientes = [l for l in cot.lineas if l.estado == "pendiente"]
|
| 767 |
if pendientes:
|
| 768 |
-
st.warning(f"{len(pendientes)} renglón(es) pendientes de revisión no saldrán en
|
| 769 |
+ ", ".join(f"{l.n}. {l.principio_activo}" for l in pendientes)
|
| 770 |
+ ". Confírmalos y vuelve a preparar la cotización.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 771 |
incluir_todo = st.checkbox("Incluir también los renglones no ofertados (uso interno)")
|
| 772 |
-
|
| 773 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 774 |
|
| 775 |
atender_orden()
|
| 776 |
pintar() # deja el panel con los últimos mensajes de esta pasada
|
|
|
|
| 21 |
from catalogo import construir_catalogo, Catalogo
|
| 22 |
from cotizacion import cotizar
|
| 23 |
from estilo import aplicar_estilo
|
| 24 |
+
import formato
|
| 25 |
+
from excel_salida import generar as generar_cotizacion
|
| 26 |
from ia import (extraer_solicitud, emparejar, interpretar_instrucciones, aplicar_respuestas, resolver_catalogo,
|
| 27 |
SUGERIR_UNIONES, contexto_agente, interpretar_orden)
|
| 28 |
from llm import LLM, ErrorIA
|
|
|
|
| 155 |
st.rerun()
|
| 156 |
|
| 157 |
|
| 158 |
+
# ---------------- formato de la cotización ----------------
|
| 159 |
+
def subir_logo(archivo):
|
| 160 |
+
id_subida = getattr(archivo, "file_id", None) or f"{archivo.name}:{archivo.size}"
|
| 161 |
+
if st.session_state.get("id_logo") == id_subida:
|
| 162 |
+
return
|
| 163 |
+
st.session_state.id_logo = id_subida
|
| 164 |
+
try:
|
| 165 |
+
formato.guardar_logo(archivo.getvalue())
|
| 166 |
+
st.toast("Logo guardado.")
|
| 167 |
+
except ValueError as e:
|
| 168 |
+
st.error(str(e))
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def panel_formato():
|
| 172 |
+
f = formato.leer()
|
| 173 |
+
with st.expander("Formato de la cotización (Excel y PDF)"):
|
| 174 |
+
st.caption("Así sale la cotización que recibe el cliente. Los cambios valen para todo el departamento y se "
|
| 175 |
+
"aplican a la próxima descarga.")
|
| 176 |
+
c_logo, c_subir = st.columns([1, 3])
|
| 177 |
+
logo = formato.logo()
|
| 178 |
+
if logo:
|
| 179 |
+
c_logo.image(logo, width=120)
|
| 180 |
+
c_logo.button("Quitar logo", on_click=formato.quitar_logo)
|
| 181 |
+
else:
|
| 182 |
+
c_logo.caption("Sin logo")
|
| 183 |
+
archivo_logo = c_subir.file_uploader("Logo (PNG o JPG)", type=["png", "jpg", "jpeg"], key="up_logo")
|
| 184 |
+
if archivo_logo:
|
| 185 |
+
subir_logo(archivo_logo)
|
| 186 |
+
|
| 187 |
+
with st.form("form_formato"):
|
| 188 |
+
c1, c2 = st.columns(2)
|
| 189 |
+
nombre = c1.text_input("Nombre de la empresa", f["empresa_nombre"])
|
| 190 |
+
rif = c1.text_input("RIF / número legal", f["empresa_rif"])
|
| 191 |
+
titulo = c2.text_input("Título del documento", f["titulo"])
|
| 192 |
+
color = c2.color_picker("Color principal", f["color"])
|
| 193 |
+
datos = st.text_area("Datos de la empresa (pie de página)", f["empresa_datos"], height=70,
|
| 194 |
+
placeholder="Dirección, teléfonos, correo...")
|
| 195 |
+
nota = st.text_area("Nota al pie", f["nota"], height=90,
|
| 196 |
+
placeholder="Ej: Oferta válida por 5 días hábiles. Precios sin IVA. Forma de pago: ...")
|
| 197 |
+
condiciones = st.checkbox("Mostrar las condiciones de la cotización (vigencia mínima, descuento...)",
|
| 198 |
+
f["mostrar_condiciones"])
|
| 199 |
+
st.markdown("**Columnas:** marca las que salen y cambia su título, su ancho o su orden (el número más "
|
| 200 |
+
"bajo va primero).")
|
| 201 |
+
df = pd.DataFrame([{"Orden": i, "Mostrar": c["visible"], "Título": c["titulo"], "Ancho": c["ancho"],
|
| 202 |
+
"Qué lleva": formato.DESCRIPCION_COLUMNA[c["clave"]], "clave": c["clave"]}
|
| 203 |
+
for i, c in enumerate(f["columnas"], 1)])
|
| 204 |
+
ed = st.data_editor(df, hide_index=True, width="stretch", num_rows="fixed", disabled=["Qué lleva"],
|
| 205 |
+
column_order=["Orden", "Mostrar", "Título", "Ancho", "Qué lleva"],
|
| 206 |
+
key=f"fmt_cols_{hash(json.dumps(f['columnas']))}",
|
| 207 |
+
column_config={
|
| 208 |
+
"Orden": st.column_config.NumberColumn(min_value=1, step=1, width=60),
|
| 209 |
+
"Mostrar": st.column_config.CheckboxColumn(width=70),
|
| 210 |
+
"Ancho": st.column_config.NumberColumn(min_value=4, max_value=80, step=1,
|
| 211 |
+
width=70),
|
| 212 |
+
})
|
| 213 |
+
opciones = list(formato.FORMATOS)
|
| 214 |
+
preferido = st.radio("Formato de descarga por defecto", opciones, format_func=formato.FORMATOS.get,
|
| 215 |
+
horizontal=True, index=opciones.index(f["formato_descarga"]))
|
| 216 |
+
guardar = st.form_submit_button("Guardar formato", type="primary")
|
| 217 |
+
if guardar:
|
| 218 |
+
filas = ed.to_dict("records")
|
| 219 |
+
filas.sort(key=lambda x: (x["Orden"] if pd.notna(x["Orden"]) else 999)) # sort estable: empates igual
|
| 220 |
+
columnas = [{"clave": x["clave"], "titulo": x["Título"], "visible": bool(x["Mostrar"]),
|
| 221 |
+
"ancho": x["Ancho"] if pd.notna(x["Ancho"]) else None} for x in filas]
|
| 222 |
+
if not any(c["visible"] for c in columnas):
|
| 223 |
+
st.error("Deja al menos una columna visible.")
|
| 224 |
+
else:
|
| 225 |
+
formato.guardar({"empresa_nombre": nombre, "empresa_rif": rif, "empresa_datos": datos,
|
| 226 |
+
"titulo": titulo, "color": color, "nota": nota, "mostrar_condiciones": condiciones,
|
| 227 |
+
"columnas": columnas, "formato_descarga": preferido})
|
| 228 |
+
st.session_state.pop("tipo_descarga", None) # la descarga vuelve al formato por defecto
|
| 229 |
+
st.toast("Formato guardado.")
|
| 230 |
+
st.rerun()
|
| 231 |
+
st.button("Restablecer el formato original", on_click=formato.restablecer,
|
| 232 |
+
help="Vuelve a los títulos, columnas y colores de fábrica (el logo se conserva).")
|
| 233 |
+
|
| 234 |
+
|
| 235 |
# ---------------- barra lateral ----------------
|
| 236 |
RUTAS_CATALOGO = {"existencias": RUTA_EXIST, "precios": RUTA_PRECIOS}
|
| 237 |
|
|
|
|
| 373 |
pintar(pasos=self.pasos)
|
| 374 |
|
| 375 |
|
| 376 |
+
MIME = {"excel": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "pdf": "application/pdf"}
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
def boton_descarga(datos: bytes, nombre: str, tipo: str = "excel"):
|
| 380 |
"""Descarga con el archivo incrustado en la página (data URI). st.download_button lo pide aparte al servidor,
|
| 381 |
y en un Space privado esa petición llega sin la sesión de Hugging Face: se bajaba su página de acceso (HTML)."""
|
| 382 |
b64 = base64.b64encode(datos).decode()
|
| 383 |
st.markdown(f'<a class="boton-descarga" download="{html.escape(nombre)}" '
|
| 384 |
+
f'href="data:{MIME[tipo]};base64,{b64}">'
|
| 385 |
+
f'Descargar {formato.FORMATOS[tipo]}</a>', unsafe_allow_html=True)
|
| 386 |
|
| 387 |
|
| 388 |
def fallo_inesperado(que_hacia: str):
|
|
|
|
| 533 |
pintar()
|
| 534 |
agente.conversacion_completa()
|
| 535 |
panel_registro()
|
| 536 |
+
panel_formato()
|
| 537 |
|
| 538 |
if not catalogo:
|
| 539 |
detener()
|
|
|
|
| 847 |
|
| 848 |
pendientes = [l for l in cot.lineas if l.estado == "pendiente"]
|
| 849 |
if pendientes:
|
| 850 |
+
st.warning(f"{len(pendientes)} renglón(es) pendientes de revisión no saldrán en la cotización: "
|
| 851 |
+ ", ".join(f"{l.n}. {l.principio_activo}" for l in pendientes)
|
| 852 |
+ ". Confírmalos y vuelve a preparar la cotización.")
|
| 853 |
+
formato_actual = formato.leer()
|
| 854 |
+
opciones = list(formato.FORMATOS)
|
| 855 |
+
tipo = st.radio("Descargar en", opciones, format_func=formato.FORMATOS.get, horizontal=True,
|
| 856 |
+
index=opciones.index(formato_actual["formato_descarga"]), key="tipo_descarga",
|
| 857 |
+
help="El formato (logo, columnas, nota...) se cambia en «Formato de la cotización», arriba.")
|
| 858 |
incluir_todo = st.checkbox("Incluir también los renglones no ofertados (uso interno)")
|
| 859 |
+
extension = "pdf" if tipo == "pdf" else "xlsx"
|
| 860 |
+
nombre = f"RESPUESTA_{Path(st.session_state.get('archivo', 'solicitud')).stem}.{extension}"
|
| 861 |
+
try:
|
| 862 |
+
datos_salida = generar_cotizacion(cot, tipo, solo_ofertados=not incluir_todo, f=formato_actual)
|
| 863 |
+
except Exception: # noqa: BLE001
|
| 864 |
+
fallo_inesperado(f"preparar el {formato.FORMATOS[tipo]} de la cotización")
|
| 865 |
+
datos_salida = None
|
| 866 |
+
if datos_salida:
|
| 867 |
+
boton_descarga(datos_salida, nombre, tipo)
|
| 868 |
|
| 869 |
atender_orden()
|
| 870 |
pintar() # deja el panel con los últimos mensajes de esta pasada
|
excel_salida.py
CHANGED
|
@@ -1,19 +1,20 @@
|
|
| 1 |
-
"""Genera el Excel
|
| 2 |
from __future__ import annotations
|
| 3 |
|
| 4 |
import io
|
|
|
|
|
|
|
| 5 |
|
| 6 |
from openpyxl import Workbook
|
|
|
|
| 7 |
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
| 8 |
from openpyxl.utils import get_column_letter
|
| 9 |
|
| 10 |
-
import
|
| 11 |
-
from cotizacion import Cotizacion
|
| 12 |
|
| 13 |
-
AZUL = "192A69"
|
| 14 |
GRIS_TEXTO = "5A6475"
|
| 15 |
TEXTO = "1F2937"
|
| 16 |
-
FONDO_ALTERNO = "E9EEF8"
|
| 17 |
COLOR_ESTADO = { # color suave en la columna de observación
|
| 18 |
"parcial": "FFF4D6",
|
| 19 |
"no_cotizado": "F1F1F1",
|
|
@@ -21,99 +22,171 @@ COLOR_ESTADO = { # color suave en la columna de observación
|
|
| 21 |
}
|
| 22 |
FMT_USD = '\\$\\ #,##0.00'
|
| 23 |
FMT_USD4 = '\\$\\ #,##0.0000'
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
-
COLUMNAS = [
|
| 26 |
-
("N°", 5), ("PRINCIPIO ACTIVO", 24), ("CONC.", 14), ("FORMA", 11), ("PRESENTACIÓN/REFERENCIA", 37),
|
| 27 |
-
("CANTIDAD SOLICITADA", 14), ("CANTIDAD DISPONIBLE", 13), ("CANTIDAD OFERTADA", 13),
|
| 28 |
-
("PRECIO UNITARIO USD", 15), ("VENCIMIENTO", 12), ("TOTAL USD", 15), ("OBSERVACIÓN", 46),
|
| 29 |
-
]
|
| 30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
-
OFERTADOS = ("completa", "parcial", "sin_cantidad")
|
| 33 |
|
|
|
|
|
|
|
| 34 |
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
(
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
wb = Workbook()
|
| 40 |
ws = wb.active
|
| 41 |
ws.title = "COTIZACION"
|
| 42 |
-
ultima = get_column_letter(
|
| 43 |
borde = Border(bottom=Side(style="thin", color="D5DAE3"))
|
|
|
|
|
|
|
| 44 |
|
| 45 |
-
# ---- encabezado ----
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
# ---- tabla ----
|
| 67 |
-
fila_enc =
|
| 68 |
-
for i,
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
ws.column_dimensions[get_column_letter(i)].width = ancho
|
| 74 |
ws.row_dimensions[fila_enc].height = 30
|
| 75 |
|
|
|
|
|
|
|
| 76 |
r = fila_enc
|
| 77 |
for idx, l in enumerate(lineas):
|
| 78 |
r += 1
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
|
|
|
| 84 |
c = ws.cell(r, col, v)
|
| 85 |
-
c.font = Font(size=8, color=TEXTO, bold=(
|
| 86 |
c.fill = PatternFill("solid", fgColor=fondo)
|
| 87 |
c.border = borde
|
| 88 |
-
c.alignment = Alignment(horizontal="left" if
|
| 89 |
vertical="center", wrap_text=True)
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
# ---- total ----
|
| 99 |
r += 1
|
| 100 |
-
|
| 101 |
-
ws[f"A{r}"] = "TOTAL GENERAL USD"
|
| 102 |
-
ws[f"K{r}"] = f"=SUM(K{fila_enc + 1}:K{r - 1})"
|
| 103 |
-
ws[f"L{r}"] = (f"{len(lineas)} rubros ofertados de {len(cot.lineas)} solicitados" if solo_ofertados
|
| 104 |
-
else cot.resumen())
|
| 105 |
-
for col in range(1, len(COLUMNAS) + 1):
|
| 106 |
c = ws.cell(r, col)
|
| 107 |
c.font = Font(bold=True, size=9, color="FFFFFF")
|
| 108 |
-
c.fill = PatternFill("solid", fgColor=
|
| 109 |
-
c.alignment = Alignment(horizontal="
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
ws.row_dimensions[r].height = 24
|
| 112 |
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
ws.freeze_panes = f"A{fila_enc + 1}"
|
| 119 |
ws.page_setup.orientation = "landscape"
|
|
@@ -124,3 +197,159 @@ def generar_excel(cot: Cotizacion, solo_ofertados: bool = True) -> bytes:
|
|
| 124 |
buf = io.BytesIO()
|
| 125 |
wb.save(buf)
|
| 126 |
return buf.getvalue()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Genera la cotización para el cliente en Excel o en PDF, con el formato que editó el departamento (formato.py)."""
|
| 2 |
from __future__ import annotations
|
| 3 |
|
| 4 |
import io
|
| 5 |
+
import math
|
| 6 |
+
from datetime import date
|
| 7 |
|
| 8 |
from openpyxl import Workbook
|
| 9 |
+
from openpyxl.drawing.image import Image as ImagenExcel
|
| 10 |
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
| 11 |
from openpyxl.utils import get_column_letter
|
| 12 |
|
| 13 |
+
import formato as fmt
|
| 14 |
+
from cotizacion import Cotizacion, Linea
|
| 15 |
|
|
|
|
| 16 |
GRIS_TEXTO = "5A6475"
|
| 17 |
TEXTO = "1F2937"
|
|
|
|
| 18 |
COLOR_ESTADO = { # color suave en la columna de observación
|
| 19 |
"parcial": "FFF4D6",
|
| 20 |
"no_cotizado": "F1F1F1",
|
|
|
|
| 22 |
}
|
| 23 |
FMT_USD = '\\$\\ #,##0.00'
|
| 24 |
FMT_USD4 = '\\$\\ #,##0.0000'
|
| 25 |
+
A_LA_IZQUIERDA = {"principio_activo", "referencia", "observacion"}
|
| 26 |
+
CANTIDADES = {"cantidad_solicitada", "cantidad_disponible", "cantidad_ofertada"}
|
| 27 |
+
OFERTADOS = ("completa", "parcial", "sin_cantidad")
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
+
def _lineas(cot: Cotizacion, solo_ofertados: bool) -> list[Linea]:
|
| 31 |
+
"""solo_ofertados=True: lo que recibe el cliente lleva únicamente los renglones que se ofertan
|
| 32 |
+
(se conserva el N° original de la solicitud para que el cliente los ubique)."""
|
| 33 |
+
return [l for l in cot.lineas if l.estado in OFERTADOS] if solo_ofertados else cot.lineas
|
| 34 |
|
|
|
|
| 35 |
|
| 36 |
+
def _valor(l: Linea, clave: str):
|
| 37 |
+
return l.total if clave == "total" else getattr(l, clave)
|
| 38 |
|
| 39 |
+
|
| 40 |
+
def _rubros(cot: Cotizacion, lineas: list[Linea], solo_ofertados: bool) -> str:
|
| 41 |
+
return (f"{len(lineas)} de {len(cot.lineas)} rubro(s) ofertados" if solo_ofertados
|
| 42 |
+
else f"{len(cot.lineas)} rubro(s)")
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _pie_total(cot: Cotizacion, lineas: list[Linea], solo_ofertados: bool) -> str:
|
| 46 |
+
return (f"{len(lineas)} rubros ofertados de {len(cot.lineas)} solicitados" if solo_ofertados
|
| 47 |
+
else cot.resumen())
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# ======================= Excel =======================
|
| 51 |
+
def generar_excel(cot: Cotizacion, solo_ofertados: bool = True, f: dict | None = None) -> bytes:
|
| 52 |
+
f = f or fmt.leer()
|
| 53 |
+
columnas = fmt.visibles(f)
|
| 54 |
+
claves = [c["clave"] for c in columnas]
|
| 55 |
+
n = len(columnas)
|
| 56 |
+
color = fmt.hex_sin_numeral(f["color"])
|
| 57 |
+
alterno = fmt.aclarar(f["color"])
|
| 58 |
+
lineas = _lineas(cot, solo_ofertados)
|
| 59 |
wb = Workbook()
|
| 60 |
ws = wb.active
|
| 61 |
ws.title = "COTIZACION"
|
| 62 |
+
ultima = get_column_letter(n)
|
| 63 |
borde = Border(bottom=Side(style="thin", color="D5DAE3"))
|
| 64 |
+
for i, c in enumerate(columnas, 1):
|
| 65 |
+
ws.column_dimensions[get_column_letter(i)].width = c["ancho"]
|
| 66 |
|
| 67 |
+
# ---- encabezado: empresa a la izquierda, título y fecha a la derecha ----
|
| 68 |
+
k = max(1, math.ceil(n / 2)) # columnas del bloque izquierdo
|
| 69 |
+
izq = lambda r: f"A{r}:{get_column_letter(k)}{r}"
|
| 70 |
+
der = (lambda r: f"{get_column_letter(k + 1)}{r}:{ultima}{r}") if n > 1 else None
|
| 71 |
+
|
| 72 |
+
def poner(rango: str, texto: str, fuente: Font, derecha: bool = False):
|
| 73 |
+
ws.merge_cells(rango)
|
| 74 |
+
celda = ws[rango.split(":")[0]]
|
| 75 |
+
celda.value = texto
|
| 76 |
+
celda.font = fuente
|
| 77 |
+
celda.alignment = Alignment(horizontal="right" if derecha else "left", vertical="center",
|
| 78 |
+
wrap_text=True)
|
| 79 |
+
|
| 80 |
+
r = 1
|
| 81 |
+
logo = fmt.logo()
|
| 82 |
+
if logo:
|
| 83 |
+
img = ImagenExcel(io.BytesIO(logo))
|
| 84 |
+
alto = 60
|
| 85 |
+
img.width, img.height = round(img.width * alto / img.height), alto
|
| 86 |
+
ws.add_image(img, "A1")
|
| 87 |
+
ws.row_dimensions[1].height = 48
|
| 88 |
+
if der:
|
| 89 |
+
poner(der(1), f["titulo"], Font(bold=True, size=18, color=color), derecha=True)
|
| 90 |
+
r = 2
|
| 91 |
+
grande = Font(bold=True, size=20 if not logo else 14, color=color)
|
| 92 |
+
textos_izq = [(f["empresa_nombre"], grande), (f["empresa_rif"], Font(size=10, color=TEXTO))]
|
| 93 |
+
textos_der = ([] if logo else [(f["titulo"], Font(bold=True, size=20, color=color))])
|
| 94 |
+
textos_der.append((f"Fecha: {cot.fecha.strftime('%d/%m/%Y')} · {_rubros(cot, lineas, solo_ofertados)}",
|
| 95 |
+
Font(size=10, color=TEXTO)))
|
| 96 |
+
if not der: # una sola columna: todo apilado
|
| 97 |
+
textos_izq += textos_der
|
| 98 |
+
textos_der = []
|
| 99 |
+
for i in range(max(len(textos_izq), len(textos_der))):
|
| 100 |
+
if i < len(textos_izq) and textos_izq[i][0]:
|
| 101 |
+
poner(izq(r), *textos_izq[i])
|
| 102 |
+
if i < len(textos_der) and der:
|
| 103 |
+
poner(der(r), *textos_der[i], derecha=True)
|
| 104 |
+
r += 1
|
| 105 |
+
poner(f"A{r}:{ultima}{r}", f"Para: {cot.cliente or 'Quien Solicite'}", Font(bold=True, size=11, color=color))
|
| 106 |
+
r += 1
|
| 107 |
+
if f["mostrar_condiciones"]:
|
| 108 |
+
poner(f"A{r}:{ultima}{r}", cot.condiciones(), Font(size=9, color=GRIS_TEXTO))
|
| 109 |
+
ws[f"A{r}"].alignment = Alignment(wrap_text=True, vertical="top")
|
| 110 |
+
ws.row_dimensions[r].height = 30
|
| 111 |
+
r += 1
|
| 112 |
|
| 113 |
# ---- tabla ----
|
| 114 |
+
fila_enc = r + 1
|
| 115 |
+
for i, c in enumerate(columnas, 1):
|
| 116 |
+
celda = ws.cell(fila_enc, i, c["titulo"])
|
| 117 |
+
celda.font = Font(bold=True, size=8, color="FFFFFF")
|
| 118 |
+
celda.fill = PatternFill("solid", fgColor=color)
|
| 119 |
+
celda.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
|
|
|
| 120 |
ws.row_dimensions[fila_enc].height = 30
|
| 121 |
|
| 122 |
+
letra = {clave: get_column_letter(i) for i, clave in enumerate(claves, 1)}
|
| 123 |
+
con_formula = "cantidad_ofertada" in letra and "precio_unitario" in letra
|
| 124 |
r = fila_enc
|
| 125 |
for idx, l in enumerate(lineas):
|
| 126 |
r += 1
|
| 127 |
+
fondo = alterno if idx % 2 else "FFFFFF"
|
| 128 |
+
for col, clave in enumerate(claves, 1):
|
| 129 |
+
v = _valor(l, clave)
|
| 130 |
+
if clave == "total" and con_formula: # fórmula: si el cliente cambia la cantidad, el total se ajusta
|
| 131 |
+
h, p = letra["cantidad_ofertada"], letra["precio_unitario"]
|
| 132 |
+
v = f'=IF(AND({h}{r}<>"",{p}{r}<>""),ROUND({h}{r}*{p}{r},2),"")'
|
| 133 |
c = ws.cell(r, col, v)
|
| 134 |
+
c.font = Font(size=8, color=TEXTO, bold=(clave == "principio_activo"))
|
| 135 |
c.fill = PatternFill("solid", fgColor=fondo)
|
| 136 |
c.border = borde
|
| 137 |
+
c.alignment = Alignment(horizontal="left" if clave in A_LA_IZQUIERDA else "center",
|
| 138 |
vertical="center", wrap_text=True)
|
| 139 |
+
if clave in CANTIDADES:
|
| 140 |
+
c.number_format = "#,##0"
|
| 141 |
+
elif clave == "precio_unitario":
|
| 142 |
+
c.number_format = FMT_USD4 if (l.precio_unitario or 1) < 0.1 else FMT_USD
|
| 143 |
+
elif clave == "vencimiento":
|
| 144 |
+
c.number_format = "mm/yyyy"
|
| 145 |
+
elif clave == "total":
|
| 146 |
+
c.number_format = FMT_USD
|
| 147 |
+
elif clave == "observacion" and l.estado in COLOR_ESTADO:
|
| 148 |
+
c.fill = PatternFill("solid", fgColor=COLOR_ESTADO[l.estado])
|
| 149 |
|
| 150 |
# ---- total ----
|
| 151 |
r += 1
|
| 152 |
+
for col in range(1, n + 1):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
c = ws.cell(r, col)
|
| 154 |
c.font = Font(bold=True, size=9, color="FFFFFF")
|
| 155 |
+
c.fill = PatternFill("solid", fgColor=color)
|
| 156 |
+
c.alignment = Alignment(horizontal="right", vertical="center", wrap_text=True)
|
| 157 |
+
total_general = (f"=SUM({letra['total']}{fila_enc + 1}:{letra['total']}{r - 1})" if "total" in letra
|
| 158 |
+
else None)
|
| 159 |
+
pie = _pie_total(cot, lineas, solo_ofertados)
|
| 160 |
+
if "total" in letra:
|
| 161 |
+
i = claves.index("total") + 1
|
| 162 |
+
ws.cell(r, i, total_general).number_format = FMT_USD
|
| 163 |
+
if i > 1:
|
| 164 |
+
if i > 2:
|
| 165 |
+
ws.merge_cells(f"A{r}:{get_column_letter(i - 1)}{r}")
|
| 166 |
+
ws.cell(r, 1, "TOTAL GENERAL USD")
|
| 167 |
+
if i < n:
|
| 168 |
+
if i + 1 < n:
|
| 169 |
+
ws.merge_cells(f"{get_column_letter(i + 1)}{r}:{ultima}{r}")
|
| 170 |
+
ws.cell(r, i + 1, pie).alignment = Alignment(horizontal="left", vertical="center", wrap_text=True)
|
| 171 |
+
else:
|
| 172 |
+
if n > 1:
|
| 173 |
+
ws.merge_cells(f"A{r}:{ultima}{r}")
|
| 174 |
+
ws.cell(r, 1, f"TOTAL GENERAL USD $ {cot_total(lineas):,.2f} · {pie}")
|
| 175 |
ws.row_dimensions[r].height = 24
|
| 176 |
|
| 177 |
+
# ---- nota y datos de la empresa ----
|
| 178 |
+
r += 1
|
| 179 |
+
for texto, color_texto in ((f["nota"], TEXTO), (f["empresa_datos"], GRIS_TEXTO)):
|
| 180 |
+
if not texto:
|
| 181 |
+
continue
|
| 182 |
+
r += 1
|
| 183 |
+
if n > 1:
|
| 184 |
+
ws.merge_cells(f"A{r}:{ultima}{r}")
|
| 185 |
+
ws[f"A{r}"] = texto
|
| 186 |
+
ws[f"A{r}"].font = Font(size=9, color=color_texto)
|
| 187 |
+
ws[f"A{r}"].alignment = Alignment(wrap_text=True, vertical="top")
|
| 188 |
+
lineas_texto = sum(1 + len(p) // 160 for p in texto.splitlines() or [""])
|
| 189 |
+
ws.row_dimensions[r].height = max(15, 13 * lineas_texto)
|
| 190 |
|
| 191 |
ws.freeze_panes = f"A{fila_enc + 1}"
|
| 192 |
ws.page_setup.orientation = "landscape"
|
|
|
|
| 197 |
buf = io.BytesIO()
|
| 198 |
wb.save(buf)
|
| 199 |
return buf.getvalue()
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def cot_total(lineas: list[Linea]) -> float:
|
| 203 |
+
return round(sum(l.total or 0 for l in lineas), 2)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
# ======================= PDF =======================
|
| 207 |
+
def _texto_pdf(l: Linea, clave: str) -> str:
|
| 208 |
+
v = _valor(l, clave)
|
| 209 |
+
if v is None or v == "":
|
| 210 |
+
return ""
|
| 211 |
+
if clave in CANTIDADES:
|
| 212 |
+
return f"{v:,}".replace(",", ".")
|
| 213 |
+
if clave in ("precio_unitario", "total"):
|
| 214 |
+
decimales = 4 if clave == "precio_unitario" and v < 0.1 else 2
|
| 215 |
+
return "$ " + f"{v:,.{decimales}f}".replace(",", "X").replace(".", ",").replace("X", ".")
|
| 216 |
+
if clave == "vencimiento" and isinstance(v, date):
|
| 217 |
+
return v.strftime("%m/%Y")
|
| 218 |
+
return str(v)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def generar_pdf(cot: Cotizacion, solo_ofertados: bool = True, f: dict | None = None) -> bytes:
|
| 222 |
+
from xml.sax.saxutils import escape
|
| 223 |
+
|
| 224 |
+
from reportlab.lib import colors
|
| 225 |
+
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_RIGHT
|
| 226 |
+
from reportlab.lib.pagesizes import landscape, letter
|
| 227 |
+
from reportlab.lib.styles import ParagraphStyle
|
| 228 |
+
from reportlab.lib.units import mm
|
| 229 |
+
from reportlab.platypus import Image, Paragraph, SimpleDocTemplate, Spacer, Table, TableStyle
|
| 230 |
+
|
| 231 |
+
f = f or fmt.leer()
|
| 232 |
+
columnas = fmt.visibles(f)
|
| 233 |
+
claves = [c["clave"] for c in columnas]
|
| 234 |
+
lineas = _lineas(cot, solo_ofertados)
|
| 235 |
+
color = colors.HexColor(f["color"])
|
| 236 |
+
alterno = colors.HexColor("#" + fmt.aclarar(f["color"]))
|
| 237 |
+
gris = colors.HexColor("#" + GRIS_TEXTO)
|
| 238 |
+
texto = colors.HexColor("#" + TEXTO)
|
| 239 |
+
|
| 240 |
+
buf = io.BytesIO()
|
| 241 |
+
margen = 12 * mm
|
| 242 |
+
doc = SimpleDocTemplate(buf, pagesize=landscape(letter), leftMargin=margen, rightMargin=margen,
|
| 243 |
+
topMargin=margen, bottomMargin=margen, title=f["titulo"], author=f["empresa_nombre"])
|
| 244 |
+
ancho_util = doc.width - 12 # el marco de la página tiene 6 pt de relleno a cada lado
|
| 245 |
+
|
| 246 |
+
def estilo(nombre, **kw):
|
| 247 |
+
base = dict(fontName="Helvetica", fontSize=8, leading=10, textColor=texto)
|
| 248 |
+
base.update(kw)
|
| 249 |
+
return ParagraphStyle(nombre, **base)
|
| 250 |
+
|
| 251 |
+
e_empresa = estilo("empresa", fontName="Helvetica-Bold", fontSize=16, leading=19, textColor=color)
|
| 252 |
+
e_titulo = estilo("titulo", fontName="Helvetica-Bold", fontSize=14, leading=17, textColor=color, alignment=TA_RIGHT)
|
| 253 |
+
e_der = estilo("der", fontSize=9, leading=11, alignment=TA_RIGHT)
|
| 254 |
+
e_izq = estilo("izq", fontSize=9, leading=11)
|
| 255 |
+
e_para = estilo("para", fontName="Helvetica-Bold", fontSize=10, leading=12, textColor=color)
|
| 256 |
+
e_cond = estilo("cond", fontSize=8, leading=10, textColor=gris)
|
| 257 |
+
e_enc = estilo("enc", fontName="Helvetica-Bold", fontSize=6.3, leading=7.6, textColor=colors.white,
|
| 258 |
+
alignment=TA_CENTER)
|
| 259 |
+
e_celda = {"izq": estilo("c_izq", fontSize=7, leading=8.5, alignment=TA_LEFT),
|
| 260 |
+
"centro": estilo("c_centro", fontSize=7, leading=8.5, alignment=TA_CENTER),
|
| 261 |
+
"negrita": estilo("c_neg", fontName="Helvetica-Bold", fontSize=7, leading=8.5)}
|
| 262 |
+
e_total = estilo("total", fontName="Helvetica-Bold", fontSize=8, leading=10, textColor=colors.white,
|
| 263 |
+
alignment=TA_RIGHT)
|
| 264 |
+
e_total_izq = estilo("total_izq", fontName="Helvetica-Bold", fontSize=8, leading=10, textColor=colors.white)
|
| 265 |
+
p = lambda t, e: Paragraph(escape(str(t)).replace("\n", "<br/>"), e)
|
| 266 |
+
|
| 267 |
+
historia = []
|
| 268 |
+
# ---- encabezado ----
|
| 269 |
+
izquierda = []
|
| 270 |
+
logo = fmt.logo()
|
| 271 |
+
if logo:
|
| 272 |
+
from PIL import Image as PILImage
|
| 273 |
+
with PILImage.open(io.BytesIO(logo)) as im:
|
| 274 |
+
w, h = im.size
|
| 275 |
+
alto = 16 * mm
|
| 276 |
+
img = Image(io.BytesIO(logo), width=min(alto * w / h, ancho_util * 0.45), height=alto)
|
| 277 |
+
img.hAlign = "LEFT"
|
| 278 |
+
izquierda.append(img)
|
| 279 |
+
if f["empresa_nombre"]:
|
| 280 |
+
izquierda.append(p(f["empresa_nombre"], e_empresa))
|
| 281 |
+
if f["empresa_rif"]:
|
| 282 |
+
izquierda.append(p(f["empresa_rif"], e_izq))
|
| 283 |
+
derecha = [p(f["titulo"], e_titulo),
|
| 284 |
+
p(f"Fecha: {cot.fecha.strftime('%d/%m/%Y')} · {_rubros(cot, lineas, solo_ofertados)}", e_der)]
|
| 285 |
+
cab = Table([[izquierda or "", derecha]], colWidths=[ancho_util * 0.5, ancho_util * 0.5])
|
| 286 |
+
cab.setStyle(TableStyle([("VALIGN", (0, 0), (-1, -1), "BOTTOM"), ("LEFTPADDING", (0, 0), (-1, -1), 0),
|
| 287 |
+
("RIGHTPADDING", (0, 0), (-1, -1), 0)]))
|
| 288 |
+
historia += [cab, Spacer(1, 4 * mm), p(f"Para: {cot.cliente or 'Quien Solicite'}", e_para)]
|
| 289 |
+
if f["mostrar_condiciones"]:
|
| 290 |
+
historia += [Spacer(1, 1.5 * mm), p(cot.condiciones(), e_cond)]
|
| 291 |
+
historia.append(Spacer(1, 4 * mm))
|
| 292 |
+
|
| 293 |
+
# ---- tabla ----
|
| 294 |
+
total_anchos = sum(c["ancho"] for c in columnas)
|
| 295 |
+
anchos = [ancho_util * c["ancho"] / total_anchos for c in columnas]
|
| 296 |
+
filas = [[p(c["titulo"], e_enc) for c in columnas]]
|
| 297 |
+
estilos = [("BACKGROUND", (0, 0), (-1, 0), color), ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
|
| 298 |
+
("LINEBELOW", (0, 1), (-1, -2), 0.4, colors.HexColor("#D5DAE3")),
|
| 299 |
+
("TOPPADDING", (0, 0), (-1, -1), 3), ("BOTTOMPADDING", (0, 0), (-1, -1), 3),
|
| 300 |
+
("LEFTPADDING", (0, 0), (-1, -1), 3), ("RIGHTPADDING", (0, 0), (-1, -1), 3)]
|
| 301 |
+
for idx, l in enumerate(lineas, 1):
|
| 302 |
+
fila = []
|
| 303 |
+
for clave in claves:
|
| 304 |
+
e = (e_celda["negrita"] if clave == "principio_activo"
|
| 305 |
+
else e_celda["izq"] if clave in A_LA_IZQUIERDA else e_celda["centro"])
|
| 306 |
+
fila.append(p(_texto_pdf(l, clave), e))
|
| 307 |
+
filas.append(fila)
|
| 308 |
+
if idx % 2 == 0:
|
| 309 |
+
estilos.append(("BACKGROUND", (0, idx), (-1, idx), alterno))
|
| 310 |
+
if "observacion" in claves and l.estado in COLOR_ESTADO:
|
| 311 |
+
j = claves.index("observacion")
|
| 312 |
+
estilos.append(("BACKGROUND", (j, idx), (j, idx), colors.HexColor("#" + COLOR_ESTADO[l.estado])))
|
| 313 |
+
|
| 314 |
+
# ---- total ----
|
| 315 |
+
total_txt = "$ " + f"{cot_total(lineas):,.2f}".replace(",", "X").replace(".", ",").replace("X", ".")
|
| 316 |
+
pie = _pie_total(cot, lineas, solo_ofertados)
|
| 317 |
+
ultima_fila = [""] * len(claves)
|
| 318 |
+
t = len(filas)
|
| 319 |
+
if "total" in claves and len(claves) > 1:
|
| 320 |
+
i = claves.index("total")
|
| 321 |
+
ultima_fila[i] = p(total_txt, e_total)
|
| 322 |
+
if i > 0:
|
| 323 |
+
ultima_fila[0] = p("TOTAL GENERAL USD", e_total)
|
| 324 |
+
estilos.append(("SPAN", (0, t), (i - 1, t)))
|
| 325 |
+
if i < len(claves) - 1:
|
| 326 |
+
ultima_fila[i + 1] = p(pie, e_total_izq)
|
| 327 |
+
estilos.append(("SPAN", (i + 1, t), (-1, t)))
|
| 328 |
+
else:
|
| 329 |
+
ultima_fila[0] = p(f"TOTAL GENERAL USD {total_txt} · {pie}", e_total)
|
| 330 |
+
estilos.append(("SPAN", (0, t), (-1, t)))
|
| 331 |
+
filas.append(ultima_fila)
|
| 332 |
+
estilos.append(("BACKGROUND", (0, t), (-1, t), color))
|
| 333 |
+
tabla = Table(filas, colWidths=anchos, repeatRows=1)
|
| 334 |
+
tabla.setStyle(TableStyle(estilos))
|
| 335 |
+
historia.append(tabla)
|
| 336 |
+
|
| 337 |
+
# ---- nota y datos de la empresa ----
|
| 338 |
+
if f["nota"]:
|
| 339 |
+
historia += [Spacer(1, 5 * mm), p(f["nota"], estilo("nota", fontSize=8.5, leading=11))]
|
| 340 |
+
if f["empresa_datos"]:
|
| 341 |
+
historia += [Spacer(1, 3 * mm), p(f["empresa_datos"], e_cond)]
|
| 342 |
+
|
| 343 |
+
def numerar(canvas, documento):
|
| 344 |
+
canvas.saveState()
|
| 345 |
+
canvas.setFont("Helvetica", 7)
|
| 346 |
+
canvas.setFillColor(gris)
|
| 347 |
+
canvas.drawRightString(documento.pagesize[0] - margen, margen / 2, f"Página {documento.page}")
|
| 348 |
+
canvas.restoreState()
|
| 349 |
+
|
| 350 |
+
doc.build(historia, onFirstPage=numerar, onLaterPages=numerar)
|
| 351 |
+
return buf.getvalue()
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def generar(cot: Cotizacion, tipo: str, solo_ofertados: bool = True, f: dict | None = None) -> bytes:
|
| 355 |
+
return (generar_pdf if tipo == "pdf" else generar_excel)(cot, solo_ofertados, f)
|
formato.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Formato de la cotización que recibe el cliente (Excel y PDF). Lo edita el departamento desde la app y se guarda en
|
| 2 |
+
DATA_DIR/formato.json (el logo en DATA_DIR/logo.png); en el Space, en el bucket. Vale para todos los usuarios.
|
| 3 |
+
|
| 4 |
+
Los valores por defecto de la empresa salen de las variables EMPRESA_NOMBRE, EMPRESA_RIF y EMPRESA_DATOS.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import copy
|
| 9 |
+
import io
|
| 10 |
+
import json
|
| 11 |
+
import re
|
| 12 |
+
|
| 13 |
+
import config
|
| 14 |
+
|
| 15 |
+
RUTA = config.DATA_DIR / "formato.json"
|
| 16 |
+
RUTA_LOGO = config.DATA_DIR / "logo.png"
|
| 17 |
+
FORMATOS = {"excel": "Excel", "pdf": "PDF"}
|
| 18 |
+
|
| 19 |
+
# clave -> (título por defecto, ancho por defecto en caracteres de Excel). El orden es el de la tabla por defecto.
|
| 20 |
+
COLUMNAS = {
|
| 21 |
+
"n": ("N°", 5),
|
| 22 |
+
"principio_activo": ("PRINCIPIO ACTIVO", 24),
|
| 23 |
+
"concentracion": ("CONC.", 14),
|
| 24 |
+
"forma": ("FORMA", 11),
|
| 25 |
+
"referencia": ("PRESENTACIÓN/REFERENCIA", 37),
|
| 26 |
+
"cantidad_solicitada": ("CANTIDAD SOLICITADA", 14),
|
| 27 |
+
"cantidad_disponible": ("CANTIDAD DISPONIBLE", 14),
|
| 28 |
+
"cantidad_ofertada": ("CANTIDAD OFERTADA", 13),
|
| 29 |
+
"precio_unitario": ("PRECIO UNITARIO USD", 15),
|
| 30 |
+
"vencimiento": ("VENCIMIENTO", 13),
|
| 31 |
+
"total": ("TOTAL USD", 15),
|
| 32 |
+
"observacion": ("OBSERVACIÓN", 46),
|
| 33 |
+
}
|
| 34 |
+
DESCRIPCION_COLUMNA = { # para el editor: qué dato lleva cada columna
|
| 35 |
+
"n": "Número de renglón de la solicitud",
|
| 36 |
+
"principio_activo": "Producto como lo pidió el cliente",
|
| 37 |
+
"concentracion": "Concentración pedida",
|
| 38 |
+
"forma": "Forma farmacéutica pedida",
|
| 39 |
+
"referencia": "Referencia del cliente o producto ofertado",
|
| 40 |
+
"cantidad_solicitada": "Unidades que pidió el cliente",
|
| 41 |
+
"cantidad_disponible": "Existencia válida por vencimiento",
|
| 42 |
+
"cantidad_ofertada": "Unidades que se ofertan",
|
| 43 |
+
"precio_unitario": "Precio por unidad",
|
| 44 |
+
"vencimiento": "Vencimiento más próximo de lo ofertado",
|
| 45 |
+
"total": "Ofertada × precio",
|
| 46 |
+
"observacion": "Explicación de cada renglón",
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def por_defecto() -> dict:
|
| 51 |
+
return {
|
| 52 |
+
"empresa_nombre": config.EMPRESA_NOMBRE,
|
| 53 |
+
"empresa_rif": config.EMPRESA_RIF,
|
| 54 |
+
"empresa_datos": config.EMPRESA_DATOS,
|
| 55 |
+
"titulo": "RESPUESTA A SOLICITUD DE COTIZACIÓN",
|
| 56 |
+
"color": "#192A69",
|
| 57 |
+
"mostrar_condiciones": True,
|
| 58 |
+
"nota": "",
|
| 59 |
+
"columnas": [{"clave": k, "titulo": t, "visible": True, "ancho": a} for k, (t, a) in COLUMNAS.items()],
|
| 60 |
+
"formato_descarga": "excel",
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _color_valido(c: str) -> bool:
|
| 65 |
+
return bool(re.fullmatch(r"#[0-9A-Fa-f]{6}", c or ""))
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def normalizar(datos: dict) -> dict:
|
| 69 |
+
"""Completa lo que falte con los valores por defecto y corrige lo que no sirva (formato viejo o editado a mano)."""
|
| 70 |
+
base = por_defecto()
|
| 71 |
+
f = {k: datos.get(k, v) for k, v in base.items()}
|
| 72 |
+
for k in ("empresa_nombre", "empresa_rif", "empresa_datos", "titulo", "nota"):
|
| 73 |
+
f[k] = str(f[k] or "").strip()
|
| 74 |
+
if not _color_valido(f["color"]):
|
| 75 |
+
f["color"] = base["color"]
|
| 76 |
+
f["mostrar_condiciones"] = bool(f["mostrar_condiciones"])
|
| 77 |
+
if f["formato_descarga"] not in FORMATOS:
|
| 78 |
+
f["formato_descarga"] = "excel"
|
| 79 |
+
columnas, vistas = [], set()
|
| 80 |
+
for c in f["columnas"] if isinstance(f["columnas"], list) else []:
|
| 81 |
+
clave = c.get("clave") if isinstance(c, dict) else None
|
| 82 |
+
if clave not in COLUMNAS or clave in vistas:
|
| 83 |
+
continue
|
| 84 |
+
vistas.add(clave)
|
| 85 |
+
titulo_def, ancho_def = COLUMNAS[clave]
|
| 86 |
+
try:
|
| 87 |
+
ancho = min(80, max(4, int(c.get("ancho") or ancho_def)))
|
| 88 |
+
except (TypeError, ValueError):
|
| 89 |
+
ancho = ancho_def
|
| 90 |
+
columnas.append({"clave": clave, "titulo": str(c.get("titulo") or "").strip() or titulo_def,
|
| 91 |
+
"visible": bool(c.get("visible", True)), "ancho": ancho})
|
| 92 |
+
for clave, (titulo, ancho) in COLUMNAS.items(): # columnas nuevas o que faltaban, al final y visibles
|
| 93 |
+
if clave not in vistas:
|
| 94 |
+
columnas.append({"clave": clave, "titulo": titulo, "visible": True, "ancho": ancho})
|
| 95 |
+
if not any(c["visible"] for c in columnas):
|
| 96 |
+
columnas[0]["visible"] = True
|
| 97 |
+
f["columnas"] = columnas
|
| 98 |
+
return f
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def leer() -> dict:
|
| 102 |
+
try:
|
| 103 |
+
return normalizar(json.loads(RUTA.read_text(encoding="utf-8")))
|
| 104 |
+
except (FileNotFoundError, json.JSONDecodeError, AttributeError):
|
| 105 |
+
return por_defecto()
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def guardar(f: dict):
|
| 109 |
+
RUTA.parent.mkdir(parents=True, exist_ok=True)
|
| 110 |
+
RUTA.write_text(json.dumps(normalizar(f), ensure_ascii=False, indent=1), encoding="utf-8")
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def restablecer():
|
| 114 |
+
RUTA.unlink(missing_ok=True)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def visibles(f: dict) -> list[dict]:
|
| 118 |
+
return [c for c in f["columnas"] if c["visible"]]
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
# ---------------- logo ----------------
|
| 122 |
+
def logo() -> bytes | None:
|
| 123 |
+
return RUTA_LOGO.read_bytes() if RUTA_LOGO.exists() else None
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def guardar_logo(datos: bytes):
|
| 127 |
+
"""Lo deja en PNG de 600 px como máximo (pesa poco y se ve bien en el Excel y el PDF). Lanza ValueError si la
|
| 128 |
+
imagen no se puede abrir."""
|
| 129 |
+
from PIL import Image
|
| 130 |
+
try:
|
| 131 |
+
img = Image.open(io.BytesIO(datos))
|
| 132 |
+
img.load()
|
| 133 |
+
except Exception as e: # noqa: BLE001
|
| 134 |
+
raise ValueError("No pude abrir la imagen del logo. Usa un PNG o JPG.") from e
|
| 135 |
+
img = img.convert("RGBA")
|
| 136 |
+
img.thumbnail((600, 600))
|
| 137 |
+
RUTA_LOGO.parent.mkdir(parents=True, exist_ok=True)
|
| 138 |
+
buf = io.BytesIO()
|
| 139 |
+
img.save(buf, format="PNG")
|
| 140 |
+
RUTA_LOGO.write_bytes(buf.getvalue())
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def quitar_logo():
|
| 144 |
+
RUTA_LOGO.unlink(missing_ok=True)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
# ---------------- colores ----------------
|
| 148 |
+
def hex_sin_numeral(color: str) -> str:
|
| 149 |
+
return color.lstrip("#").upper()
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def aclarar(color: str, cuanto: float = 0.9) -> str:
|
| 153 |
+
"""Mezcla el color con blanco: para el fondo alterno de las filas."""
|
| 154 |
+
c = hex_sin_numeral(color)
|
| 155 |
+
r, g, b = (int(c[i:i + 2], 16) for i in (0, 2, 4))
|
| 156 |
+
r, g, b = (round(x + (255 - x) * cuanto) for x in (r, g, b))
|
| 157 |
+
return f"{r:02X}{g:02X}{b:02X}"
|
requirements.txt
CHANGED
|
@@ -8,3 +8,4 @@ pdfplumber>=0.11
|
|
| 8 |
pypdfium2>=4.30
|
| 9 |
pillow>=10.0
|
| 10 |
python-dotenv>=1.0
|
|
|
|
|
|
| 8 |
pypdfium2>=4.30
|
| 9 |
pillow>=10.0
|
| 10 |
python-dotenv>=1.0
|
| 11 |
+
reportlab>=4.2
|