This commit is contained in:
Lizandro Guarnizo
2026-06-18 12:25:44 -05:00
parent 65ff7995e8
commit 408ea50d21
12 changed files with 1042 additions and 1100 deletions
+52 -90
View File
@@ -1,9 +1,12 @@
import json as json_lib
import httpx
from datetime import datetime
from fastapi import APIRouter, Request, Form, Depends
from fastapi.responses import JSONResponse
from app.database import get_connection
from app.auth import get_current_user
from app.services.firebird_service import FirebirdService
from app.services.json_generator import generar_terceros, generar_transaccion
from app.services.firebird_service import get_firebird_from_config
from app.services.json_generator import generar_transaccion, agrupar_por_factura
router = APIRouter(prefix="/transaccion", tags=["transaccion"])
@@ -45,16 +48,9 @@ async def preview_transaccion(
if not q:
return JSONResponse({"success": False, "message": "Consulta no encontrada"})
fb = FirebirdService()
fb_success, fb_msg = fb.connect(
configs.get("firebird_host", "localhost"),
int(configs.get("firebird_port", 3050)),
configs.get("firebird_database", ""),
configs.get("firebird_user", "SYSDBA"),
configs.get("firebird_password", "masterkey"),
)
if not fb_success:
return JSONResponse({"success": False, "message": f"Error Firebird: {fb_msg}"})
fb, ok, msg = get_firebird_from_config(configs)
if not ok:
return JSONResponse({"success": False, "message": f"Error Firebird: {msg}"})
params = {"fecha_ini": fecha_inicio, "fecha_fin": fecha_fin}
if ":factura" in q["query_text"] and factura:
@@ -66,26 +62,14 @@ async def preview_transaccion(
if not success:
return JSONResponse({"success": False, "message": error})
# Agrupar por paciente y factura
from collections import defaultdict
grupos = defaultdict(lambda: {"factura": "", "procedimientos": [], "paciente": {}})
for row in rows:
doc_key = (row.get("tipo_doc_paciente", "CC"), row.get("num_doc_paciente", ""))
fact = row.get("num_factura", factura)
grupos[(fact, doc_key)]["factura"] = fact
grupos[(fact, doc_key)]["procedimientos"].append(dict(row))
grupos = agrupar_por_factura(rows, factura)
json_result = []
for (fact, doc_key), grupo in grupos.items():
paciente_data = {"tipoDocumentoIdentificacion": doc_key[0], "numDocumentoIdentificacion": doc_key[1]}
trans = generar_transaccion(
fact,
configs.get("num_documento_obligado", ""),
paciente_data,
grupo["procedimientos"],
)
json_result.append(trans)
json_result.append(generar_transaccion(
fact, configs.get("num_documento_obligado", ""),
paciente_data, grupo["procedimientos"],
))
return JSONResponse({
"success": True,
@@ -107,11 +91,6 @@ async def send_transaccion(
fecha_inicio: str = Form(...),
fecha_fin: str = Form(...),
):
import json as json_lib
import httpx
from datetime import datetime
from collections import defaultdict
conn = get_connection()
q = conn.execute("SELECT * FROM queries WHERE id = ?", (query_id,)).fetchone()
configs = {row["key"]: row["value"] for row in conn.execute("SELECT * FROM config").fetchall()}
@@ -120,16 +99,9 @@ async def send_transaccion(
if not q:
return JSONResponse({"success": False, "message": "Consulta no encontrada"})
fb = FirebirdService()
fb_success, fb_msg = fb.connect(
configs.get("firebird_host", "localhost"),
int(configs.get("firebird_port", 3050)),
configs.get("firebird_database", ""),
configs.get("firebird_user", "SYSDBA"),
configs.get("firebird_password", "masterkey"),
)
if not fb_success:
return JSONResponse({"success": False, "message": f"Error Firebird: {fb_msg}"})
fb, ok, msg = get_firebird_from_config(configs)
if not ok:
return JSONResponse({"success": False, "message": f"Error Firebird: {msg}"})
params = {"fecha_ini": fecha_inicio, "fecha_fin": fecha_fin}
if ":factura" in q["query_text"] and factura:
@@ -143,14 +115,7 @@ async def send_transaccion(
if not rows:
return JSONResponse({"success": False, "message": "No se encontraron datos"})
# Agrupar
grupos = defaultdict(lambda: {"factura": "", "procedimientos": [], "paciente": {}})
for row in rows:
doc_key = (row.get("tipo_doc_paciente", "CC"), row.get("num_doc_paciente", ""))
fact = row.get("num_factura", factura)
grupos[(fact, doc_key)]["factura"] = fact
grupos[(fact, doc_key)]["procedimientos"].append(dict(row))
grupos = agrupar_por_factura(rows, factura)
api_url = configs.get("api_url", "")
api_key = configs.get("api_key", "")
api_method = configs.get("api_method", "POST")
@@ -162,52 +127,49 @@ async def send_transaccion(
total_errores = 0
resultados = []
for (fact, doc_key), grupo in grupos.items():
paciente_data = {"tipoDocumentoIdentificacion": doc_key[0], "numDocumentoIdentificacion": doc_key[1]}
trans_json = generar_transaccion(
fact,
configs.get("num_documento_obligado", ""),
paciente_data,
grupo["procedimientos"],
)
async with httpx.AsyncClient(timeout=int(configs.get("api_timeout", 30))) as client:
for (fact, doc_key), grupo in grupos.items():
paciente_data = {"tipoDocumentoIdentificacion": doc_key[0], "numDocumentoIdentificacion": doc_key[1]}
trans_json = generar_transaccion(
fact, configs.get("num_documento_obligado", ""),
paciente_data, grupo["procedimientos"],
)
try:
async with httpx.AsyncClient(timeout=int(configs.get("api_timeout", 30))) as client:
status_ok = False
response_text = ""
try:
if api_method == "POST":
resp = await client.post(api_url + "/transaccion", json=trans_json, headers=headers)
else:
resp = await client.put(api_url + "/transaccion", json=trans_json, headers=headers)
status_ok = resp.is_success
response_text = resp.text[:1000]
except Exception as e:
response_text = str(e)
status_ok = resp.is_success
response_text = resp.text[:1000]
except Exception as e:
status_ok = False
response_text = str(e)
if status_ok:
total_enviados += 1
else:
total_errores += 1
if status_ok:
total_enviados += 1
else:
total_errores += 1
resultados.append({"factura": fact, "success": status_ok})
resultados.append({"factura": fact, "success": status_ok})
# Guardar log
conn = get_connection()
conn.execute("""
INSERT INTO envios (user_id, tipo, factura, fecha_inicio, fecha_fin,
pacientes_count, servicios_count, status, json_enviado, respuesta_api, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (
user["user_id"], "transaccion", fact,
fecha_inicio, fecha_fin,
1, len(grupo["procedimientos"]),
"success" if status_ok else "error",
json_lib.dumps(trans_json, indent=2, ensure_ascii=False)[:5000],
response_text,
datetime.now().isoformat(),
))
conn.commit()
conn.close()
conn = get_connection()
conn.execute("""
INSERT INTO envios (user_id, tipo, factura, fecha_inicio, fecha_fin,
pacientes_count, servicios_count, status, json_enviado, respuesta_api, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (
user["user_id"], "transaccion", fact,
fecha_inicio, fecha_fin,
1, len(grupo["procedimientos"]),
"success" if status_ok else "error",
json_lib.dumps(trans_json, indent=2, ensure_ascii=False)[:5000],
response_text,
datetime.now().isoformat(),
))
conn.commit()
conn.close()
return JSONResponse({
"success": total_errores == 0,