Salida con formato de presupuesto
Browse files- README.md +13 -6
- app.py +47 -21
- excel_salida.py +254 -228
- formato.py +51 -39
- ia.py +3 -2
README.md
CHANGED
|
@@ -64,12 +64,19 @@ solicitud anterior. También avisa si es la misma solicitud que ya tiene leída
|
|
| 64 |
si persiste, comunicarse con `CONTACTO_SOPORTE`. El detalle técnico queda en los logs del
|
| 65 |
servidor (en el Space: *Logs*), en las líneas que empiezan por `[llm]` y `[app]`.
|
| 66 |
|
| 67 |
-
**
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
**Descarga:** el archivo va incrustado en la página. El botón estándar de Streamlit lo pedía aparte al
|
| 75 |
servidor y, en un Space privado, esa petición llegaba sin la sesión de Hugging Face y se descargaba su página de
|
|
|
|
| 64 |
si persiste, comunicarse con `CONTACTO_SOPORTE`. El detalle técnico queda en los logs del
|
| 65 |
servidor (en el Space: *Logs*), en las líneas que empiezan por `[llm]` y `[app]`.
|
| 66 |
|
| 67 |
+
**Presupuesto (Excel o PDF):** lo que recibe el cliente sale con diseño de presupuesto: logo y nombre arriba a la
|
| 68 |
+
izquierda, «PRESUPUESTO» a la derecha, un recuadro con los datos del cliente (Cliente, Dirección, No. ID Fiscal,
|
| 69 |
+
Dirección de despacho, Tlf.) y la fecha, la tabla (Descripción —nuestro producto—, Venc. MM/AA, Cant., P/Unidad,
|
| 70 |
+
Total) y al pie el almacén, el total de unidades, el total, el impuesto, el neto y «DOCUMENTO NO FISCAL».
|
| 71 |
+
- En «Formato del presupuesto» se edita: logo, nombre y segunda línea bajo el logo, título, color, almacén por
|
| 72 |
+
defecto, impuesto (%), texto legal, pie de página, una nota, si se muestran las condiciones junto a la fecha, y las
|
| 73 |
+
columnas (mostrar u ocultar, renombrar, ancho y orden; hay columnas opcionales: N°, pedido del cliente y
|
| 74 |
+
observación). Se guarda en `data/formato.json` y `data/logo.png` (en el Space, en el bucket) y vale para todos.
|
| 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 |
+
- Al descargar se elige Excel o PDF (A4 vertical). El Excel conserva las fórmulas del total de cada renglón, del total,
|
| 79 |
+
del impuesto y del neto.
|
| 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
|
app.py
CHANGED
|
@@ -102,11 +102,18 @@ def huella() -> str:
|
|
| 102 |
return h.hexdigest()
|
| 103 |
|
| 104 |
|
| 105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
try:
|
| 107 |
-
|
| 108 |
except (FileNotFoundError, json.JSONDecodeError):
|
| 109 |
return {}
|
|
|
|
| 110 |
|
| 111 |
|
| 112 |
# ---------------- arreglos de las alertas del catálogo ----------------
|
|
@@ -257,9 +264,10 @@ def subir_logo(archivo):
|
|
| 257 |
|
| 258 |
def panel_formato():
|
| 259 |
f = formato.leer()
|
| 260 |
-
with st.expander("Formato
|
| 261 |
-
st.caption("Así sale
|
| 262 |
-
"aplican a la próxima descarga.
|
|
|
|
| 263 |
c_logo, c_subir = st.columns([1, 3])
|
| 264 |
logo = formato.logo()
|
| 265 |
if logo:
|
|
@@ -273,16 +281,21 @@ def panel_formato():
|
|
| 273 |
|
| 274 |
with st.form("form_formato"):
|
| 275 |
c1, c2 = st.columns(2)
|
| 276 |
-
nombre = c1.text_input("Nombre
|
| 277 |
-
rif = c1.text_input("
|
| 278 |
titulo = c2.text_input("Título del documento", f["titulo"])
|
| 279 |
-
color = c2.color_picker("Color
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 286 |
st.markdown("**Columnas:** marca las que salen y cambia su título, su ancho o su orden (el número más "
|
| 287 |
"bajo va primero).")
|
| 288 |
df = pd.DataFrame([{"Orden": i, "Mostrar": c["visible"], "Título": c["titulo"], "Ancho": c["ancho"],
|
|
@@ -311,6 +324,7 @@ def panel_formato():
|
|
| 311 |
else:
|
| 312 |
formato.guardar({"empresa_nombre": nombre, "empresa_rif": rif, "empresa_datos": datos,
|
| 313 |
"titulo": titulo, "color": color, "nota": nota, "mostrar_condiciones": condiciones,
|
|
|
|
| 314 |
"columnas": columnas, "formato_descarga": preferido})
|
| 315 |
st.session_state.pop("tipo_descarga", None) # la descarga vuelve al formato por defecto
|
| 316 |
st.toast("Formato guardado.")
|
|
@@ -723,7 +737,8 @@ def leer_solicitud(archivo, h: str):
|
|
| 723 |
st.session_state.archivo = archivo.name
|
| 724 |
st.session_state.huella_solicitud = h
|
| 725 |
st.session_state.unidad_cantidad = sol.unidad_cantidad if sol.unidad_cantidad != "no_claro" else None
|
| 726 |
-
for k in ("cotizacion", "cantidades", "ver_cotizacion_igual", "escribir", "vencimiento_elegido"
|
|
|
|
| 727 |
st.session_state.pop(k, None)
|
| 728 |
documentos.registrar_solicitud(h, archivo.name, sol.cliente, len(sol.items))
|
| 729 |
preguntas = preguntas_de(sol, emp, st.session_state.unidad_cantidad, None)
|
|
@@ -982,7 +997,10 @@ if "instr_pendiente" in st.session_state: # instrucciones que el agente anotó
|
|
| 982 |
|
| 983 |
def al_elegir_cliente():
|
| 984 |
if st.session_state.cliente_guardado != "—":
|
| 985 |
-
|
|
|
|
|
|
|
|
|
|
| 986 |
|
| 987 |
|
| 988 |
with c2:
|
|
@@ -996,7 +1014,11 @@ with c3:
|
|
| 996 |
instrucciones = st.text_area(
|
| 997 |
"Instrucciones especiales para este cliente (opcional)", key="instr_cliente",
|
| 998 |
placeholder="Ej: 10% de descuento, máximo 20.000 unidades por producto, no cotizar heparina")
|
| 999 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1000 |
|
| 1001 |
u1, u2, _ = st.columns([1.3, 1, 2])
|
| 1002 |
modo_actual = st.session_state.get("unidad_cantidad")
|
|
@@ -1029,7 +1051,8 @@ if st.button("Preparar cotización", type="primary") or st.session_state.pop("ge
|
|
| 1029 |
st.rerun()
|
| 1030 |
|
| 1031 |
if guardar and cliente.strip():
|
| 1032 |
-
clientes[cliente.strip()] = instrucciones
|
|
|
|
| 1033 |
RUTA_CLIENTES.write_text(json.dumps(clientes, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 1034 |
|
| 1035 |
# Se guardan los datos de entrada (no el resultado) para recalcular sin IA cuando cambien las cantidades
|
|
@@ -1115,12 +1138,15 @@ elif "cotizacion" in st.session_state:
|
|
| 1115 |
opciones = list(formato.FORMATOS)
|
| 1116 |
tipo = st.radio("Descargar en", opciones, format_func=formato.FORMATOS.get, horizontal=True,
|
| 1117 |
index=opciones.index(formato_actual["formato_descarga"]), key="tipo_descarga",
|
| 1118 |
-
help="El formato (logo, columnas,
|
| 1119 |
incluir_todo = st.checkbox("Incluir también los renglones no ofertados (uso interno)")
|
| 1120 |
extension = "pdf" if tipo == "pdf" else "xlsx"
|
| 1121 |
-
nombre = f"
|
| 1122 |
try:
|
| 1123 |
-
|
|
|
|
|
|
|
|
|
|
| 1124 |
except Exception: # noqa: BLE001
|
| 1125 |
fallo_inesperado(f"preparar el {formato.FORMATOS[tipo]} de la cotización")
|
| 1126 |
datos_salida = None
|
|
|
|
| 102 |
return h.hexdigest()
|
| 103 |
|
| 104 |
|
| 105 |
+
CAMPOS_CLIENTE = {"direccion": "Dirección", "rif": "No. ID Fiscal", "despacho": "Dirección de despacho",
|
| 106 |
+
"telefono": "Teléfono"}
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def leer_clientes() -> dict[str, dict]:
|
| 110 |
+
"""Clientes guardados: {nombre: {"instrucciones", "direccion", "rif", "despacho", "telefono"}}. Los guardados
|
| 111 |
+
antes solo tenían las instrucciones (un texto) y se leen igual."""
|
| 112 |
try:
|
| 113 |
+
datos = json.loads(RUTA_CLIENTES.read_text(encoding="utf-8"))
|
| 114 |
except (FileNotFoundError, json.JSONDecodeError):
|
| 115 |
return {}
|
| 116 |
+
return {n: (v if isinstance(v, dict) else {"instrucciones": str(v or "")}) for n, v in datos.items()}
|
| 117 |
|
| 118 |
|
| 119 |
# ---------------- arreglos de las alertas del catálogo ----------------
|
|
|
|
| 264 |
|
| 265 |
def panel_formato():
|
| 266 |
f = formato.leer()
|
| 267 |
+
with st.expander("Formato del presupuesto (Excel y PDF)"):
|
| 268 |
+
st.caption("Así sale el presupuesto que recibe el cliente. Los cambios valen para todo el departamento y se "
|
| 269 |
+
"aplican a la próxima descarga. Los datos de cada cliente (dirección, ID fiscal...) se llenan en "
|
| 270 |
+
"«Cliente e instrucciones».")
|
| 271 |
c_logo, c_subir = st.columns([1, 3])
|
| 272 |
logo = formato.logo()
|
| 273 |
if logo:
|
|
|
|
| 281 |
|
| 282 |
with st.form("form_formato"):
|
| 283 |
c1, c2 = st.columns(2)
|
| 284 |
+
nombre = c1.text_input("Nombre bajo el logo", f["empresa_nombre"])
|
| 285 |
+
rif = c1.text_input("Segunda línea bajo el logo (RIF, opcional)", f["empresa_rif"])
|
| 286 |
titulo = c2.text_input("Título del documento", f["titulo"])
|
| 287 |
+
color = c2.color_picker("Color del título y del nombre", f["color"])
|
| 288 |
+
c3, c4, c5 = st.columns([2, 1, 2])
|
| 289 |
+
almacen = c3.text_input("Almacén (por defecto)", f["almacen"],
|
| 290 |
+
help="Se puede cambiar en cada presupuesto, en «Cliente e instrucciones».")
|
| 291 |
+
impuesto = c4.number_input("Impuesto (%)", min_value=0.0, max_value=100.0, value=float(f["impuesto_pct"]),
|
| 292 |
+
step=1.0, help="0 si los productos están exentos.")
|
| 293 |
+
legal = c5.text_input("Texto legal", f["texto_legal"], placeholder="DOCUMENTO NO FISCAL")
|
| 294 |
+
datos = st.text_input("Pie de página", f["empresa_datos"], placeholder="Nombre de la empresa, dirección...")
|
| 295 |
+
nota = st.text_area("Nota (debajo de los totales)", f["nota"], height=80,
|
| 296 |
+
placeholder="Ej: Oferta válida por 5 días hábiles. Forma de pago: ...")
|
| 297 |
+
condiciones = st.checkbox("Mostrar las condiciones (precio por caja o unidad, vencimiento mínimo, "
|
| 298 |
+
"descuento) junto a la fecha", f["mostrar_condiciones"])
|
| 299 |
st.markdown("**Columnas:** marca las que salen y cambia su título, su ancho o su orden (el número más "
|
| 300 |
"bajo va primero).")
|
| 301 |
df = pd.DataFrame([{"Orden": i, "Mostrar": c["visible"], "Título": c["titulo"], "Ancho": c["ancho"],
|
|
|
|
| 324 |
else:
|
| 325 |
formato.guardar({"empresa_nombre": nombre, "empresa_rif": rif, "empresa_datos": datos,
|
| 326 |
"titulo": titulo, "color": color, "nota": nota, "mostrar_condiciones": condiciones,
|
| 327 |
+
"almacen": almacen, "impuesto_pct": impuesto, "texto_legal": legal,
|
| 328 |
"columnas": columnas, "formato_descarga": preferido})
|
| 329 |
st.session_state.pop("tipo_descarga", None) # la descarga vuelve al formato por defecto
|
| 330 |
st.toast("Formato guardado.")
|
|
|
|
| 737 |
st.session_state.archivo = archivo.name
|
| 738 |
st.session_state.huella_solicitud = h
|
| 739 |
st.session_state.unidad_cantidad = sol.unidad_cantidad if sol.unidad_cantidad != "no_claro" else None
|
| 740 |
+
for k in ("cotizacion", "cantidades", "ver_cotizacion_igual", "escribir", "vencimiento_elegido", "cli_direccion",
|
| 741 |
+
"cli_rif", "cli_despacho", "cli_telefono", "cli_almacen", "cliente_guardado"):
|
| 742 |
st.session_state.pop(k, None)
|
| 743 |
documentos.registrar_solicitud(h, archivo.name, sol.cliente, len(sol.items))
|
| 744 |
preguntas = preguntas_de(sol, emp, st.session_state.unidad_cantidad, None)
|
|
|
|
| 997 |
|
| 998 |
def al_elegir_cliente():
|
| 999 |
if st.session_state.cliente_guardado != "—":
|
| 1000 |
+
guardado = clientes.get(st.session_state.cliente_guardado, {})
|
| 1001 |
+
st.session_state.instr_cliente = guardado.get("instrucciones", "")
|
| 1002 |
+
for campo in CAMPOS_CLIENTE:
|
| 1003 |
+
st.session_state[f"cli_{campo}"] = guardado.get(campo, "")
|
| 1004 |
|
| 1005 |
|
| 1006 |
with c2:
|
|
|
|
| 1014 |
instrucciones = st.text_area(
|
| 1015 |
"Instrucciones especiales para este cliente (opcional)", key="instr_cliente",
|
| 1016 |
placeholder="Ej: 10% de descuento, máximo 20.000 unidades por producto, no cotizar heparina")
|
| 1017 |
+
d1, d2 = st.columns(2)
|
| 1018 |
+
for i, (campo, etiqueta) in enumerate(CAMPOS_CLIENTE.items()):
|
| 1019 |
+
(d1 if i % 2 == 0 else d2).text_input(etiqueta, key=f"cli_{campo}")
|
| 1020 |
+
st.text_input("Almacén", key="cli_almacen", placeholder=formato.leer()["almacen"] or "Almacén del presupuesto")
|
| 1021 |
+
guardar = st.checkbox("Guardar los datos y las instrucciones de este cliente")
|
| 1022 |
|
| 1023 |
u1, u2, _ = st.columns([1.3, 1, 2])
|
| 1024 |
modo_actual = st.session_state.get("unidad_cantidad")
|
|
|
|
| 1051 |
st.rerun()
|
| 1052 |
|
| 1053 |
if guardar and cliente.strip():
|
| 1054 |
+
clientes[cliente.strip()] = {"instrucciones": instrucciones,
|
| 1055 |
+
**{c: st.session_state.get(f"cli_{c}", "").strip() for c in CAMPOS_CLIENTE}}
|
| 1056 |
RUTA_CLIENTES.write_text(json.dumps(clientes, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 1057 |
|
| 1058 |
# Se guardan los datos de entrada (no el resultado) para recalcular sin IA cuando cambien las cantidades
|
|
|
|
| 1138 |
opciones = list(formato.FORMATOS)
|
| 1139 |
tipo = st.radio("Descargar en", opciones, format_func=formato.FORMATOS.get, horizontal=True,
|
| 1140 |
index=opciones.index(formato_actual["formato_descarga"]), key="tipo_descarga",
|
| 1141 |
+
help="El formato (logo, columnas, impuesto...) se cambia en «Formato del presupuesto», arriba.")
|
| 1142 |
incluir_todo = st.checkbox("Incluir también los renglones no ofertados (uso interno)")
|
| 1143 |
extension = "pdf" if tipo == "pdf" else "xlsx"
|
| 1144 |
+
nombre = f"PRESUPUESTO_{Path(st.session_state.get('archivo', 'solicitud')).stem}.{extension}"
|
| 1145 |
try:
|
| 1146 |
+
datos_doc = {"cliente": sol_final.cliente, "almacen": st.session_state.get("cli_almacen", "").strip(),
|
| 1147 |
+
**{c: st.session_state.get(f"cli_{c}", "").strip() for c in CAMPOS_CLIENTE}}
|
| 1148 |
+
datos_salida = generar_cotizacion(cot, tipo, solo_ofertados=not incluir_todo, f=formato_actual,
|
| 1149 |
+
doc=datos_doc)
|
| 1150 |
except Exception: # noqa: BLE001
|
| 1151 |
fallo_inesperado(f"preparar el {formato.FORMATOS[tipo]} de la cotización")
|
| 1152 |
datos_salida = None
|
excel_salida.py
CHANGED
|
@@ -1,270 +1,296 @@
|
|
| 1 |
-
"""Genera
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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,
|
| 11 |
from openpyxl.utils import get_column_letter
|
| 12 |
|
| 13 |
import formato as fmt
|
| 14 |
from cotizacion import Cotizacion, Linea
|
| 15 |
|
| 16 |
-
|
| 17 |
-
TEXTO = "
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
"no_cotizado": "F1F1F1",
|
| 21 |
-
"pendiente": "FFE1CC",
|
| 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:
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
|
| 40 |
-
def
|
| 41 |
-
return
|
| 42 |
-
else f"{len(cot.lineas)} rubro(s)")
|
| 43 |
|
| 44 |
|
| 45 |
-
def
|
| 46 |
-
return (
|
| 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 |
-
|
|
|
|
| 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 = "
|
| 62 |
ultima = get_column_letter(n)
|
| 63 |
-
|
| 64 |
for i, c in enumerate(columnas, 1):
|
| 65 |
-
ws.column_dimensions[get_column_letter(i)].width = c["ancho"]
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
|
|
|
| 69 |
izq = lambda r: f"A{r}:{get_column_letter(k)}{r}"
|
| 70 |
-
der =
|
| 71 |
|
| 72 |
-
def poner(rango: str, texto
|
| 73 |
-
|
|
|
|
| 74 |
celda = ws[rango.split(":")[0]]
|
| 75 |
celda.value = texto
|
| 76 |
celda.font = fuente
|
| 77 |
-
celda.alignment = Alignment(horizontal=
|
| 78 |
-
|
| 79 |
|
| 80 |
-
|
| 81 |
logo = fmt.logo()
|
|
|
|
| 82 |
if logo:
|
| 83 |
img = ImagenExcel(io.BytesIO(logo))
|
| 84 |
-
alto =
|
| 85 |
img.width, img.height = round(img.width * alto / img.height), alto
|
| 86 |
ws.add_image(img, "A1")
|
| 87 |
-
ws.row_dimensions[1].height =
|
| 88 |
-
if der:
|
| 89 |
-
poner(der(1), f["titulo"], Font(bold=True, size=18, color=color), derecha=True)
|
| 90 |
r = 2
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 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 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
|
|
|
|
|
|
| 111 |
r += 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
# ---- tabla ----
|
| 114 |
-
fila_enc = r
|
| 115 |
for i, c in enumerate(columnas, 1):
|
| 116 |
-
celda = ws.cell(
|
| 117 |
-
celda.font = Font(bold=True, size=
|
| 118 |
-
celda.
|
| 119 |
-
celda.
|
| 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 = "
|
| 124 |
-
|
| 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:
|
| 131 |
-
|
| 132 |
-
v = f'=IF(AND({
|
| 133 |
c = ws.cell(r, col, v)
|
| 134 |
-
c.font = Font(size=
|
| 135 |
-
c.
|
| 136 |
-
c.
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 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/
|
| 145 |
-
|
| 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 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
ws.cell(
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
ws
|
| 187 |
-
ws
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
ws.page_setup.fitToWidth = 1
|
| 194 |
ws.page_setup.fitToHeight = 0
|
| 195 |
ws.sheet_properties.pageSetUpPr.fitToPage = True
|
| 196 |
-
|
| 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
|
| 212 |
-
return
|
| 213 |
-
if clave
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 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
|
| 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 |
-
|
|
|
|
| 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 =
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
|
| 246 |
def estilo(nombre, **kw):
|
| 247 |
-
base = dict(fontName="Helvetica", fontSize=8, leading=
|
| 248 |
base.update(kw)
|
| 249 |
return ParagraphStyle(nombre, **base)
|
| 250 |
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 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()
|
|
@@ -272,84 +298,84 @@ def generar_pdf(cot: Cotizacion, solo_ofertados: bool = True, f: dict | None = N
|
|
| 272 |
from PIL import Image as PILImage
|
| 273 |
with PILImage.open(io.BytesIO(logo)) as im:
|
| 274 |
w, h = im.size
|
| 275 |
-
alto =
|
| 276 |
-
img = Image(io.BytesIO(logo), width=min(alto * w / h,
|
| 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"],
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
|
|
|
|
|
|
| 289 |
if f["mostrar_condiciones"]:
|
| 290 |
-
|
| 291 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
|
| 293 |
# ---- tabla ----
|
| 294 |
total_anchos = sum(c["ancho"] for c in columnas)
|
| 295 |
-
anchos = [
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 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
|
| 336 |
-
|
| 337 |
-
# ----
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 338 |
if f["nota"]:
|
| 339 |
historia += [Spacer(1, 5 * mm), p(f["nota"], estilo("nota", fontSize=8.5, leading=11))]
|
| 340 |
-
if f["
|
| 341 |
-
historia += [Spacer(1,
|
| 342 |
|
| 343 |
-
def
|
| 344 |
canvas.saveState()
|
| 345 |
-
canvas.setFont("Helvetica", 7)
|
| 346 |
canvas.setFillColor(gris)
|
| 347 |
-
|
|
|
|
|
|
|
| 348 |
canvas.restoreState()
|
| 349 |
|
| 350 |
-
|
| 351 |
return buf.getvalue()
|
| 352 |
|
| 353 |
|
| 354 |
-
def generar(cot: Cotizacion, tipo: str, solo_ofertados: bool = True, f: dict | None = None
|
| 355 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Genera el presupuesto para el cliente en Excel o en PDF, con el formato que editó el departamento (formato.py).
|
| 2 |
+
|
| 3 |
+
Diseño: logo y nombre arriba a la izquierda, título (PRESUPUESTO) a la derecha, recuadro con los datos del cliente,
|
| 4 |
+
tabla con un renglón por producto ofertado y, al pie, almacén, total de unidades, total, impuesto, neto y el texto
|
| 5 |
+
legal (DOCUMENTO NO FISCAL).
|
| 6 |
+
"""
|
| 7 |
from __future__ import annotations
|
| 8 |
|
| 9 |
import io
|
|
|
|
| 10 |
from datetime import date
|
| 11 |
|
| 12 |
from openpyxl import Workbook
|
| 13 |
from openpyxl.drawing.image import Image as ImagenExcel
|
| 14 |
+
from openpyxl.styles import Alignment, Border, Font, Side
|
| 15 |
from openpyxl.utils import get_column_letter
|
| 16 |
|
| 17 |
import formato as fmt
|
| 18 |
from cotizacion import Cotizacion, Linea
|
| 19 |
|
| 20 |
+
GRIS = "6B7280"
|
| 21 |
+
TEXTO = "111827"
|
| 22 |
+
LINEA_SUAVE = "E5E7EB"
|
| 23 |
+
NUMERICAS = {"cantidad", "precio", "total"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
OFERTADOS = ("completa", "parcial", "sin_cantidad")
|
| 25 |
+
CAMPOS_CLIENTE = [("cliente", "Cliente"), ("direccion", "Dirección"), ("rif", "No. ID Fiscal"),
|
| 26 |
+
("despacho", "Dirección de Despacho"), ("telefono", "Tlf.")]
|
| 27 |
|
| 28 |
|
| 29 |
def _lineas(cot: Cotizacion, solo_ofertados: bool) -> list[Linea]:
|
| 30 |
+
"""solo_ofertados=True: el presupuesto lleva únicamente lo que se oferta."""
|
|
|
|
| 31 |
return [l for l in cot.lineas if l.estado in OFERTADOS] if solo_ofertados else cot.lineas
|
| 32 |
|
| 33 |
|
| 34 |
+
def _columnas(f: dict, solo_ofertados: bool) -> list[dict]:
|
| 35 |
+
cols = fmt.visibles(f)
|
| 36 |
+
if not solo_ofertados and not any(c["clave"] == "observacion" for c in cols):
|
| 37 |
+
obs = next(c for c in f["columnas"] if c["clave"] == "observacion")
|
| 38 |
+
cols = cols + [obs] # uso interno: se ve por qué no se oferta cada renglón
|
| 39 |
+
return cols
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _pedido(l: Linea) -> str:
|
| 43 |
+
return " ".join(t for t in (l.principio_activo, l.concentracion, l.forma) if t)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
def _valor(l: Linea, clave: str):
|
| 47 |
+
if clave == "descripcion":
|
| 48 |
+
return l.producto_ofertado if (l.estado in OFERTADOS and l.producto_ofertado) else _pedido(l)
|
| 49 |
+
return {"vencimiento": l.vencimiento, "cantidad": l.cantidad_ofertada, "precio": l.precio_unitario,
|
| 50 |
+
"total": l.total, "n": l.n, "pedido": _pedido(l), "observacion": l.observacion}.get(clave)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _totales(lineas: list[Linea], f: dict) -> tuple[float, float, float, float]:
|
| 54 |
+
unidades = sum(l.cantidad_ofertada or 0 for l in lineas)
|
| 55 |
+
total = round(sum(l.total or 0 for l in lineas), 2)
|
| 56 |
+
impuesto = round(total * f["impuesto_pct"] / 100, 2)
|
| 57 |
+
return unidades, total, impuesto, round(total + impuesto, 2)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _datos(cot: Cotizacion, doc: dict | None, f: dict) -> dict:
|
| 61 |
+
doc = dict(doc or {})
|
| 62 |
+
doc.setdefault("cliente", cot.cliente)
|
| 63 |
+
doc["cliente"] = doc.get("cliente") or cot.cliente or "Quien Solicite"
|
| 64 |
+
doc["almacen"] = doc.get("almacen") or f["almacen"]
|
| 65 |
+
return doc
|
| 66 |
|
| 67 |
|
| 68 |
+
def _num(v: float | None, decimales: int = 2) -> str:
|
| 69 |
+
return "" if v is None else f"{v:,.{decimales}f}"
|
|
|
|
| 70 |
|
| 71 |
|
| 72 |
+
def _venc(v) -> str:
|
| 73 |
+
return v.strftime("%m/%y") if isinstance(v, date) else ""
|
|
|
|
| 74 |
|
| 75 |
|
| 76 |
# ======================= Excel =======================
|
| 77 |
+
def generar_excel(cot: Cotizacion, solo_ofertados: bool = True, f: dict | None = None, doc: dict | None = None) -> bytes:
|
| 78 |
f = f or fmt.leer()
|
| 79 |
+
doc = _datos(cot, doc, f)
|
| 80 |
+
columnas = _columnas(f, solo_ofertados)
|
| 81 |
claves = [c["clave"] for c in columnas]
|
| 82 |
n = len(columnas)
|
| 83 |
color = fmt.hex_sin_numeral(f["color"])
|
|
|
|
| 84 |
lineas = _lineas(cot, solo_ofertados)
|
| 85 |
wb = Workbook()
|
| 86 |
ws = wb.active
|
| 87 |
+
ws.title = "PRESUPUESTO"
|
| 88 |
ultima = get_column_letter(n)
|
| 89 |
+
escala = 90 / sum(c["ancho"] for c in columnas) # el ancho total de la hoja, repartido según el formato
|
| 90 |
for i, c in enumerate(columnas, 1):
|
| 91 |
+
ws.column_dimensions[get_column_letter(i)].width = max(6, round(c["ancho"] * escala, 1))
|
| 92 |
+
fina = Side(style="thin", color="9CA3AF")
|
| 93 |
+
gruesa = Side(style="medium", color=TEXTO)
|
| 94 |
+
suave = Side(style="thin", color=LINEA_SUAVE)
|
| 95 |
+
k = max(1, (n + 1) // 2) # columnas de la mitad izquierda
|
| 96 |
izq = lambda r: f"A{r}:{get_column_letter(k)}{r}"
|
| 97 |
+
der = lambda r: f"{get_column_letter(min(n, k + 1))}{r}:{ultima}{r}"
|
| 98 |
|
| 99 |
+
def poner(rango: str, texto, fuente: Font, horizontal: str = "left", vertical: str = "center"):
|
| 100 |
+
if ":" in rango and rango.split(":")[0] != rango.split(":")[1]:
|
| 101 |
+
ws.merge_cells(rango)
|
| 102 |
celda = ws[rango.split(":")[0]]
|
| 103 |
celda.value = texto
|
| 104 |
celda.font = fuente
|
| 105 |
+
celda.alignment = Alignment(horizontal=horizontal, vertical=vertical, wrap_text=True)
|
| 106 |
+
return celda
|
| 107 |
|
| 108 |
+
# ---- encabezado: logo y nombre a la izquierda, título a la derecha ----
|
| 109 |
logo = fmt.logo()
|
| 110 |
+
r = 1
|
| 111 |
if logo:
|
| 112 |
img = ImagenExcel(io.BytesIO(logo))
|
| 113 |
+
alto = 55
|
| 114 |
img.width, img.height = round(img.width * alto / img.height), alto
|
| 115 |
ws.add_image(img, "A1")
|
| 116 |
+
ws.row_dimensions[1].height = 44
|
|
|
|
|
|
|
| 117 |
r = 2
|
| 118 |
+
poner(der(1), f["titulo"], Font(bold=True, size=18, color=color), "right")
|
| 119 |
+
if f["empresa_nombre"]:
|
| 120 |
+
poner(izq(r), f["empresa_nombre"], Font(bold=True, size=10, color=color))
|
| 121 |
+
r += 1
|
| 122 |
+
if f["empresa_rif"]:
|
| 123 |
+
poner(izq(r), f["empresa_rif"], Font(size=9, color=GRIS))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
r += 1
|
|
|
|
| 125 |
r += 1
|
| 126 |
+
|
| 127 |
+
# ---- recuadro del cliente: datos a la izquierda, fecha y condiciones a la derecha ----
|
| 128 |
+
ini_caja = r
|
| 129 |
+
for clave, etiqueta in CAMPOS_CLIENTE:
|
| 130 |
+
poner(izq(r), f"{etiqueta}: {doc.get(clave) or ''}".rstrip(), Font(size=9, color=TEXTO))
|
| 131 |
+
ws[f"A{r}"].font = Font(size=9, color=TEXTO, bold=False)
|
| 132 |
r += 1
|
| 133 |
+
derecha = f"Fecha: {cot.fecha.strftime('%d/%m/%Y')}"
|
| 134 |
+
if f["mostrar_condiciones"]:
|
| 135 |
+
derecha += "\n" + cot.condiciones()
|
| 136 |
+
poner(f"{get_column_letter(min(n, k + 1))}{ini_caja}:{ultima}{r - 1}" if n > 1 else f"A{r}", derecha,
|
| 137 |
+
Font(size=8.5, color=GRIS), "left", "top")
|
| 138 |
+
for fila in range(ini_caja, r):
|
| 139 |
+
for col in range(1, n + 1):
|
| 140 |
+
c = ws.cell(fila, col)
|
| 141 |
+
c.border = Border(left=fina if col in (1, k + 1) else None, right=fina if col in (k, n) else None,
|
| 142 |
+
top=fina if fila == ini_caja else None, bottom=fina if fila == r - 1 else None)
|
| 143 |
+
r += 1
|
| 144 |
|
| 145 |
# ---- tabla ----
|
| 146 |
+
fila_enc = r
|
| 147 |
for i, c in enumerate(columnas, 1):
|
| 148 |
+
celda = ws.cell(r, i, c["titulo"])
|
| 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 |
letra = {clave: get_column_letter(i) for i, clave in enumerate(claves, 1)}
|
| 153 |
+
con_formula = "cantidad" in letra and "precio" in letra
|
| 154 |
+
for l in lineas:
|
|
|
|
| 155 |
r += 1
|
|
|
|
| 156 |
for col, clave in enumerate(claves, 1):
|
| 157 |
v = _valor(l, clave)
|
| 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",
|
| 165 |
+
wrap_text=clave in ("descripcion", "pedido", "observacion"))
|
| 166 |
+
if clave in ("cantidad", "total"):
|
| 167 |
+
c.number_format = "#,##0.00"
|
| 168 |
+
elif clave == "precio":
|
| 169 |
+
c.number_format = "#,##0.0000" if (l.precio_unitario or 1) < 0.1 else "#,##0.00"
|
|
|
|
| 170 |
elif clave == "vencimiento":
|
| 171 |
+
c.number_format = "mm/yy"
|
| 172 |
+
ultima_fila = r
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
for col in range(1, n + 1):
|
| 174 |
+
ws.cell(ultima_fila + 1, col).border = Border(top=gruesa)
|
| 175 |
+
|
| 176 |
+
# ---- pie: almacén, total de unidades y totales ----
|
| 177 |
+
unidades, total, impuesto, neto = _totales(lineas, f)
|
| 178 |
+
r = ultima_fila + 2
|
| 179 |
+
negrita = Font(bold=True, size=9, color=TEXTO)
|
| 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 |
+
rango_q = (f"{letra['cantidad']}{fila_enc + 1}:{letra['cantidad']}{ultima_fila}" if "cantidad" in letra else None)
|
| 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 |
+
col_t = n # los montos van en la última columna, las etiquetas a su izquierda
|
| 189 |
+
col_e = max(1, n - 1)
|
| 190 |
+
rango_t = (f"{letra['total']}{fila_enc + 1}:{letra['total']}{ultima_fila}" if "total" in letra else None)
|
| 191 |
+
filas_monto = {}
|
| 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")
|
| 198 |
+
m = ws.cell(fila, col_t, valor)
|
| 199 |
+
m.number_format = "#,##0.00"
|
| 200 |
+
m.font = negrita
|
| 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 ----
|
| 213 |
+
if f["nota"]:
|
| 214 |
+
poner(f"A{r}:{ultima}{r}", f["nota"], Font(size=9, color=TEXTO), vertical="top")
|
| 215 |
+
ws.row_dimensions[r].height = max(15, 13 * sum(1 + len(p) // 110 for p in f["nota"].splitlines() or [""]))
|
| 216 |
+
r += 2
|
| 217 |
+
if f["texto_legal"]:
|
| 218 |
+
poner(f"A{r}:{ultima}{r}", f["texto_legal"], Font(bold=True, size=10, color=TEXTO), "center")
|
| 219 |
+
r += 2
|
| 220 |
+
if f["empresa_datos"]:
|
| 221 |
+
poner(f"A{r}:{ultima}{r}", f["empresa_datos"], Font(size=8, color=GRIS))
|
| 222 |
+
|
| 223 |
+
ws.page_setup.orientation = "portrait"
|
| 224 |
+
ws.page_setup.paperSize = ws.PAPERSIZE_A4
|
| 225 |
ws.page_setup.fitToWidth = 1
|
| 226 |
ws.page_setup.fitToHeight = 0
|
| 227 |
ws.sheet_properties.pageSetUpPr.fitToPage = True
|
| 228 |
+
ws.print_title_rows = f"{fila_enc}:{fila_enc}"
|
| 229 |
buf = io.BytesIO()
|
| 230 |
wb.save(buf)
|
| 231 |
return buf.getvalue()
|
| 232 |
|
| 233 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
# ======================= PDF =======================
|
| 235 |
def _texto_pdf(l: Linea, clave: str) -> str:
|
| 236 |
v = _valor(l, clave)
|
| 237 |
if v is None or v == "":
|
| 238 |
return ""
|
| 239 |
+
if clave in ("cantidad", "total"):
|
| 240 |
+
return _num(v)
|
| 241 |
+
if clave == "precio":
|
| 242 |
+
return _num(v, 4 if v < 0.1 else 2)
|
| 243 |
+
if clave == "vencimiento":
|
| 244 |
+
return _venc(v)
|
|
|
|
| 245 |
return str(v)
|
| 246 |
|
| 247 |
|
| 248 |
+
def generar_pdf(cot: Cotizacion, solo_ofertados: bool = True, f: dict | None = None, doc: dict | None = None) -> bytes:
|
| 249 |
from xml.sax.saxutils import escape
|
| 250 |
|
| 251 |
from reportlab.lib import colors
|
| 252 |
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_RIGHT
|
| 253 |
+
from reportlab.lib.pagesizes import A4
|
| 254 |
from reportlab.lib.styles import ParagraphStyle
|
| 255 |
from reportlab.lib.units import mm
|
| 256 |
from reportlab.platypus import Image, Paragraph, SimpleDocTemplate, Spacer, Table, TableStyle
|
| 257 |
|
| 258 |
f = f or fmt.leer()
|
| 259 |
+
doc_datos = _datos(cot, doc, f)
|
| 260 |
+
columnas = _columnas(f, solo_ofertados)
|
| 261 |
claves = [c["clave"] for c in columnas]
|
| 262 |
lineas = _lineas(cot, solo_ofertados)
|
| 263 |
color = colors.HexColor(f["color"])
|
|
|
|
|
|
|
| 264 |
texto = colors.HexColor("#" + TEXTO)
|
| 265 |
+
gris = colors.HexColor("#" + GRIS)
|
| 266 |
+
borde = colors.HexColor("#9CA3AF")
|
| 267 |
+
suave = colors.HexColor("#" + LINEA_SUAVE)
|
| 268 |
|
| 269 |
buf = io.BytesIO()
|
| 270 |
+
margen = 15 * mm
|
| 271 |
+
pdf = SimpleDocTemplate(buf, pagesize=A4, leftMargin=margen, rightMargin=margen, topMargin=margen,
|
| 272 |
+
bottomMargin=margen + 4 * mm, title=f["titulo"], author=f["empresa_nombre"])
|
| 273 |
+
ancho = pdf.width - 12 # el marco tiene 6 pt de relleno a cada lado
|
| 274 |
|
| 275 |
def estilo(nombre, **kw):
|
| 276 |
+
base = dict(fontName="Helvetica", fontSize=8.5, leading=11, textColor=texto)
|
| 277 |
base.update(kw)
|
| 278 |
return ParagraphStyle(nombre, **base)
|
| 279 |
|
| 280 |
+
e_titulo = estilo("titulo", fontName="Helvetica-Bold", fontSize=17, leading=20, textColor=color, alignment=TA_RIGHT)
|
| 281 |
+
e_empresa = estilo("empresa", fontName="Helvetica-Bold", fontSize=9, leading=11, textColor=color)
|
| 282 |
+
e_rif = estilo("rif", fontSize=8, leading=10, textColor=gris)
|
| 283 |
+
e_cliente = estilo("cliente", fontSize=8.5, leading=13)
|
| 284 |
+
e_der = estilo("der", fontSize=8, leading=10.5, textColor=gris)
|
| 285 |
+
e_enc = {"izq": estilo("enc_i", fontName="Helvetica-Bold", fontSize=8.5),
|
| 286 |
+
"der": estilo("enc_d", fontName="Helvetica-Bold", fontSize=8.5, alignment=TA_RIGHT)}
|
| 287 |
+
e_celda = {"izq": estilo("c_i", fontSize=8.5), "der": estilo("c_d", fontSize=8.5, alignment=TA_RIGHT)}
|
| 288 |
+
e_pie = estilo("pie", fontName="Helvetica-Bold", fontSize=8.5)
|
| 289 |
+
e_pie_der = estilo("pie_d", fontName="Helvetica-Bold", fontSize=8.5, alignment=TA_RIGHT)
|
| 290 |
+
e_legal = estilo("legal", fontName="Helvetica-Bold", fontSize=9.5, alignment=TA_CENTER)
|
|
|
|
|
|
|
|
|
|
| 291 |
p = lambda t, e: Paragraph(escape(str(t)).replace("\n", "<br/>"), e)
|
|
|
|
| 292 |
historia = []
|
| 293 |
+
|
| 294 |
# ---- encabezado ----
|
| 295 |
izquierda = []
|
| 296 |
logo = fmt.logo()
|
|
|
|
| 298 |
from PIL import Image as PILImage
|
| 299 |
with PILImage.open(io.BytesIO(logo)) as im:
|
| 300 |
w, h = im.size
|
| 301 |
+
alto = 17 * mm
|
| 302 |
+
img = Image(io.BytesIO(logo), width=min(alto * w / h, ancho * 0.45), height=alto)
|
| 303 |
img.hAlign = "LEFT"
|
| 304 |
izquierda.append(img)
|
| 305 |
if f["empresa_nombre"]:
|
| 306 |
izquierda.append(p(f["empresa_nombre"], e_empresa))
|
| 307 |
if f["empresa_rif"]:
|
| 308 |
+
izquierda.append(p(f["empresa_rif"], e_rif))
|
| 309 |
+
cab = Table([[izquierda or "", p(f["titulo"], e_titulo)]], colWidths=[ancho * 0.55, ancho * 0.45])
|
| 310 |
+
cab.setStyle(TableStyle([("VALIGN", (0, 0), (0, 0), "TOP"), ("VALIGN", (1, 0), (1, 0), "TOP"),
|
| 311 |
+
("LEFTPADDING", (0, 0), (-1, -1), 0), ("RIGHTPADDING", (0, 0), (-1, -1), 0)]))
|
| 312 |
+
historia += [cab, Spacer(1, 4 * mm)]
|
| 313 |
+
|
| 314 |
+
# ---- recuadro del cliente ----
|
| 315 |
+
datos_cli = "<br/>".join(f"<b>{escape(et)}:</b> {escape(str(doc_datos.get(c) or ''))}" for c, et in CAMPOS_CLIENTE)
|
| 316 |
+
derecha = f"<b>Fecha:</b> {cot.fecha.strftime('%d/%m/%Y')}"
|
| 317 |
if f["mostrar_condiciones"]:
|
| 318 |
+
derecha += "<br/><br/>" + escape(cot.condiciones())
|
| 319 |
+
caja = Table([[Paragraph(datos_cli, e_cliente), Paragraph(derecha, e_der)]],
|
| 320 |
+
colWidths=[ancho * 0.63, ancho * 0.37])
|
| 321 |
+
caja.setStyle(TableStyle([("BOX", (0, 0), (-1, -1), 0.8, borde), ("LINEBEFORE", (1, 0), (1, 0), 0.8, borde),
|
| 322 |
+
("VALIGN", (0, 0), (-1, -1), "TOP"), ("TOPPADDING", (0, 0), (-1, -1), 6),
|
| 323 |
+
("BOTTOMPADDING", (0, 0), (-1, -1), 6), ("LEFTPADDING", (0, 0), (-1, -1), 7)]))
|
| 324 |
+
historia += [caja, Spacer(1, 5 * mm)]
|
| 325 |
|
| 326 |
# ---- tabla ----
|
| 327 |
total_anchos = sum(c["ancho"] for c in columnas)
|
| 328 |
+
anchos = [ancho * c["ancho"] / total_anchos for c in columnas]
|
| 329 |
+
lado = lambda clave: "der" if clave in NUMERICAS else "izq"
|
| 330 |
+
filas = [[p(c["titulo"], e_enc[lado(c["clave"])]) for c in columnas]]
|
| 331 |
+
filas += [[p(_texto_pdf(l, clave), e_celda[lado(clave)]) for clave in claves] for l in lineas]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 332 |
tabla = Table(filas, colWidths=anchos, repeatRows=1)
|
| 333 |
+
estilos = [("LINEABOVE", (0, 0), (-1, 0), 0.6, borde), ("LINEBELOW", (0, 0), (-1, 0), 1.2, texto),
|
| 334 |
+
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#F9FAFB")),
|
| 335 |
+
("VALIGN", (0, 0), (-1, -1), "MIDDLE"), ("TOPPADDING", (0, 0), (-1, -1), 3),
|
| 336 |
+
("BOTTOMPADDING", (0, 0), (-1, -1), 3), ("LEFTPADDING", (0, 0), (-1, -1), 4),
|
| 337 |
+
("RIGHTPADDING", (0, 0), (-1, -1), 4)]
|
| 338 |
+
if len(filas) > 2:
|
| 339 |
+
estilos.append(("LINEBELOW", (0, 1), (-1, -2), 0.4, suave))
|
| 340 |
+
estilos.append(("LINEBELOW", (0, -1), (-1, -1), 1.2, texto))
|
| 341 |
tabla.setStyle(TableStyle(estilos))
|
| 342 |
+
historia += [tabla, Spacer(1, 2.5 * mm)]
|
| 343 |
+
|
| 344 |
+
# ---- pie: almacén, total de unidades y totales ----
|
| 345 |
+
unidades, total, impuesto, neto = _totales(lineas, f)
|
| 346 |
+
linea_monto = lambda v: Paragraph(f"<b>{_num(v)}</b>", e_pie_der)
|
| 347 |
+
pie = Table([
|
| 348 |
+
[p(f"ALMACEN: {doc_datos['almacen']}".rstrip(), e_pie),
|
| 349 |
+
Paragraph(f"<b>TOTAL UNIDADES:</b><br/>{_num(unidades)}", e_celda["izq"]),
|
| 350 |
+
p("TOTAL....:", e_pie_der), linea_monto(total)],
|
| 351 |
+
["", "", p("IMPUESTO:", e_pie_der), linea_monto(impuesto)],
|
| 352 |
+
["", "", p("NETO:", e_pie_der), linea_monto(neto)],
|
| 353 |
+
], colWidths=[ancho * 0.36, ancho * 0.30, ancho * 0.16, ancho * 0.18])
|
| 354 |
+
pie.setStyle(TableStyle([("VALIGN", (0, 0), (-1, -1), "TOP"), ("LEFTPADDING", (0, 0), (-1, -1), 4),
|
| 355 |
+
("RIGHTPADDING", (0, 0), (-1, -1), 4), ("LINEBELOW", (3, 0), (3, 2), 0.8, borde),
|
| 356 |
+
("TOPPADDING", (0, 0), (-1, -1), 3), ("BOTTOMPADDING", (0, 0), (-1, -1), 3)]))
|
| 357 |
+
historia.append(pie)
|
| 358 |
+
|
| 359 |
+
# ---- nota y texto legal ----
|
| 360 |
if f["nota"]:
|
| 361 |
historia += [Spacer(1, 5 * mm), p(f["nota"], estilo("nota", fontSize=8.5, leading=11))]
|
| 362 |
+
if f["texto_legal"]:
|
| 363 |
+
historia += [Spacer(1, 7 * mm), p(f["texto_legal"], e_legal)]
|
| 364 |
|
| 365 |
+
def pie_pagina(canvas, documento):
|
| 366 |
canvas.saveState()
|
| 367 |
+
canvas.setFont("Helvetica", 7.5)
|
| 368 |
canvas.setFillColor(gris)
|
| 369 |
+
if f["empresa_datos"]:
|
| 370 |
+
canvas.drawString(margen, margen / 1.6, f["empresa_datos"][:150])
|
| 371 |
+
canvas.drawRightString(documento.pagesize[0] - margen, margen / 1.6, f"Página {documento.page}")
|
| 372 |
canvas.restoreState()
|
| 373 |
|
| 374 |
+
pdf.build(historia, onFirstPage=pie_pagina, onLaterPages=pie_pagina)
|
| 375 |
return buf.getvalue()
|
| 376 |
|
| 377 |
|
| 378 |
+
def generar(cot: Cotizacion, tipo: str, solo_ofertados: bool = True, f: dict | None = None,
|
| 379 |
+
doc: dict | None = None) -> bytes:
|
| 380 |
+
"""doc: datos del cliente y del documento (cliente, direccion, rif, despacho, telefono, almacen)."""
|
| 381 |
+
return (generar_pdf if tipo == "pdf" else generar_excel)(cot, solo_ofertados, f, doc)
|
formato.py
CHANGED
|
@@ -1,11 +1,12 @@
|
|
| 1 |
-
"""Formato
|
| 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
|
|
@@ -15,49 +16,47 @@ import config
|
|
| 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
|
| 20 |
COLUMNAS = {
|
| 21 |
-
"
|
| 22 |
-
"
|
| 23 |
-
"
|
| 24 |
-
"
|
| 25 |
-
"
|
| 26 |
-
"
|
| 27 |
-
"
|
| 28 |
-
"
|
| 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 |
-
"
|
| 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 caja o por unidad, según cómo pide el cliente",
|
| 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": "
|
| 56 |
-
"color": "#
|
| 57 |
"mostrar_condiciones": True,
|
| 58 |
"nota": "",
|
| 59 |
-
"
|
| 60 |
-
"
|
|
|
|
|
|
|
|
|
|
| 61 |
}
|
| 62 |
|
| 63 |
|
|
@@ -66,32 +65,44 @@ def _color_valido(c: str) -> bool:
|
|
| 66 |
|
| 67 |
|
| 68 |
def normalizar(datos: dict) -> dict:
|
| 69 |
-
"""Completa lo que falte con los valores por defecto y corrige lo que no sirva
|
|
|
|
| 70 |
base = por_defecto()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
f = {k: datos.get(k, v) for k, v in base.items()}
|
| 72 |
-
|
|
|
|
| 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"] = "
|
| 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",
|
| 92 |
-
for clave, (titulo, ancho) in COLUMNAS.items(): # columnas
|
| 93 |
if clave not in vistas:
|
| 94 |
-
columnas.append({"clave": clave, "titulo": titulo, "visible":
|
| 95 |
if not any(c["visible"] for c in columnas):
|
| 96 |
columnas[0]["visible"] = True
|
| 97 |
f["columnas"] = columnas
|
|
@@ -101,13 +112,14 @@ def normalizar(datos: dict) -> dict:
|
|
| 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),
|
|
|
|
| 111 |
|
| 112 |
|
| 113 |
def restablecer():
|
|
@@ -150,7 +162,7 @@ def hex_sin_numeral(color: str) -> str:
|
|
| 150 |
|
| 151 |
|
| 152 |
def aclarar(color: str, cuanto: float = 0.9) -> str:
|
| 153 |
-
"""Mezcla el color con blanco: para
|
| 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))
|
|
|
|
| 1 |
+
"""Formato del presupuesto 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 |
+
Diseño de presupuesto: logo y nombre arriba a la izquierda, título a la derecha, recuadro con los datos del cliente,
|
| 5 |
+
tabla (Descripción, Venc., Cant., P/Unidad, Total) y al pie almacén, total de unidades, total, impuesto y neto.
|
| 6 |
Los valores por defecto de la empresa salen de las variables EMPRESA_NOMBRE, EMPRESA_RIF y EMPRESA_DATOS.
|
| 7 |
"""
|
| 8 |
from __future__ import annotations
|
| 9 |
|
|
|
|
| 10 |
import io
|
| 11 |
import json
|
| 12 |
import re
|
|
|
|
| 16 |
RUTA = config.DATA_DIR / "formato.json"
|
| 17 |
RUTA_LOGO = config.DATA_DIR / "logo.png"
|
| 18 |
FORMATOS = {"excel": "Excel", "pdf": "PDF"}
|
| 19 |
+
VERSION = 2 # 1: tabla de respuesta a la solicitud · 2: presupuesto
|
| 20 |
|
| 21 |
+
# clave -> (título por defecto, ancho relativo, visible por defecto). El orden es el de la tabla por defecto.
|
| 22 |
COLUMNAS = {
|
| 23 |
+
"descripcion": ("Descripción", 46, True),
|
| 24 |
+
"vencimiento": ("Venc.", 8, True),
|
| 25 |
+
"cantidad": ("Cant.", 10, True),
|
| 26 |
+
"precio": ("P/Unidad", 11, True),
|
| 27 |
+
"total": ("Total", 12, True),
|
| 28 |
+
"n": ("N°", 5, False),
|
| 29 |
+
"pedido": ("Pedido del cliente", 30, False),
|
| 30 |
+
"observacion": ("Observación", 28, False),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
}
|
| 32 |
DESCRIPCION_COLUMNA = { # para el editor: qué dato lleva cada columna
|
| 33 |
+
"descripcion": "Nuestro producto ofertado (o lo que pidió el cliente si no se oferta)",
|
| 34 |
+
"vencimiento": "Vencimiento más próximo de lo ofertado (MM/AA)",
|
| 35 |
+
"cantidad": "Cantidad ofertada",
|
| 36 |
+
"precio": "Precio por caja o por unidad, según cómo pide el cliente",
|
| 37 |
+
"total": "Cantidad × precio",
|
| 38 |
"n": "Número de renglón de la solicitud",
|
| 39 |
+
"pedido": "Cómo lo pidió el cliente",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
"observacion": "Explicación de cada renglón",
|
| 41 |
}
|
| 42 |
+
COLOR_VIEJO = "#192A69" # el del formato anterior: al migrar se cambia por el sobrio del presupuesto
|
| 43 |
|
| 44 |
|
| 45 |
def por_defecto() -> dict:
|
| 46 |
return {
|
| 47 |
+
"version": VERSION,
|
| 48 |
"empresa_nombre": config.EMPRESA_NOMBRE,
|
| 49 |
"empresa_rif": config.EMPRESA_RIF,
|
| 50 |
"empresa_datos": config.EMPRESA_DATOS,
|
| 51 |
+
"titulo": "PRESUPUESTO",
|
| 52 |
+
"color": "#1F2937",
|
| 53 |
"mostrar_condiciones": True,
|
| 54 |
"nota": "",
|
| 55 |
+
"almacen": "",
|
| 56 |
+
"impuesto_pct": 0.0,
|
| 57 |
+
"texto_legal": "DOCUMENTO NO FISCAL",
|
| 58 |
+
"columnas": [{"clave": k, "titulo": t, "visible": v, "ancho": a} for k, (t, a, v) in COLUMNAS.items()],
|
| 59 |
+
"formato_descarga": "pdf",
|
| 60 |
}
|
| 61 |
|
| 62 |
|
|
|
|
| 65 |
|
| 66 |
|
| 67 |
def normalizar(datos: dict) -> dict:
|
| 68 |
+
"""Completa lo que falte con los valores por defecto y corrige lo que no sirva. Un formato guardado con el diseño
|
| 69 |
+
anterior conserva la empresa, el logo y la nota, pero toma las columnas y el título del presupuesto."""
|
| 70 |
base = por_defecto()
|
| 71 |
+
datos = dict(datos)
|
| 72 |
+
if datos.get("version") != VERSION:
|
| 73 |
+
for k in ("columnas", "titulo", "formato_descarga", "mostrar_condiciones"):
|
| 74 |
+
datos.pop(k, None)
|
| 75 |
+
if str(datos.get("color", "")).upper() == COLOR_VIEJO:
|
| 76 |
+
datos.pop("color")
|
| 77 |
f = {k: datos.get(k, v) for k, v in base.items()}
|
| 78 |
+
f["version"] = VERSION
|
| 79 |
+
for k in ("empresa_nombre", "empresa_rif", "empresa_datos", "titulo", "nota", "almacen", "texto_legal"):
|
| 80 |
f[k] = str(f[k] or "").strip()
|
| 81 |
if not _color_valido(f["color"]):
|
| 82 |
f["color"] = base["color"]
|
| 83 |
f["mostrar_condiciones"] = bool(f["mostrar_condiciones"])
|
| 84 |
+
try:
|
| 85 |
+
f["impuesto_pct"] = min(100.0, max(0.0, float(f["impuesto_pct"] or 0)))
|
| 86 |
+
except (TypeError, ValueError):
|
| 87 |
+
f["impuesto_pct"] = 0.0
|
| 88 |
if f["formato_descarga"] not in FORMATOS:
|
| 89 |
+
f["formato_descarga"] = "pdf"
|
| 90 |
columnas, vistas = [], set()
|
| 91 |
for c in f["columnas"] if isinstance(f["columnas"], list) else []:
|
| 92 |
clave = c.get("clave") if isinstance(c, dict) else None
|
| 93 |
if clave not in COLUMNAS or clave in vistas:
|
| 94 |
continue
|
| 95 |
vistas.add(clave)
|
| 96 |
+
titulo_def, ancho_def, visible_def = COLUMNAS[clave]
|
| 97 |
try:
|
| 98 |
ancho = min(80, max(4, int(c.get("ancho") or ancho_def)))
|
| 99 |
except (TypeError, ValueError):
|
| 100 |
ancho = ancho_def
|
| 101 |
columnas.append({"clave": clave, "titulo": str(c.get("titulo") or "").strip() or titulo_def,
|
| 102 |
+
"visible": bool(c.get("visible", visible_def)), "ancho": ancho})
|
| 103 |
+
for clave, (titulo, ancho, visible) in COLUMNAS.items(): # columnas que faltaban, al final
|
| 104 |
if clave not in vistas:
|
| 105 |
+
columnas.append({"clave": clave, "titulo": titulo, "visible": visible, "ancho": ancho})
|
| 106 |
if not any(c["visible"] for c in columnas):
|
| 107 |
columnas[0]["visible"] = True
|
| 108 |
f["columnas"] = columnas
|
|
|
|
| 112 |
def leer() -> dict:
|
| 113 |
try:
|
| 114 |
return normalizar(json.loads(RUTA.read_text(encoding="utf-8")))
|
| 115 |
+
except (FileNotFoundError, json.JSONDecodeError, AttributeError, TypeError):
|
| 116 |
return por_defecto()
|
| 117 |
|
| 118 |
|
| 119 |
def guardar(f: dict):
|
| 120 |
RUTA.parent.mkdir(parents=True, exist_ok=True)
|
| 121 |
+
RUTA.write_text(json.dumps(normalizar({**f, "version": VERSION}), ensure_ascii=False, indent=1),
|
| 122 |
+
encoding="utf-8")
|
| 123 |
|
| 124 |
|
| 125 |
def restablecer():
|
|
|
|
| 162 |
|
| 163 |
|
| 164 |
def aclarar(color: str, cuanto: float = 0.9) -> str:
|
| 165 |
+
"""Mezcla el color con blanco: para fondos suaves."""
|
| 166 |
c = hex_sin_numeral(color)
|
| 167 |
r, g, b = (int(c[i:i + 2], 16) for i in (0, 2, 4))
|
| 168 |
r, g, b = (round(x + (255 - x) * cuanto) for x in (r, g, b))
|
ia.py
CHANGED
|
@@ -497,13 +497,14 @@ No inventes cifras ni digas que hiciste algo que no está en las acciones."""
|
|
| 497 |
|
| 498 |
|
| 499 |
def contexto_agente(catalogo: Catalogo | None, solicitud: Solicitud | None, emparejamiento: ResultadoEmparejamiento | None,
|
| 500 |
-
cotizacion=None, instrucciones: str = "", clientes: dict[str,
|
| 501 |
unidad: str | None = None, preguntas: list[str] | None = None) -> str:
|
| 502 |
"""Lo que el agente sabe del trabajo en curso, en texto, para responder preguntas y entender órdenes."""
|
| 503 |
partes = []
|
| 504 |
if clientes:
|
| 505 |
partes.append("CLIENTES GUARDADOS (nombre: condiciones comerciales guardadas):\n"
|
| 506 |
-
+ "\n".join(f"- {n}: {c or 'sin condiciones'}"
|
|
|
|
| 507 |
if catalogo is None:
|
| 508 |
partes.append("CATÁLOGO: todavía no se cargaron los Excel de existencias y precios.")
|
| 509 |
else:
|
|
|
|
| 497 |
|
| 498 |
|
| 499 |
def contexto_agente(catalogo: Catalogo | None, solicitud: Solicitud | None, emparejamiento: ResultadoEmparejamiento | None,
|
| 500 |
+
cotizacion=None, instrucciones: str = "", clientes: dict[str, dict] | None = None,
|
| 501 |
unidad: str | None = None, preguntas: list[str] | None = None) -> str:
|
| 502 |
"""Lo que el agente sabe del trabajo en curso, en texto, para responder preguntas y entender órdenes."""
|
| 503 |
partes = []
|
| 504 |
if clientes:
|
| 505 |
partes.append("CLIENTES GUARDADOS (nombre: condiciones comerciales guardadas):\n"
|
| 506 |
+
+ "\n".join(f"- {n}: {(c.get('instrucciones') if isinstance(c, dict) else c) or 'sin condiciones'}"
|
| 507 |
+
for n, c in sorted(clientes.items())))
|
| 508 |
if catalogo is None:
|
| 509 |
partes.append("CATÁLOGO: todavía no se cargaron los Excel de existencias y precios.")
|
| 510 |
else:
|