File size: 1,903 Bytes
598559d
 
 
 
 
 
e0b5e77
598559d
e0b5e77
598559d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0b5e77
 
598559d
 
 
e0b5e77
 
598559d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from __future__ import annotations

from datetime import datetime
from typing import Any, Dict

from jinja2 import Environment, FileSystemLoader, select_autoescape
from weasyprint import HTML

from .config import BASE_DIR  # si lo usas para rutas

TEMPLATES_DIR = BASE_DIR / "templates"

TEMPLATE_MAP: Dict[str, str] = {
    "RESTlet": "RESTlet.html.j2",
    "ClientScript": "ClientScript.html.j2",
    "Map/Reduce": "MapReduce.html.j2",
    "MapReduce": "MapReduce.html.j2",
    "Scheduled": "ScheduledScript.html.j2",
    "ScheduledScript": "ScheduledScript.html.j2",
    "Suitelet": "Suitelet.html.j2",
    "UserEvent": "UserEventScript.html.j2",
    "UserEventScript": "UserEventScript.html.j2",
    "UserModule.js": "InternalModule.html.j2",
    "InternalModule": "InternalModule.html.j2",
}

env = Environment(
    loader=FileSystemLoader(str(TEMPLATES_DIR)),
    autoescape=select_autoescape(["html", "xml"]),
    trim_blocks=True,
    lstrip_blocks=True,
)


def _resolve_template(doc: Dict[str, Any]) -> str:
    metadata = doc.get("metadata") or {}
    script_type = (
        metadata.get("script_type") or metadata.get("type") or "InternalModule"
    )
    return TEMPLATE_MAP.get(script_type, "InternalModule.html.j2")


def render_html(doc: Dict[str, Any]) -> str:
    template_name = _resolve_template(doc)
    template = env.get_template(template_name)
    html = template.render(
        doc=doc,
        generated_at=datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC"),
    )
    return html


def render_pdf_bytes(doc: Dict[str, Any]) -> bytes:
    """
    Genera un PDF vectorial a partir del HTML usando WeasyPrint.
    El texto es seleccionable.
    """
    html = render_html(doc)

    # base_url permite que WeasyPrint resuelva rutas relativas (si tuvieras CSS/imagenes locales)
    pdf_bytes: bytes = HTML(string=html, base_url=str(TEMPLATES_DIR)).write_pdf()
    return pdf_bytes