TNS API (C#) expects System.Char for tipoDocumento; "PE" and "PT" caused
400 validation errors. Mapped both to "E" (Cédula Extranjería).
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Agrega columna sin_contrato en tabla contratos (migration automatica)
- Contrato 040 marcado excluir=0, sin_contrato=1 en seed
- load_sin_contrato_set() retorna contratos que deben ir con null
- generar_rda_paciente acepta sin_contrato_set y fuerza numeroContrato=null
- Automation paso 2 y 3 pasan sin_contrato_set al generador
- Pagina contratos: columna y toggle "Sin contrato", checkbox en modal editar
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Agrega paso 3 en automatización: envía RDA desde PRESSERV_DIAN (prefijos RCXC/SC) para pacientes EPS con PS_NUM IS NOT NULL
- Filtra paso 2 con PS_NUM IS NULL para separar particulares/empresas de EPS
- Elimina parámetro copago y función _calcular_descuento_pct (código muerto)
- Limpia referencia a d.copago en automation.html (UI paso 3)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
El check `"012".lstrip("0") == "12"` causaba false positive marcando
contratos EPS como particulares. Ahora la heurística solo aplica si el
contrato no está en la tabla contratos; si está, el tipo_usuario del mapa
tiene precedencia y también controla es_particular.
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>
- 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>
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>
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>
HORAINICIORECEPCION es campo TIME en Firebird — fdb lo devuelve como
datetime.time sin fecha. _fmt_datetime recibía '06:08:29' y lo pasaba
tal cual al JSON. TNS rechazaba por formato inválido.
- _fmt_datetime ahora maneja entrada solo-fecha → agrega 00:00:00
- generar_rda_paciente combina HORAINICIORECEPCION + FECHA_RECEPCION
antes de llamar _fmt_datetime cuando detecta hora sin fecha
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Adds _clean_times() that recursively walks every string in the result
dict and applies re.sub(r'\s*:\s*', ':'), guaranteeing no "12: 47: 37"
spaces survive to the TNS API regardless of Firebird driver behaviour.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
re.sub('\s*:\s*', ':') captura cualquier tipo de espacio alrededor
de los dos puntos, incluyendo tipos no-ASCII que .replace() no atrapa.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
La documentacion marca CodFormaPago como Requerido=Si. Su ausencia
causaba 'Datos incorrectos' en TNS.
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>
Usa strftime en vez de isoformat y aplica re.sub para eliminar
espacios alrededor de los dos puntos en strings de tiempo de fdb.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Elimina codFormaPago del header principal (queda en detalleFormaPago)
- Añade fechaAutorizacion con la fecha de recepcion (dd/MM/yyyy)
- Añade vigenciaAutorizacion: 0 para particular, 30 para EPS/convenio
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>
- json_generator: limpia DOCIDMEDICO a solo dígitos (eg "9410/86" → "941086") para que TNS acepte el código
- test_rda.html: resultado con syntax highlight en JSON enviado y respuesta TNS, mejor legibilidad del error TNS, botones Resp.TNS y JSON env. con íconos
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>
Previous order: [:19] then replace(": ", ":") would truncate "06: 59: 28"
to "06: 59: " before cleaning, losing the seconds entirely.
Correct order: clean spaces first, then [:19].
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
TNS schema marks both as optional — null may bypass company-level validation
that rejects empty string "". Falls back to config default if set.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- 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>