68 lines
1.7 KiB
Elixir
68 lines
1.7 KiB
Elixir
defmodule ApiWeb.DownloadpdfController do
|
|
use ApiWeb, :controller
|
|
alias Api.Downloadpdf
|
|
alias File
|
|
require Logger
|
|
|
|
def index(conn, %{"idstudyreport" => idstudyreport}) do
|
|
# Obtenemos los datos JSON del informe
|
|
Logger.info("hash antes de llamar a la funcion: #{idstudyreport}")
|
|
|
|
json = Downloadpdf.get_report_query(idstudyreport)
|
|
Logger.debug("resultado query: #{inspect(json)}")
|
|
|
|
# Verifica si el JSON es nulo o vacío
|
|
if json == nil or json == %{} do
|
|
Logger.error("Error: JSON is None or empty")
|
|
conn
|
|
|> send_resp(500, "Error generating PDF")
|
|
else
|
|
|
|
# Codificamos el JSON en una cadena para poder escribirlo en un archivo.
|
|
json = Jason.encode!(json)
|
|
|
|
Envar.load(".env")
|
|
Envar.require_env_file(".env")
|
|
|
|
python_executable = Envar.get("PYTHON_EXECUTABLE")
|
|
Logger.info("executable -> #{python_executable}")
|
|
python_script = Envar.get("PYTHON_SCRIPT")
|
|
Logger.info("script -> #{python_script}")
|
|
|
|
command = "#{python_executable} #{python_script}"
|
|
|
|
Logger.info("comando -> #{command}")
|
|
|
|
port = Port.open({:spawn, command}, [:binary, :use_stdio, :stderr_to_stdout, :exit_status])
|
|
|
|
Port.command(port, json <> "\n")
|
|
|
|
res = do_flush(<<0>>)
|
|
# IO.puts(res)
|
|
case json do
|
|
{:error, mensaje} ->
|
|
|
|
Logger.error("No se encontraron resultados para el reporte -> #{inspect(mensaje)}")
|
|
conn
|
|
|> put_status(:not_found)
|
|
|> html(mensaje)
|
|
|
|
_ ->
|
|
conn
|
|
|> put_resp_content_type("application/pdf")
|
|
|> send_resp(200, res)
|
|
end
|
|
|
|
end
|
|
end
|
|
|
|
defp do_flush(data) do
|
|
receive do
|
|
{_port, {:data, d}} ->
|
|
do_flush(data <> d)
|
|
_ ->
|
|
data
|
|
end
|
|
end
|
|
end
|