Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,11 @@
public class NikshayDiagnosisGate {

private boolean sputumDone;
// 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;
private boolean xrayClosed;
private boolean xraySkip;

Expand All @@ -21,9 +24,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() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,10 +173,8 @@
+ " 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), ''), '') = '' "
Expand All @@ -189,6 +187,45 @@
+ "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
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") + ")";
}

// 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 "
Expand All @@ -214,7 +251,8 @@
+ "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 "
Expand All @@ -236,10 +274,11 @@
+ " 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 + " "
Expand Down Expand Up @@ -385,7 +424,7 @@
*/
public List<NikshayIdGenerateBeneficiaryDTO> findEligibleBeneficiaries() {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
List<NikshayIdGenerateBeneficiaryDTO> beneficiaries = jdbcTemplate.query(ELIGIBLE_BENEFICIARIES_SQL,

Check warning on line 427 in src/main/java/com/iemr/admin/repo/nikshayidgenerate/NikshayIdGenerateRepository.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Make sure using a dynamically formatted SQL query is safe here.

See more on https://sonarcloud.io/project/issues?id=PSMRI_Admin-API&issues=AaHjQpAoqHBeEI_XX14W&open=AaHjQpAoqHBeEI_XX14W&pullRequest=166
(rs, rowNum) -> mapRow(rs));
addHouseholdMembers(beneficiaries);
return beneficiaries;
Expand Down Expand Up @@ -508,12 +547,25 @@
}

// 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);
// 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,
""" + 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))
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 + """

Check warning on line 567 in src/main/java/com/iemr/admin/repo/nikshayidgenerate/NikshayIdGenerateRepository.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use only spaces or only tabs for indentation

See more on https://sonarcloud.io/project/issues?id=PSMRI_Admin-API&issues=AaHjVCdfLsa-L6o-xAdZ&open=AaHjVCdfLsa-L6o-xAdZ&pullRequest=166
, 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')
Expand All @@ -529,7 +581,7 @@
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. */
Expand All @@ -539,10 +591,12 @@
return gates;
}
List<Map.Entry<Long, NikshayDiagnosisGate>> rows = new NamedParameterJdbcTemplate(dataSource).query(
DIAGNOSIS_GATE_SQL, new MapSqlParameterSource("benRegIds", benRegIds), (rs, rowNum) -> {

Check warning on line 594 in src/main/java/com/iemr/admin/repo/nikshayidgenerate/NikshayIdGenerateRepository.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Make sure using a dynamically formatted SQL query is safe here.

See more on https://sonarcloud.io/project/issues?id=PSMRI_Admin-API&issues=AaHjQpAoqHBeEI_XX14Y&open=AaHjQpAoqHBeEI_XX14Y&pullRequest=166
NikshayDiagnosisGate gate = new NikshayDiagnosisGate();
gate.setSputumDone(rs.getInt("sputum_done") == 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);
gate.setXrayClosed(rs.getInt("xray_closed") == 1);
gate.setXraySkip(rs.getInt("xray_skip") == 1);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -508,8 +508,9 @@
}

/**
* 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<Long> indexIds = new ArrayList<>();
Expand All @@ -522,19 +523,28 @@
memberIds.add(member.getBeneficiaryId());
}
Map<Long, NikshayDiagnosisGate> gates = nikshayIdGenerateRepository.findDiagnosisGate(memberIds);
List<Long> waiting = new ArrayList<>();
for (Long memberId : memberIds) {
NikshayDiagnosisGate gate = gates.get(memberId);
if (gate == null || !gate.tested()) {
waiting.add(memberId);
List<String> 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<Long> benRegIds) {
List<NikshayPhaseCandidate> rows = phaseStatusService.findRows(phase, benRegIds);
if (rows.isEmpty()) {
Expand All @@ -549,6 +559,7 @@
* 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 (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
Expand All @@ -557,7 +568,7 @@
* run under the contact's (or, for the counts, the index patient's) beneficiary ID. The
* index patient's CONTACTS phase and each contact's ENROLMENT phase are recorded.
*/
private void addContacts(NikshaySession session, NikshayIdGenerateBeneficiaryDTO index, NikshayEnrollResult indexResult,

Check failure on line 571 in src/main/java/com/iemr/admin/service/nikshayidgenerate/NikshayIdGenerateService.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this method to reduce its Cognitive Complexity from 28 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=PSMRI_Admin-API&issues=AaHjQo9qqHBeEI_XX14U&open=AaHjQo9qqHBeEI_XX14U&pullRequest=166
NikshayPhaseRun run) {
phaseStatusService.markInProgress(index.getBeneficiaryId(), index.getBeneficiaryType(), null,
NikshayPhase.CONTACTS);
Expand All @@ -580,13 +591,26 @@
return;
}

// A TB-positive member (confirmed, form, suspected or NAAT order) is enrolled as their own index patient, not as a contact
List<Long> memberIds = new ArrayList<>();
for (NikshayHouseholdMemberDTO member : index.getHouseholdMembers()) {
memberIds.add(member.getBeneficiaryId());
}
Map<Long, NikshayDiagnosisGate> gates = nikshayIdGenerateRepository.findDiagnosisGate(memberIds);

int added = 0;
int toAdd = 0;
NikshayFailureReason firstFailure = null;
for (NikshayHouseholdMemberDTO member : index.getHouseholdMembers()) {

Check warning on line 604 in src/main/java/com/iemr/admin/service/nikshayidgenerate/NikshayIdGenerateService.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Reduce the total number of break and continue statements in this loop to use at most one.

See more on https://sonarcloud.io/project/issues?id=PSMRI_Admin-API&issues=AaHjQo9qqHBeEI_XX14T&open=AaHjQo9qqHBeEI_XX14T&pullRequest=166
if (member.getNikshayId() != null) {
continue;
}
NikshayDiagnosisGate gate = gates.get(member.getBeneficiaryId());
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;
}
toAdd++;
NikshayIdGenerateBeneficiaryDTO contact = toContact(index, member);
List<String> problems = beneficiaryValidator.validate(contact);
Expand Down
Loading