FACTURA_DIAN.FECHAFACT is DATE type, incompatible with datetime strings. CAST to TIMESTAMP allows comparison with :fecha_ini/:fecha_fin params. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1063 lines
44 KiB
Python
1063 lines
44 KiB
Python
import json as json_lib
|
|
from datetime import datetime, date
|
|
from fastapi import APIRouter, Request, Form, Depends
|
|
from fastapi.responses import JSONResponse
|
|
import httpx
|
|
|
|
from app.database import get_connection
|
|
from app.auth import get_current_user
|
|
from app.services.firebird_service import get_firebird_from_config
|
|
from app.services.json_generator import (
|
|
generar_tercero_api,
|
|
generar_rda_paciente,
|
|
agrupar_por_recepcion,
|
|
agrupar_por_factura,
|
|
generar_factura_venta,
|
|
)
|
|
from app.services.api_client import get_tns_token, TNS_BASE
|
|
from app.services.whatsapp_sync import sync_paciente, sync_todos, guardar_sync_log
|
|
from app.routes.contratos import load_contrato_map, load_excluded_set, load_sin_contrato_set, load_excluded_ventas_set
|
|
from app.utils.activity import log_activity, get_ip
|
|
|
|
router = APIRouter(prefix="/automation", tags=["automation"])
|
|
|
|
# Query para obtener pacientes únicos por rango de fecha + contrato
|
|
_SQL_PACIENTES = """
|
|
SELECT DISTINCT
|
|
p.CODIGO,
|
|
p.TIPOIDENT,
|
|
p.DOCIDENT,
|
|
p.NOMBRES,
|
|
p.APELLIDOS,
|
|
p.DIRECCION,
|
|
p.CIUDAD AS COD_CIUDAD,
|
|
c.NOMBRE AS NOM_CIUDAD,
|
|
p.TELEFONOS,
|
|
p.EMAIL,
|
|
p.F_NACIMIENTO,
|
|
p.SEXO,
|
|
p.TIPORES,
|
|
p.CODETNIA
|
|
FROM PACIENTE p
|
|
JOIN RECEPCION r ON r.COD_PACIENTE = p.CODIGO
|
|
LEFT JOIN EMPRESA e ON e.NIT = r.NIT_EMPRESA
|
|
LEFT JOIN CIUDAD c ON c.CODIGO = p.CIUDAD
|
|
WHERE r.FECHA_RECEPCION BETWEEN :fecha_ini AND :fecha_fin
|
|
AND r.NUM_FACTURA > 0
|
|
AND r.PS_NUM IS NULL
|
|
AND r.PREFIJO != 'CMXC'
|
|
{filtro_contrato_pac}
|
|
"""
|
|
|
|
# Query para obtener recepciones con exámenes por rango de fecha + contrato
|
|
_SQL_RDA = """
|
|
SELECT
|
|
r.IDRECEPCION,
|
|
r.PREFIJO,
|
|
r.NUM_FACTURA,
|
|
r.FECHA_RECEPCION,
|
|
r.COD_PACIENTE,
|
|
r.NIT_EMPRESA,
|
|
r.DIAG_PPAL,
|
|
r.TIPOUSU,
|
|
r.TIPOUSUSISPRO,
|
|
r.AUTORIZACION,
|
|
r.CLASEPROC,
|
|
r.HORAINICIORECEPCION,
|
|
r.VALORTOTAL,
|
|
r.VALORDESC,
|
|
rel.COD_EXAMEN,
|
|
COALESCE(NULLIF(TRIM(ex.NUM_ISS), ''), TRIM(rel.COD_EXAMEN)) AS CUPS,
|
|
rel.PRECIO,
|
|
COALESCE(t.VALOR, rel.PRECIO) AS PRECIO_TARIFA,
|
|
rel.FECHA_REPORTADO,
|
|
m.COD_ESPECIALIDAD,
|
|
COALESCE(NULLIF(TRIM(m.CODIGO), ''), NULLIF(TRIM(r.USUARIO), ''), '') AS profesional,
|
|
e.CODCONTRATO,
|
|
TRIM(m.DOCIDMEDICO) AS DOCIDMEDICO
|
|
FROM RECEPCION r
|
|
JOIN RELACION rel ON rel.IDRECEPCION = r.IDRECEPCION
|
|
LEFT JOIN EXAMEN ex ON TRIM(ex.CODIGO) = TRIM(rel.COD_EXAMEN)
|
|
LEFT JOIN MEDICO m ON m.CODIGO = r.COD_MEDICO
|
|
LEFT JOIN EMPRESA e ON e.NIT = r.NIT_EMPRESA
|
|
LEFT JOIN TARIFA t ON TRIM(t.COD_EXAMEN) = TRIM(rel.COD_EXAMEN) AND t.TARIFA = e.TARIFA
|
|
WHERE r.FECHA_RECEPCION BETWEEN :fecha_ini AND :fecha_fin
|
|
AND r.NUM_FACTURA > 0
|
|
AND r.PS_NUM IS NULL
|
|
AND r.PREFIJO != 'CMXC'
|
|
{filtro_contrato_rda}
|
|
ORDER BY r.IDRECEPCION
|
|
"""
|
|
|
|
|
|
_SQL_PACIENTES_EPS = """
|
|
SELECT DISTINCT
|
|
p.CODIGO,
|
|
p.TIPOIDENT,
|
|
p.DOCIDENT,
|
|
p.NOMBRES,
|
|
p.APELLIDOS,
|
|
p.DIRECCION,
|
|
p.CIUDAD AS COD_CIUDAD,
|
|
c.NOMBRE AS NOM_CIUDAD,
|
|
p.TELEFONOS,
|
|
p.EMAIL,
|
|
p.F_NACIMIENTO,
|
|
p.SEXO,
|
|
p.TIPORES,
|
|
p.CODETNIA
|
|
FROM PACIENTE p
|
|
JOIN RECEPCION r ON r.COD_PACIENTE = p.CODIGO
|
|
JOIN PRESSERV_DIAN ps ON ps.ID_RECEP = r.IDRECEPCION
|
|
LEFT JOIN CIUDAD c ON c.CODIGO = p.CIUDAD
|
|
WHERE r.FECHA_RECEPCION BETWEEN :fecha_ini AND :fecha_fin
|
|
AND (ps.PS_ANULADA IS NULL OR ps.PS_ANULADA = 'F')
|
|
"""
|
|
|
|
_SQL_PRESERV = """
|
|
SELECT
|
|
ps.ID_PS,
|
|
ps.PS_PREFIJO,
|
|
ps.PS_NUMERO,
|
|
r.IDRECEPCION,
|
|
r.FECHA_RECEPCION,
|
|
r.COD_PACIENTE,
|
|
r.NIT_EMPRESA,
|
|
r.DIAG_PPAL,
|
|
r.TIPOUSU,
|
|
r.TIPOUSUSISPRO,
|
|
r.AUTORIZACION,
|
|
r.CLASEPROC,
|
|
r.HORAINICIORECEPCION,
|
|
r.VALORTOTAL,
|
|
r.VALORDESC,
|
|
COALESCE((SELECT FIRST 1 pg.VALOR FROM PAGOS pg
|
|
WHERE pg.NUMRECEP = r.IDRECEPCION
|
|
AND pg.ESINICIAL = 'T'), 0) AS COPAGO,
|
|
rel.COD_EXAMEN,
|
|
COALESCE(NULLIF(TRIM(ex.NUM_ISS), ''), TRIM(rel.COD_EXAMEN)) AS CUPS,
|
|
rel.PRECIO,
|
|
COALESCE(t.VALOR, rel.PRECIO) AS PRECIO_TARIFA,
|
|
rel.FECHA_REPORTADO,
|
|
m.COD_ESPECIALIDAD,
|
|
COALESCE(NULLIF(TRIM(m.CODIGO), ''), NULLIF(TRIM(r.USUARIO), ''), '') AS profesional,
|
|
e.CODCONTRATO,
|
|
TRIM(m.DOCIDMEDICO) AS DOCIDMEDICO
|
|
FROM PRESSERV_DIAN ps
|
|
JOIN RECEPCION r ON r.IDRECEPCION = ps.ID_RECEP
|
|
JOIN RELACION rel ON rel.IDRECEPCION = r.IDRECEPCION
|
|
LEFT JOIN EXAMEN ex ON TRIM(ex.CODIGO) = TRIM(rel.COD_EXAMEN)
|
|
LEFT JOIN MEDICO m ON m.CODIGO = r.COD_MEDICO
|
|
LEFT JOIN EMPRESA e ON e.NIT = r.NIT_EMPRESA
|
|
LEFT JOIN TARIFA t ON TRIM(t.COD_EXAMEN) = TRIM(rel.COD_EXAMEN) AND t.TARIFA = e.TARIFA
|
|
WHERE r.FECHA_RECEPCION BETWEEN :fecha_ini AND :fecha_fin
|
|
AND (ps.PS_ANULADA IS NULL OR ps.PS_ANULADA = 'F')
|
|
ORDER BY ps.ID_PS, rel.COD_EXAMEN
|
|
"""
|
|
|
|
|
|
_SQL_VENTAS = """
|
|
SELECT
|
|
r.IDRECEPCION,
|
|
r.PREFIJO,
|
|
r.NUM_FACTURA,
|
|
r.FECHA_RECEPCION,
|
|
r.COD_PACIENTE,
|
|
r.NIT_EMPRESA,
|
|
r.VALORTOTAL,
|
|
r.VALORDESC,
|
|
rel.COD_EXAMEN,
|
|
COALESCE(NULLIF(TRIM(ex.NUM_ISS), ''), TRIM(rel.COD_EXAMEN)) AS CUPS,
|
|
rel.PRECIO,
|
|
COALESCE(t.VALOR, rel.PRECIO) AS PRECIO_TARIFA,
|
|
TRIM(e.CODCONTRATO) AS CODCONTRATO,
|
|
CAST(fd.FECHAFACT AS VARCHAR(30)) AS FECHAFACT
|
|
FROM RECEPCION r
|
|
JOIN FACTURA_DIAN fd ON fd.PREFIJO = r.PREFIJO AND fd.NUM_FACTURA = r.NUM_FACTURA
|
|
JOIN RELACION rel ON rel.IDRECEPCION = r.IDRECEPCION
|
|
LEFT JOIN EXAMEN ex ON TRIM(ex.CODIGO) = TRIM(rel.COD_EXAMEN)
|
|
LEFT JOIN EMPRESA e ON e.NIT = r.NIT_EMPRESA
|
|
LEFT JOIN TARIFA t ON TRIM(t.COD_EXAMEN) = TRIM(rel.COD_EXAMEN) AND t.TARIFA = e.TARIFA
|
|
WHERE CAST(fd.FECHAFACT AS TIMESTAMP) BETWEEN :fecha_ini AND :fecha_fin
|
|
AND (fd.ANULADA IS NULL OR fd.ANULADA = 'F')
|
|
AND r.PREFIJO = 'CMXC'
|
|
ORDER BY r.NUM_FACTURA, r.IDRECEPCION
|
|
"""
|
|
|
|
_SQL_RDA_BY_ID = """
|
|
SELECT
|
|
r.IDRECEPCION, r.PREFIJO, r.NUM_FACTURA, r.FECHA_RECEPCION,
|
|
r.COD_PACIENTE, r.NIT_EMPRESA, r.DIAG_PPAL, r.TIPOUSU, r.TIPOUSUSISPRO,
|
|
r.AUTORIZACION, r.CLASEPROC, r.HORAINICIORECEPCION, r.VALORTOTAL, r.VALORDESC,
|
|
rel.COD_EXAMEN,
|
|
COALESCE(NULLIF(TRIM(ex.NUM_ISS), ''), TRIM(rel.COD_EXAMEN)) AS CUPS,
|
|
rel.PRECIO, COALESCE(t.VALOR, rel.PRECIO) AS PRECIO_TARIFA,
|
|
rel.FECHA_REPORTADO, m.COD_ESPECIALIDAD,
|
|
COALESCE(NULLIF(TRIM(m.CODIGO), ''), NULLIF(TRIM(r.USUARIO), ''), '') AS profesional,
|
|
e.CODCONTRATO, TRIM(m.DOCIDMEDICO) AS DOCIDMEDICO
|
|
FROM RECEPCION r
|
|
JOIN RELACION rel ON rel.IDRECEPCION = r.IDRECEPCION
|
|
LEFT JOIN EXAMEN ex ON TRIM(ex.CODIGO) = TRIM(rel.COD_EXAMEN)
|
|
LEFT JOIN MEDICO m ON m.CODIGO = r.COD_MEDICO
|
|
LEFT JOIN EMPRESA e ON e.NIT = r.NIT_EMPRESA
|
|
LEFT JOIN TARIFA t ON TRIM(t.COD_EXAMEN) = TRIM(rel.COD_EXAMEN) AND t.TARIFA = e.TARIFA
|
|
WHERE r.IDRECEPCION = :idrecepcion
|
|
ORDER BY rel.COD_EXAMEN
|
|
"""
|
|
|
|
_SQL_PRESERV_BY_ID = """
|
|
SELECT
|
|
ps.ID_PS, ps.PS_PREFIJO, ps.PS_NUMERO,
|
|
r.IDRECEPCION, r.FECHA_RECEPCION, r.COD_PACIENTE, r.NIT_EMPRESA,
|
|
r.DIAG_PPAL, r.TIPOUSU, r.TIPOUSUSISPRO, r.AUTORIZACION,
|
|
r.CLASEPROC, r.HORAINICIORECEPCION, r.VALORTOTAL, r.VALORDESC,
|
|
COALESCE((SELECT FIRST 1 pg.VALOR FROM PAGOS pg
|
|
WHERE pg.NUMRECEP = r.IDRECEPCION AND pg.ESINICIAL = 'T'), 0) AS COPAGO,
|
|
rel.COD_EXAMEN,
|
|
COALESCE(NULLIF(TRIM(ex.NUM_ISS), ''), TRIM(rel.COD_EXAMEN)) AS CUPS,
|
|
rel.PRECIO, COALESCE(t.VALOR, rel.PRECIO) AS PRECIO_TARIFA,
|
|
rel.FECHA_REPORTADO, m.COD_ESPECIALIDAD,
|
|
COALESCE(NULLIF(TRIM(m.CODIGO), ''), NULLIF(TRIM(r.USUARIO), ''), '') AS profesional,
|
|
e.CODCONTRATO, TRIM(m.DOCIDMEDICO) AS DOCIDMEDICO
|
|
FROM PRESSERV_DIAN ps
|
|
JOIN RECEPCION r ON r.IDRECEPCION = ps.ID_RECEP
|
|
JOIN RELACION rel ON rel.IDRECEPCION = r.IDRECEPCION
|
|
LEFT JOIN EXAMEN ex ON TRIM(ex.CODIGO) = TRIM(rel.COD_EXAMEN)
|
|
LEFT JOIN MEDICO m ON m.CODIGO = r.COD_MEDICO
|
|
LEFT JOIN EMPRESA e ON e.NIT = r.NIT_EMPRESA
|
|
LEFT JOIN TARIFA t ON TRIM(t.COD_EXAMEN) = TRIM(rel.COD_EXAMEN) AND t.TARIFA = e.TARIFA
|
|
WHERE ps.ID_PS = :id_ps
|
|
AND (ps.PS_ANULADA IS NULL OR ps.PS_ANULADA = 'F')
|
|
ORDER BY rel.COD_EXAMEN
|
|
"""
|
|
|
|
_SQL_VENTAS_BY_FACTURA = """
|
|
SELECT
|
|
r.IDRECEPCION, r.PREFIJO, r.NUM_FACTURA, r.FECHA_RECEPCION,
|
|
r.COD_PACIENTE, r.NIT_EMPRESA, r.VALORTOTAL, r.VALORDESC,
|
|
rel.COD_EXAMEN,
|
|
COALESCE(NULLIF(TRIM(ex.NUM_ISS), ''), TRIM(rel.COD_EXAMEN)) AS CUPS,
|
|
rel.PRECIO, COALESCE(t.VALOR, rel.PRECIO) AS PRECIO_TARIFA,
|
|
TRIM(e.CODCONTRATO) AS CODCONTRATO
|
|
FROM RECEPCION r
|
|
JOIN RELACION rel ON rel.IDRECEPCION = r.IDRECEPCION
|
|
LEFT JOIN EXAMEN ex ON TRIM(ex.CODIGO) = TRIM(rel.COD_EXAMEN)
|
|
LEFT JOIN EMPRESA e ON e.NIT = r.NIT_EMPRESA
|
|
LEFT JOIN TARIFA t ON TRIM(t.COD_EXAMEN) = TRIM(rel.COD_EXAMEN) AND t.TARIFA = e.TARIFA
|
|
WHERE r.PREFIJO = :prefijo AND r.NUM_FACTURA = :num_factura
|
|
ORDER BY r.IDRECEPCION
|
|
"""
|
|
|
|
_SQL_VENTAS_BY_IDRECEP = """
|
|
SELECT r.PREFIJO, r.NUM_FACTURA
|
|
FROM RECEPCION r
|
|
WHERE r.IDRECEPCION = :idrecepcion
|
|
"""
|
|
|
|
_SQL_PAC_BY_CODIGO = """
|
|
SELECT
|
|
p.CODIGO, p.TIPOIDENT, p.DOCIDENT, p.NOMBRES, p.APELLIDOS,
|
|
p.DIRECCION, p.CIUDAD AS COD_CIUDAD, c.NOMBRE AS NOM_CIUDAD,
|
|
p.TELEFONOS, p.EMAIL, p.F_NACIMIENTO, p.SEXO, p.TIPORES, p.CODETNIA
|
|
FROM PACIENTE p
|
|
LEFT JOIN CIUDAD c ON c.CODIGO = p.CIUDAD
|
|
WHERE p.CODIGO = :codigo
|
|
"""
|
|
|
|
|
|
def _agrupar_por_presserv(rows: list) -> dict:
|
|
"""Agrupa filas de pre-servicios por ID_PS."""
|
|
from collections import defaultdict
|
|
grupos = defaultdict(list)
|
|
for row in rows:
|
|
grupos[row.get("ID_PS")].append(dict(row))
|
|
return grupos
|
|
|
|
|
|
@router.get("")
|
|
async def automation_page(request: Request, user: dict = Depends(get_current_user)):
|
|
today = date.today().isoformat()
|
|
return request.app.state.templates.TemplateResponse("automation.html", {
|
|
"request": request, "user": user, "today": today,
|
|
})
|
|
|
|
|
|
@router.get("/debug-cmxc")
|
|
async def debug_cmxc(request: Request, user: dict = Depends(get_current_user), fecha: str = ""):
|
|
"""Diagnóstico temporal: muestra recepciones CMXC y sus envíos para una fecha."""
|
|
if not fecha:
|
|
fecha = date.today().isoformat()
|
|
|
|
# Recepciones CMXC en Firebird
|
|
conn_cfg = get_connection()
|
|
configs = {row["key"]: row["value"] for row in conn_cfg.execute("SELECT * FROM config").fetchall()}
|
|
conn_cfg.close()
|
|
fb, fb_ok, fb_msg = get_firebird_from_config(configs)
|
|
if not fb_ok:
|
|
return JSONResponse({"error": fb_msg})
|
|
ok, err, rows_fb = fb.execute_query("""
|
|
SELECT r.IDRECEPCION, r.PREFIJO, r.NUM_FACTURA, r.PS_NUM,
|
|
r.NIT_EMPRESA, r.VALORTOTAL, r.FECHA_RECEPCION,
|
|
e.CODCONTRATO
|
|
FROM RECEPCION r
|
|
LEFT JOIN EMPRESA e ON e.NIT = r.NIT_EMPRESA
|
|
WHERE r.FECHA_RECEPCION BETWEEN :fecha_ini AND :fecha_fin
|
|
AND r.PREFIJO = 'CMXC'
|
|
ORDER BY r.IDRECEPCION
|
|
""", {"fecha_ini": f"{fecha} 00:00:00", "fecha_fin": f"{fecha} 23:59:59"})
|
|
fb.disconnect()
|
|
if not ok:
|
|
return JSONResponse({"error": err})
|
|
|
|
from app.routes.contratos import load_excluded_set
|
|
excluded = load_excluded_set()
|
|
|
|
rows_con_estado = []
|
|
for r in rows_fb:
|
|
cod = str(r.get("CODCONTRATO") or "").strip()
|
|
rows_con_estado.append({**r, "excluido": cod in excluded})
|
|
|
|
# Envíos en SQLite
|
|
conn_sq = get_connection()
|
|
envios_recientes = conn_sq.execute("""
|
|
SELECT id, factura, tipo, status, created_at
|
|
FROM envios ORDER BY id DESC LIMIT 15
|
|
""").fetchall()
|
|
conn_sq.close()
|
|
|
|
return JSONResponse({
|
|
"fecha": fecha,
|
|
"excluidos_configurados": sorted(excluded),
|
|
"cmxc_firebird": {"total": len(rows_fb), "rows": rows_con_estado},
|
|
"envios_recientes": [dict(e) for e in envios_recientes],
|
|
})
|
|
|
|
|
|
def _build_sql(contrato: str):
|
|
if contrato:
|
|
fp = "AND e.CODCONTRATO = :contrato"
|
|
fr = "AND e.CODCONTRATO = :contrato"
|
|
else:
|
|
fp = ""
|
|
fr = ""
|
|
return (
|
|
_SQL_PACIENTES.format(filtro_contrato_pac=fp),
|
|
_SQL_RDA.format(filtro_contrato_rda=fr),
|
|
)
|
|
|
|
|
|
@router.post("/preview")
|
|
async def preview_automation(
|
|
request: Request,
|
|
user: dict = Depends(get_current_user),
|
|
fecha: str = Form(...),
|
|
contrato: str = Form(""),
|
|
):
|
|
conn = get_connection()
|
|
configs = {row["key"]: row["value"] for row in conn.execute("SELECT * FROM config").fetchall()}
|
|
conn.close()
|
|
|
|
fb, fb_ok, fb_msg = get_firebird_from_config(configs)
|
|
if not fb_ok:
|
|
return JSONResponse({"success": False, "message": f"Error Firebird: {fb_msg}"})
|
|
|
|
fecha_ini = f"{fecha} 00:00:00"
|
|
fecha_fin = f"{fecha} 23:59:59"
|
|
params = {"fecha_ini": fecha_ini, "fecha_fin": fecha_fin}
|
|
if contrato:
|
|
params["contrato"] = contrato.strip()
|
|
|
|
sql_pac, sql_rda = _build_sql(contrato.strip())
|
|
|
|
ok1, err1, rows_pac = fb.execute_query(sql_pac, params)
|
|
if not ok1:
|
|
fb.disconnect()
|
|
return JSONResponse({"success": False, "message": f"Error BD pacientes: {err1}"})
|
|
|
|
ok2, err2, rows_rda = fb.execute_query(sql_rda, params)
|
|
if not ok2:
|
|
fb.disconnect()
|
|
return JSONResponse({"success": False, "message": f"Error BD RDA: {err2}"})
|
|
|
|
ok3, err3, rows_ps = fb.execute_query(_SQL_PRESERV, {"fecha_ini": fecha_ini, "fecha_fin": fecha_fin})
|
|
if not ok3:
|
|
fb.disconnect()
|
|
return JSONResponse({"success": False, "message": f"Error BD Pre-servicios: {err3}"})
|
|
|
|
ok4, err4, rows_vta = fb.execute_query(_SQL_VENTAS, {"fecha_ini": fecha_ini, "fecha_fin": fecha_fin})
|
|
fb.disconnect()
|
|
if not ok4:
|
|
return JSONResponse({"success": False, "message": f"Error BD Ventas: {err4}"})
|
|
|
|
excluded = load_excluded_set()
|
|
excluded_ventas = load_excluded_ventas_set()
|
|
|
|
grupos_all = agrupar_por_recepcion(rows_rda)
|
|
grupos = {k: v for k, v in grupos_all.items()
|
|
if str(v[0].get("CODCONTRATO") or "").strip() not in excluded}
|
|
excluidos_count = len(grupos_all) - len(grupos)
|
|
total_examenes = sum(len(v) for v in grupos.values())
|
|
|
|
grupos_ps_all = _agrupar_por_presserv(rows_ps)
|
|
grupos_ps = {k: v for k, v in grupos_ps_all.items()
|
|
if str(v[0].get("CODCONTRATO") or "").strip() not in excluded}
|
|
|
|
contrato_map = load_contrato_map()
|
|
sin_contrato_set = load_sin_contrato_set()
|
|
prof_def = configs.get("profesional_default", "")
|
|
esp_def = configs.get("especialidad_default", "")
|
|
remis_def = configs.get("remisionante_default", "00")
|
|
prefijo_def = configs.get("prefijo_tns_default", "00")
|
|
|
|
preservicios_preview = []
|
|
for id_ps, grupo_rows in grupos_ps.items():
|
|
ps_prefijo = str(grupo_rows[0].get("PS_PREFIJO") or "SC").strip()
|
|
ps_numero = str(grupo_rows[0].get("PS_NUMERO") or "").strip()
|
|
rda_json = generar_rda_paciente(
|
|
grupo_rows, prof_def, esp_def, remis_def, prefijo_def,
|
|
numero_override=ps_numero,
|
|
contrato_map=contrato_map,
|
|
prefijo_override="00" if ps_prefijo == "RCXC" else ps_prefijo,
|
|
sin_contrato_set=sin_contrato_set,
|
|
)
|
|
preservicios_preview.append({
|
|
"factura": f"{ps_prefijo}-{ps_numero.zfill(5)}",
|
|
"paciente": str(grupo_rows[0].get("COD_PACIENTE", "")),
|
|
"fecha": str(grupo_rows[0].get("FECHA_RECEPCION", ""))[:10],
|
|
"examenes": len(grupo_rows),
|
|
"json": rda_json,
|
|
})
|
|
|
|
# Agrupar RDA por COD_PACIENTE
|
|
rda_por_pac = {}
|
|
for id_rec, filas in grupos.items():
|
|
cod = str(filas[0].get("COD_PACIENTE", ""))
|
|
num_fac = str(filas[0].get("NUM_FACTURA") or "").strip()
|
|
rda_json_prev = generar_rda_paciente(
|
|
filas, prof_def, esp_def, remis_def, prefijo_def,
|
|
numero_override=num_fac,
|
|
contrato_map=contrato_map,
|
|
sin_contrato_set=sin_contrato_set,
|
|
)
|
|
if cod not in rda_por_pac:
|
|
rda_por_pac[cod] = []
|
|
rda_por_pac[cod].append({
|
|
"id_recepcion": id_rec,
|
|
"factura": f"{str(filas[0].get('PREFIJO', '')).strip()}-{filas[0].get('NUM_FACTURA', '')}",
|
|
"fecha": str(filas[0].get("FECHA_RECEPCION", ""))[:10],
|
|
"examenes": len(filas),
|
|
"valor": float(filas[0].get("VALORTOTAL") or 0),
|
|
"diag": str(filas[0].get("DIAG_PPAL") or ""),
|
|
"contrato": str(filas[0].get("CODCONTRATO") or "").strip(),
|
|
"json": rda_json_prev,
|
|
})
|
|
|
|
pacientes_preview = [
|
|
{
|
|
"codigo": str(p.get("CODIGO", "")),
|
|
"doc": str(p.get("DOCIDENT", "")),
|
|
"nombre": f"{p.get('NOMBRES', '')} {p.get('APELLIDOS', '')}".strip(),
|
|
"tipo": str(p.get("TIPOIDENT", "")),
|
|
"rda": rda_por_pac.get(str(p.get("CODIGO", "")), []),
|
|
}
|
|
for p in rows_pac
|
|
if rda_por_pac.get(str(p.get("CODIGO", "")))
|
|
]
|
|
|
|
grupos_vta = {}
|
|
for k, v in agrupar_por_factura(rows_vta).items():
|
|
if not isinstance(v, list) or not v:
|
|
continue
|
|
if int(v[0].get("NUM_FACTURA") or 0) == 0:
|
|
continue
|
|
if str(v[0].get("CODCONTRATO") or "").strip() in excluded_ventas:
|
|
continue
|
|
grupos_vta[k] = v
|
|
|
|
ventas_preview = []
|
|
ventas_gen_errors = []
|
|
for num_fac_key, grupo_rows in grupos_vta.items():
|
|
num_fac = str(grupo_rows[0].get("NUM_FACTURA") or "").strip()
|
|
prefijo = str(grupo_rows[0].get("PREFIJO") or "").strip()
|
|
try:
|
|
venta_json = generar_factura_venta(grupo_rows, default_vendedor="00",
|
|
default_prefijo=prefijo_def, numero_override=num_fac)
|
|
except Exception as exc:
|
|
import traceback as _tb
|
|
ventas_gen_errors.append({"factura": num_fac, "error": str(exc),
|
|
"traceback": _tb.format_exc()})
|
|
continue
|
|
ventas_preview.append({
|
|
"factura": f"{prefijo}-{num_fac}",
|
|
"paciente": str(grupo_rows[0].get("COD_PACIENTE", "")),
|
|
"fecha": str(grupo_rows[0].get("FECHA_RECEPCION", ""))[:10],
|
|
"contrato": str(grupo_rows[0].get("CODCONTRATO") or "").strip(),
|
|
"examenes": len(grupo_rows),
|
|
"json": venta_json,
|
|
})
|
|
|
|
return JSONResponse({
|
|
"success": True,
|
|
"fecha": fecha,
|
|
"pacientes": len(pacientes_preview),
|
|
"recepciones": len(grupos),
|
|
"examenes": total_examenes,
|
|
"excluidos": excluidos_count,
|
|
"preservicios": len(grupos_ps),
|
|
"ventas": len(grupos_vta),
|
|
"ventas_gen_errors": ventas_gen_errors,
|
|
"pacientes_preview": pacientes_preview,
|
|
"preservicios_preview": preservicios_preview,
|
|
"ventas_preview": ventas_preview,
|
|
})
|
|
|
|
|
|
@router.post("/run")
|
|
async def run_automation(
|
|
request: Request,
|
|
user: dict = Depends(get_current_user),
|
|
fecha: str = Form(...),
|
|
contrato: str = Form(""),
|
|
pasos: str = Form("terceros,rda,preserv,ventas"),
|
|
):
|
|
conn = get_connection()
|
|
configs = {row["key"]: row["value"] for row in conn.execute("SELECT * FROM config").fetchall()}
|
|
conn.close()
|
|
|
|
fb, fb_ok, fb_msg = get_firebird_from_config(configs)
|
|
if not fb_ok:
|
|
return JSONResponse({"success": False, "message": f"Error Firebird: {fb_msg}"})
|
|
|
|
fecha_ini = f"{fecha} 00:00:00"
|
|
fecha_fin = f"{fecha} 23:59:59"
|
|
params = {"fecha_ini": fecha_ini, "fecha_fin": fecha_fin}
|
|
if contrato:
|
|
params["contrato"] = contrato.strip()
|
|
|
|
sql_pac, sql_rda = _build_sql(contrato.strip())
|
|
|
|
# ── Paso 1: obtener pacientes únicos (particulares) ───────────────────────
|
|
ok1, err1, rows_pac = fb.execute_query(sql_pac, params)
|
|
if not ok1:
|
|
fb.disconnect()
|
|
return JSONResponse({"success": False, "message": f"Error Firebird pacientes: {err1}"})
|
|
|
|
# ── Paso 2: obtener recepciones ───────────────────────────────────────────
|
|
ok2, err2, rows_rda = fb.execute_query(sql_rda, params)
|
|
if not ok2:
|
|
fb.disconnect()
|
|
return JSONResponse({"success": False, "message": f"Error Firebird RDA: {err2}"})
|
|
|
|
# ── Paso 3: obtener pre-servicios ─────────────────────────────────────────
|
|
ok3, err3, rows_ps = fb.execute_query(_SQL_PRESERV, {"fecha_ini": fecha_ini, "fecha_fin": fecha_fin})
|
|
if not ok3:
|
|
fb.disconnect()
|
|
return JSONResponse({"success": False, "message": f"Error Firebird Pre-servicios: {err3}"})
|
|
|
|
# ── Pacientes EPS (para registrar terceros en paso 1) ─────────────────────
|
|
ok4, err4, rows_pac_eps = fb.execute_query(_SQL_PACIENTES_EPS, {"fecha_ini": fecha_ini, "fecha_fin": fecha_fin})
|
|
if not ok4:
|
|
fb.disconnect()
|
|
return JSONResponse({"success": False, "message": f"Error Firebird pacientes EPS: {err4}"})
|
|
|
|
# ── Ventas (Factura Venta) ────────────────────────────────────────────────
|
|
ok5, err5, rows_vta = fb.execute_query(_SQL_VENTAS, {"fecha_ini": fecha_ini, "fecha_fin": fecha_fin})
|
|
fb.disconnect()
|
|
if not ok5:
|
|
return JSONResponse({"success": False, "message": f"Error Firebird Ventas: {err5}"})
|
|
|
|
# Fusionar pacientes: particulares + EPS, deduplicando por CODIGO
|
|
codigos_vistos = {str(r.get("CODIGO")) for r in rows_pac}
|
|
rows_pac_todos = list(rows_pac) + [r for r in rows_pac_eps if str(r.get("CODIGO")) not in codigos_vistos]
|
|
|
|
if not rows_pac_todos and not rows_rda and not rows_ps and not rows_vta:
|
|
return JSONResponse({"success": False, "message": f"No hay datos para la fecha {fecha}"})
|
|
|
|
# ── Login TNS ─────────────────────────────────────────────────────────────
|
|
token, token_err = await get_tns_token(
|
|
configs.get("tns_empresa", ""),
|
|
configs.get("tns_usuario", ""),
|
|
configs.get("tns_password", ""),
|
|
)
|
|
if not token:
|
|
return JSONResponse({"success": False, "message": f"Error login TNS: {token_err}"})
|
|
|
|
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {token}"}
|
|
api_sucursal = configs.get("api_sucursal", "")
|
|
timeout = int(configs.get("api_timeout", 30))
|
|
|
|
pac_map = {str(r.get("CODIGO", "")): str(r.get("DOCIDENT") or "").strip() for r in rows_pac_todos}
|
|
|
|
pasos_set = {p.strip() for p in pasos.split(",")}
|
|
resultado = {
|
|
"fecha": fecha,
|
|
"pasos": list(pasos_set),
|
|
"paso1_terceros": {"enviados": 0, "errores": 0, "detalle": []},
|
|
"paso2_rda": {"enviados": 0, "errores": 0, "detalle": []},
|
|
"paso3_preserv": {"enviados": 0, "errores": 0, "detalle": []},
|
|
"paso4_ventas": {"enviados": 0, "errores": 0, "detalle": []},
|
|
}
|
|
|
|
# Pacientes cuyo tercero falló → no enviar RDA para ellos
|
|
terceros_fallidos: set[str] = set()
|
|
|
|
# ── PASO 1: Enviar Terceros (particulares + EPS) ─────────────────────────
|
|
if "terceros" in pasos_set:
|
|
async with httpx.AsyncClient(timeout=timeout) as client:
|
|
for row in rows_pac_todos:
|
|
tercero_json = generar_tercero_api(row)
|
|
doc = tercero_json["nit"]
|
|
nombre = tercero_json["nombre"]
|
|
codigo_pac = str(row.get("CODIGO", ""))
|
|
try:
|
|
resp = await client.post(
|
|
f"{TNS_BASE}/v2/tablas/Tercero/Crear",
|
|
json=tercero_json, headers=headers,
|
|
)
|
|
status, msg = _parse_tns_resp(resp)
|
|
except Exception as e:
|
|
status, msg = "error", str(e)
|
|
|
|
if status == "error":
|
|
resultado["paso1_terceros"]["errores"] += 1
|
|
terceros_fallidos.add(codigo_pac)
|
|
else:
|
|
resultado["paso1_terceros"]["enviados"] += 1
|
|
|
|
resultado["paso1_terceros"]["detalle"].append({
|
|
"codigo": codigo_pac, "doc": doc, "nombre": nombre,
|
|
"ok": status != "error", "status": status, "msg": msg,
|
|
})
|
|
|
|
_guardar_envio(user["user_id"], "terceros", fecha, tercero_json, msg, status,
|
|
cedula=str(row.get("DOCIDENT") or "").strip())
|
|
|
|
# ── Sync paralelo a WhatsApp Lab (silencioso) ─────────────────────────────
|
|
wa_url = configs.get("whatsapp_url", "").rstrip("/")
|
|
wa_key = configs.get("whatsapp_api_key", "")
|
|
if "terceros" in pasos_set and wa_url and wa_key and rows_pac:
|
|
ingest_url = f"{wa_url}/api/lab/ingest_paciente.php"
|
|
try:
|
|
wa_resultado = await sync_todos(rows_pac, ingest_url, wa_key, timeout, modo="upsert")
|
|
guardar_sync_log(wa_resultado, user["user_id"], origen="automation", modo="upsert")
|
|
except Exception:
|
|
pass
|
|
|
|
# ── PASO 2: Enviar RDA Paciente ───────────────────────────────────────────
|
|
excluded = load_excluded_set()
|
|
sin_contrato_set = load_sin_contrato_set()
|
|
grupos_all = agrupar_por_recepcion(rows_rda)
|
|
grupos = {k: v for k, v in grupos_all.items()
|
|
if str(v[0].get("CODCONTRATO") or "").strip() not in excluded}
|
|
resultado["paso2_rda"]["excluidos"] = len(grupos_all) - len(grupos)
|
|
|
|
endpoint = f"{TNS_BASE}/v2/rda/RdaPaciente/Insertar?codigosucursal={api_sucursal or '00'}"
|
|
prof_def = configs.get("profesional_default", "")
|
|
esp_def = configs.get("especialidad_default", "")
|
|
remis_def = configs.get("remisionante_default", "00")
|
|
prefijo_def = configs.get("prefijo_tns_default", "00")
|
|
contrato_map = load_contrato_map()
|
|
|
|
if "rda" in pasos_set:
|
|
async with httpx.AsyncClient(timeout=timeout) as client:
|
|
for id_recepcion, grupo_rows in grupos.items():
|
|
cod_pac = str(grupo_rows[0].get("COD_PACIENTE", ""))
|
|
if cod_pac in terceros_fallidos:
|
|
resultado["paso2_rda"]["detalle"].append({
|
|
"idrecepcion": id_recepcion,
|
|
"factura": str(grupo_rows[0].get("NUM_FACTURA") or id_recepcion),
|
|
"paciente": cod_pac,
|
|
"examenes": len(grupo_rows),
|
|
"ok": False, "msg": "Omitido: tercero no creado en TNS",
|
|
})
|
|
resultado["paso2_rda"]["errores"] += 1
|
|
continue
|
|
num_fac = str(grupo_rows[0].get("NUM_FACTURA") or "").strip()
|
|
num_override = num_fac
|
|
rda_json = generar_rda_paciente(grupo_rows, prof_def, esp_def, remis_def, prefijo_def, num_override, contrato_map=contrato_map, sin_contrato_set=sin_contrato_set)
|
|
factura = num_override or str(id_recepcion)
|
|
try:
|
|
resp = await client.post(endpoint, json=rda_json, headers=headers)
|
|
status, msg = _parse_tns_resp(resp)
|
|
except Exception as e:
|
|
status, msg = "error", str(e)
|
|
|
|
if status == "error":
|
|
resultado["paso2_rda"]["errores"] += 1
|
|
else:
|
|
resultado["paso2_rda"]["enviados"] += 1
|
|
|
|
resultado["paso2_rda"]["detalle"].append({
|
|
"idrecepcion": id_recepcion,
|
|
"factura": factura,
|
|
"paciente": str(grupo_rows[0].get("COD_PACIENTE", "")),
|
|
"examenes": len(grupo_rows),
|
|
"ok": status != "error", "status": status, "msg": msg,
|
|
})
|
|
|
|
_guardar_envio(user["user_id"], "transaccion", factura, rda_json, msg, status,
|
|
fecha_inicio=fecha, fecha_fin=fecha, servicios=len(grupo_rows),
|
|
idrecepcion=id_recepcion, contrato=str(grupo_rows[0].get("CODCONTRATO") or "").strip(),
|
|
cedula=pac_map.get(str(grupo_rows[0].get("COD_PACIENTE", "")), ""))
|
|
|
|
# ── PASO 3: Enviar Pre-servicios (RCXC / SC) ──────────────────────────────
|
|
grupos_ps_all = _agrupar_por_presserv(rows_ps)
|
|
grupos_ps = {k: v for k, v in grupos_ps_all.items()
|
|
if str(v[0].get("CODCONTRATO") or "").strip() not in excluded}
|
|
resultado["paso3_preserv"]["excluidos"] = len(grupos_ps_all) - len(grupos_ps)
|
|
|
|
if "preserv" in pasos_set:
|
|
async with httpx.AsyncClient(timeout=timeout) as client:
|
|
for id_ps, grupo_rows in grupos_ps.items():
|
|
cod_pac = str(grupo_rows[0].get("COD_PACIENTE", ""))
|
|
if cod_pac in terceros_fallidos:
|
|
resultado["paso3_preserv"]["detalle"].append({
|
|
"idrecepcion": id_ps,
|
|
"factura": str(grupo_rows[0].get("PS_NUMERO") or id_ps),
|
|
"paciente": cod_pac,
|
|
"examenes": len(grupo_rows),
|
|
"ok": False, "msg": "Omitido: tercero no creado en TNS",
|
|
})
|
|
resultado["paso3_preserv"]["errores"] += 1
|
|
continue
|
|
ps_prefijo = str(grupo_rows[0].get("PS_PREFIJO") or "SC").strip()
|
|
ps_numero = str(grupo_rows[0].get("PS_NUMERO") or "").strip()
|
|
rda_json = generar_rda_paciente(
|
|
grupo_rows, prof_def, esp_def, remis_def, prefijo_def,
|
|
numero_override=ps_numero,
|
|
contrato_map=contrato_map,
|
|
prefijo_override="00" if ps_prefijo == "RCXC" else ps_prefijo,
|
|
sin_contrato_set=sin_contrato_set,
|
|
)
|
|
factura_ps = f"{ps_prefijo}-{ps_numero.zfill(5)}"
|
|
try:
|
|
resp = await client.post(endpoint, json=rda_json, headers=headers)
|
|
status, msg = _parse_tns_resp(resp)
|
|
except Exception as e:
|
|
status, msg = "error", str(e)
|
|
|
|
if status == "error":
|
|
resultado["paso3_preserv"]["errores"] += 1
|
|
else:
|
|
resultado["paso3_preserv"]["enviados"] += 1
|
|
|
|
resultado["paso3_preserv"]["detalle"].append({
|
|
"idrecepcion": id_ps,
|
|
"factura": factura_ps,
|
|
"paciente": str(grupo_rows[0].get("COD_PACIENTE", "")),
|
|
"examenes": len(grupo_rows),
|
|
"ok": status != "error", "status": status, "msg": msg,
|
|
})
|
|
|
|
_guardar_envio(user["user_id"], "transaccion", factura_ps, rda_json, msg, status,
|
|
fecha_inicio=fecha, fecha_fin=fecha, servicios=len(grupo_rows),
|
|
idrecepcion=id_ps, contrato=str(grupo_rows[0].get("CODCONTRATO") or "").strip(),
|
|
cedula=pac_map.get(str(grupo_rows[0].get("COD_PACIENTE", "")), ""))
|
|
|
|
# ── PASO 4: Enviar Facturas Venta ─────────────────────────────────────────
|
|
excluded_ventas = load_excluded_ventas_set()
|
|
grupos_vta_all = agrupar_por_factura(rows_vta)
|
|
grupos_vta = {}
|
|
for k, v in grupos_vta_all.items():
|
|
if not isinstance(v, list) or not v:
|
|
continue
|
|
if int(v[0].get("NUM_FACTURA") or 0) == 0:
|
|
continue
|
|
if str(v[0].get("CODCONTRATO") or "").strip() in excluded_ventas:
|
|
continue
|
|
grupos_vta[k] = v
|
|
resultado["paso4_ventas"]["excluidos"] = len(grupos_vta_all) - len(grupos_vta)
|
|
|
|
endpoint_venta = f"{TNS_BASE}/v2/facturacion/Ventas/Crear?codigosucursal={api_sucursal or '00'}"
|
|
if "ventas" in pasos_set:
|
|
async with httpx.AsyncClient(timeout=timeout) as client:
|
|
for num_fac_key, grupo_rows in grupos_vta.items():
|
|
num_fac = str(grupo_rows[0].get("NUM_FACTURA") or "").strip()
|
|
prefijo = str(grupo_rows[0].get("PREFIJO") or "").strip()
|
|
venta_json = generar_factura_venta(grupo_rows, default_vendedor="00",
|
|
default_prefijo=prefijo_def, numero_override=num_fac)
|
|
factura_display = f"{prefijo}-{num_fac}"
|
|
contrato_vta = str(grupo_rows[0].get("CODCONTRATO") or "").strip()
|
|
id_rec_display = str(grupo_rows[0].get("IDRECEPCION") or "")
|
|
try:
|
|
resp = await client.post(endpoint_venta, json=venta_json, headers=headers)
|
|
status, msg = _parse_tns_resp(resp)
|
|
except Exception as e:
|
|
status, msg = "error", str(e)
|
|
|
|
if status == "error":
|
|
resultado["paso4_ventas"]["errores"] += 1
|
|
else:
|
|
resultado["paso4_ventas"]["enviados"] += 1
|
|
|
|
resultado["paso4_ventas"]["detalle"].append({
|
|
"idrecepcion": id_rec_display,
|
|
"factura": factura_display,
|
|
"paciente": str(grupo_rows[0].get("COD_PACIENTE", "")),
|
|
"examenes": len(grupo_rows),
|
|
"ok": status != "error", "status": status, "msg": msg,
|
|
})
|
|
|
|
_guardar_envio(user["user_id"], "ventas", factura_display, venta_json, msg, status,
|
|
fecha_inicio=fecha, fecha_fin=fecha, servicios=len(grupo_rows),
|
|
idrecepcion=id_rec_display, contrato=contrato_vta,
|
|
cedula=pac_map.get(str(grupo_rows[0].get("COD_PACIENTE", "")), ""))
|
|
|
|
r1 = resultado["paso1_terceros"]
|
|
r2 = resultado["paso2_rda"]
|
|
r3 = resultado["paso3_preserv"]
|
|
r4 = resultado["paso4_ventas"]
|
|
log_activity(user["user_id"], user["username"], "automation_run",
|
|
f"Fecha {fecha} | Terceros: {r1['enviados']} OK/{r1['errores']} err | "
|
|
f"RDA: {r2['enviados']} OK/{r2['errores']} err | "
|
|
f"PreServ: {r3['enviados']} OK/{r3['errores']} err | "
|
|
f"Ventas: {r4['enviados']} OK/{r4['errores']} err",
|
|
get_ip(request))
|
|
return JSONResponse({"success": True, "resultado": resultado})
|
|
|
|
|
|
_YA_WARNING = (
|
|
"ya esta registrado", "ya existe", "already exist",
|
|
"ya existe una autorización", "ya existe un rda",
|
|
)
|
|
|
|
def _parse_tns_resp(resp) -> tuple[str, str]:
|
|
"""Parsea respuesta TNS. Retorna (status, msg) donde status es 'success'|'warning'|'error'."""
|
|
raw_body = resp.text
|
|
try:
|
|
body = resp.json()
|
|
raw_status = body.get("status")
|
|
if isinstance(raw_status, bool):
|
|
ok = raw_status
|
|
elif isinstance(raw_status, int):
|
|
ok = raw_status < 400
|
|
else:
|
|
ok = bool(raw_status) or bool((body.get("data") or {}).get("success"))
|
|
msg = raw_body # siempre guardamos el JSON crudo completo
|
|
except Exception:
|
|
ok = resp.is_success
|
|
msg = raw_body[:500]
|
|
|
|
if not ok and any(s in msg.lower() for s in _YA_WARNING):
|
|
return "warning", msg
|
|
return ("success" if ok else "error"), msg
|
|
|
|
|
|
def _guardar_envio(user_id, tipo, factura, json_data, respuesta, status,
|
|
fecha_inicio=None, fecha_fin=None, servicios=0,
|
|
idrecepcion=None, contrato=None, cedula=None):
|
|
try:
|
|
conn = get_connection()
|
|
conn.execute("""
|
|
INSERT INTO envios (user_id, tipo, factura, idrecepcion, contrato, cedula,
|
|
fecha_inicio, fecha_fin,
|
|
pacientes_count, servicios_count, status, json_enviado, respuesta_api, mensaje_tns, created_at)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
""", (
|
|
user_id, tipo, factura, idrecepcion, contrato, cedula,
|
|
fecha_inicio, fecha_fin,
|
|
1, servicios,
|
|
status,
|
|
json_lib.dumps(json_data, indent=2, ensure_ascii=False)[:10000],
|
|
respuesta[:5000] if respuesta else "",
|
|
respuesta[:500] if respuesta else "",
|
|
datetime.now().isoformat(),
|
|
))
|
|
conn.commit()
|
|
conn.close()
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
@router.post("/reenviar-tercero")
|
|
async def reenviar_tercero(
|
|
request: Request,
|
|
user: dict = Depends(get_current_user),
|
|
codigo: str = Form(...),
|
|
):
|
|
conn = get_connection()
|
|
configs = {row["key"]: row["value"] for row in conn.execute("SELECT * FROM config").fetchall()}
|
|
conn.close()
|
|
|
|
fb, fb_ok, fb_msg = get_firebird_from_config(configs)
|
|
if not fb_ok:
|
|
return JSONResponse({"success": False, "message": f"Error Firebird: {fb_msg}"})
|
|
|
|
ok, err, rows = fb.execute_query(_SQL_PAC_BY_CODIGO, {"codigo": codigo.strip()})
|
|
fb.disconnect()
|
|
|
|
if not ok or not rows:
|
|
return JSONResponse({"success": False, "message": err or "Paciente no encontrado"})
|
|
|
|
tercero_json = generar_tercero_api(dict(rows[0]))
|
|
token, token_err = await get_tns_token(
|
|
configs.get("tns_empresa", ""), configs.get("tns_usuario", ""), configs.get("tns_password", "")
|
|
)
|
|
if not token:
|
|
return JSONResponse({"success": False, "message": f"Token TNS: {token_err}"})
|
|
|
|
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {token}"}
|
|
try:
|
|
async with httpx.AsyncClient(timeout=int(configs.get("api_timeout", 30))) as client:
|
|
resp = await client.post(f"{TNS_BASE}/v2/tablas/Tercero/Crear", json=tercero_json, headers=headers)
|
|
ok_r = resp.is_success
|
|
msg = resp.json().get("message", "") if ok_r else resp.text[:200]
|
|
except Exception as e:
|
|
ok_r = False
|
|
msg = str(e)
|
|
|
|
_guardar_envio(user["user_id"], "terceros", codigo, tercero_json, msg, ok_r)
|
|
return JSONResponse({"success": ok_r, "message": msg})
|
|
|
|
|
|
@router.post("/reenviar-rda")
|
|
async def reenviar_rda(
|
|
request: Request,
|
|
user: dict = Depends(get_current_user),
|
|
idrecepcion: int = Form(...),
|
|
tipo: str = Form("rda"),
|
|
):
|
|
conn = get_connection()
|
|
configs = {row["key"]: row["value"] for row in conn.execute("SELECT * FROM config").fetchall()}
|
|
conn.close()
|
|
|
|
fb, fb_ok, fb_msg = get_firebird_from_config(configs)
|
|
if not fb_ok:
|
|
return JSONResponse({"success": False, "message": f"Error Firebird: {fb_msg}"})
|
|
|
|
if tipo == "preserv":
|
|
ok, err, rows = fb.execute_query(_SQL_PRESERV_BY_ID, {"id_ps": idrecepcion})
|
|
else:
|
|
ok, err, rows = fb.execute_query(_SQL_RDA_BY_ID, {"idrecepcion": idrecepcion})
|
|
fb.disconnect()
|
|
|
|
if not ok or not rows:
|
|
return JSONResponse({"success": False, "message": err or "Sin datos"})
|
|
|
|
excluded = load_excluded_set()
|
|
contrato = str(rows[0].get("CODCONTRATO") or "").strip()
|
|
if contrato in excluded:
|
|
return JSONResponse({"success": False, "message": f"Contrato {contrato} excluido"})
|
|
|
|
prof_def = configs.get("profesional_default", "")
|
|
esp_def = configs.get("especialidad_default", "")
|
|
remis_def = configs.get("remisionante_default", "00")
|
|
prefijo_def = configs.get("prefijo_tns_default", "00")
|
|
contrato_map = load_contrato_map()
|
|
sin_contrato_set = load_sin_contrato_set()
|
|
api_sucursal = configs.get("api_sucursal", "") or "00"
|
|
|
|
if tipo == "preserv":
|
|
from collections import defaultdict
|
|
grupos_ps: dict = defaultdict(list)
|
|
for row in rows:
|
|
grupos_ps[row.get("ID_PS")].append(dict(row))
|
|
grupo_rows = list(grupos_ps.values())[0]
|
|
ps_prefijo = str(grupo_rows[0].get("PS_PREFIJO") or "SC").strip()
|
|
ps_numero = str(grupo_rows[0].get("PS_NUMERO") or "").strip()
|
|
rda_json = generar_rda_paciente(
|
|
grupo_rows, prof_def, esp_def, remis_def, prefijo_def,
|
|
numero_override=ps_numero, contrato_map=contrato_map,
|
|
prefijo_override="00" if ps_prefijo == "RCXC" else ps_prefijo,
|
|
sin_contrato_set=sin_contrato_set,
|
|
)
|
|
factura = f"{ps_prefijo}-{ps_numero.zfill(5)}"
|
|
else:
|
|
grupos = agrupar_por_recepcion(rows)
|
|
grupo_rows = list(grupos.values())[0]
|
|
num_fac = str(grupo_rows[0].get("NUM_FACTURA") or "").strip()
|
|
rda_json = generar_rda_paciente(
|
|
grupo_rows, prof_def, esp_def, remis_def, prefijo_def,
|
|
numero_override=num_fac, contrato_map=contrato_map,
|
|
sin_contrato_set=sin_contrato_set,
|
|
)
|
|
factura = num_fac or str(idrecepcion)
|
|
|
|
token, token_err = await get_tns_token(
|
|
configs.get("tns_empresa", ""), configs.get("tns_usuario", ""), configs.get("tns_password", "")
|
|
)
|
|
if not token:
|
|
return JSONResponse({"success": False, "message": f"Token TNS: {token_err}"})
|
|
|
|
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {token}"}
|
|
endpoint = f"{TNS_BASE}/v2/rda/RdaPaciente/Insertar?codigosucursal={api_sucursal}"
|
|
try:
|
|
async with httpx.AsyncClient(timeout=int(configs.get("api_timeout", 30))) as client:
|
|
resp = await client.post(endpoint, json=rda_json, headers=headers)
|
|
ok_r = resp.is_success
|
|
msg = resp.json().get("message", "") if ok_r else resp.text[:200]
|
|
except Exception as e:
|
|
ok_r = False
|
|
msg = str(e)
|
|
|
|
_guardar_envio(user["user_id"], "transaccion", factura, rda_json, msg, ok_r,
|
|
idrecepcion=idrecepcion, contrato=contrato)
|
|
return JSONResponse({"success": ok_r, "message": msg})
|
|
|
|
|
|
@router.post("/reenviar-venta")
|
|
async def reenviar_venta(
|
|
request: Request,
|
|
user: dict = Depends(get_current_user),
|
|
idrecepcion: int = Form(...),
|
|
):
|
|
conn = get_connection()
|
|
configs = {row["key"]: row["value"] for row in conn.execute("SELECT * FROM config").fetchall()}
|
|
conn.close()
|
|
|
|
fb, fb_ok, fb_msg = get_firebird_from_config(configs)
|
|
if not fb_ok:
|
|
return JSONResponse({"success": False, "message": f"Error Firebird: {fb_msg}"})
|
|
|
|
# Primero obtener PREFIJO y NUM_FACTURA de esa recepción
|
|
ok0, err0, ref = fb.execute_query(_SQL_VENTAS_BY_IDRECEP, {"idrecepcion": idrecepcion})
|
|
if not ok0 or not ref:
|
|
fb.disconnect()
|
|
return JSONResponse({"success": False, "message": err0 or "Recepción no encontrada"})
|
|
prefijo = str(ref[0].get("PREFIJO") or "").strip()
|
|
num_factura_int = int(ref[0].get("NUM_FACTURA") or 0)
|
|
if num_factura_int == 0:
|
|
fb.disconnect()
|
|
return JSONResponse({"success": False, "message": "Factura sin número asignado (00000)"})
|
|
|
|
# Traer TODAS las recepciones de esa factura para incluir todos los servicios
|
|
ok, err, rows = fb.execute_query(_SQL_VENTAS_BY_FACTURA,
|
|
{"prefijo": prefijo, "num_factura": num_factura_int})
|
|
fb.disconnect()
|
|
|
|
if not ok or not rows:
|
|
return JSONResponse({"success": False, "message": err or "Sin datos"})
|
|
|
|
excluded_ventas = load_excluded_ventas_set()
|
|
contrato_vta = str(rows[0].get("CODCONTRATO") or "").strip()
|
|
if contrato_vta in excluded_ventas:
|
|
return JSONResponse({"success": False, "message": f"Contrato {contrato_vta} excluido"})
|
|
|
|
grupo_rows = [dict(r) for r in rows]
|
|
prefijo_def = configs.get("prefijo_tns_default", "00")
|
|
num_fac = str(num_factura_int)
|
|
venta_json = generar_factura_venta(grupo_rows, default_vendedor="00",
|
|
default_prefijo=prefijo_def, numero_override=num_fac)
|
|
factura_display = f"{prefijo}-{num_fac}"
|
|
|
|
token, token_err = await get_tns_token(
|
|
configs.get("tns_empresa", ""), configs.get("tns_usuario", ""), configs.get("tns_password", "")
|
|
)
|
|
if not token:
|
|
return JSONResponse({"success": False, "message": f"Token TNS: {token_err}"})
|
|
|
|
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {token}"}
|
|
endpoint = f"{TNS_BASE}/v2/facturacion/Ventas/Crear"
|
|
try:
|
|
async with httpx.AsyncClient(timeout=int(configs.get("api_timeout", 30))) as client:
|
|
resp = await client.post(endpoint, json=venta_json, headers=headers)
|
|
ok_r = resp.is_success
|
|
msg = resp.json().get("message", "") if ok_r else resp.text[:200]
|
|
except Exception as e:
|
|
ok_r = False
|
|
msg = str(e)
|
|
|
|
_guardar_envio(user["user_id"], "ventas", factura_display, venta_json, msg, ok_r,
|
|
idrecepcion=idrecepcion, contrato=contrato_vta)
|
|
return JSONResponse({"success": ok_r, "message": msg})
|