- Columna excluir en tabla contratos (migración automática)
- 25 contratos nuevos sembrados con excluir=1 (laboratorios externos, clínicas, médicos particulares)
- load_excluded_set() en contratos.py para consultar el set en runtime
- preview: marca items excluidos y los reporta en el conteo
- send/send-one/send-direct: bloquea envío si contrato está excluido
- automation preview+run: filtra excluidos antes del loop, reporta count
- UI /contratos: columna Envío TNS con toggle Activo/Excluido, fila en rojo si excluida
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Nuevo endpoint POST /transaccion/send-direct y panel "Enviar RDA directo"
en la UI: ingresa Tipo (prefijo) y Número, busca en Firebird y envía a TNS
sin necesidad de rango de fechas ni pasar por el flujo de preview.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Agrega tabla `contratos` en SQLite sembrada con los 17 contratos del
laboratorio. `generar_rda_paciente` consulta el mapa contrato→tipoUsuario
como primera prioridad antes de derivar de TIPOUSU/TIPOUSUSISPRO.
Incluye CRUD en /contratos con UI en sidebar.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Queries Firebird RECEPCION+RELACION+EXAMEN for today's date,
filters by HORAINICIORECEPCION >= now-5min in Python, returns
list of {recepcion_id, hora, cod_examen, nombre, cups, precio}.
Auth via X-Lab-Key header (whatsapp_api_key config value).
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Nueva tabla sync_wa_log (total, created, skipped, updated, errores, origen, modo)
- Log guardado en /pacientes/sync-all, /terceros/send y /automation/run
- Ruta GET /pacientes/historial devuelve últimos 100 registros
- UI: tabla de historial con origen, modo, conteos y detalle de errores
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
sync_todos() ahora acepta modo='insertar'|'upsert'. La ruta /pacientes/sync-all
usa insertar: skippea cédulas que ya están en lab_pacientes. Los hooks
automáticos (terceros/automation) siguen en upsert.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- 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>
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>
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>
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>
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>
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>
- 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>
- 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>
- 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>
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>
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>
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>
- 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>
- 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>
- 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>
- 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>