From 28fc0a2379cea78661df43abb11f6de27e31317f Mon Sep 17 00:00:00 2001 From: chetansaroya Date: Mon, 16 Nov 2026 12:57:04 +0530 Subject: [PATCH 1/2] stop:816 Nikshay Workflow: Bug. --- .../NikshayDiagnosisGate.java | 19 +++++-- .../NikshayIdGenerateRepository.java | 50 ++++++++++++++++--- .../NikshayIdGenerateService.java | 40 ++++++++++++--- 3 files changed, 90 insertions(+), 19 deletions(-) diff --git a/src/main/java/com/iemr/admin/data/nikshayidgenerate/NikshayDiagnosisGate.java b/src/main/java/com/iemr/admin/data/nikshayidgenerate/NikshayDiagnosisGate.java index 9a8896c..eb2d016 100644 --- a/src/main/java/com/iemr/admin/data/nikshayidgenerate/NikshayDiagnosisGate.java +++ b/src/main/java/com/iemr/admin/data/nikshayidgenerate/NikshayDiagnosisGate.java @@ -11,8 +11,10 @@ public class NikshayDiagnosisGate { private boolean sputumDone; + private boolean sputumPositive; private boolean sputumClosed; private boolean xrayDone; + private boolean xrayClear; private boolean xrayClosed; private boolean xraySkip; @@ -21,9 +23,20 @@ public boolean positiveReady() { return sputumDone && xraySettled(); } - /** Index or contact has been tested: sputum finished and X-ray finished or skipped. */ - public boolean tested() { - return (sputumDone || sputumClosed) && xraySettled(); + /** + * What a household member still waits for before the index patient's contacts are + * added, or null when nothing. A negative chest X-ray needs no sputum. A TB Presumptive, + * closed, refused or skipped X-ray needs a sputum result (a closed or refused sputum + * order keeps waiting). + */ + public String contactWaitsFor() { + if (!xraySettled()) { + return "X-ray"; + } + if (xrayClear || sputumDone) { + return null; + } + return "NAAT result"; } private boolean xraySettled() { diff --git a/src/main/java/com/iemr/admin/repo/nikshayidgenerate/NikshayIdGenerateRepository.java b/src/main/java/com/iemr/admin/repo/nikshayidgenerate/NikshayIdGenerateRepository.java index c5bb711..870d48c 100644 --- a/src/main/java/com/iemr/admin/repo/nikshayidgenerate/NikshayIdGenerateRepository.java +++ b/src/main/java/com/iemr/admin/repo/nikshayidgenerate/NikshayIdGenerateRepository.java @@ -173,10 +173,8 @@ public class NikshayIdGenerateRepository { + " conf.benRegID IS NOT NULL " + " OR IFNULL(sus.is_tb_confirmed, 0) = 1 " + " OR IFNULL(sus.is_confirmed, 0) = 1 " - + " OR ( " - + " LOWER(IFNULL(COALESCE(diag.truenat_result, sus.sputum_test_result), '')) LIKE '%detect%' " - + " AND LOWER(IFNULL(COALESCE(diag.truenat_result, sus.sputum_test_result), '')) NOT LIKE '%not detect%' " - + " ) " + + " OR " + positiveResult("COALESCE(diag.truenat_result, sus.sputum_test_result)") + " " + + " OR " + positiveNaatOrder("m.BenRegId") + " " + " ) " + " AND IFNULL(NULLIF(TRIM(d.nikshayId), ''), '') = '' " + " AND IFNULL(NULLIF(TRIM(sus.nikshay_id), ''), '') = '' " @@ -189,6 +187,24 @@ private static String detected(String column) { + "AND LOWER(IFNULL(" + column + ", '')) NOT LIKE '%not detect%')"; } + // A TB-positive TrueNat / sputum result: "M. Tb detected" or "TB Positive" + private static String positiveResult(String column) { + return "(" + detected(column) + " OR LOWER(TRIM(IFNULL(" + column + ", ''))) = 'tb positive')"; + } + + // The beneficiary (BenRegId column) has a completed MTB order whose result is TB positive; + // the same rule the contacts phase uses (DIAGNOSIS_GATE_SQL sputum_positive) + private static String positiveNaatOrder(String benRegIdColumn) { + return "EXISTS (SELECT 1 FROM db_iemr.tb_diagnostic_order po " + + "JOIN db_iemr.tb_diagnostic_result pr " + + " ON pr.external_order_id = po.external_order_id AND pr.deleted = 0 " + + "JOIN db_identity.m_beneficiaryregidmapping pm " + + " ON pm.BeneficiaryID = po.beneficiary_id AND pm.Deleted = 0 " + + "WHERE pm.BenRegId = " + benRegIdColumn + " AND po.order_type = 'MTB' " + + " AND po.status = 'COMPLETED' AND (po.deleted = 0 OR po.deleted IS NULL) " + + " AND " + positiveResult("pr.result_summary") + ")"; + } + // Latest X-ray result of household member "mem" from the Stop TB diagnostics form private static final String FORM_XRAY_SQL = "(SELECT dx.digital_chest_xray_result " + "FROM db_iemr.tb_stoptb_diagnostics dx " @@ -214,7 +230,8 @@ private static String detected(String column) { + "ORDER BY ox.created_date DESC, ox.id DESC LIMIT 1)"; // A member of the household (each from their latest rmnch row) who stops it from being - // all negative: not TB screened, ever TB confirmed or M. Tb detected, or no clear X-ray. + // all negative: not TB screened, ever TB confirmed or TB positive (form, suspected or NAAT + // order result), or no clear X-ray. // The X-ray is clear when at least one of the two results says Normal or "Abnormal but // not TB Presumptive" and neither says anything else private static final String MEMBER_NOT_CLEARED_SQL = "SELECT 1 FROM db_identity.i_beneficiarydetails_rmnch mem " @@ -236,10 +253,11 @@ private static String detected(String column) { + " OR EXISTS (SELECT 1 FROM db_iemr.tb_suspected x3 " + " WHERE (x3.benRegID = mem.BeneficiaryRegID OR x3.ben_id = mem.BeneficiaryRegID) " + " AND (IFNULL(x3.is_tb_confirmed, 0) = 1 OR IFNULL(x3.is_confirmed, 0) = 1 " - + " OR " + detected("x3.sputum_test_result") + ")) " + + " OR " + positiveResult("x3.sputum_test_result") + ")) " + " OR EXISTS (SELECT 1 FROM db_iemr.tb_stoptb_diagnostics d3 " + " WHERE d3.ben_reg_id = mem.BeneficiaryRegID AND d3.deleted = 0 " - + " AND " + detected("d3.truenat_result") + ") " + + " AND " + positiveResult("d3.truenat_result") + ") " + + " OR " + positiveNaatOrder("mem.BeneficiaryRegID") + " " + " OR NOT ( " + " (" + FORM_XRAY_SQL + " IS NOT NULL OR " + ORDER_XRAY_SQL + " IS NOT NULL) " + " AND LOWER(TRIM(IFNULL(" + FORM_XRAY_SQL + ", 'normal'))) IN " + CLEAR_XRAY + " " @@ -508,12 +526,26 @@ public int saveEnrollment(NikshayEnrollResult result) { } // Sputum (MTB or Rif) and chest X-ray state for each BenRegId, from tb_diagnostic_order. + // xray_clear: the latest completed chest X-ray result is negative (CLEAR_XRAY); + // sputum_positive: a completed MTB result says TB positive or M. Tb detected. private static final String DIAGNOSIS_GATE_SQL = """ SELECT m.BenRegId AS ben_reg_id, MAX(CASE WHEN o.order_type IN ('MTB', 'MDR_RIF') AND o.status = 'COMPLETED' AND NULLIF(TRIM(r.result_summary), '') IS NOT NULL THEN 1 ELSE 0 END) AS sputum_done, + MAX(CASE WHEN o.order_type = 'MTB' AND o.status = 'COMPLETED' + AND """ + positiveResult("r.result_summary") + """ + THEN 1 ELSE 0 END) AS sputum_positive, MAX(CASE WHEN o.order_type IN ('MTB', 'MDR_RIF') AND o.status IN ('CLOSED', 'REFUSED') THEN 1 ELSE 0 END) AS sputum_closed, + IFNULL((SELECT LOWER(TRIM(rx.result_summary)) + FROM db_iemr.tb_diagnostic_order ox + JOIN db_iemr.tb_diagnostic_result rx + ON rx.external_order_id = ox.external_order_id AND rx.deleted = 0 + WHERE ox.beneficiary_id = m.BeneficiaryID AND ox.order_type = 'XRAY_CHEST' + AND ox.status = 'COMPLETED' AND (ox.deleted = 0 OR ox.deleted IS NULL) + AND NULLIF(TRIM(rx.result_summary), '') IS NOT NULL + ORDER BY ox.created_date DESC, ox.id DESC LIMIT 1) IN """ + CLEAR_XRAY + """ + , 0) AS xray_clear, MAX(CASE WHEN o.order_type = 'XRAY_CHEST' AND o.status = 'COMPLETED' AND NULLIF(TRIM(r.result_summary), '') IS NOT NULL THEN 1 ELSE 0 END) AS xray_done, MAX(CASE WHEN o.order_type = 'XRAY_CHEST' AND o.status IN ('CLOSED', 'REFUSED') @@ -529,7 +561,7 @@ OR LOWER(TRIM(IFNULL(o.reason_to_close, ''))) = 'kid') LEFT JOIN db_iemr.tb_diagnostic_result r ON r.external_order_id = o.external_order_id AND r.deleted = 0 WHERE m.BenRegId IN (:benRegIds) AND m.Deleted = 0 - GROUP BY m.BenRegId + GROUP BY m.BenRegId, m.BeneficiaryID """; /** Chest X-ray and sputum state for each given BenRegId. A BenRegId with no orders is absent. */ @@ -542,7 +574,9 @@ public Map findDiagnosisGate(List benRegIds) { DIAGNOSIS_GATE_SQL, new MapSqlParameterSource("benRegIds", benRegIds), (rs, rowNum) -> { NikshayDiagnosisGate gate = new NikshayDiagnosisGate(); gate.setSputumDone(rs.getInt("sputum_done") == 1); + gate.setSputumPositive(rs.getInt("sputum_positive") == 1); gate.setSputumClosed(rs.getInt("sputum_closed") == 1); + gate.setXrayClear(rs.getInt("xray_clear") == 1); gate.setXrayDone(rs.getInt("xray_done") == 1); gate.setXrayClosed(rs.getInt("xray_closed") == 1); gate.setXraySkip(rs.getInt("xray_skip") == 1); diff --git a/src/main/java/com/iemr/admin/service/nikshayidgenerate/NikshayIdGenerateService.java b/src/main/java/com/iemr/admin/service/nikshayidgenerate/NikshayIdGenerateService.java index c9a2971..0c8f0b4 100644 --- a/src/main/java/com/iemr/admin/service/nikshayidgenerate/NikshayIdGenerateService.java +++ b/src/main/java/com/iemr/admin/service/nikshayidgenerate/NikshayIdGenerateService.java @@ -508,8 +508,9 @@ private boolean setPortalVillageId(NikshaySession session, NikshayIdGenerateVill } /** - * Null when the index patient's tests are in Ni-kshay and every household member has - * finished sputum and chest X-ray in AMRIT. Otherwise the reason contacts must wait. + * Null when the index patient's tests are in Ni-kshay and every household member is + * ready (NikshayDiagnosisGate.contactWaitsFor). Otherwise the reason contacts must wait, + * with what each member waits for. */ private String contactsNotTested(NikshayIdGenerateBeneficiaryDTO index) { List indexIds = new ArrayList<>(); @@ -522,19 +523,28 @@ private String contactsNotTested(NikshayIdGenerateBeneficiaryDTO index) { memberIds.add(member.getBeneficiaryId()); } Map gates = nikshayIdGenerateRepository.findDiagnosisGate(memberIds); - List waiting = new ArrayList<>(); - for (Long memberId : memberIds) { - NikshayDiagnosisGate gate = gates.get(memberId); - if (gate == null || !gate.tested()) { - waiting.add(memberId); + List waiting = new ArrayList<>(); + for (NikshayHouseholdMemberDTO member : index.getHouseholdMembers()) { + NikshayDiagnosisGate gate = gates.get(member.getBeneficiaryId()); + String waitsFor = gate == null ? "X-ray" : gate.contactWaitsFor(); + if (waitsFor != null) { + waiting.add("(" + member.getBeneficiaryId() + ", " + memberName(member) + ") " + waitsFor); } } if (!waiting.isEmpty()) { - return "Waits until these contacts have finished sputum and chest X-ray: " + waiting; + return "Waits until these contacts have their tests: " + String.join(", ", waiting); } return null; } + // First and last name, or "name unknown" when both are empty + private static String memberName(NikshayHouseholdMemberDTO member) { + String first = member.getFirstName() == null ? "" : member.getFirstName().trim(); + String last = member.getLastName() == null ? "" : member.getLastName().trim(); + String name = (first + " " + last).trim(); + return name.isEmpty() ? "name unknown" : name; + } + private boolean phaseSettled(NikshayPhase phase, List benRegIds) { List rows = phaseStatusService.findRows(phase, benRegIds); if (rows.isEmpty()) { @@ -549,6 +559,7 @@ private boolean phaseSettled(NikshayPhase phase, List benRegIds) { * Adds the index patient's household members to Ni-kshay as their contacts (BRD section * 8.1, spec Flow 2-A), with the same NAAT device login. First the household counts are * written on the index patient (ContactTracing), then each member not yet in Ni-kshay + * and not TB positive (their NAAT says so; they are enrolled as their own index patient) * is validated and enrolled with Source = contactTracing. The counts must go first: * beta Ni-kshay links a contact to the index only when the index already has them. When * the counts are not accepted, no contact is added. The contacts are added against the @@ -580,6 +591,13 @@ private void addContacts(NikshaySession session, NikshayIdGenerateBeneficiaryDTO return; } + // A member whose NAAT is TB positive is enrolled as their own index patient, not as a contact + List memberIds = new ArrayList<>(); + for (NikshayHouseholdMemberDTO member : index.getHouseholdMembers()) { + memberIds.add(member.getBeneficiaryId()); + } + Map gates = nikshayIdGenerateRepository.findDiagnosisGate(memberIds); + int added = 0; int toAdd = 0; NikshayFailureReason firstFailure = null; @@ -587,6 +605,12 @@ private void addContacts(NikshaySession session, NikshayIdGenerateBeneficiaryDTO if (member.getNikshayId() != null) { continue; } + NikshayDiagnosisGate gate = gates.get(member.getBeneficiaryId()); + if (gate != null && gate.isSputumPositive()) { + logger.info("Member {} of index {} is TB positive: enrolled as their own index patient, not as a contact", + member.getBeneficiaryId(), sourcePatientId); + continue; + } toAdd++; NikshayIdGenerateBeneficiaryDTO contact = toContact(index, member); List problems = beneficiaryValidator.validate(contact); From e4833719ab4b0bf8ba5a2a06804f96e12ba0c8ed Mon Sep 17 00:00:00 2001 From: chetansaroya Date: Mon, 16 Nov 2026 13:17:05 +0530 Subject: [PATCH 2/2] stop:816 Nikshay Workflow: code rabbit review resolved. --- .../NikshayDiagnosisGate.java | 3 +- .../NikshayIdGenerateRepository.java | 34 +++++++++++++++---- .../NikshayIdGenerateService.java | 6 ++-- 3 files changed, 32 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/iemr/admin/data/nikshayidgenerate/NikshayDiagnosisGate.java b/src/main/java/com/iemr/admin/data/nikshayidgenerate/NikshayDiagnosisGate.java index eb2d016..db0dd30 100644 --- a/src/main/java/com/iemr/admin/data/nikshayidgenerate/NikshayDiagnosisGate.java +++ b/src/main/java/com/iemr/admin/data/nikshayidgenerate/NikshayDiagnosisGate.java @@ -11,7 +11,8 @@ public class NikshayDiagnosisGate { private boolean sputumDone; - private boolean sputumPositive; + // TB positive by any source index eligibility uses (confirmed, form, suspected or NAAT order) + private boolean tbPositive; private boolean sputumClosed; private boolean xrayDone; private boolean xrayClear; diff --git a/src/main/java/com/iemr/admin/repo/nikshayidgenerate/NikshayIdGenerateRepository.java b/src/main/java/com/iemr/admin/repo/nikshayidgenerate/NikshayIdGenerateRepository.java index 870d48c..ad30886 100644 --- a/src/main/java/com/iemr/admin/repo/nikshayidgenerate/NikshayIdGenerateRepository.java +++ b/src/main/java/com/iemr/admin/repo/nikshayidgenerate/NikshayIdGenerateRepository.java @@ -192,8 +192,7 @@ private static String positiveResult(String column) { return "(" + detected(column) + " OR LOWER(TRIM(IFNULL(" + column + ", ''))) = 'tb positive')"; } - // The beneficiary (BenRegId column) has a completed MTB order whose result is TB positive; - // the same rule the contacts phase uses (DIAGNOSIS_GATE_SQL sputum_positive) + // The beneficiary (BenRegId column) has a completed MTB order whose result is TB positive private static String positiveNaatOrder(String benRegIdColumn) { return "EXISTS (SELECT 1 FROM db_iemr.tb_diagnostic_order po " + "JOIN db_iemr.tb_diagnostic_result pr " @@ -205,6 +204,28 @@ private static String positiveNaatOrder(String benRegIdColumn) { + " AND " + positiveResult("pr.result_summary") + ")"; } + // The beneficiary (BenRegId column) is TB positive by the same sources as + // ELIGIBLE_BENEFICIARIES_SQL: a TB confirmed case, their latest tb_suspected row confirmed, + // their latest Stop TB form TrueNat (else latest suspected sputum) result positive, or a + // positive MTB order. The contacts phase uses it so a TB-positive member is never added as a contact. + private static String tbPositive(String benRegIdColumn) { + String latestForm = "(SELECT d2.truenat_result FROM db_iemr.tb_stoptb_diagnostics d2 " + + "WHERE d2.ben_reg_id = " + benRegIdColumn + " AND d2.deleted = 0 ORDER BY d2.id DESC LIMIT 1)"; + return "(EXISTS (SELECT 1 FROM db_iemr.tb_confirmed_cases c2 WHERE c2.benRegID = " + benRegIdColumn + ") " + + "OR IFNULL(" + latestSuspected("is_tb_confirmed", benRegIdColumn) + ", 0) = 1 " + + "OR IFNULL(" + latestSuspected("is_confirmed", benRegIdColumn) + ", 0) = 1 " + + "OR " + positiveResult("COALESCE(" + latestForm + ", " + + latestSuspected("sputum_test_result", benRegIdColumn) + ")") + " " + + "OR " + positiveNaatOrder(benRegIdColumn) + ")"; + } + + // One column of the beneficiary's latest tb_suspected row (same row as the eligibility query) + private static String latestSuspected(String column, String benRegIdColumn) { + return "(SELECT x2." + column + " FROM db_iemr.tb_suspected x2 " + + "WHERE x2.benRegID = " + benRegIdColumn + " OR x2.ben_id = " + benRegIdColumn + " " + + "ORDER BY x2.id DESC LIMIT 1)"; + } + // Latest X-ray result of household member "mem" from the Stop TB diagnostics form private static final String FORM_XRAY_SQL = "(SELECT dx.digital_chest_xray_result " + "FROM db_iemr.tb_stoptb_diagnostics dx " @@ -527,14 +548,13 @@ public int saveEnrollment(NikshayEnrollResult result) { // Sputum (MTB or Rif) and chest X-ray state for each BenRegId, from tb_diagnostic_order. // xray_clear: the latest completed chest X-ray result is negative (CLEAR_XRAY); - // sputum_positive: a completed MTB result says TB positive or M. Tb detected. + // tb_positive: TB positive by any source index eligibility uses (tbPositive). private static final String DIAGNOSIS_GATE_SQL = """ SELECT m.BenRegId AS ben_reg_id, MAX(CASE WHEN o.order_type IN ('MTB', 'MDR_RIF') AND o.status = 'COMPLETED' AND NULLIF(TRIM(r.result_summary), '') IS NOT NULL THEN 1 ELSE 0 END) AS sputum_done, - MAX(CASE WHEN o.order_type = 'MTB' AND o.status = 'COMPLETED' - AND """ + positiveResult("r.result_summary") + """ - THEN 1 ELSE 0 END) AS sputum_positive, + """ + tbPositive("m.BenRegId") + """ + AS tb_positive, MAX(CASE WHEN o.order_type IN ('MTB', 'MDR_RIF') AND o.status IN ('CLOSED', 'REFUSED') THEN 1 ELSE 0 END) AS sputum_closed, IFNULL((SELECT LOWER(TRIM(rx.result_summary)) @@ -574,7 +594,7 @@ public Map findDiagnosisGate(List benRegIds) { DIAGNOSIS_GATE_SQL, new MapSqlParameterSource("benRegIds", benRegIds), (rs, rowNum) -> { NikshayDiagnosisGate gate = new NikshayDiagnosisGate(); gate.setSputumDone(rs.getInt("sputum_done") == 1); - gate.setSputumPositive(rs.getInt("sputum_positive") == 1); + gate.setTbPositive(rs.getInt("tb_positive") == 1); gate.setSputumClosed(rs.getInt("sputum_closed") == 1); gate.setXrayClear(rs.getInt("xray_clear") == 1); gate.setXrayDone(rs.getInt("xray_done") == 1); diff --git a/src/main/java/com/iemr/admin/service/nikshayidgenerate/NikshayIdGenerateService.java b/src/main/java/com/iemr/admin/service/nikshayidgenerate/NikshayIdGenerateService.java index 0c8f0b4..d5eb676 100644 --- a/src/main/java/com/iemr/admin/service/nikshayidgenerate/NikshayIdGenerateService.java +++ b/src/main/java/com/iemr/admin/service/nikshayidgenerate/NikshayIdGenerateService.java @@ -559,7 +559,7 @@ private boolean phaseSettled(NikshayPhase phase, List benRegIds) { * Adds the index patient's household members to Ni-kshay as their contacts (BRD section * 8.1, spec Flow 2-A), with the same NAAT device login. First the household counts are * written on the index patient (ContactTracing), then each member not yet in Ni-kshay - * and not TB positive (their NAAT says so; they are enrolled as their own index patient) + * and not TB positive (by any source index eligibility uses; they are enrolled as their own index patient) * is validated and enrolled with Source = contactTracing. The counts must go first: * beta Ni-kshay links a contact to the index only when the index already has them. When * the counts are not accepted, no contact is added. The contacts are added against the @@ -591,7 +591,7 @@ private void addContacts(NikshaySession session, NikshayIdGenerateBeneficiaryDTO return; } - // A member whose NAAT is TB positive is enrolled as their own index patient, not as a contact + // A TB-positive member (confirmed, form, suspected or NAAT order) is enrolled as their own index patient, not as a contact List memberIds = new ArrayList<>(); for (NikshayHouseholdMemberDTO member : index.getHouseholdMembers()) { memberIds.add(member.getBeneficiaryId()); @@ -606,7 +606,7 @@ private void addContacts(NikshaySession session, NikshayIdGenerateBeneficiaryDTO continue; } NikshayDiagnosisGate gate = gates.get(member.getBeneficiaryId()); - if (gate != null && gate.isSputumPositive()) { + if (gate != null && gate.isTbPositive()) { logger.info("Member {} of index {} is TB positive: enrolled as their own index patient, not as a contact", member.getBeneficiaryId(), sourcePatientId); continue;