Commit Graph
63 Commits
Author SHA1 Message Date
Lizandro GuarnizoandClaude Sonnet 4.6 e7c6bc794a feat(pacientes): sync de pacientes Firebird → WhatsApp Lab
- Nuevo servicio whatsapp_sync.py: mapeo de campos RIPS→lab_pacientes
  y cliente HTTP para /api/lab/ingest_paciente.php
- Nueva ruta /pacientes con sync masiva por rango de fechas o todos
- Hook en /terceros/send y /automation/run: sync silencioso a WhatsApp
  después de cada envío a TNS
- Config: campos whatsapp_url y whatsapp_api_key + botón probar conexión

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-09 10:49:00 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 b4288ac899 fix: remove undefined facturas_usadas_sesion causing double RDA submission on test-rda
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-07 12:00:33 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 07038ac431 fix: clean time spaces in logs view without modifying stored data
Applies _clean_times when serving json_enviado in /logs/detalle
so old records with "12: 47: 37" display correctly as "12:47:37".

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 17:36:45 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 72973973d4 feat: calculate real discount % from TARIFA vs RELACION.PRECIO
Joins TARIFA using EMPRESA.TARIFA to get the base price per exam,
then calculates descuento = round((sum(TARIFA) - sum(PRECIO)) / sum(TARIFA) * 100)
and sends it as integer percentage in the RDA header encabezado.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 17:26:49 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 15f6ca65db feat: add descuento from RECEPCION.VALORDESC to RDA header
Pulls r.VALORDESC in all SQL queries (automation, test_rda, queries
defaults) and maps it to the top-level descuento field in the
RdaPaciente JSON encabezado.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 17:13:46 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 f35a39bc9b fix: add EXAMEN join to QUERY_DEFAULTS so CUPs codes survive restarts
ensure_defaults() runs on every startup and was overwriting the db
queries with the old versions from QUERY_DEFAULTS — wiping any manual
fixes. Now the source-of-truth in code has the EXAMEN join and CUPS
column, so transaccion page always shows CUPs after any restart.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 14:38:30 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 b12e8fcf88 feat: use EXAMEN.NUM_ISS as codigoMaterial (CUPs) via LEFT JOIN EXAMEN
CH4=902210, PO=907106, GRAM=901107, etc. Falls back to COD_EXAMEN if empty.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 12:53:16 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 b22b47a1e1 debug: search 903967 across all candidate tables
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 12:34:50 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 fb81ddf263 debug: search PROTOCOLO table and all CUP fields system-wide
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 12:32:27 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 942d68b75d debug: catch all exceptions and return traceback as JSON
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 12:31:24 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 bc5fc36a5d debug: explore RELACION_HIMS table for CUPS_REF field
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 12:30:12 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 68aa5e0355 feat: join ITEM on COD_PROTOCOLO to get CUPS_DETALLE as codigoMaterial
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 12:29:33 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 d95e2b67ff debug: probe possible ITEM join fields, show first row without join
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 12:27:44 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 41ee88c1b4 fix: remove rel.DESCUENTO (column does not exist in RELACION table)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 12:26:09 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 b4748e34d8 debug: minimal endpoint - only ITEM columns and sample row
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 12:25:20 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 d1c1d3205f revert: remove broken ITEM join until correct field name is known
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 12:24:01 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 e6d0b74992 debug: show ITEM columns and first row to find join key
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 12:22:35 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 ff08c1b3a8 feat: use ITEM.CUPS_DETALLE as codigoMaterial in RDA
LEFT JOIN ITEM on COD_EXAMEN to get CUPS_DETALLE. Falls back to
COD_EXAMEN if CUPS is empty. Applied to automation, test_rda, and
saved queries in SQLite.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 12:20:22 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 9aa04307c6 debug: query ITEM table columns and CUPS_DETALLE samples
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 12:15:33 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 44af9680f2 fix: add LIKE %CUP% search across all tables in debug endpoint
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 12:14:21 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 0896e14e62 fix: simplify debug cups endpoint to avoid Firebird CONTAINING error
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 12:13:30 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 8b2f8eb3be fix: add rel.DESCUENTO to all SQL queries; update debug endpoint with discount check
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 12:11:00 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 8732db9c1f fix: use Firebird PREFIJO as codigoPrefijo; add debug endpoint to find CUPs field
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 12:07:43 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 ed9fead353 fix: remove valor field from detallePedido; filter by PREFIJO in transaccion
- json_generator: remove valor entirely from detalle items (not even 0)
- transaccion: after fetching rows, filter by prefix if user typed full
  factura like "LHXC03726" and query returns PREFIJO column

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 12:00:42 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 1548aadf3c fix: set valor=0 in detallePedido; parse full factura (prefix+number) in search
- json_generator: send valor:0 per item instead of PRECIO from Firebird
- test_rda + transaccion: accept "LHXC03726" format — extracts numeric part
  for NUM_FACTURA and letter prefix for PREFIJO filter when prefix present

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 11:54:08 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 4b77f0a0ac fix: quitar rel.DESCUENTO — columna no existe en tabla RELACION de Firebird
json_generator ya usa row.get('DESCUENTO') or 0 como fallback.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-30 21:15:10 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 c7428a196b fix: quitar codFormaPago header, fechaAutorizacion=hoy, descuento de Firebird
- Elimina codFormaPago del header RDA (no va segun JSON de referencia)
- fechaAutorizacion usa fecha de hoy, no la de recepcion
- descuento toma rel.DESCUENTO de Firebird en vez de hardcodeado 0
- Agrega rel.DESCUENTO al SELECT en test_rda y automation

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-30 16:12:48 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 be1910b5d8 fix: send numero sin prefijo LHXC en RDA TNS
TNS espera solo el numero numerico (ej: "4001"), no el formato
combinado con prefijo (ej: "LHXC04001"). El codigoPrefijo "00"
ya referencia la serie correcta en la configuracion de TNS.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 21:09:58 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 90de09b22c Fix RDA: quitar campos demograficos del RDA (solo van en Tercero); identidadGenero con ceros "01"/"02"
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 20:50:39 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 58bdb4ae55 Agrega campos demograficos paciente en RDA y Tercero (etnia, zona, identidadGenero, divPolitica, antecedentes, fechaNac, direccion)
- SQL RDA join PACIENTE para obtener datos demograficos
- generar_rda_paciente: incluye etnia, identidadGenero, zona, divisionPoliticaAdministrativa, antecedentes, fechaNacimiento, direccion
- generar_tercero_api: agrega identidadGenero, divisionPoliticaAdministrativa, antecedentes; default ciudad Cucuta 54001

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 20:49:12 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 69372a5673 Agrega filtro convenio en automation/transaccion/test-rda y fix particular (contrato 12)
- automation: filtro contrato en SQL pacientes+RDA, numero LHXC en run()
- transaccion: filtro contrato en preview/send-one/send
- test-rda: filtro tipo_usuario (11/07/12), default contrato "12", acepta "12"/"012"
- json_generator: detecta particular por CODCONTRATO "12"/"012" además de NIT_EMPRESA PART; fuerza tipousuario="12", codFormaPago="CLIP", plazoDias="0"

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 20:23:00 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 d7afbe9b7d Numero TNS = formato RIPS limpio: LHXC03990 sin sufijo idrecepcion
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 20:07:05 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 88f684a006 Usa formato RIPS completo para numero TNS: LHXC03990-314522
El numero del kardex en TNS ahora incluye el PREFIJO de Firebird y el
NUM_FACTURA zero-padded a 5 dígitos, igual al numFactura del RIPS
(ej: LHXC03404). Se agrega -{idrecepcion} al final para garantizar
unicidad ya que múltiples IDRECEPCION comparten el mismo NUM_FACTURA.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 20:03:03 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 6905a4132e Simplifica numero único en TNS: siempre usar {factura}-{idrecepcion}
Elimina la lógica condicional que dependía de rda_test_log para detectar
colisiones. Ahora cada IDRECEPCION siempre genera un numero único y
reproducible en TNS sin consultar historial previo.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 19:59:31 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 d9d3deef6c Fix colisión de numero de factura en TNS cuando varios IDRECEPCION comparten NUM_FACTURA
- json_generator: agrega parámetro numero_override para usar un número alternativo
- test_rda: detecta si el NUM_FACTURA ya fue enviado exitosamente (sesión o rda_test_log) y usa "{factura}-{idrecepcion}" como numero único en TNS
- transaccion: misma lógica en envío masivo, evita que el segundo IDRECEPCION de la misma factura falle con 409

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 19:50:30 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 7699303a53 Mejora Transacción y Historial: estado por fila, envío individual y filtros avanzados
- Transacción: tabla con estado Enviado/Pendiente/Error por IDRECEPCION, botón enviar fila a fila o masivo, modal con JSON + respuesta TNS por registro
- Historial: filtros por fecha, tipo, IDRECEPCION/contrato; paginación 50 por página; modal con 3 tabs (JSON enviado / Respuesta TNS / Mensaje)
- DB: migración automática para agregar columnas idrecepcion, contrato, mensaje_tns a tabla envios
- Logs route: nuevo endpoint /logs/detalle/{id} para cargar detalle completo vía JS

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 19:40:11 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 ef71a1db56 test-rda: add preview, ver más pagination, sent tracking, default contrato=011
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 19:32:53 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 e477aa2bea Fix error display: show TNS response separately, default filter contrato=011
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 19:25:33 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 da99a446f1 Filter candidatos: only records where ALL exams are in configured TNS list (NOT EXISTS)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 19:21:42 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 b5e56f2238 Fix error display in test-rda, remove PO from default article filter
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 19:19:06 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 c1cbe54105 Fix candidatos: uppercase column keys, filter by TNS-configured articles, show last 10
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 19:15:26 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 c2977011ee Fix get_firebird_from_config call in test_rda (returns tuple fb, ok, msg)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 19:06:32 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 c64a68ec6f Add test-rda page, fix prefijo/remisionante/especialidad for TNS RDA sends
- New /test-rda route: list Firebird candidates with valid contract/factura,
  send individual RDA with auto tercero creation and full result display
