Download formato.py from andervier/agosto: direct link, hf CLI and curl.
- Browser
- Download file 6.68 kB
-
https://huggingface.co/spaces/andervier/agosto/resolve/main/formato.py
- Command line
-
hf download hf://spaces/andervier/agosto/formato.py
-
curl -L -o formato.py https://huggingface.co/spaces/andervier/agosto/resolve/main/formato.py
6.68 kB
| """Formato del presupuesto que recibe el cliente (Excel y PDF). Lo edita el departamento desde la app y se guarda en | |
| DATA_DIR/formato.json (el logo en DATA_DIR/logo.png); en el Space, en el bucket. Vale para todos los usuarios. | |
| Dise帽o de presupuesto: logo y nombre arriba a la izquierda, t铆tulo a la derecha, recuadro con los datos del cliente, | |
| tabla (Descripci贸n, Venc., Cant., P/Unidad, Total) y al pie almac茅n, total de unidades, total, impuesto y neto. | |
| Los valores por defecto de la empresa salen de las variables EMPRESA_NOMBRE, EMPRESA_RIF y EMPRESA_DATOS. | |
| """ | |
| from __future__ import annotations | |
| import io | |
| import json | |
| import re | |
| import config | |
| RUTA = config.DATA_DIR / "formato.json" | |
| RUTA_LOGO = config.DATA_DIR / "logo.png" | |
| FORMATOS = {"excel": "Excel", "pdf": "PDF"} | |
| VERSION = 2 # 1: tabla de respuesta a la solicitud 路 2: presupuesto | |
| # clave -> (t铆tulo por defecto, ancho relativo, visible por defecto). El orden es el de la tabla por defecto. | |
| COLUMNAS = { | |
| "descripcion": ("Descripci贸n", 46, True), | |
| "vencimiento": ("Venc.", 8, True), | |
| "cantidad": ("Cant.", 10, True), | |
| "precio": ("P/Unidad", 11, True), | |
| "total": ("Total", 12, True), | |
| "n": ("N掳", 5, False), | |
| "pedido": ("Pedido del cliente", 30, False), | |
| "observacion": ("Observaci贸n", 28, False), | |
| } | |
| DESCRIPCION_COLUMNA = { # para el editor: qu茅 dato lleva cada columna | |
| "descripcion": "Nuestro producto ofertado (o lo que pidi贸 el cliente si no se oferta)", | |
| "vencimiento": "Vencimiento m谩s pr贸ximo de lo ofertado (MM/AA)", | |
| "cantidad": "Cantidad ofertada", | |
| "precio": "Precio por caja o por unidad, seg煤n c贸mo pide el cliente", | |
| "total": "Cantidad 脳 precio", | |
| "n": "N煤mero de rengl贸n de la solicitud", | |
| "pedido": "C贸mo lo pidi贸 el cliente", | |
| "observacion": "Explicaci贸n de cada rengl贸n", | |
| } | |
| COLOR_VIEJO = "#192A69" # el del formato anterior: al migrar se cambia por el sobrio del presupuesto | |
| def por_defecto() -> dict: | |
| return { | |
| "version": VERSION, | |
| "empresa_nombre": config.EMPRESA_NOMBRE, | |
| "empresa_rif": config.EMPRESA_RIF, | |
| "empresa_datos": config.EMPRESA_DATOS, | |
| "titulo": "PRESUPUESTO", | |
| "color": "#1F2937", | |
| "mostrar_condiciones": True, | |
| "nota": "", | |
| "almacen": "", | |
| "impuesto_pct": 0.0, | |
| "texto_legal": "DOCUMENTO NO FISCAL", | |
| "columnas": [{"clave": k, "titulo": t, "visible": v, "ancho": a} for k, (t, a, v) in COLUMNAS.items()], | |
| "formato_descarga": "pdf", | |
| } | |
| def _color_valido(c: str) -> bool: | |
| return bool(re.fullmatch(r"#[0-9A-Fa-f]{6}", c or "")) | |
| def normalizar(datos: dict) -> dict: | |
| """Completa lo que falte con los valores por defecto y corrige lo que no sirva. Un formato guardado con el dise帽o | |
| anterior conserva la empresa, el logo y la nota, pero toma las columnas y el t铆tulo del presupuesto.""" | |
| base = por_defecto() | |
| datos = dict(datos) | |
| if datos.get("version") != VERSION: | |
| for k in ("columnas", "titulo", "formato_descarga", "mostrar_condiciones"): | |
| datos.pop(k, None) | |
| if str(datos.get("color", "")).upper() == COLOR_VIEJO: | |
| datos.pop("color") | |
| f = {k: datos.get(k, v) for k, v in base.items()} | |
| f["version"] = VERSION | |
| for k in ("empresa_nombre", "empresa_rif", "empresa_datos", "titulo", "nota", "almacen", "texto_legal"): | |
| f[k] = str(f[k] or "").strip() | |
| if not _color_valido(f["color"]): | |
| f["color"] = base["color"] | |
| f["mostrar_condiciones"] = bool(f["mostrar_condiciones"]) | |
| try: | |
| f["impuesto_pct"] = min(100.0, max(0.0, float(f["impuesto_pct"] or 0))) | |
| except (TypeError, ValueError): | |
| f["impuesto_pct"] = 0.0 | |
| if f["formato_descarga"] not in FORMATOS: | |
| f["formato_descarga"] = "pdf" | |
| columnas, vistas = [], set() | |
| for c in f["columnas"] if isinstance(f["columnas"], list) else []: | |
| clave = c.get("clave") if isinstance(c, dict) else None | |
| if clave not in COLUMNAS or clave in vistas: | |
| continue | |
| vistas.add(clave) | |
| titulo_def, ancho_def, visible_def = COLUMNAS[clave] | |
| try: | |
| ancho = min(80, max(4, int(c.get("ancho") or ancho_def))) | |
| except (TypeError, ValueError): | |
| ancho = ancho_def | |
| columnas.append({"clave": clave, "titulo": str(c.get("titulo") or "").strip() or titulo_def, | |
| "visible": bool(c.get("visible", visible_def)), "ancho": ancho}) | |
| for clave, (titulo, ancho, visible) in COLUMNAS.items(): # columnas que faltaban, al final | |
| if clave not in vistas: | |
| columnas.append({"clave": clave, "titulo": titulo, "visible": visible, "ancho": ancho}) | |
| if not any(c["visible"] for c in columnas): | |
| columnas[0]["visible"] = True | |
| f["columnas"] = columnas | |
| return f | |
| def leer() -> dict: | |
| try: | |
| return normalizar(json.loads(RUTA.read_text(encoding="utf-8"))) | |
| except (FileNotFoundError, json.JSONDecodeError, AttributeError, TypeError): | |
| return por_defecto() | |
| def guardar(f: dict): | |
| RUTA.parent.mkdir(parents=True, exist_ok=True) | |
| RUTA.write_text(json.dumps(normalizar({**f, "version": VERSION}), ensure_ascii=False, indent=1), | |
| encoding="utf-8") | |
| def restablecer(): | |
| RUTA.unlink(missing_ok=True) | |
| def visibles(f: dict) -> list[dict]: | |
| return [c for c in f["columnas"] if c["visible"]] | |
| # ---------------- logo ---------------- | |
| def logo() -> bytes | None: | |
| return RUTA_LOGO.read_bytes() if RUTA_LOGO.exists() else None | |
| def guardar_logo(datos: bytes): | |
| """Acepta PNG, JPG o WebP y lo guarda como PNG de 600 px como m谩ximo: Excel no admite WebP, y as铆 pesa poco y se | |
| ve bien en el Excel y el PDF. Lanza ValueError si la imagen no se puede abrir.""" | |
| from PIL import Image | |
| try: | |
| img = Image.open(io.BytesIO(datos)) | |
| img.load() | |
| except Exception as e: # noqa: BLE001 | |
| raise ValueError("No pude abrir la imagen del logo. Usa un PNG, JPG o WebP.") from e | |
| img = img.convert("RGBA") | |
| img.thumbnail((600, 600)) | |
| RUTA_LOGO.parent.mkdir(parents=True, exist_ok=True) | |
| buf = io.BytesIO() | |
| img.save(buf, format="PNG") | |
| RUTA_LOGO.write_bytes(buf.getvalue()) | |
| def quitar_logo(): | |
| RUTA_LOGO.unlink(missing_ok=True) | |
| # ---------------- colores ---------------- | |
| def hex_sin_numeral(color: str) -> str: | |
| return color.lstrip("#").upper() | |
| def aclarar(color: str, cuanto: float = 0.9) -> str: | |
| """Mezcla el color con blanco: para fondos suaves.""" | |
| c = hex_sin_numeral(color) | |
| r, g, b = (int(c[i:i + 2], 16) for i in (0, 2, 4)) | |
| r, g, b = (round(x + (255 - x) * cuanto) for x in (r, g, b)) | |
| return f"{r:02X}{g:02X}{b:02X}" | |