- json_generator: use prefijo_tns_default config instead of Firebird PREFIJO,
  add profesionalRemisionante from DOCIDMEDICO or remisionante_default config
- All queries: add DOCIDMEDICO column from MEDICO JOIN
- automation/transaccion: add remisionante_default and prefijo_tns_default params
- config: add remisionante_default (00) and prefijo_tns_default (00) keys
- automation SQL: filter NUM_FACTURA > 0 to skip unbilled records
- config.html: add UI fields for new config keys

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 18:57:54 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 3017c7956e Fix numeroContrato: use EMPRESA.CODCONTRATO from Firebird, sucursal default 00
- Join EMPRESA table in all RDA queries to get CODCONTRATO (TNS contract code)
- Use EMPRESA.CODCONTRATO as numeroContrato instead of raw NIT_EMPRESA
- Especialidad always uses default_especialidad (ignore Firebird COD_ESPECIALIDAD)
- sucursal defaults to '00' (not empty) in config and endpoints
- Fix config template label: especialidad default is TNS code not Firebird code

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 18:01:32 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 c70f0f1062 Fix profesional/especialidad: use MEDICO.CODIGO first, add config defaults
- SQL query now prioritizes MEDICO.CODIGO over RECEPCION.USUARIO as profesional
  (USUARIO is the billing clerk; MEDICO is the medical professional)
- Add profesional_default and especialidad_default config keys for when
  Firebird data is empty or contains invalid values (e.g. especialidad = ".")
- generar_rda_paciente accepts default_profesional and default_especialidad params
- ensure_defaults in queries.py now updates existing query records on startup

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 16:12:16 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 fbdce1c790 Add error message to send resultados so TNS errors are visible in response
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 15:59:21 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 63fcbe3611 Fix factura input parsing: extract numeric part from "LHXC 3918" format
NUM_FACTURA is numeric in Firebird — strip prefix and spaces before querying.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-25 20:53:16 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 0ec4ae3e66 Fix JSON generation: numero factura, forma pago, tipousuario, hora format
- numero: usar NUM_FACTURA en lugar de cadena vacía
- codFormaPago: CLIP (particular) / INST (EPS) según TNS real
- tipousuario: fallback desde TIPOUSU cuando TIPOUSUSISPRO es NULL
- fechaHoraEgreso: última FECHA_REPORTADO en lugar de FECHA_RECEPCION
- _fmt_datetime: eliminar espacios en tiempo ("06: 08: 29" → "06:08:29")
- especialidad: limpiar valores basura (., -, 0, 00)
- telefono: fallback "0000000" cuando vacío (campo requerido TNS)
- profesional: COALESCE(USUARIO, MEDICO.CODIGO) en queries SQL

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-25 20:48:22 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 dbaf49b30e Automation preview: show RDA per patient on click
Preview now returns all patients with their grouped receptions.
Clicking a patient row expands/collapses their RDA list showing
factura, fecha, exam count, diagnosis, and total value.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-25 19:49:21 -05:00
Lizandro GuarnizoandClaude Sonnet 4.6 c920b45640 Audit fixes: date format, prefijo query, and UI labels
- transaccion: append " 00:00:00" / " 23:59:59" to date params so Firebird BETWEEN works correctly with TIMESTAMP columns
- queries.py QUERY_DEFAULTS: remove :prefijo from RDA por factura (matches DB state)
- terceros.html: mark doc_num as required with visual indicator

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-25 19:31:53 -05:00