diff --git a/src/main/java/com/iemr/flw/controller/DiagnosticOrderController.java b/src/main/java/com/iemr/flw/controller/DiagnosticOrderController.java index 1725b5af..e795ac04 100644 --- a/src/main/java/com/iemr/flw/controller/DiagnosticOrderController.java +++ b/src/main/java/com/iemr/flw/controller/DiagnosticOrderController.java @@ -98,7 +98,10 @@ public String retryOrder(@RequestParam Long beneficiaryId, @RequestParam String @PostMapping("/order/result") @Operation(summary = "Get the diagnostic result for beneficiaryId+orderType, at whatever stage it's currently in " - + "(targets the latest order unless visitCode is given)") + + "(targets the latest order unless visitCode is given). results[] has one entry per test: the order's " + + "own (XRAY_CHEST / MTB / MTB_PLUS), then MDR_RIF on an MTB order once its RIF test exists. status INVALID: the MTB/RIF test came back " + + "invalid (e.g. Error-2) and the machine is retesting the same order — it is still polled and " + + "moves to COMPLETED when the retest result arrives.") public String getOrderResult(@RequestParam Long beneficiaryId, @RequestParam String orderType, @RequestParam(required = false) Long visitCode) { OutputResponse response = new OutputResponse(); @@ -114,7 +117,8 @@ public String getOrderResult(@RequestParam Long beneficiaryId, @RequestParam Str @PostMapping("/order/poll") @Operation(summary = "Trigger an immediate poll for one beneficiary+orderType's diagnostic order and return the result (ops use). " - + "Targets the latest order unless visitCode is given") + + "Targets the latest order unless visitCode is given. An invalid MTB/RIF result gives status INVALID " + + "(still polled, no retest order); an invalid X-ray closes the order and pushes a retest.") public String pollOrder(@RequestParam Long beneficiaryId, @RequestParam String orderType, @RequestParam(required = false) Long visitCode) { OutputResponse response = new OutputResponse(); @@ -129,11 +133,19 @@ public String pollOrder(@RequestParam Long beneficiaryId, @RequestParam String o } @PostMapping("/order/manualResult") - @Operation(summary = "Exactly one of resultSummary/reasonToClose is required. resultSummary: manually submit " - + "a diagnostic result for a beneficiary's latest order of the given type, for use when no vendor " - + "device is integrated. Stored as-is; tbPresence, tbConfidence, and drugResistancePresence are left " - + "null since nothing derives them. Rejected if that order is already COMPLETED. reasonToClose: close " - + "the order instead (same behavior as reasonToClose on /order/push), sourcing patient/orderEvent " + @Operation(summary = "Send either a result (resultSummary and/or mdrRifResult) or one reasonToClose. resultSummary: " + + "manually submit a diagnostic result for a beneficiary's latest order of the given type, for use when " + + "no vendor device is integrated. Stored like a vendor result, one row per test in results[]. " + + "MTB/MTB_PLUS orders carry two results: resultSummary is the MTB result; mdrRifResult is the MDR RIF " + + "result, stored as the order's MDR_RIF result (and tb_suspected's MDR RIF result), only allowed on a positive MTB. " + + "A positive MTB without mdrRifResult leaves the order open until RIF is in: PENDING if it was pushed " + + "to a vendor (polling continues, and the vendor's result replaces a differing manual one), " + + "MANUAL_ENTRY if there is no vendor (send mdrRifResult or reasonToCloseRif). Otherwise the order " + + "is COMPLETED; a vendor's differing result still replaces it when its documents are fetched. " + + "An invalid result (resultSummary or mdrRifResult \"Invalid/Error\") closes the order. " + + "Rejected if that order is already COMPLETED or CLOSED (push a new order to test again). Closing (same as on /order/push): reasonToCloseXray for " + + "XRAY_CHEST; reasonToCloseMTB when the MTB test wasn't done; reasonToCloseRif when MTB was positive but " + + "MDR RIF wasn't done — closes that same order, keeping its MTB result. Patient/orderEvent are sourced " + "from the beneficiary's existing order for this type.") public String submitManualResult(@RequestBody @Valid ManualDiagnosticResultRequestDto request, @RequestHeader("JwtToken") String jwtToken) { @@ -150,7 +162,8 @@ public String submitManualResult(@RequestBody @Valid ManualDiagnosticResultReque @GetMapping("/order/getBeneficiariesByStatus") @Operation(summary = "Get beneficiary IDs bucketed by diagnostic order status for the given order type, " - + "optionally filtered by village and/or provider service map") + + "optionally filtered by village and/or provider service map. invalid: MTB/RIF invalid, waiting for " + + "the machine's own retest") public ResponseEntity getBeneficiariesByStatus( @RequestParam DiagnosticOrderType orderType, @RequestParam(required = false) Integer villageId, diff --git a/src/main/java/com/iemr/flw/domain/iemr/DiagnosticOrder.java b/src/main/java/com/iemr/flw/domain/iemr/DiagnosticOrder.java index 5ea9a458..7a4c476d 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/DiagnosticOrder.java +++ b/src/main/java/com/iemr/flw/domain/iemr/DiagnosticOrder.java @@ -52,8 +52,17 @@ public class DiagnosticOrder { @Column(name = "error_message", columnDefinition = "TEXT") private String errorMessage; - @Column(name = "reason_to_close", columnDefinition = "TEXT") - private String reasonToClose; + // Why the order was closed, one column per test (see DiagnosticCloseStage): xray, mtb, or mdrrif + // for an MTB/MTB_PLUS order whose MTB was positive but whose MDR RIF test wasn't done. Set through + // setReasonToClose(stage, reason). The old reason_to_close column is no longer mapped. + @Column(name = "reason_to_close_xray", columnDefinition = "TEXT") + private String reasonToCloseXray; + + @Column(name = "reason_to_close_mtb", columnDefinition = "TEXT") + private String reasonToCloseMTB; + + @Column(name = "reason_to_close_mdrrif", columnDefinition = "TEXT") + private String reasonToCloseMDRRIF; @Column(name = "push_response_json", columnDefinition = "LONGTEXT") private String pushResponseJson; @@ -115,4 +124,12 @@ public class DiagnosticOrder { @org.hibernate.annotations.CreationTimestamp @Column(name = "synced_date") private Timestamp syncedDate; + + public void setReasonToClose(com.iemr.flw.masterEnum.DiagnosticCloseStage stage, String reason) { + switch (stage) { + case XRAY -> reasonToCloseXray = reason; + case MTB -> reasonToCloseMTB = reason; + case RIF -> reasonToCloseMDRRIF = reason; + } + } } diff --git a/src/main/java/com/iemr/flw/domain/iemr/DiagnosticResult.java b/src/main/java/com/iemr/flw/domain/iemr/DiagnosticResult.java index 55e5a0ca..deaa4b11 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/DiagnosticResult.java +++ b/src/main/java/com/iemr/flw/domain/iemr/DiagnosticResult.java @@ -9,7 +9,7 @@ @Entity @Table(name = "tb_diagnostic_result", schema = "db_iemr", - uniqueConstraints = @UniqueConstraint(columnNames = {"external_order_id"})) + uniqueConstraints = @UniqueConstraint(columnNames = {"external_order_id", "result_type"})) @Data public class DiagnosticResult { @@ -23,6 +23,10 @@ public class DiagnosticResult { @Column(name = "external_order_id", length = 100) private String externalOrderId; + // Which test this row holds (DiagnosticResultType): the order's own test, or MDR_RIF. + @Column(name = "result_type", length = 20) + private String resultType; + @Column(name = "beneficiary_id") private Long beneficiaryId; diff --git a/src/main/java/com/iemr/flw/dto/DiagnosticOrderRequestDto.java b/src/main/java/com/iemr/flw/dto/DiagnosticOrderRequestDto.java index abf8475e..4a2beb64 100644 --- a/src/main/java/com/iemr/flw/dto/DiagnosticOrderRequestDto.java +++ b/src/main/java/com/iemr/flw/dto/DiagnosticOrderRequestDto.java @@ -19,7 +19,12 @@ public class DiagnosticOrderRequestDto { private String orderEvent; - private String reasonToClose; + // Close instead of pushing/entering a result — send at most one, for the test that wasn't done: + // reasonToCloseXray (XRAY_CHEST); reasonToCloseMTB (MTB/MTB_PLUS, MTB test not done); + // reasonToCloseRif (MTB/MTB_PLUS, MTB was positive but the MDR RIF test wasn't done). + private String reasonToCloseXray; + private String reasonToCloseMTB; + private String reasonToCloseRif; @NotNull @Valid diff --git a/src/main/java/com/iemr/flw/dto/DiagnosticOrderResultDto.java b/src/main/java/com/iemr/flw/dto/DiagnosticOrderResultDto.java index 531800f7..de182bdc 100644 --- a/src/main/java/com/iemr/flw/dto/DiagnosticOrderResultDto.java +++ b/src/main/java/com/iemr/flw/dto/DiagnosticOrderResultDto.java @@ -3,18 +3,22 @@ import lombok.Data; import lombok.NoArgsConstructor; +import java.util.ArrayList; +import java.util.List; + @Data @NoArgsConstructor public class DiagnosticOrderResultDto { + private Long beneficiaryId; + private Long visitCode; private String externalOrderId; private String orderType; private String status; - private String providerStatus; - private String resultSummary; private String errorMessage; - private String reasonToClose; - private Boolean tbPresence; - private Double tbConfidence; - private Boolean drugResistancePresence; + private String reasonToCloseXray; + private String reasonToCloseMTB; + private String reasonToCloseMDRRIF; + // One entry per tb_diagnostic_result row: the order's own test first, then MDR_RIF when present. + private List results = new ArrayList<>(); } \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/DiagnosticOrderStatusSummaryDto.java b/src/main/java/com/iemr/flw/dto/DiagnosticOrderStatusSummaryDto.java index 88eafcab..1b31eb9d 100644 --- a/src/main/java/com/iemr/flw/dto/DiagnosticOrderStatusSummaryDto.java +++ b/src/main/java/com/iemr/flw/dto/DiagnosticOrderStatusSummaryDto.java @@ -15,4 +15,6 @@ public class DiagnosticOrderStatusSummaryDto { private List failed; private List closed; private List awaitingManualEntry; + // MTB/RIF invalid, waiting for the machine's own retest (still polled). + private List invalid; } diff --git a/src/main/java/com/iemr/flw/dto/DiagnosticResultItemDto.java b/src/main/java/com/iemr/flw/dto/DiagnosticResultItemDto.java new file mode 100644 index 00000000..e94a2482 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/DiagnosticResultItemDto.java @@ -0,0 +1,19 @@ +package com.iemr.flw.dto; + +import lombok.Data; +import lombok.NoArgsConstructor; + +/** One test's result on an order: the order's own test, or MDR_RIF on an MTB/MTB_PLUS order. */ +@Data +@NoArgsConstructor +public class DiagnosticResultItemDto { + + // XRAY_CHEST, MTB, MTB_PLUS or MDR_RIF + private String resultType; + private String providerStatus; + private String resultSummary; + private Boolean tbPresence; + private Double tbConfidence; + // MDR_RIF only: true = DR TB, false = Non DR TB, null = not done / indeterminate + private Boolean drugResistancePresence; +} diff --git a/src/main/java/com/iemr/flw/dto/ManualDiagnosticResultRequestDto.java b/src/main/java/com/iemr/flw/dto/ManualDiagnosticResultRequestDto.java index cd6a10a8..73a2a459 100644 --- a/src/main/java/com/iemr/flw/dto/ManualDiagnosticResultRequestDto.java +++ b/src/main/java/com/iemr/flw/dto/ManualDiagnosticResultRequestDto.java @@ -14,7 +14,18 @@ public class ManualDiagnosticResultRequestDto { @NotNull private String orderType; + // MTB / MTB_PLUS: the MTB test's result (e.g. "TB Positive", "TB Negative"). private String resultSummary; - private String reasonToClose; + // MTB / MTB_PLUS only: the MDR RIF result run on the same order after a positive MTB + // (e.g. "DR TB", "Non DR TB"). Send it with resultSummary, or on its own in a later call + // once the MTB result is stored. + private String mdrRifResult; + + // Close instead of pushing/entering a result — send at most one, for the test that wasn't done: + // reasonToCloseXray (XRAY_CHEST); reasonToCloseMTB (MTB/MTB_PLUS, MTB test not done); + // reasonToCloseRif (MTB/MTB_PLUS, MTB was positive but the MDR RIF test wasn't done). + private String reasonToCloseXray; + private String reasonToCloseMTB; + private String reasonToCloseRif; } diff --git a/src/main/java/com/iemr/flw/integration/provider/DiagnosticDocumentAsset.java b/src/main/java/com/iemr/flw/integration/provider/DiagnosticDocumentAsset.java index a43d1d55..7aa276d8 100644 --- a/src/main/java/com/iemr/flw/integration/provider/DiagnosticDocumentAsset.java +++ b/src/main/java/com/iemr/flw/integration/provider/DiagnosticDocumentAsset.java @@ -18,4 +18,5 @@ public class DiagnosticDocumentAsset { private String contentType; private String fileName; private String base64Content; + private String component; } diff --git a/src/main/java/com/iemr/flw/integration/provider/DiagnosticPollResult.java b/src/main/java/com/iemr/flw/integration/provider/DiagnosticPollResult.java index 9f652bf6..cbcff799 100644 --- a/src/main/java/com/iemr/flw/integration/provider/DiagnosticPollResult.java +++ b/src/main/java/com/iemr/flw/integration/provider/DiagnosticPollResult.java @@ -20,4 +20,30 @@ public class DiagnosticPollResult { private Boolean tbPresence; private Double tbConfidence; private Boolean drugResistancePresence; + // The MDR RIF test's own summary (e.g. "DR TB", "Non DR TB", "Indeterminate"), run on the same + // order when MTB is positive. Null when no RIF test ran or it isn't finished. + private String drugResistanceSummary; + // The MDR RIF test's own status from the vendor (PENDING / COMPLETED / FAILED). Null when there is + // no RIF test. + private String drugResistanceStatus; + // The order's own test's status (MTB / MTB_PLUS component) from the vendor, kept apart from the + // order status above: an MTB test is COMPLETED while the order stays PENDING for its RIF test. + // Null when the vendor reported none (X-ray, manual entry) — the result row then works it out. + private String mainStatus; + + public DiagnosticPollResult(DiagnosticOrderStatus status, String providerOrderId, String resultSummary, + String rawResponseJson, List assets, String errorMessage, + Boolean tbPresence, Double tbConfidence, Boolean drugResistancePresence, + String drugResistanceSummary) { + this(status, providerOrderId, resultSummary, rawResponseJson, assets, errorMessage, tbPresence, + tbConfidence, drugResistancePresence, drugResistanceSummary, null, null); + } + + public DiagnosticPollResult(DiagnosticOrderStatus status, String providerOrderId, String resultSummary, + String rawResponseJson, List assets, String errorMessage, + Boolean tbPresence, Double tbConfidence, Boolean drugResistancePresence, + String drugResistanceSummary, String drugResistanceStatus) { + this(status, providerOrderId, resultSummary, rawResponseJson, assets, errorMessage, tbPresence, + tbConfidence, drugResistancePresence, drugResistanceSummary, drugResistanceStatus, null); + } } diff --git a/src/main/java/com/iemr/flw/integration/provider/DiagnosticProviderFactory.java b/src/main/java/com/iemr/flw/integration/provider/DiagnosticProviderFactory.java index 1656799c..19af06a5 100644 --- a/src/main/java/com/iemr/flw/integration/provider/DiagnosticProviderFactory.java +++ b/src/main/java/com/iemr/flw/integration/provider/DiagnosticProviderFactory.java @@ -38,7 +38,7 @@ public DiagnosticProvider getProvider(String providerCode) { return provider; } - // XRAY_CHEST is routed to its own vendor; the TrueNat family (MTB/MTB_PLUS/MDR_RIF) shares + // XRAY_CHEST is routed to its own vendor; the TrueNat family (MTB/MTB_PLUS) shares // another, each configurable independently so a new vendor can be swapped in for either group // without a code change. public String getProviderCodeForOrderType(DiagnosticOrderType orderType) { diff --git a/src/main/java/com/iemr/flw/integration/provider/TrueNatResultRules.java b/src/main/java/com/iemr/flw/integration/provider/TrueNatResultRules.java new file mode 100644 index 00000000..3d67ee27 --- /dev/null +++ b/src/main/java/com/iemr/flw/integration/provider/TrueNatResultRules.java @@ -0,0 +1,56 @@ +package com.iemr.flw.integration.provider; + +import com.iemr.flw.masterEnum.DiagnosticOrderType; + +/** + * How a TrueNat (MTB / MTB_PLUS) order's two results are read, shared by the vendor poll and + * manual entry so both store the same thing. One order carries both tests: the MTB result itself, + * and an MDR RIF result that is only run when MTB comes back positive. + */ +public final class TrueNatResultRules { + + public static final String SUMMARY_TB_POSITIVE = "TB Positive"; + public static final String SUMMARY_TB_NEGATIVE = "TB Negative"; + public static final String SUMMARY_DR_TB = "DR TB"; + public static final String SUMMARY_NON_DR_TB = "Non DR TB"; + + private TrueNatResultRules() { + } + + public static boolean isTrueNat(String orderType) { + return DiagnosticOrderType.MTB.name().equals(orderType) || DiagnosticOrderType.MTB_PLUS.name().equals(orderType); + } + + /** A positive MTB result is followed by an MDR RIF test on the same order. */ + public static boolean needsMdrRif(String mtbSummary) { + return mtbSummary != null && SUMMARY_TB_POSITIVE.equalsIgnoreCase(mtbSummary.trim()); + } + + /** TB presence from the MTB result; null for non-TrueNat orders or an unknown/error summary. */ + public static Boolean classifyTbPresence(String orderType, String summary) { + if (!isTrueNat(orderType) || summary == null) { + return null; + } + if (SUMMARY_TB_POSITIVE.equalsIgnoreCase(summary.trim())) { + return true; + } + if (SUMMARY_TB_NEGATIVE.equalsIgnoreCase(summary.trim())) { + return false; + } + return null; + } + + /** Rifampicin resistance from the MDR RIF result; null when there is none or it is indeterminate. */ + public static Boolean classifyDrugResistance(String summary) { + if (summary == null) { + return null; + } + if (SUMMARY_DR_TB.equalsIgnoreCase(summary.trim())) { + return true; + } + if (SUMMARY_NON_DR_TB.equalsIgnoreCase(summary.trim())) { + return false; + } + return null; + } +} diff --git a/src/main/java/com/iemr/flw/integration/provider/emrlite/EmrLiteProvider.java b/src/main/java/com/iemr/flw/integration/provider/emrlite/EmrLiteProvider.java index 754711ce..c65dc81c 100644 --- a/src/main/java/com/iemr/flw/integration/provider/emrlite/EmrLiteProvider.java +++ b/src/main/java/com/iemr/flw/integration/provider/emrlite/EmrLiteProvider.java @@ -7,6 +7,7 @@ import com.iemr.flw.integration.provider.DiagnosticCancelResult; import com.iemr.flw.integration.provider.DiagnosticDocumentAsset; import com.iemr.flw.integration.provider.DiagnosticPollResult; +import com.iemr.flw.integration.provider.TrueNatResultRules; import com.iemr.flw.integration.provider.DiagnosticProvider; import com.iemr.flw.integration.provider.DiagnosticPushResult; import com.iemr.flw.integration.provider.emrlite.dto.*; @@ -37,11 +38,10 @@ public class EmrLiteProvider implements DiagnosticProvider { private static final Logger logger = LoggerFactory.getLogger(EmrLiteProvider.class); private static final String PROVIDER_CODE = DiagnosticProviderCode.EMRLITE.name(); - private static final String SUMMARY_TB_POSITIVE = "TB Positive"; - private static final String SUMMARY_TB_NEGATIVE = "TB Negative"; - private static final String SUMMARY_DR_TB = "DR TB"; - private static final String SUMMARY_NON_DR_TB = "Non DR TB"; private static final String SUMMARY_TB_PRESUMPTIVE = "TB Presumptive"; + private static final String MDR_RIF_COMPONENT = "mdr_rif"; + private static final String VENDOR_DICOM_CONTENT_TYPE = "dicom/dcm"; + private static final String DICOM_CONTENT_TYPE = "application/dicom"; @Value("${diagnostic.emrlite.xray.order-url}") private String xrayOrderUrl; @@ -147,22 +147,64 @@ public DiagnosticPollResult pollResult(DiagnosticOrder order, boolean includeAss } EmrLiteResultResponse result = gson.fromJson(envelope.getData(), EmrLiteResultResponse.class); - DiagnosticOrderStatus status = deriveOrderStatus(result); + boolean xray = DiagnosticOrderType.XRAY_CHEST.name().equals(order.getOrderType()); + + // TrueNat orders report per component: the test itself under its own orderType key + // ("mtb" / "mtb_plus"), plus "mdr_rif" which the vendor adds when MTB comes back positive. + EmrLiteResultResponse.Component testComponent = xray ? null : component(result, order.getOrderType()); + EmrLiteResultResponse.Component mdrRif = xray ? null : component(result, MDR_RIF_COMPONENT); + String summary = xray || testComponent == null + ? (result.getResult() != null ? result.getResult().getSummary() : null) + : testComponent.getSummary(); + String drugResistanceSummary = mdrRif != null ? mdrRif.getSummary() : null; - String summary = result.getResult() != null ? result.getResult().getSummary() : null; + DiagnosticOrderStatus status = deriveOrderStatus(result); + if (!xray && awaitingMdrRif(summary, mdrRif)) { + // A positive MTB triggers an MDR RIF test on the same order — keep the order PENDING so the + // scheduler keeps polling until the RIF result is in, instead of completing on MTB alone. + status = DiagnosticOrderStatus.PENDING; + } List assets = mapAssets(result); Boolean tbPresence; - Double tbConfidence = null; // dropped for X-ray; MTB/MTB_PLUS/MDR_RIF never populated this either - if (DiagnosticOrderType.XRAY_CHEST.name().equals(order.getOrderType())) { + Double tbConfidence = null; // dropped for X-ray; MTB/MTB_PLUS never populated this either + if (xray) { tbPresence = classifyXrayTbPresenceFromSummary(status, summary); } else { tbPresence = classifyTbPresenceFromSummary(order.getOrderType(), summary); } - Boolean drugResistancePresence = classifyDrugResistanceFromSummary(order.getOrderType(), summary); + Boolean drugResistancePresence = classifyDrugResistanceFromSummary(drugResistanceSummary); + + DiagnosticPollResult pollResult = new DiagnosticPollResult(status, order.getExternalOrderId(), summary, + responseBody, assets, null, tbPresence, tbConfidence, drugResistancePresence, drugResistanceSummary); + pollResult.setDrugResistanceStatus(mdrRif != null && mdrRif.getStatus() != null + ? mdrRif.getStatus().toUpperCase(java.util.Locale.ROOT) : null); + // The MTB test's own status, so a finished MTB is stored COMPLETED even while the order waits + // for RIF (IN_PROGRESS is read as PENDING, as for the order). + pollResult.setMainStatus(testComponent != null && testComponent.getStatus() != null + ? DiagnosticOrderStatus.fromString(testComponent.getStatus()).name() : null); + return pollResult; + } + + private EmrLiteResultResponse.Component component(EmrLiteResultResponse result, String key) { + if (result.getComponents() == null) { + return null; + } + return result.getComponents().entrySet().stream() + .filter(e -> e.getKey().equalsIgnoreCase(key)) + .map(Map.Entry::getValue) + .findFirst() + .orElse(null); + } - return new DiagnosticPollResult(status, order.getExternalOrderId(), summary, responseBody, assets, null, - tbPresence, tbConfidence, drugResistancePresence); + // True while a positive MTB's MDR RIF test hasn't reached a terminal state yet (not created by the + // vendor yet, or still running). A FAILED RIF is terminal — deriveOrderStatus already reports it. + private boolean awaitingMdrRif(String summary, EmrLiteResultResponse.Component mdrRif) { + if (!TrueNatResultRules.needsMdrRif(summary)) { + return false; + } + return mdrRif == null + || !("COMPLETED".equalsIgnoreCase(mdrRif.getStatus()) || "FAILED".equalsIgnoreCase(mdrRif.getStatus())); } @Override @@ -214,31 +256,14 @@ public boolean checkHealth(DiagnosticOrderType orderType) { } Boolean classifyTbPresenceFromSummary(String orderType, String summary) { - if (!DiagnosticOrderType.MTB.name().equals(orderType) && !DiagnosticOrderType.MTB_PLUS.name().equals(orderType)) { - return null; // TB presence isn't tested for this orderType — not applicable, not a confirmed negative - } - if (SUMMARY_TB_POSITIVE.equalsIgnoreCase(summary)) { - return true; - } - if (SUMMARY_TB_NEGATIVE.equalsIgnoreCase(summary)) { - return false; - } - return null; // Error/Indeterminate/anything else — genuinely unknown, not a confirmed negative + return TrueNatResultRules.classifyTbPresence(orderType, summary); } - // MDR_RIF's summary reports rifampicin drug-resistance, not raw TB presence — kept as its own - // field rather than folded into tbPresence. - Boolean classifyDrugResistanceFromSummary(String orderType, String summary) { - if (!DiagnosticOrderType.MDR_RIF.name().equals(orderType)) { - return null; // Drug resistance isn't tested for this orderType — not applicable, not a confirmed negative - } - if (SUMMARY_DR_TB.equalsIgnoreCase(summary)) { - return true; - } - if (SUMMARY_NON_DR_TB.equalsIgnoreCase(summary)) { - return false; - } - return null; // Error/Indeterminate/anything else — genuinely unknown, not a confirmed negative + // The mdr_rif component's summary reports rifampicin drug-resistance, not raw TB presence — kept + // as its own field rather than folded into tbPresence. Null summary = no RIF test (MTB negative, + // X-ray) or not finished yet. + Boolean classifyDrugResistanceFromSummary(String summary) { + return TrueNatResultRules.classifyDrugResistance(summary); } // X-ray summary carries no numeric score (tbConfidence is always null for this order type — @@ -254,7 +279,7 @@ Boolean classifyXrayTbPresenceFromSummary(DiagnosticOrderStatus status, String s // Provider's top-level "status" is unreliable on its own (can report COMPLETED while a // component is still PENDING), so true completion is derived from the components map instead. private DiagnosticOrderStatus deriveOrderStatus(EmrLiteResultResponse result) { - Map components = result.getComponents(); + Map components = result.getComponents(); if (components == null || components.isEmpty()) { return DiagnosticOrderStatus.fromString(result.getStatus()); } @@ -300,18 +325,40 @@ private String describeErrorData(JsonElement data) { return detail.append(")").toString(); } + // X-ray files sit in the top-level result; TrueNat files sit in each component's result, so each + // one is tagged with its component key ("mtb" / "mdr_rif") to keep the two reports apart. private List mapAssets(EmrLiteResultResponse result) { - if (result.getResult() == null || result.getResult().getAssets() == null) { - return new ArrayList<>(); - } List assets = new ArrayList<>(); - for (EmrLiteResultResponse.AssetDto assetDto : result.getResult().getAssets()) { - assets.add(new DiagnosticDocumentAsset( - assetDto.getType(), assetDto.getContentType(), assetDto.getFileName(), assetDto.getBase64())); + if (result.getResult() != null) { + addAssets(assets, result.getResult().getAssets(), null); + } + if (result.getComponents() != null) { + result.getComponents().forEach((key, component) -> { + if (component != null && component.getResult() != null) { + addAssets(assets, component.getResult().getAssets(), key); + } + }); } return assets; } + private void addAssets(List assets, List assetDtos, + String component) { + if (assetDtos == null) { + return; + } + for (EmrLiteResultResponse.AssetDto assetDto : assetDtos) { + assets.add(new DiagnosticDocumentAsset(assetDto.getType(), toStandardContentType(assetDto.getContentType()), + assetDto.getFileName(), assetDto.getBase64(), component)); + } + } + + // EMR Lite labels the X-ray capture "dicom/dcm", which isn't a registered media type — store and + // serve it as the standard application/dicom instead. + private String toStandardContentType(String contentType) { + return VENDOR_DICOM_CONTENT_TYPE.equalsIgnoreCase(contentType) ? DICOM_CONTENT_TYPE : contentType; + } + private String doPost(String url, String jsonBody) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); diff --git a/src/main/java/com/iemr/flw/integration/provider/emrlite/dto/EmrLiteResultResponse.java b/src/main/java/com/iemr/flw/integration/provider/emrlite/dto/EmrLiteResultResponse.java index a9b33bb6..a9f27ca0 100644 --- a/src/main/java/com/iemr/flw/integration/provider/emrlite/dto/EmrLiteResultResponse.java +++ b/src/main/java/com/iemr/flw/integration/provider/emrlite/dto/EmrLiteResultResponse.java @@ -6,6 +6,8 @@ import java.util.List; import java.util.Map; +// XRAY_CHEST carries its summary/assets in the top-level "result"; TrueNat orders (MTB) carry them +// per component instead ("mtb", and "mdr_rif" once a positive MTB triggers it), with no top-level result. @Data @NoArgsConstructor public class EmrLiteResultResponse { @@ -13,14 +15,16 @@ public class EmrLiteResultResponse { private String externalOrderId; private String orderType; private String status; - private Map components; + private Map components; private ResultDto result; @Data @NoArgsConstructor - public static class ComponentStatus { + public static class Component { private String status; private String provider; + private String summary; + private ComponentResultDto result; } @Data @@ -32,6 +36,14 @@ public static class ResultDto { private List assets; } + @Data + @NoArgsConstructor + public static class ComponentResultDto { + private Object rawJson; + private String reportedAt; + private List assets; + } + @Data @NoArgsConstructor public static class AssetDto { diff --git a/src/main/java/com/iemr/flw/masterEnum/DiagnosticCloseStage.java b/src/main/java/com/iemr/flw/masterEnum/DiagnosticCloseStage.java new file mode 100644 index 00000000..61e7e2e2 --- /dev/null +++ b/src/main/java/com/iemr/flw/masterEnum/DiagnosticCloseStage.java @@ -0,0 +1,11 @@ +package com.iemr.flw.masterEnum; + +/** + * Which test a close reason is for, and so which reason_to_close_* column it lands in. A TrueNat + * (MTB / MTB_PLUS) order carries two tests: MTB itself, then MDR RIF after a positive MTB. + */ +public enum DiagnosticCloseStage { + XRAY, // reason_to_close_xray — X-ray not done + MTB, // reason_to_close_mtb — MTB test not done + RIF // reason_to_close_mdrrif — MTB positive, MDR RIF test not done +} diff --git a/src/main/java/com/iemr/flw/masterEnum/DiagnosticDocumentType.java b/src/main/java/com/iemr/flw/masterEnum/DiagnosticDocumentType.java index 3e26e5e5..8a189680 100644 --- a/src/main/java/com/iemr/flw/masterEnum/DiagnosticDocumentType.java +++ b/src/main/java/com/iemr/flw/masterEnum/DiagnosticDocumentType.java @@ -1,7 +1,8 @@ package com.iemr.flw.masterEnum; -// XRAY_CHEST orders can carry up to three distinct artifacts (raw capture, AI-annotated capture, -// CAD report), each needing its own value under the (benRegID, documentType) storage key. +// XRAY_CHEST orders can carry up to three distinct artifacts (raw DICOM capture, AI heatmap, +// CAD report), and an MTB order up to two (the MTB report, plus the MDR RIF report when MTB is +// positive) — each needing its own value under the (externalOrderId, documentType) storage key. public enum DiagnosticDocumentType { XRAY_CHEST, XRAY_CHEST_ANNOTATED, @@ -11,23 +12,31 @@ public enum DiagnosticDocumentType { MDR_RIF_REPORT; private static final String REPORT_ASSET_TYPE = "REPORT"; + private static final String HEATMAP_ASSET_TYPE = "HEATMAP"; private static final String SECONDARY_CAPTURE_ASSET_TYPE = "SECONDARY_CAPTURE"; + private static final String MDR_RIF_COMPONENT = "mdr_rif"; - public static DiagnosticDocumentType from(String orderType, String assetType) { + // component = which test on the order produced the file (see DiagnosticDocumentAsset); only + // TrueNat orders use it, to tell the MDR RIF report apart from the MTB one. + public static DiagnosticDocumentType from(String orderType, String assetType, String component) { DiagnosticOrderType type = DiagnosticOrderType.fromCode(orderType); if (type == DiagnosticOrderType.XRAY_CHEST) { if (REPORT_ASSET_TYPE.equalsIgnoreCase(assetType)) { return CAD; } - if (SECONDARY_CAPTURE_ASSET_TYPE.equalsIgnoreCase(assetType)) { + if (HEATMAP_ASSET_TYPE.equalsIgnoreCase(assetType) + || SECONDARY_CAPTURE_ASSET_TYPE.equalsIgnoreCase(assetType)) { return XRAY_CHEST_ANNOTATED; } - return XRAY_CHEST; + return XRAY_CHEST; // PRIMARY_CAPTURE — the DICOM image + } + if (MDR_RIF_COMPONENT.equalsIgnoreCase(component)) { + return MDR_RIF_REPORT; } switch (type) { case MTB: return MTB_REPORT; case MTB_PLUS: return MTB_PLUS_REPORT; - case MDR_RIF: return MDR_RIF_REPORT; + case MDR_RIF: return MDR_RIF_REPORT; // legacy MDR_RIF orders default: throw new IllegalArgumentException("Unknown orderType for document classification: " + orderType); } } @@ -39,11 +48,10 @@ public DiagnosticOrderType impliedOrderType() { case CAD: return DiagnosticOrderType.XRAY_CHEST; case MTB_REPORT: + case MDR_RIF_REPORT: // MDR RIF runs on the MTB order itself — there is no separate MDR_RIF order return DiagnosticOrderType.MTB; case MTB_PLUS_REPORT: return DiagnosticOrderType.MTB_PLUS; - case MDR_RIF_REPORT: - return DiagnosticOrderType.MDR_RIF; default: throw new IllegalArgumentException("Unknown orderType for document type: " + this); } diff --git a/src/main/java/com/iemr/flw/masterEnum/DiagnosticOrderStatus.java b/src/main/java/com/iemr/flw/masterEnum/DiagnosticOrderStatus.java index ce444fcb..6e24fe26 100644 --- a/src/main/java/com/iemr/flw/masterEnum/DiagnosticOrderStatus.java +++ b/src/main/java/com/iemr/flw/masterEnum/DiagnosticOrderStatus.java @@ -6,7 +6,10 @@ public enum DiagnosticOrderStatus { COMPLETED, FAILED, CLOSED, - MANUAL_ENTRY; + MANUAL_ENTRY, + // MTB/RIF test came back invalid (e.g. "Error-2"); the TrueNat machine retests the same order by + // itself, so the order is not closed — it keeps being polled until the retest result arrives. + INVALID; public static DiagnosticOrderStatus fromString(String value) { if (value == null) return PENDING; diff --git a/src/main/java/com/iemr/flw/masterEnum/DiagnosticResultType.java b/src/main/java/com/iemr/flw/masterEnum/DiagnosticResultType.java new file mode 100644 index 00000000..7cd6441f --- /dev/null +++ b/src/main/java/com/iemr/flw/masterEnum/DiagnosticResultType.java @@ -0,0 +1,13 @@ +package com.iemr.flw.masterEnum; + +/** + * Which test a tb_diagnostic_result row holds. An order has one row for its own test (named like its + * orderType) and, for MTB / MTB_PLUS, a second MDR_RIF row once the RIF test exists (run after a + * positive MTB on the same order). + */ +public enum DiagnosticResultType { + XRAY_CHEST, + MTB, + MTB_PLUS, + MDR_RIF +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/DiagnosticDocumentRepo.java b/src/main/java/com/iemr/flw/repo/iemr/DiagnosticDocumentRepo.java index b7565205..2b0e48cf 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/DiagnosticDocumentRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/DiagnosticDocumentRepo.java @@ -15,6 +15,8 @@ public interface DiagnosticDocumentRepo extends JpaRepository findByExternalOrderIdAndDocumentTypeAndDeletedFalse(String externalOrderId, String documentType); + boolean existsByExternalOrderIdAndDeletedFalse(String externalOrderId); + @Transactional @Modifying @Query("UPDATE DiagnosticDocument d SET d.vanSerialNo = d.id WHERE d.id = :id") diff --git a/src/main/java/com/iemr/flw/repo/iemr/DiagnosticOrderRepo.java b/src/main/java/com/iemr/flw/repo/iemr/DiagnosticOrderRepo.java index bba6e3c6..6234c341 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/DiagnosticOrderRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/DiagnosticOrderRepo.java @@ -33,16 +33,34 @@ Optional findFirstByBeneficiaryIdAndOrderTypeAndDeletedFalseOrd List findXrayDueForPoll(); @Query("SELECT o FROM DiagnosticOrder o WHERE o.orderType IN ('MTB', 'MTB_PLUS', 'MDR_RIF') " + - "AND o.status IN ('PENDING', 'IN_PROGRESS') " + + "AND o.status IN ('PENDING', 'IN_PROGRESS', 'INVALID') " + "AND o.deleted = false " + "ORDER BY o.lastPolledAt ASC NULLS FIRST") List findTrueNatDueForPoll(); // The (disabled) daily close only touches orders created within [dayStart, dayEnd) — i.e. today's. - @Query("SELECT o FROM DiagnosticOrder o WHERE o.status IN ('PENDING', 'IN_PROGRESS') AND o.deleted = false " + + @Query("SELECT o FROM DiagnosticOrder o WHERE o.status IN ('PENDING', 'IN_PROGRESS', 'INVALID') AND o.deleted = false " + "AND o.createdDate >= :dayStart AND o.createdDate < :dayEnd") List findAllOutstandingOrders(@Param("dayStart") Timestamp dayStart, @Param("dayEnd") Timestamp dayEnd); + // COMPLETED orders the vendor accepted (providerOrderId is set only on a successful push) whose + // documents still need fetching: no stored document at all, or an MTB/MTB_PLUS order whose MTB + // result is TB Positive but has no MDR RIF report yet (the vendor adds the RIF test, and its + // report, after a positive MTB). Mostly orders whose result was entered manually, which the poll + // no longer visits. Excludes orders the vendor never received: no-vendor orders and failed pushes. + @Query("SELECT o FROM DiagnosticOrder o WHERE o.deleted = false " + + "AND o.externalOrderId IS NOT NULL AND o.providerOrderId IS NOT NULL " + + "AND o.status = 'COMPLETED' " + + "AND (NOT EXISTS (SELECT d.id FROM DiagnosticDocument d " + + " WHERE d.externalOrderId = o.externalOrderId AND d.deleted = false) " + + " OR (o.orderType IN ('MTB', 'MTB_PLUS') " + + " AND EXISTS (SELECT r.id FROM DiagnosticResult r WHERE r.externalOrderId = o.externalOrderId " + + " AND r.deleted = false AND r.resultType IN ('MTB', 'MTB_PLUS') AND r.resultSummary = 'TB Positive') " + + " AND NOT EXISTS (SELECT d.id FROM DiagnosticDocument d WHERE d.externalOrderId = o.externalOrderId " + + " AND d.deleted = false AND d.documentType = 'MDR_RIF_REPORT'))) " + + "ORDER BY o.createdDate ASC") + List findOrdersNeedingDocuments(); + @Transactional @Modifying @Query("UPDATE DiagnosticOrder o SET o.vanSerialNo = o.id WHERE o.id = :id") @@ -115,7 +133,7 @@ List findBeneficiaryIdsAwaitingManualEntry(@Param("orderType") String orde // The five queries above in one pass: beneficiaryId + status of each beneficiary's latest order, // same filters, for the caller to bucket by status. @Query("SELECT o.beneficiaryId, o.status FROM DiagnosticOrder o WHERE o.orderType = :orderType AND o.deleted = false " + - "AND o.status IN ('PENDING', 'IN_PROGRESS', 'COMPLETED', 'FAILED', 'CLOSED', 'CANCELLED', 'EXPIRED', 'REFUSED', 'MANUAL_ENTRY') " + + "AND o.status IN ('PENDING', 'IN_PROGRESS', 'COMPLETED', 'FAILED', 'CLOSED', 'CANCELLED', 'EXPIRED', 'REFUSED', 'MANUAL_ENTRY', 'INVALID') " + "AND o.id = (SELECT MAX(o2.id) FROM DiagnosticOrder o2 " + "WHERE o2.beneficiaryId = o.beneficiaryId AND o2.orderType = :orderType AND o2.deleted = false) " + "AND o.beneficiaryId IN (SELECT b.beneficiaryID FROM BenFlowStatus b WHERE b.deleted = false " + @@ -130,7 +148,7 @@ List findLatestOrderStatusByBeneficiary(@Param("orderType") String ord // earlier day, which createAndPushOrder would return instead of creating a new one anyway. @Query("SELECT COUNT(o) > 0 FROM DiagnosticOrder o WHERE o.beneficiaryId = :beneficiaryId " + "AND o.orderType = :orderType AND o.deleted = false " + - "AND (o.createdDate >= :dayStart OR o.status IN ('PENDING', 'IN_PROGRESS', 'COMPLETED', 'MANUAL_ENTRY'))") + "AND (o.createdDate >= :dayStart OR o.status IN ('PENDING', 'IN_PROGRESS', 'COMPLETED', 'MANUAL_ENTRY', 'INVALID'))") boolean hasOrderTodayOrOpen(@Param("beneficiaryId") Long beneficiaryId, @Param("orderType") String orderType, @Param("dayStart") Timestamp dayStart); } diff --git a/src/main/java/com/iemr/flw/repo/iemr/DiagnosticResultRepo.java b/src/main/java/com/iemr/flw/repo/iemr/DiagnosticResultRepo.java index 00d4fd26..98b1fe57 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/DiagnosticResultRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/DiagnosticResultRepo.java @@ -8,12 +8,19 @@ import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; +import java.util.List; import java.util.Optional; @Repository public interface DiagnosticResultRepo extends JpaRepository { - Optional findByExternalOrderIdAndDeletedFalse(String externalOrderId); + // One order has a row per test (resultType): its own test, plus MDR_RIF on MTB/MTB_PLUS orders. + Optional findByExternalOrderIdAndResultTypeAndDeletedFalse(String externalOrderId, String resultType); + + // Including soft-deleted rows: the unique (external_order_id, result_type) key covers them too. + Optional findByExternalOrderIdAndResultType(String externalOrderId, String resultType); + + List findAllByExternalOrderIdAndDeletedFalse(String externalOrderId); @Transactional @Modifying diff --git a/src/main/java/com/iemr/flw/repo/iemr/OptionConditionRepo.java b/src/main/java/com/iemr/flw/repo/iemr/OptionConditionRepo.java index 7ec5cad5..ecf9f09a 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/OptionConditionRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/OptionConditionRepo.java @@ -51,6 +51,17 @@ Optional findByQuestionOption_OptionIdAndActionTypeAndTargetSec + "AND oc.targetQuestion IS NOT NULL") List findTargetQuestionIdsByVersionId(@Param("versionId") Long versionId); + /** + * Parent → child edges of the SHOW_QUESTION graph for a version, as + * [parentQuestionId, targetQuestionId] pairs. Active conditions only. + */ + @Query("SELECT oc.questionOption.sectionQuestion.questionId, oc.targetQuestion.questionId " + + "FROM OptionCondition oc " + + "WHERE oc.questionOption.sectionQuestion.formSection.formVersion.versionId = :versionId " + + "AND oc.actionType = 'SHOW_QUESTION' AND oc.targetQuestion IS NOT NULL " + + "AND oc.isActive = true") + List findShowQuestionEdgesByVersionId(@Param("versionId") Long versionId); + /** * Loads all conditions for a set of options in one query. * JOIN FETCH ensures questionOption, targetQuestion, and targetSection are hydrated diff --git a/src/main/java/com/iemr/flw/repo/iemr/QuestionResponseRepo.java b/src/main/java/com/iemr/flw/repo/iemr/QuestionResponseRepo.java index 4ba957b5..c9e91dfc 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/QuestionResponseRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/QuestionResponseRepo.java @@ -43,10 +43,10 @@ public interface QuestionResponseRepo extends JpaRepository findBySectionResponseIdIn(Collection sectionResponseIds); - void deleteByQuestionIdAndSectionResponseId(Long questionId, Long sectionResponseId); - void deleteBySectionResponseIdIn(Collection sectionResponseIds); + void deleteBySectionResponseIdAndQuestionIdIn(Long sectionResponseId, Collection questionIds); + // See SectionResponseRepo.updateVanSerialNo for why this is a targeted UPDATE, not a // second full-entity save. @Modifying diff --git a/src/main/java/com/iemr/flw/service/DiagnosticOrderService.java b/src/main/java/com/iemr/flw/service/DiagnosticOrderService.java index 42fb1c33..71beae39 100644 --- a/src/main/java/com/iemr/flw/service/DiagnosticOrderService.java +++ b/src/main/java/com/iemr/flw/service/DiagnosticOrderService.java @@ -35,6 +35,17 @@ public interface DiagnosticOrderService { */ void expireOrder(DiagnosticOrder order, String reason) throws Exception; + /** + * Document back-fill: fetches the vendor's documents for an order that needs them (see + * DiagnosticOrderRepo.findOrdersNeedingDocuments) and stores any it returns. When the order's + * result was entered manually, the vendor's result also overwrites it wherever they differ. + * Skipped (returns false) if the beneficiary is busy, the order is no longer COMPLETED, or the + * vendor returned neither documents nor a differing result. + * + * @return true when documents were stored or the manual result was overwritten + */ + boolean fetchMissingDocuments(DiagnosticOrder order) throws Exception; + DiagnosticOrderResultDto triggerManualPoll(Long beneficiaryId, String orderType, Long visitCode) throws Exception; DiagnosticOrder retryPoll(Long beneficiaryId, String orderType, Long visitCode) throws Exception; diff --git a/src/main/java/com/iemr/flw/service/impl/ConditionalAnswerPruner.java b/src/main/java/com/iemr/flw/service/impl/ConditionalAnswerPruner.java new file mode 100644 index 00000000..e0c7194a --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/ConditionalAnswerPruner.java @@ -0,0 +1,88 @@ +/* + * AMRIT – Accessible Medical Records via Integrated Technology + * Integrated EHR (Electronic Health Records) Solution + * + * Copyright (C) "Piramal Swasthya Management and Research Institute" + * + * This file is part of AMRIT. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see https://www.gnu.org/licenses/. + */ +package com.iemr.flw.service.impl; + +import com.iemr.flw.repo.iemr.OptionConditionRepo; +import com.iemr.flw.repo.iemr.QuestionResponseRepo; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import java.util.ArrayDeque; +import java.util.Collection; +import java.util.Deque; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +/** + * Clears answers before a re-save so that SHOW_QUESTION children hidden by an edited parent + * don't keep their stale answers. For every question being saved, its own answer and the answers + * of all its descendants (children, grandchildren, …) are deleted; children that are still visible + * are re-sent by the client alongside their parent and get re-inserted. + * + * @author Piramal Swasthya + */ +@RequiredArgsConstructor +@Component +public class ConditionalAnswerPruner { + + private final OptionConditionRepo optionConditionRepo; + private final QuestionResponseRepo questionResponseRepo; + + /** parentQuestionId → questionIds shown by any of its options. Load once per save. */ + public Map> loadChildrenByParent(Long versionId) { + Map> childrenByParent = new HashMap<>(); + for (Object[] edge : optionConditionRepo.findShowQuestionEdgesByVersionId(versionId)) { + childrenByParent.computeIfAbsent((Long) edge[0], k -> new HashSet<>()).add((Long) edge[1]); + } + return childrenByParent; + } + + /** + * Deletes, within one section response, the answers of the given questions plus all their + * descendants. Must run before any new answers are inserted, otherwise a parent processed after + * its child would wipe the child's freshly inserted answer. + */ + public void deleteWithDescendants(Long sectionResponseId, Collection questionIds, + Map> childrenByParent) { + if (questionIds.isEmpty()) { + return; + } + Set toDelete = collectWithDescendants(questionIds, childrenByParent); + questionResponseRepo.deleteBySectionResponseIdAndQuestionIdIn(sectionResponseId, toDelete); + } + + /** BFS over the SHOW_QUESTION graph; the visited set also guards against misconfigured cycles. */ + static Set collectWithDescendants(Collection roots, Map> childrenByParent) { + Set visited = new LinkedHashSet<>(); + Deque queue = new ArrayDeque<>(roots); + while (!queue.isEmpty()) { + Long questionId = queue.poll(); + if (visited.add(questionId)) { + queue.addAll(childrenByParent.getOrDefault(questionId, Set.of())); + } + } + return visited; + } +} diff --git a/src/main/java/com/iemr/flw/service/impl/DiagnosticDocumentServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiagnosticDocumentServiceImpl.java index 6c0f1f58..54f1e7a2 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiagnosticDocumentServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiagnosticDocumentServiceImpl.java @@ -16,6 +16,9 @@ import org.springframework.dao.DataIntegrityViolationException; import org.springframework.stereotype.Service; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -25,12 +28,16 @@ import java.util.Base64; import java.util.Locale; import java.util.Optional; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; @Service public class DiagnosticDocumentServiceImpl implements DiagnosticDocumentService { private static final Logger logger = LoggerFactory.getLogger(DiagnosticDocumentServiceImpl.class); private static final String DEFAULT_CONTENT_TYPE = "application/pdf"; + // Files are gzipped before encryption (raw DICOMs are ~3x smaller); older files are plain ".enc". + private static final String GZIP_ENCRYPTED_FILE_SUFFIX = ".gz.enc"; @Value("${diagnostic.documents.storage-root}") private String storageRoot; @@ -56,7 +63,7 @@ public void ingestAsset(Long beneficiaryId, String orderType, String externalOrd byte[] originalBytes = Base64.getDecoder().decode(asset.getBase64Content()); String sha256Hash = sha256Hex(originalBytes); - DiagnosticDocumentType documentType = DiagnosticDocumentType.from(orderType, asset.getType()); + DiagnosticDocumentType documentType = DiagnosticDocumentType.from(orderType, asset.getType(), asset.getComponent()); Optional existing = diagnosticDocumentRepo .findByExternalOrderIdAndDocumentTypeAndDeletedFalse(externalOrderId, documentType.name()); if (existing.isPresent() && sha256Hash.equals(existing.get().getSha256Hash())) { @@ -66,12 +73,13 @@ public void ingestAsset(Long beneficiaryId, String orderType, String externalOrd } long epochTime = Instant.now().toEpochMilli(); - String storedFileName = externalOrderId + ".enc"; + String storedFileName = externalOrderId + GZIP_ENCRYPTED_FILE_SUFFIX; String relativeDir = beneficiaryId + "/" + orderType + "/" + documentType.name(); // Documents must never touch disk unencrypted: encrypt in memory first, write only ciphertext. - String base64Original = Base64.getEncoder().encodeToString(originalBytes); - String encryptedPayload = cryptoUtil.encrypt(base64Original); + // Compress before encrypting - ciphertext doesn't compress. The hash stays that of the original. + String base64Compressed = Base64.getEncoder().encodeToString(gzip(originalBytes)); + String encryptedPayload = cryptoUtil.encrypt(base64Compressed); Path dir = Paths.get(storageRoot, relativeDir); Files.createDirectories(dir); @@ -79,6 +87,7 @@ public void ingestAsset(Long beneficiaryId, String orderType, String externalOrd Files.write(filePath, encryptedPayload.getBytes(StandardCharsets.UTF_8)); DiagnosticDocument document = existing.orElseGet(DiagnosticDocument::new); + String previousStoredPath = document.getStoredPath(); if (document.getVanID() == null) { // Inherit from the parent order rather than re-reading Redis — the document belongs // to whichever van originated the order, not whichever van happens to be polling now. @@ -106,6 +115,10 @@ public void ingestAsset(Long beneficiaryId, String orderType, String externalOrd logger.warn("Lost document upsert race for externalOrderId={}, documentType={}", externalOrderId, documentType); return; } + // A replaced legacy ".enc" file isn't overwritten by the new ".gz.enc" one, so remove it. + if (previousStoredPath != null && !previousStoredPath.equals(document.getStoredPath())) { + Files.deleteIfExists(Paths.get(storageRoot, previousStoredPath)); + } logger.info("Diagnostic document ingested: beneficiaryId={}, orderType={}, epochTime={}", beneficiaryId, orderType, epochTime); @@ -134,11 +147,12 @@ public DiagnosticDocumentContent fetch(Long beneficiaryId, DiagnosticDocumentTyp Path filePath = Paths.get(storageRoot, document.getStoredPath()); String encryptedPayload = new String(Files.readAllBytes(filePath), StandardCharsets.UTF_8); - String base64Original = cryptoUtil.decrypt(encryptedPayload); - if (base64Original == null) { + String base64Content = cryptoUtil.decrypt(encryptedPayload); + if (base64Content == null) { throw new Exception("Failed to decrypt document for beneficiaryId=" + beneficiaryId + ", documentType=" + documentType); } - byte[] originalBytes = Base64.getDecoder().decode(base64Original); + byte[] content = Base64.getDecoder().decode(base64Content); + byte[] originalBytes = document.getStoredPath().endsWith(GZIP_ENCRYPTED_FILE_SUFFIX) ? gunzip(content) : content; String recomputedHash = sha256Hex(originalBytes); if (!recomputedHash.equals(document.getSha256Hash())) { @@ -152,6 +166,20 @@ public DiagnosticDocumentContent fetch(Long beneficiaryId, DiagnosticDocumentTyp return new DiagnosticDocumentContent(originalBytes, document.getContentType()); } + private static byte[] gzip(byte[] data) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try (GZIPOutputStream gz = new GZIPOutputStream(out)) { + gz.write(data); + } + return out.toByteArray(); + } + + private static byte[] gunzip(byte[] compressed) throws IOException { + try (GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(compressed))) { + return in.readAllBytes(); + } + } + private static String sha256Hex(byte[] data) throws Exception { byte[] digest = MessageDigest.getInstance("SHA-256").digest(data); StringBuilder hex = new StringBuilder(digest.length * 2); diff --git a/src/main/java/com/iemr/flw/service/impl/DiagnosticOrderServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiagnosticOrderServiceImpl.java index 913a747a..367439c6 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiagnosticOrderServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiagnosticOrderServiceImpl.java @@ -7,18 +7,23 @@ import com.iemr.flw.domain.iemr.User; import com.iemr.flw.dto.DiagnosticOrderRequestDto; import com.iemr.flw.dto.DiagnosticOrderResultDto; +import com.iemr.flw.dto.DiagnosticResultItemDto; import com.iemr.flw.dto.DiagnosticOrderStatusSummaryDto; import com.iemr.flw.dto.ManualDiagnosticResultRequestDto; import com.iemr.flw.dto.VendorHealthDto; import com.iemr.flw.integration.provider.DiagnosticCancelResult; import com.iemr.flw.integration.provider.DiagnosticDocumentAsset; import com.iemr.flw.integration.provider.DiagnosticPollResult; +import com.iemr.flw.integration.provider.TrueNatResultRules; import com.iemr.flw.integration.provider.DiagnosticProvider; import com.iemr.flw.integration.provider.DiagnosticProviderFactory; import com.iemr.flw.integration.provider.DiagnosticPushResult; import com.iemr.flw.masterEnum.DiagnosticOrderStatus; +import com.iemr.flw.masterEnum.DiagnosticCloseStage; +import com.iemr.flw.masterEnum.DiagnosticResultType; import com.iemr.flw.masterEnum.DiagnosticOrderType; import com.iemr.flw.repo.identity.BeneficiaryRepo; +import com.iemr.flw.repo.iemr.DiagnosticDocumentRepo; import com.iemr.flw.repo.iemr.DiagnosticOrderRepo; import com.iemr.flw.repo.iemr.DiagnosticResultRepo; import com.iemr.flw.repo.iemr.EmployeeMasterRepo; @@ -56,7 +61,8 @@ public class DiagnosticOrderServiceImpl implements DiagnosticOrderService { private static final Set BLOCKING_STATUSES = Set.of( DiagnosticOrderStatus.PENDING.name(), DiagnosticOrderStatus.COMPLETED.name(), - DiagnosticOrderStatus.MANUAL_ENTRY.name()); + DiagnosticOrderStatus.MANUAL_ENTRY.name(), + DiagnosticOrderStatus.INVALID.name()); private static final Set NON_REUSABLE_ON_CLOSE_STATUSES = Set.of( DiagnosticOrderStatus.COMPLETED.name(), @@ -64,15 +70,18 @@ public class DiagnosticOrderServiceImpl implements DiagnosticOrderService { DiagnosticOrderStatus.CLOSED.name()); // Statuses the scheduler polls and the daily cutoff expires — matches findXrayDueForPoll / - // findTrueNatDueForPoll / findAllOutstandingOrders. + // findTrueNatDueForPoll / findAllOutstandingOrders. INVALID (TrueNat only) is still polled: the + // machine retests the same order itself and the retest result arrives on it later. private static final Set OUTSTANDING_STATUSES = Set.of( DiagnosticOrderStatus.PENDING.name(), - DiagnosticOrderStatus.IN_PROGRESS.name()); + DiagnosticOrderStatus.IN_PROGRESS.name(), + DiagnosticOrderStatus.INVALID.name()); // Invalid test outcomes: the result is still recorded (result row, tb_suspected write-back, documents) // but the order is CLOSED instead of COMPLETED, so a retest can be pushed. The vendor reports an - // invalid MTB/MDR_RIF run as "Error-2"; a manual entry uses "Invalid/Error". + // invalid MTB run as "Error-2"; a manual entry uses "Invalid/Error". private static final String XRAY_INVALID_RESULT = "AI Invalid Result"; + private static final String XRAY_TB_PRESUMPTIVE = "TB Presumptive"; private static final String SPUTUM_INVALID_POLLED_RESULT = "Error-2"; private static final String SPUTUM_INVALID_MANUAL_RESULT = "Invalid/Error"; @@ -91,6 +100,9 @@ public class DiagnosticOrderServiceImpl implements DiagnosticOrderService { @Autowired private DiagnosticDocumentService diagnosticDocumentService; + @Autowired + private DiagnosticDocumentRepo diagnosticDocumentRepo; + @Autowired private CampConfigService campConfigService; @@ -204,10 +216,14 @@ private DiagnosticOrder createAndPushOrderLocked(DiagnosticOrderRequestDto reque String patientDateOfBirth = request.getPatient().getDateOfBirth(); String patientSex = request.getPatient().getSex(); - String reasonToClose = request.getReasonToClose(); - if (reasonToClose != null) { + CloseReason close = resolveCloseReason(orderType, request.getReasonToCloseXray(), + request.getReasonToCloseMTB(), request.getReasonToCloseRif()); + if (close != null) { + if (close.stage() == DiagnosticCloseStage.RIF) { + return closeRifStageLocked(beneficiaryId, orderType, close.reason(), createdBy); + } return closeOrder(beneficiaryId, orderType, orderEvent, patientFirstName, patientLastName, - patientDateOfBirth, patientSex, reasonToClose, createdBy); + patientDateOfBirth, patientSex, close, createdBy); } Integer vanID = campConfigService.getVanID(); @@ -327,12 +343,12 @@ private DiagnosticOrder pushToProvider(DiagnosticOrder order, String providerCod return order; } - // Shared by createAndPushOrder (push with reasonToClose) and submitManualResult (manualResult - // with reasonToClose) — resolves the same visit/provider/externalOrderId a normal push would, then + // Shared by createAndPushOrder (push with a reasonToClose*) and submitManualResult (manualResult + // with a reasonToClose*) for the XRAY and MTB stages — resolves the same visit/provider/externalOrderId a normal push would, then // closes the order via saveRefusedOrder. Identical outcome regardless of which endpoint triggered it. private DiagnosticOrder closeOrder(Long beneficiaryId, DiagnosticOrderType orderType, String orderEvent, String patientFirstName, String patientLastName, String patientDateOfBirth, String patientSex, - String reasonToClose, String actingUserId) throws Exception { + CloseReason close, String actingUserId) throws Exception { Integer vanID = campConfigService.getVanID(); Integer parkingPlaceID = campConfigService.getParkingPlaceID(); @@ -347,21 +363,24 @@ private DiagnosticOrder closeOrder(Long beneficiaryId, DiagnosticOrderType order String providerCode = providerFactory.getProviderCodeForOrderType(orderType); String externalOrderId = String.format("%s-%d-%s", UUID.randomUUID(), visitCode, orderType.name()); return saveRefusedOrder(beneficiaryId, visitCode, orderType, orderEvent, providerCode, externalOrderId, - patientFirstName, patientLastName, patientDateOfBirth, patientSex, reasonToClose, actingUserId); + patientFirstName, patientLastName, patientDateOfBirth, patientSex, close, actingUserId); } // manualResult's reasonToClose variant has no patient/orderEvent in its request — it sources them // from the beneficiary's own most recent order for this orderType (whatever its status), since that // information already exists there. No prior order at all means there's nothing to source it from. private DiagnosticOrder closeOrderManually(Long beneficiaryId, DiagnosticOrderType orderType, - String reasonToClose, String actingUserId) throws Exception { + CloseReason close, String actingUserId) throws Exception { return withBeneficiaryLock(beneficiaryId, () -> { + if (close.stage() == DiagnosticCloseStage.RIF) { + return closeRifStageLocked(beneficiaryId, orderType, close.reason(), actingUserId); + } DiagnosticOrder source = diagnosticOrderRepo .findFirstByBeneficiaryIdAndOrderTypeAndDeletedFalseOrderByCreatedDateDesc(beneficiaryId, orderType.name()) .orElseThrow(() -> new Exception("No diagnostic order found for beneficiaryId=" + beneficiaryId + ", orderType=" + orderType.name() + " — cannot close a record that was never created")); return closeOrder(beneficiaryId, orderType, source.getOrderEvent(), source.getPatientFirstName(), - source.getPatientLastName(), source.getPatientDateOfBirth(), source.getPatientSex(), reasonToClose, + source.getPatientLastName(), source.getPatientDateOfBirth(), source.getPatientSex(), close, actingUserId); }); } @@ -373,7 +392,7 @@ private DiagnosticOrder closeOrderManually(Long beneficiaryId, DiagnosticOrderTy // Refused orders are saved as-is and never pushed to the vendor. private DiagnosticOrder saveRefusedOrder(Long beneficiaryId, Long visitCode, DiagnosticOrderType orderType, String orderEvent, String providerCode, String externalOrderId, String patientFirstName, - String patientLastName, String patientDateOfBirth, String patientSex, String reasonToClose, + String patientLastName, String patientDateOfBirth, String patientSex, CloseReason close, String actingUserId) { Optional latest = diagnosticOrderRepo .findFirstByBeneficiaryIdAndOrderTypeAndDeletedFalseOrderByCreatedDateDesc(beneficiaryId, orderType.name()); @@ -401,7 +420,7 @@ private DiagnosticOrder saveRefusedOrder(Long beneficiaryId, Long visitCode, Dia order.setCreatedBy(actingUserId); } order.setStatus(DiagnosticOrderStatus.CLOSED.name()); - order.setReasonToClose(reasonToClose); + order.setReasonToClose(close.stage(), close.reason()); order.setErrorMessage(null); order.setModifiedBy(actingUserId); order.setManuallyEnteredBy(actingUserId); @@ -410,7 +429,7 @@ private DiagnosticOrder saveRefusedOrder(Long beneficiaryId, Long visitCode, Dia try { order = diagnosticOrderRepo.save(order); if (order.getVanSerialNo() == null) diagnosticOrderRepo.updateVanSerialNo(order.getId()); - notifyProviderOrderClosed(order, reasonToClose); + notifyProviderOrderClosed(order, close.reason()); return order; } catch (DataIntegrityViolationException dive) { Optional winner = diagnosticOrderRepo @@ -451,61 +470,58 @@ public DiagnosticOrderResultDto processResult(DiagnosticOrder order, DiagnosticP return processResult(order, pollResult, false, "SYSTEM"); } + // Saves a poll/manual outcome. Results are one tb_diagnostic_result row per test: the order's own + // test (resultType = orderType) and, on MTB/MTB_PLUS orders, an MDR_RIF row once RIF data exists. private DiagnosticOrderResultDto processResult(DiagnosticOrder order, DiagnosticPollResult pollResult, boolean writeBackWhenClosed, String actingUser) throws Exception { - Optional existingResult = diagnosticResultRepo.findByExternalOrderIdAndDeletedFalse(order.getExternalOrderId()); + Optional existingMain = mainResult(order); + Optional existingRif = rifResult(order); + boolean hasRif = hasRifData(pollResult); + // The MTB result no longer calls for RIF (e.g. the vendor corrected a positive to negative) and + // no RIF result came with it: the stored RIF row is stale and is invalidated below. + boolean dropRif = existingRif.isPresent() && !hasRif && rifNoLongerNeeded(order, pollResult.getResultSummary()); // A poll that brings nothing new must not rewrite the rows: every rewrite resets processed // (so MMU re-uploads the order) and would re-send it to every tablet. - boolean resultUnchanged = existingResult.isPresent() && sameResult(existingResult.get(), pollResult); + boolean mainUnchanged = existingMain.isPresent() && sameMainResult(order, existingMain.get(), pollResult); + boolean rifUnchanged = !dropRif + && (!hasRif || (existingRif.isPresent() && sameRifResult(existingRif.get(), pollResult))); boolean orderUnchanged = sameOrderStatus(order, pollResult); - DiagnosticResult result = existingResult.orElseGet(DiagnosticResult::new); - if (resultUnchanged && orderUnchanged && !writeBackWhenClosed) { + if (mainUnchanged && rifUnchanged && orderUnchanged && !writeBackWhenClosed) { ingestAssets(order, pollResult); diagnosticOrderRepo.recordUnchangedPoll(order.getId(), new Timestamp(System.currentTimeMillis()), order.getRetryCount()); - DiagnosticOrderResultDto unchanged = new DiagnosticOrderResultDto(); - unchanged.setExternalOrderId(order.getExternalOrderId()); - unchanged.setOrderType(order.getOrderType()); - unchanged.setStatus(order.getStatus()); - unchanged.setProviderStatus(result.getProviderStatus()); - unchanged.setResultSummary(result.getResultSummary()); - unchanged.setErrorMessage(order.getErrorMessage()); - unchanged.setReasonToClose(order.getReasonToClose()); - unchanged.setTbPresence(result.getTbPresence()); - unchanged.setTbConfidence(result.getTbConfidence()); - unchanged.setDrugResistancePresence(result.getDrugResistancePresence()); + DiagnosticOrderResultDto unchanged = toResultDto(order); + applyResults(unchanged, existingMain.orElse(null), existingRif.orElse(null)); return unchanged; } - result.setExternalOrderId(order.getExternalOrderId()); - result.setBeneficiaryId(order.getBeneficiaryId()); - result.setProviderStatus(pollResult.getStatus().name()); - result.setResultSummary(pollResult.getResultSummary()); - // The vendor embeds each asset's base64 file content directly inline in its response body - // when assets are requested — never persist that raw JSON verbatim (it's unencrypted, unlike - // the same content on local disk). Only store rawResponseJson from the asset-free call. - if (pollResult.getAssets() == null || pollResult.getAssets().isEmpty()) { - result.setRawResponseJson(pollResult.getRawResponseJson()); - } - result.setTbPresence(pollResult.getTbPresence()); - result.setTbConfidence(pollResult.getTbConfidence()); - result.setDrugResistancePresence(pollResult.getDrugResistancePresence()); - result.setCreatedBy(actingUser); - result.setModifiedBy(actingUser); - if (result.getVanID() == null) { - // Inherit from the parent order rather than re-reading Redis — the result belongs - // to whichever van originated the order, not whichever van happens to be polling now. - result.setVanID(order.getVanID()); - result.setParkingPlaceID(order.getParkingPlaceID()); - } - try { - diagnosticResultRepo.save(result); - if (result.getVanSerialNo() == null) diagnosticResultRepo.updateVanSerialNo(result.getId()); - } catch (DataIntegrityViolationException dive) { - // Only a first insert can lose a race (unique external_order_id). Any other integrity - // failure means the result was not saved, so the order must not move on without it. - if (existingResult.isPresent()) throw dive; - logger.warn("Lost result upsert race for externalOrderId={}", order.getExternalOrderId()); - result = diagnosticResultRepo.findByExternalOrderIdAndDeletedFalse(order.getExternalOrderId()).orElse(result); + + DiagnosticResult main = saveResultRow(order, existingMain, order.getOrderType(), actingUser, row -> { + row.setProviderStatus(mainRowStatus(order, pollResult)); + row.setResultSummary(pollResult.getResultSummary()); + // The vendor embeds each asset's base64 file content directly inline in its response body + // when assets are requested — never persist that raw JSON verbatim (it's unencrypted, unlike + // the same content on local disk). Only store rawResponseJson from the asset-free call. + if (pollResult.getAssets() == null || pollResult.getAssets().isEmpty()) { + row.setRawResponseJson(pollResult.getRawResponseJson()); + } + row.setTbPresence(pollResult.getTbPresence()); + row.setTbConfidence(pollResult.getTbConfidence()); + }); + DiagnosticResult rif = existingRif.orElse(null); + if (hasRif) { + rif = saveResultRow(order, existingRif, DiagnosticResultType.MDR_RIF.name(), actingUser, row -> { + row.setProviderStatus(rifStatus(pollResult)); + row.setResultSummary(blankToNull(pollResult.getDrugResistanceSummary())); + row.setDrugResistancePresence(pollResult.getDrugResistancePresence()); + }); + } else if (dropRif) { + DiagnosticResult stale = existingRif.get(); + logger.warn("Invalidating MDR_RIF result '{}' for externalOrderId={}: MTB result is now '{}'", + stale.getResultSummary(), order.getExternalOrderId(), pollResult.getResultSummary()); + stale.setDeleted(true); + stale.setModifiedBy(actingUser); + diagnosticResultRepo.save(stale); + rif = null; } ingestAssets(order, pollResult); @@ -520,25 +536,98 @@ private DiagnosticOrderResultDto processResult(DiagnosticOrder order, Diagnostic order.setProcessed("N"); diagnosticOrderRepo.save(order); + // writeBackWhenClosed is set by the manual paths (manual entry, closing the RIF test, the + // vendor replacing a manual result) and for invalid outcomes. On those paths a positive MTB + // still waiting for RIF (PENDING for a vendor order, MANUAL_ENTRY without one) is written to + // tb_suspected straight away too; mdrRifResult follows when RIF is in. + // An INVALID result is written back too (as the invalid outcome was before); the machine's + // retest result overwrites it later. if (DiagnosticOrderStatus.COMPLETED.name().equals(order.getStatus()) - || (writeBackWhenClosed && DiagnosticOrderStatus.CLOSED.name().equals(order.getStatus()))) { - recordTbSuspectedResult(order, result); + || DiagnosticOrderStatus.INVALID.name().equals(order.getStatus()) + || (DiagnosticOrderStatus.FAILED.name().equals(order.getStatus()) && main.getResultSummary() != null) + || (writeBackWhenClosed && DiagnosticOrderStatus.CLOSED.name().equals(order.getStatus())) + || (writeBackWhenClosed && main.getResultSummary() != null + && (DiagnosticOrderStatus.MANUAL_ENTRY.name().equals(order.getStatus()) + || DiagnosticOrderStatus.PENDING.name().equals(order.getStatus())))) { + recordTbSuspectedResult(order, main, rif != null ? rif.getResultSummary() : null, dropRif); } - DiagnosticOrderResultDto dto = new DiagnosticOrderResultDto(); - dto.setExternalOrderId(order.getExternalOrderId()); - dto.setOrderType(order.getOrderType()); - dto.setStatus(order.getStatus()); - dto.setErrorMessage(order.getErrorMessage()); - dto.setReasonToClose(order.getReasonToClose()); - dto.setProviderStatus(result.getProviderStatus()); - dto.setResultSummary(result.getResultSummary()); - dto.setTbPresence(result.getTbPresence()); - dto.setTbConfidence(result.getTbConfidence()); - dto.setDrugResistancePresence(result.getDrugResistancePresence()); + DiagnosticOrderResultDto dto = toResultDto(order); + applyResults(dto, main, rif); return dto; } + // Inserts or updates one result row of this order. Only a first insert can lose a race (unique + // external_order_id + result_type); then the winner's row is returned. Any other integrity failure + // means the result was not saved, so the order must not move on without it. + private DiagnosticResult saveResultRow(DiagnosticOrder order, Optional existing, String resultType, + String actingUser, java.util.function.Consumer fill) { + // No live row: reuse a soft-deleted one (e.g. an invalidated MDR_RIF row) if there is one, since + // the unique (external_order_id, result_type) key still covers it and a new insert would fail. + DiagnosticResult row = existing + .or(() -> diagnosticResultRepo.findByExternalOrderIdAndResultType(order.getExternalOrderId(), resultType)) + .orElseGet(DiagnosticResult::new); + row.setDeleted(false); + row.setExternalOrderId(order.getExternalOrderId()); + row.setResultType(resultType); + row.setBeneficiaryId(order.getBeneficiaryId()); + fill.accept(row); + row.setCreatedBy(row.getCreatedBy() != null ? row.getCreatedBy() : actingUser); + row.setModifiedBy(actingUser); + if (row.getVanID() == null) { + // Inherit from the parent order rather than re-reading Redis — the result belongs + // to whichever van originated the order, not whichever van happens to be polling now. + row.setVanID(order.getVanID()); + row.setParkingPlaceID(order.getParkingPlaceID()); + } + boolean insert = row.getId() == null; + try { + diagnosticResultRepo.save(row); + if (row.getVanSerialNo() == null) diagnosticResultRepo.updateVanSerialNo(row.getId()); + return row; + } catch (DataIntegrityViolationException dive) { + if (!insert) throw dive; + logger.warn("Lost result upsert race for externalOrderId={}, resultType={}", + order.getExternalOrderId(), resultType); + return diagnosticResultRepo + .findByExternalOrderIdAndResultTypeAndDeletedFalse(order.getExternalOrderId(), resultType) + .orElseThrow(() -> dive); // no winner: the insert failed for another reason + } + } + + // The order's own test row (X-ray, MTB or MTB_PLUS). + private Optional mainResult(DiagnosticOrder order) { + if (order.getExternalOrderId() == null) return Optional.empty(); + return diagnosticResultRepo.findByExternalOrderIdAndResultTypeAndDeletedFalse( + order.getExternalOrderId(), order.getOrderType()); + } + + // The MDR RIF row of an MTB/MTB_PLUS order, once its RIF test exists. + private Optional rifResult(DiagnosticOrder order) { + if (order.getExternalOrderId() == null || !TrueNatResultRules.isTrueNat(order.getOrderType())) { + return Optional.empty(); + } + return diagnosticResultRepo.findByExternalOrderIdAndResultTypeAndDeletedFalse( + order.getExternalOrderId(), DiagnosticResultType.MDR_RIF.name()); + } + + // A TrueNat order whose MTB result is known and isn't positive: no RIF test applies to it. + private static boolean rifNoLongerNeeded(DiagnosticOrder order, String mtbSummary) { + return TrueNatResultRules.isTrueNat(order.getOrderType()) + && blankToNull(mtbSummary) != null && !TrueNatResultRules.needsMdrRif(mtbSummary); + } + + private static boolean hasRifData(DiagnosticPollResult p) { + return blankToNull(p.getDrugResistanceSummary()) != null || p.getDrugResistanceStatus() != null + || p.getDrugResistancePresence() != null; + } + + // RIF row status: the vendor's RIF component status, else COMPLETED once a RIF result exists. + private static String rifStatus(DiagnosticPollResult p) { + if (p.getDrugResistanceStatus() != null) return p.getDrugResistanceStatus(); + return DiagnosticOrderStatus.COMPLETED.name(); + } + // Best-effort link from a diagnostic order back to the tb_suspected referral that presumably // prompted it. Not every diagnostic order originates from a TB referral, so a miss here is // expected and must never fail/block the push or result flow — just log and move on. @@ -550,19 +639,31 @@ private TBSuspected findTbSuspected(Long beneficiaryId) { return tbSuspected; } - private void recordTbSuspectedResult(DiagnosticOrder order, DiagnosticResult result) { + // drugResistanceSummary is the MDR RIF result the vendor runs on the same MTB order when MTB is + // positive; null when no RIF test ran (MTB negative, manual entry), so an earlier value is kept — + // unless clearRif: this order's RIF result was invalidated, so the value it wrote is cleared. + private void recordTbSuspectedResult(DiagnosticOrder order, DiagnosticResult result, String drugResistanceSummary, + boolean clearRif) { TBSuspected tbSuspected = findTbSuspected(order.getBeneficiaryId()); if (tbSuspected == null) return; DiagnosticOrderType type = DiagnosticOrderType.fromCode(order.getOrderType()); if (type == DiagnosticOrderType.XRAY_CHEST) { tbSuspected.setIsChestXRayDone(true); tbSuspected.setChestXRayResult(result.getResultSummary()); - } else if (type == DiagnosticOrderType.MDR_RIF) { - tbSuspected.setIsSputumCollected(true); - tbSuspected.setMdrRifResult(result.getResultSummary()); } else if (type == DiagnosticOrderType.MTB){ tbSuspected.setIsSputumCollected(true); tbSuspected.setSputumTestResult(result.getResultSummary()); + } else if (type == DiagnosticOrderType.MDR_RIF) { + // Legacy MDR_RIF order: its own result is the RIF result (as written back before MDR RIF + // moved onto the MTB order) + tbSuspected.setIsSputumCollected(true); + if (result.getResultSummary() != null) { + tbSuspected.setMdrRifResult(result.getResultSummary()); + } + } + // MDR RIF runs on both TrueNat order types (MTB and MTB_PLUS) after a positive MTB result + if (TrueNatResultRules.isTrueNat(order.getOrderType()) && (drugResistanceSummary != null || clearRif)) { + tbSuspected.setMdrRifResult(drugResistanceSummary); } tbSuspected.setProcessed("N"); tbSuspectedRepo.save(tbSuspected); @@ -636,7 +737,7 @@ public void expireOrder(DiagnosticOrder order, String reason) throws Exception { } DiagnosticOrder fresh = current.get(); fresh.setStatus(DiagnosticOrderStatus.CLOSED.name()); - fresh.setReasonToClose(reason); + fresh.setReasonToClose(stageOf(fresh), reason); fresh.setLastPolledAt(new Timestamp(System.currentTimeMillis())); fresh.setModifiedBy("SYSTEM"); fresh.setProcessed("N"); @@ -646,15 +747,140 @@ public void expireOrder(DiagnosticOrder order, String reason) throws Exception { }); } - private static boolean sameResult(DiagnosticResult stored, DiagnosticPollResult polled) { - return java.util.Objects.equals(stored.getProviderStatus(), polled.getStatus() == null ? null : polled.getStatus().name()) + // Same stale-copy rule as pollOnce: re-read under the lock, so an order that was reopened, deleted + // or got its documents after the batch was loaded is skipped instead of polled again. + @Override + public boolean fetchMissingDocuments(DiagnosticOrder order) throws Exception { + Optional received = withBeneficiaryLockIfFree(order.getBeneficiaryId(), () -> { + Optional current = diagnosticOrderRepo.findById(order.getId()) + .filter(o -> !Boolean.TRUE.equals(o.getDeleted())) + .filter(o -> DiagnosticOrderStatus.COMPLETED.name().equals(o.getStatus())); + if (current.isEmpty()) { + logger.info("Skipping document fetch for orderId={}: no longer COMPLETED", order.getId()); + return false; + } + DiagnosticOrder fresh = current.get(); + DiagnosticPollResult vendor = providerFactory.getProvider(fresh.getProviderCode()).pollResult(fresh, true); + if (vendor == null) { + return false; + } + boolean gotDocuments = vendor.getAssets() != null && !vendor.getAssets().isEmpty(); + if (gotDocuments) { + ingestAssets(fresh, vendor); + } else { + logger.info("Vendor returned no documents yet for orderId={}", fresh.getId()); + } + boolean overwritten = fresh.getManuallyEnteredBy() != null && overwriteManualResult(fresh, vendor); + return gotDocuments || overwritten; + }); + return received.orElse(false); + } + + // A manually entered result is replaced by the vendor's wherever the vendor has a value and it + // differs: the MTB / X-ray result, and the MDR RIF result. A value the vendor doesn't have yet + // (e.g. RIF still running) keeps what was entered. The order status is then worked out the same + // way as for manual entry, and the result row and tb_suspected are rewritten via processResult. + private boolean overwriteManualResult(DiagnosticOrder order, DiagnosticPollResult vendor) throws Exception { + DiagnosticResult storedMain = mainResult(order).orElse(null); + DiagnosticResult storedRif = rifResult(order).orElse(null); + String storedSummary = storedMain != null ? storedMain.getResultSummary() : null; + String storedRifSummary = storedRif != null ? storedRif.getResultSummary() : null; + + String vendorSummary = blankToNull(vendor.getResultSummary()); + String vendorRif = blankToNull(vendor.getDrugResistanceSummary()); + boolean summaryChanged = vendorSummary != null && !vendorSummary.equalsIgnoreCase( + storedSummary == null ? "" : storedSummary.trim()); + boolean rifChanged = vendorRif != null && !vendorRif.equalsIgnoreCase( + storedRifSummary == null ? "" : storedRifSummary.trim()); + // A RIF status change with no RIF result (e.g. the vendor's RIF test FAILED) counts too. + String vendorRifStatus = vendor.getDrugResistanceStatus(); + boolean rifStatusChanged = vendorRifStatus != null && !vendorRifStatus.equalsIgnoreCase( + storedRif != null && storedRif.getProviderStatus() != null ? storedRif.getProviderStatus() : ""); + // The vendor's MTB test status goes with the vendor's MTB result: used (and compared) only when + // the vendor has an MTB result. Without one the stored manual result is kept, and its row + // status is worked out from it (mainRowStatus). + String vendorMainStatus = vendorSummary != null ? vendor.getMainStatus() : null; + boolean mainStatusChanged = vendorMainStatus != null && !vendorMainStatus.equalsIgnoreCase( + storedMain != null && storedMain.getProviderStatus() != null ? storedMain.getProviderStatus() : ""); + if (!summaryChanged && !rifChanged && !rifStatusChanged && !mainStatusChanged) { + return false; + } + + String summary = vendorSummary != null ? vendorSummary : storedSummary; + Boolean tbPresence = summaryChanged ? vendor.getTbPresence() + : (storedMain != null ? storedMain.getTbPresence() : null); + // The stored RIF is kept only while the MTB result still calls for RIF; once the vendor's MTB + // isn't positive, a RIF result the vendor didn't send is dropped (processResult invalidates it). + DiagnosticResult keptRif = rifNoLongerNeeded(order, summary) ? null : storedRif; + String rifSummary = vendorRif != null ? vendorRif + : (keptRif != null ? keptRif.getResultSummary() : null); + Boolean drugResistance = vendorRif != null ? TrueNatResultRules.classifyDrugResistance(vendorRif) + : (keptRif != null ? keptRif.getDrugResistancePresence() : null); + String rifStatus = vendorRifStatus != null ? vendorRifStatus + : vendorRif != null ? DiagnosticOrderStatus.COMPLETED.name() + : (keptRif != null ? keptRif.getProviderStatus() : null); + + // Same rules as the poll. A test the vendor reports FAILED makes the order FAILED; an invalid + // vendor MTB/RIF result ("Error-2") makes it INVALID, so the poll resumes and picks up the + // machine's retest; any other invalid result (X-ray, a manual "Invalid/Error" kept) closes it. + // Otherwise it stays COMPLETED: a positive MTB with no RIF yet is picked up again by the + // back-fill until the vendor's RIF report arrives. + boolean trueNat = TrueNatResultRules.isTrueNat(order.getOrderType()); + DiagnosticOrderStatus status = trueNat && DiagnosticOrderStatus.FAILED.equals(vendor.getStatus()) + ? DiagnosticOrderStatus.FAILED : DiagnosticOrderStatus.COMPLETED; + DiagnosticPollResult merged = new DiagnosticPollResult(status, null, summary, null, null, null, + tbPresence, null, drugResistance, rifSummary, rifStatus); + merged.setMainStatus(vendorMainStatus); + if (!markInvalidTrueNatResult(order, merged) && status == DiagnosticOrderStatus.COMPLETED + && (isInvalidResult(order.getOrderType(), summary, SPUTUM_INVALID_POLLED_RESULT) + || isInvalidResult(order.getOrderType(), summary, SPUTUM_INVALID_MANUAL_RESULT))) { + merged.setStatus(DiagnosticOrderStatus.CLOSED); + } + status = merged.getStatus(); + + logger.warn("Overwriting manually entered result with vendor's for orderId={} (externalOrderId={}): " + + "{} '{}' -> '{}', MDR_RIF '{}' -> '{}', status {} -> {}", + order.getId(), order.getExternalOrderId(), order.getOrderType(), storedSummary, summary, + storedRifSummary, rifSummary, order.getStatus(), status); + processResult(order, merged, true, "SYSTEM"); + if (summaryChanged && status == DiagnosticOrderStatus.COMPLETED) { + pushMtbOrderAfterPositiveXray(order, tbPresence); + } + return true; + } + + // providerStatus of the order's own test row (X-ray / MTB / MTB_PLUS), kept apart from the order + // status: a finished MTB is COMPLETED while the order stays PENDING / INVALID / CLOSED over its RIF + // test (whose row carries the RIF status). The vendor's component status when it gave one; + // otherwise (manual entry, a manual result kept over an empty vendor one, the vendor replacing a + // manual result, closing RIF) COMPLETED for a valid MTB result, else the order status. + private static String mainRowStatus(DiagnosticOrder order, DiagnosticPollResult p) { + if (p.getMainStatus() != null) { + return p.getMainStatus(); + } + String summary = blankToNull(p.getResultSummary()); + if (TrueNatResultRules.isTrueNat(order.getOrderType()) && summary != null + && !isInvalidResult(order.getOrderType(), summary, SPUTUM_INVALID_POLLED_RESULT) + && !isInvalidResult(order.getOrderType(), summary, SPUTUM_INVALID_MANUAL_RESULT)) { + return DiagnosticOrderStatus.COMPLETED.name(); + } + return p.getStatus() == null ? null : p.getStatus().name(); + } + + private static boolean sameMainResult(DiagnosticOrder order, DiagnosticResult stored, DiagnosticPollResult polled) { + return java.util.Objects.equals(stored.getProviderStatus(), mainRowStatus(order, polled)) && java.util.Objects.equals(stored.getResultSummary(), polled.getResultSummary()) && java.util.Objects.equals(stored.getTbPresence(), polled.getTbPresence()) && java.util.Objects.equals(stored.getTbConfidence(), polled.getTbConfidence()) - && java.util.Objects.equals(stored.getDrugResistancePresence(), polled.getDrugResistancePresence()) && (polled.getAssets() == null || polled.getAssets().isEmpty()); } + private static boolean sameRifResult(DiagnosticResult stored, DiagnosticPollResult polled) { + return java.util.Objects.equals(stored.getProviderStatus(), rifStatus(polled)) + && java.util.Objects.equals(stored.getResultSummary(), blankToNull(polled.getDrugResistanceSummary())) + && java.util.Objects.equals(stored.getDrugResistancePresence(), polled.getDrugResistancePresence()); + } + private static boolean sameOrderStatus(DiagnosticOrder order, DiagnosticPollResult polled) { return polled.getStatus() != null && polled.getStatus().name().equals(order.getStatus()) @@ -683,7 +909,10 @@ private DiagnosticPollResult pollOnceLocked(DiagnosticOrder order) throws Except return null; } DiagnosticProvider provider = providerFactory.getProvider(order.getProviderCode()); - DiagnosticPollResult result = provider.pollResult(order, false); + DiagnosticPollResult result = keepManualWhereVendorEmpty(order, provider.pollResult(order, false)); + // An invalid MTB/RIF run is retested by the machine on this same order: INVALID, saved below via + // processResult like any open status, and polled on — no close, no retest order, no reports yet. + markInvalidTrueNatResult(order, result); if (DiagnosticOrderStatus.COMPLETED.equals(result.getStatus())) { // Save as COMPLETED (or CLOSED for an invalid outcome) now, without assets, so a failure // fetching/ingesting assets below doesn't also lose the already-confirmed status (see @@ -694,18 +923,57 @@ private DiagnosticPollResult pollOnceLocked(DiagnosticOrder order) throws Except // Before the asset fetch below: if that throws, this CLOSED order is never polled // again, so the retest must already exist by then. pushRetestOrder(order); + } else { + // Also before the asset fetch, for the same reason. + pushMtbOrderAfterPositiveXray(order, result.getTbPresence()); } result = provider.pollResult(order, true); // Only ingest the documents this time — the result/order fields were already saved above // and this second, asset-bearing response carries the same status/summary, so re-saving // them again would just be a redundant duplicate write. ingestAssets(order, result); + } else if (order.getManuallyEnteredBy() != null && vendorChangedManualResult(order, result)) { + // Vendor replaced part of a manual result while the order is still open: rewrite + // tb_suspected too, since the manual value is already there. + processResult(order, result, true, "SYSTEM"); } else { processResult(order, result); } return result; } + // Order whose result was entered by hand and is still being polled (a positive MTB waiting for + // RIF): the vendor's values replace the manual ones, but a value the vendor doesn't have yet + // (empty summary while its test runs, no RIF yet) keeps what was entered. + private DiagnosticPollResult keepManualWhereVendorEmpty(DiagnosticOrder order, DiagnosticPollResult vendor) { + if (vendor == null || order.getManuallyEnteredBy() == null) { + return vendor; + } + mainResult(order).ifPresent(manual -> { + if (blankToNull(vendor.getResultSummary()) == null) { + vendor.setResultSummary(manual.getResultSummary()); + vendor.setTbPresence(manual.getTbPresence()); + vendor.setMainStatus(null); + } + }); + // The manual RIF is kept only while the (merged) MTB result still calls for RIF. + if (!hasRifData(vendor) && !rifNoLongerNeeded(order, vendor.getResultSummary())) { + rifResult(order).ifPresent(manualRif -> { + vendor.setDrugResistanceSummary(manualRif.getResultSummary()); + vendor.setDrugResistancePresence(manualRif.getDrugResistancePresence()); + vendor.setDrugResistanceStatus(manualRif.getProviderStatus()); + }); + } + return vendor; + } + + private boolean vendorChangedManualResult(DiagnosticOrder order, DiagnosticPollResult merged) { + String storedSummary = mainResult(order).map(DiagnosticResult::getResultSummary).orElse(null); + String storedRif = rifResult(order).map(DiagnosticResult::getResultSummary).orElse(null); + return !java.util.Objects.equals(storedSummary, merged.getResultSummary()) + || !java.util.Objects.equals(storedRif, blankToNull(merged.getDrugResistanceSummary())); + } + private DiagnosticOrder findLatestOrder(Long beneficiaryId, String orderType) throws Exception { DiagnosticOrderType type = DiagnosticOrderType.fromCode(orderType); return diagnosticOrderRepo @@ -741,9 +1009,18 @@ public DiagnosticOrderResultDto triggerManualPoll(Long beneficiaryId, String ord + order.getManuallyEnteredBy() + " and a vendor poll would overwrite it"); } DiagnosticProvider provider = providerFactory.getProvider(order.getProviderCode()); + boolean wasCompleted = DiagnosticOrderStatus.COMPLETED.name().equals(order.getStatus()); DiagnosticPollResult pollResult = provider.pollResult(order, true); + markInvalidTrueNatResult(order, pollResult); boolean invalid = closeIfInvalidPolledResult(order, pollResult); - return processResult(order, pollResult, invalid, "SYSTEM"); + DiagnosticOrderResultDto dto = processResult(order, pollResult, invalid, "SYSTEM"); + // Same follow-up as the scheduled poll: an X-ray this call completes as TB Presumptive gets + // its MTB order. Only on the transition to COMPLETED — the scheduler skips a completed order, + // so this is the only chance; re-polling an already completed X-ray creates nothing. + if (!wasCompleted && DiagnosticOrderStatus.COMPLETED.name().equals(order.getStatus())) { + pushMtbOrderAfterPositiveXray(order, pollResult.getTbPresence()); + } + return dto; }); } @@ -794,40 +1071,56 @@ public DiagnosticOrderResultDto getOrderResult(Long beneficiaryId, String orderT ? diagnosticOrderRepo.findFirstByBeneficiaryIdAndVisitCodeAndOrderTypeAndDeletedFalseOrderByCreatedDateDesc(beneficiaryId, visitCode, orderType) : diagnosticOrderRepo.findFirstByBeneficiaryIdAndOrderTypeAndDeletedFalseOrderByCreatedDateDesc(beneficiaryId, orderType); if (orderOpt.isEmpty()) { - DiagnosticOrderResultDto dto = new DiagnosticOrderResultDto(); - dto.setOrderType(orderType); - dto.setStatus("NOT_FOUND"); - return dto; + return notFoundResult(beneficiaryId, orderType, visitCode); } DiagnosticOrder order = orderOpt.get(); DiagnosticOrderResultDto dto = toResultDto(order); + applyResults(dto, mainResult(order).orElse(null), rifResult(order).orElse(null)); + return dto; + } - diagnosticResultRepo.findByExternalOrderIdAndDeletedFalse(order.getExternalOrderId()).ifPresent(result -> { - dto.setProviderStatus(result.getProviderStatus()); - dto.setResultSummary(result.getResultSummary()); - dto.setTbPresence(result.getTbPresence()); - dto.setTbConfidence(result.getTbConfidence()); - dto.setDrugResistancePresence(result.getDrugResistancePresence()); - }); + private static DiagnosticOrderResultDto notFoundResult(Long beneficiaryId, String orderType, Long visitCode) { + DiagnosticOrderResultDto dto = new DiagnosticOrderResultDto(); + dto.setBeneficiaryId(beneficiaryId); + dto.setVisitCode(visitCode); + dto.setOrderType(orderType); + dto.setStatus("NOT_FOUND"); return dto; } + // results = the order's own test row first, then its MDR_RIF row; missing rows are left out. + private static void applyResults(DiagnosticOrderResultDto dto, DiagnosticResult main, DiagnosticResult rif) { + List items = new ArrayList<>(); + if (main != null) items.add(toResultItem(main)); + if (rif != null) items.add(toResultItem(rif)); + dto.setResults(items); + } + + private static DiagnosticResultItemDto toResultItem(DiagnosticResult row) { + DiagnosticResultItemDto item = new DiagnosticResultItemDto(); + item.setResultType(row.getResultType()); + item.setProviderStatus(row.getProviderStatus()); + item.setResultSummary(row.getResultSummary()); + item.setTbPresence(row.getTbPresence()); + item.setTbConfidence(row.getTbConfidence()); + item.setDrugResistancePresence(row.getDrugResistancePresence()); + return item; + } + + private static void applyReasonToClose(DiagnosticOrderResultDto dto, DiagnosticOrder order) { + dto.setReasonToCloseXray(order.getReasonToCloseXray()); + dto.setReasonToCloseMTB(order.getReasonToCloseMTB()); + dto.setReasonToCloseMDRRIF(order.getReasonToCloseMDRRIF()); + } + @Override public java.util.Map> getOrderRecordsByIds(java.util.Collection ids) { java.util.Map> out = new java.util.LinkedHashMap<>(); for (DiagnosticOrder order : diagnosticOrderRepo.findAllById(ids)) { if (Boolean.TRUE.equals(order.getDeleted())) continue; DiagnosticOrderResultDto dto = toResultDto(order); - if (order.getExternalOrderId() != null) { - diagnosticResultRepo.findByExternalOrderIdAndDeletedFalse(order.getExternalOrderId()).ifPresent(result -> { - dto.setProviderStatus(result.getProviderStatus()); - dto.setResultSummary(result.getResultSummary()); - dto.setTbPresence(result.getTbPresence()); - dto.setTbConfidence(result.getTbConfidence()); - dto.setDrugResistancePresence(result.getDrugResistancePresence()); - }); - } + applyResults(dto, mainResult(order).orElse(null), rifResult(order).orElse(null)); java.util.Map m = new java.util.LinkedHashMap<>(); m.put("id", order.getId()); m.put("beneficiaryId", order.getBeneficiaryId()); @@ -836,13 +1129,11 @@ public java.util.Map> getOrderRecordsByIds(j m.put("externalOrderId", dto.getExternalOrderId()); m.put("orderType", dto.getOrderType()); m.put("status", dto.getStatus()); - m.put("providerStatus", dto.getProviderStatus()); - m.put("resultSummary", dto.getResultSummary()); m.put("errorMessage", dto.getErrorMessage()); - m.put("reasonToClose", dto.getReasonToClose()); - m.put("tbPresence", dto.getTbPresence()); - m.put("tbConfidence", dto.getTbConfidence()); - m.put("drugResistancePresence", dto.getDrugResistancePresence()); + m.put("reasonToCloseXray", dto.getReasonToCloseXray()); + m.put("reasonToCloseMTB", dto.getReasonToCloseMTB()); + m.put("reasonToCloseMDRRIF", dto.getReasonToCloseMDRRIF()); + m.put("results", dto.getResults()); out.put(order.getId(), m); } return out; @@ -850,11 +1141,13 @@ public java.util.Map> getOrderRecordsByIds(j private DiagnosticOrderResultDto toResultDto(DiagnosticOrder order) { DiagnosticOrderResultDto dto = new DiagnosticOrderResultDto(); + dto.setBeneficiaryId(order.getBeneficiaryId()); + dto.setVisitCode(order.getVisitCode()); dto.setExternalOrderId(order.getExternalOrderId()); dto.setOrderType(order.getOrderType()); dto.setStatus(order.getStatus()); dto.setErrorMessage(order.getErrorMessage()); - dto.setReasonToClose(order.getReasonToClose()); + applyReasonToClose(dto, order); return dto; } @@ -867,6 +1160,7 @@ public DiagnosticOrderStatusSummaryDto getOrderStatusSummary(String orderType, I List failed = new ArrayList<>(); List closed = new ArrayList<>(); List awaitingManualEntry = new ArrayList<>(); + List invalid = new ArrayList<>(); // One query instead of one per bucket; buckets are the same status groups the per-bucket // queries used (matched case-insensitively, like the database comparison was). for (Object[] row : diagnosticOrderRepo.findLatestOrderStatusByBeneficiary(type.name(), villageId, providerServiceMapId)) { @@ -878,10 +1172,11 @@ public DiagnosticOrderStatusSummaryDto getOrderStatusSummary(String orderType, I case "FAILED" -> failed.add(beneficiaryId); case "CLOSED", "CANCELLED", "EXPIRED", "REFUSED" -> closed.add(beneficiaryId); case "MANUAL_ENTRY" -> awaitingManualEntry.add(beneficiaryId); + case "INVALID" -> invalid.add(beneficiaryId); default -> { } } } - return new DiagnosticOrderStatusSummaryDto(awaitingProviderResult, completed, failed, closed, awaitingManualEntry); + return new DiagnosticOrderStatusSummaryDto(awaitingProviderResult, completed, failed, closed, awaitingManualEntry, invalid); } @Override @@ -904,19 +1199,23 @@ public VendorHealthDto checkVendorHealth(String orderType) throws Exception { @Override public DiagnosticOrderResultDto submitManualResult(ManualDiagnosticResultRequestDto request, String jwtToken) throws Exception { - boolean hasResult = request.getResultSummary() != null && !request.getResultSummary().isBlank(); - boolean hasReasonToClose = request.getReasonToClose() != null && !request.getReasonToClose().isBlank(); - if (hasResult == hasReasonToClose) { - throw new IllegalArgumentException("Exactly one of resultSummary or reasonToClose must be provided"); + boolean hasResult = (request.getResultSummary() != null && !request.getResultSummary().isBlank()) + || (request.getMdrRifResult() != null && !request.getMdrRifResult().isBlank()); + DiagnosticOrderType orderType = DiagnosticOrderType.fromCode(request.getOrderType()); + CloseReason close = resolveCloseReason(orderType, request.getReasonToCloseXray(), + request.getReasonToCloseMTB(), request.getReasonToCloseRif()); + if (hasResult == (close != null)) { + throw new IllegalArgumentException("Provide either a result (resultSummary and/or mdrRifResult) or " + + "one reasonToClose (reasonToCloseXray / reasonToCloseMTB / reasonToCloseRif), not both"); } String actingUserName = resolveActingUserName(jwtToken); - if (hasReasonToClose) { - DiagnosticOrderType orderType = DiagnosticOrderType.fromCode(request.getOrderType()); - DiagnosticOrder closed = closeOrderManually(request.getBeneficiaryId(), orderType, - request.getReasonToClose(), actingUserName); - return toResultDto(closed); + if (close != null) { + DiagnosticOrder closed = closeOrderManually(request.getBeneficiaryId(), orderType, close, actingUserName); + DiagnosticOrderResultDto dto = toResultDto(closed); + applyResults(dto, mainResult(closed).orElse(null), rifResult(closed).orElse(null)); + return dto; } return withBeneficiaryLock(request.getBeneficiaryId(), @@ -930,20 +1229,143 @@ private DiagnosticOrderResultDto submitManualResultLocked(ManualDiagnosticResult throw new IllegalStateException("Cannot submit manual result: order is already COMPLETED (beneficiaryId=" + request.getBeneficiaryId() + ", orderType=" + request.getOrderType() + ")"); } + // A CLOSED order is final too (a test not done, or an invalid result; one closed with a reason + // was also cancelled on the vendor). Reopening it would leave a result next to the reason the + // test wasn't done. To test again, push a new order — a push never reuses a CLOSED order. + if (DiagnosticOrderStatus.CLOSED.name().equals(order.getStatus())) { + throw new IllegalStateException("Cannot submit manual result: order is CLOSED (beneficiaryId=" + + request.getBeneficiaryId() + ", orderType=" + request.getOrderType() + + ") — push a new order to test again"); + } + String mtbSummary = blankToNull(request.getResultSummary()); + String mdrRifResult = blankToNull(request.getMdrRifResult()); + boolean trueNat = TrueNatResultRules.isTrueNat(order.getOrderType()); + if (mdrRifResult != null && !trueNat) { + throw new IllegalArgumentException("mdrRifResult only applies to MTB/MTB_PLUS orders, not " + + order.getOrderType()); + } + if (mtbSummary == null) { + // RIF entered on its own: the MTB result must already be stored, and positive. + mtbSummary = mainResult(order).map(DiagnosticResult::getResultSummary).orElse(null); + if (mtbSummary == null) { + throw new IllegalStateException("Cannot submit mdrRifResult: no MTB result stored yet for this order " + + "(beneficiaryId=" + request.getBeneficiaryId() + ") — send resultSummary first or with it"); + } + } + if (mdrRifResult != null && !TrueNatResultRules.needsMdrRif(mtbSummary)) { + throw new IllegalArgumentException("mdrRifResult is only run on a positive MTB result; MTB result is '" + + mtbSummary + "'"); + } order.setManuallyEnteredBy(actingUserName); - // An invalid test outcome is still recorded exactly like a normal result (result row + - // tb_suspected write-back), but the order is CLOSED rather than COMPLETED. - DiagnosticOrderStatus status = isInvalidResult(order.getOrderType(), request.getResultSummary(), - SPUTUM_INVALID_MANUAL_RESULT) - ? DiagnosticOrderStatus.CLOSED - : DiagnosticOrderStatus.COMPLETED; + // Same rules as the vendor poll: an invalid test outcome is recorded like a normal result but + // CLOSES the order; a positive MTB leaves the order open until its MDR RIF result is in. + // While open, an order the vendor received stays PENDING so the poll keeps running and brings + // the vendor's MTB/RIF result and reports (its values replace these where they differ); an + // order with no vendor stays MANUAL_ENTRY, waiting for mdrRifResult or reasonToCloseRif. + // An invalid RIF result entered by hand is handled like an invalid MTB result entered by hand: + // the order is CLOSED (the MTB row keeps its result, the RIF row records the invalid value). + boolean invalidRif = isInvalidRifResult(mdrRifResult); + DiagnosticOrderStatus status; + if (isInvalidResult(order.getOrderType(), mtbSummary, SPUTUM_INVALID_MANUAL_RESULT) || invalidRif) { + status = DiagnosticOrderStatus.CLOSED; + } else if (trueNat && mdrRifResult == null && TrueNatResultRules.needsMdrRif(mtbSummary)) { + status = order.getProviderOrderId() != null ? DiagnosticOrderStatus.PENDING : DiagnosticOrderStatus.MANUAL_ENTRY; + } else { + status = DiagnosticOrderStatus.COMPLETED; + } + // tbPresence as the vendor poll derives it: X-ray -> only "TB Presumptive" on a completed result + // is positive; TrueNat -> from the MTB result. + Boolean tbPresence = trueNat + ? TrueNatResultRules.classifyTbPresence(order.getOrderType(), mtbSummary) + : (status == DiagnosticOrderStatus.COMPLETED ? XRAY_TB_PRESUMPTIVE.equalsIgnoreCase(mtbSummary) : null); DiagnosticPollResult pollResult = new DiagnosticPollResult( - status, null, request.getResultSummary(), null, null, null, null, null, null); + status, null, mtbSummary, null, null, null, tbPresence, null, + TrueNatResultRules.classifyDrugResistance(mdrRifResult), mdrRifResult, + invalidRif ? DiagnosticOrderStatus.CLOSED.name() : null); return processResult(order, pollResult, true, actingUserName); } + private record CloseReason(DiagnosticCloseStage stage, String reason) { + } + + // At most one reasonToClose* may be sent, and it must fit the order type: Xray for XRAY_CHEST, + // MTB/Rif for MTB and MTB_PLUS. Null when none was sent. + private static CloseReason resolveCloseReason(DiagnosticOrderType orderType, String xray, String mtb, String rif) { + List given = new ArrayList<>(); + if (blankToNull(xray) != null) given.add(new CloseReason(DiagnosticCloseStage.XRAY, xray.trim())); + if (blankToNull(mtb) != null) given.add(new CloseReason(DiagnosticCloseStage.MTB, mtb.trim())); + if (blankToNull(rif) != null) given.add(new CloseReason(DiagnosticCloseStage.RIF, rif.trim())); + if (given.isEmpty()) { + return null; + } + if (given.size() > 1) { + throw new IllegalArgumentException("Send only one of reasonToCloseXray, reasonToCloseMTB, reasonToCloseRif"); + } + CloseReason close = given.get(0); + boolean xrayOrder = orderType == DiagnosticOrderType.XRAY_CHEST; + if (xrayOrder != (close.stage() == DiagnosticCloseStage.XRAY)) { + throw new IllegalArgumentException(xrayOrder + ? "XRAY_CHEST orders are closed with reasonToCloseXray" + : orderType.name() + " orders are closed with reasonToCloseMTB or reasonToCloseRif"); + } + return close; + } + + // Stage for a close with no explicit choice (the daily expiry): RIF when a TrueNat order's MTB + // result is in and positive, otherwise the order's own test. + private DiagnosticCloseStage stageOf(DiagnosticOrder order) { + if (DiagnosticOrderType.XRAY_CHEST.name().equals(order.getOrderType())) { + return DiagnosticCloseStage.XRAY; + } + boolean mtbPositive = mainResult(order) + .map(r -> TrueNatResultRules.needsMdrRif(r.getResultSummary())) + .orElse(false); + return mtbPositive ? DiagnosticCloseStage.RIF : DiagnosticCloseStage.MTB; + } + + // reasonToCloseRif: the beneficiary's latest order of this type has a positive MTB result and is + // still waiting for MDR RIF. That same order is CLOSED with reason_to_close_mdrrif; its MTB result + // stays and is written back to tb_suspected like a finished result. Caller holds the beneficiary lock. + private DiagnosticOrder closeRifStageLocked(Long beneficiaryId, DiagnosticOrderType orderType, String reason, + String actingUserId) throws Exception { + DiagnosticOrder order = diagnosticOrderRepo + .findFirstByBeneficiaryIdAndOrderTypeAndDeletedFalseOrderByCreatedDateDesc(beneficiaryId, orderType.name()) + .orElseThrow(() -> new IllegalStateException("No " + orderType.name() + + " order found for beneficiaryId=" + beneficiaryId + " to close the MDR RIF test on")); + String mtbSummary = mainResult(order).map(DiagnosticResult::getResultSummary).orElse(null); + boolean awaitingRif = Set.of(DiagnosticOrderStatus.PENDING.name(), DiagnosticOrderStatus.IN_PROGRESS.name(), + DiagnosticOrderStatus.MANUAL_ENTRY.name(), DiagnosticOrderStatus.INVALID.name()).contains(order.getStatus()); + if (!awaitingRif || !TrueNatResultRules.needsMdrRif(mtbSummary)) { + throw new IllegalStateException("reasonToCloseRif needs the latest " + orderType.name() + " order to have a " + + "positive MTB result and still be waiting for MDR RIF (status=" + order.getStatus() + + ", MTB result=" + mtbSummary + "); use reasonToCloseMTB to close the MTB test instead"); + } + order.setReasonToClose(DiagnosticCloseStage.RIF, reason); + order.setManuallyEnteredBy(actingUserId); + // RIF didn't take place: only reason_to_close_mdrrif (set above) records it — no MDR_RIF result + // row is created. The MTB row keeps its result. + DiagnosticPollResult pollResult = new DiagnosticPollResult(DiagnosticOrderStatus.CLOSED, null, mtbSummary, + null, null, null, TrueNatResultRules.classifyTbPresence(order.getOrderType(), mtbSummary), null, + null, null); + processResult(order, pollResult, true, actingUserId); + notifyProviderOrderClosed(order, reason); + return order; + } + + private static String blankToNull(String value) { + return value == null || value.isBlank() ? null : value.trim(); + } + // sputumInvalidResult differs by source: SPUTUM_INVALID_POLLED_RESULT for vendor polls, // SPUTUM_INVALID_MANUAL_RESULT for manual entry. The X-ray value is the same for both. + // isInvalidResult goes by order type, so it can't judge a RIF value: an invalid RIF result is the + // manual "Invalid/Error" or the vendor's "Error-2". + private static boolean isInvalidRifResult(String rifResult) { + String rif = blankToNull(rifResult); + return rif != null && (SPUTUM_INVALID_MANUAL_RESULT.equalsIgnoreCase(rif) + || SPUTUM_INVALID_POLLED_RESULT.equalsIgnoreCase(rif)); + } + private static boolean isInvalidResult(String orderTypeCode, String resultSummary, String sputumInvalidResult) { if (resultSummary == null) { return false; @@ -953,7 +1375,7 @@ private static boolean isInvalidResult(String orderTypeCode, String resultSummar if (type == DiagnosticOrderType.XRAY_CHEST) { return XRAY_INVALID_RESULT.equalsIgnoreCase(summary); } - if (type == DiagnosticOrderType.MTB || type == DiagnosticOrderType.MDR_RIF) { + if (type == DiagnosticOrderType.MTB) { return sputumInvalidResult.equalsIgnoreCase(summary); } return false; @@ -1016,6 +1438,60 @@ private void pushRetestOrderLocked(DiagnosticOrder closed) { } } + // An X-ray the vendor reports as TB Presumptive (tbPresence true) is followed by an MTB order for + // the same patient, created through createAndPushOrderLocked exactly like a push from the app: + // same visit lookup, dedup (an MTB order the app already pushed is returned, not duplicated) and + // vendor routing (MANUAL_ENTRY when MTB has no vendor). The caller already holds the beneficiary + // lock. Never throws — a failure here must not undo the saved X-ray result. + private void pushMtbOrderAfterPositiveXray(DiagnosticOrder xray, Boolean tbPresence) { + if (!DiagnosticOrderType.XRAY_CHEST.name().equals(xray.getOrderType()) || !Boolean.TRUE.equals(tbPresence)) { + return; + } + try { + DiagnosticOrderRequestDto request = new DiagnosticOrderRequestDto(); + request.setBeneficiaryId(xray.getBeneficiaryId()); + request.setOrderType(DiagnosticOrderType.MTB.name()); + request.setOrderEvent(xray.getOrderEvent()); + DiagnosticOrderRequestDto.PatientDto patient = new DiagnosticOrderRequestDto.PatientDto(); + patient.setFirstName(xray.getPatientFirstName()); + patient.setLastName(xray.getPatientLastName()); + patient.setDateOfBirth(xray.getPatientDateOfBirth()); + patient.setSex(xray.getPatientSex()); + request.setPatient(patient); + DiagnosticOrder mtb = createAndPushOrderLocked(request, "SYSTEM"); + logger.info("MTB order after TB Presumptive X-ray: xrayOrderId={}, mtbOrderId={}, externalOrderId={}, status={}", + xray.getId(), mtb.getId(), mtb.getExternalOrderId(), mtb.getStatus()); + } catch (Exception e) { + logger.error("Failed to create MTB order after TB Presumptive X-ray, xrayOrderId={}: {}", + xray.getId(), e.getMessage()); + } + } + + // MTB/MTB_PLUS: an invalid run — the MTB or RIF result "Error-2" — sets the poll result to INVALID. + // The machine retests the same order by itself, so it is polled on rather than closed. A test the + // vendor reports FAILED is not invalid: the order stays FAILED, as the vendor reported it. + // "Indeterminate" is a real RIF result, not an error. Returns true when it changed the status. + private static boolean markInvalidTrueNatResult(DiagnosticOrder order, DiagnosticPollResult result) { + if (result == null || !TrueNatResultRules.isTrueNat(order.getOrderType()) + || DiagnosticOrderStatus.FAILED.equals(result.getStatus())) { + return false; + } + String mtb = blankToNull(result.getResultSummary()); + String rif = blankToNull(result.getDrugResistanceSummary()); + boolean invalid = (DiagnosticOrderStatus.COMPLETED.equals(result.getStatus()) + && SPUTUM_INVALID_POLLED_RESULT.equalsIgnoreCase(mtb == null ? "" : mtb)) + || SPUTUM_INVALID_POLLED_RESULT.equalsIgnoreCase(rif == null ? "" : rif); + if (invalid) { + result.setStatus(DiagnosticOrderStatus.INVALID); + // Only the test that failed is INVALID: an invalid MTB run marks its own row; with a RIF + // error the MTB row keeps its (valid) status and the RIF row the vendor's RIF status. + if (SPUTUM_INVALID_POLLED_RESULT.equalsIgnoreCase(mtb == null ? "" : mtb)) { + result.setMainStatus(DiagnosticOrderStatus.INVALID.name()); + } + } + return invalid; + } + // A vendor poll that COMPLETED with an invalid outcome is downgraded to CLOSED in place. // Returns true when that happened, so the caller still writes the result back to tb_suspected. private static boolean closeIfInvalidPolledResult(DiagnosticOrder order, DiagnosticPollResult result) { diff --git a/src/main/java/com/iemr/flw/service/impl/DiagnosticPollSchedulerService.java b/src/main/java/com/iemr/flw/service/impl/DiagnosticPollSchedulerService.java index 1a36e8cd..08197afe 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiagnosticPollSchedulerService.java +++ b/src/main/java/com/iemr/flw/service/impl/DiagnosticPollSchedulerService.java @@ -14,7 +14,9 @@ import java.sql.Timestamp; import java.time.LocalDate; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.function.Supplier; @Service @@ -71,6 +73,65 @@ private void pollDueOrders(String label, DiagnosticOrderType orderType, Supplier logger.info("Polled {} of {} pending {} diagnostic orders", polled, candidates.size(), label); } + // A completed order's documents come from a second vendor call after the result is saved; if that + // call fails the order stays COMPLETED with no documents and the regular poll never revisits it. + // A result entered manually COMPLETES the order, so the poll stops visiting it: its documents (MTB + // report, then the MDR RIF report) only arrive here, and the vendor's result overwrites the manual + // one where they differ. This job runs at application startup and then every hour. + @Scheduled(fixedDelayString = "${diagnostic.documents.backfill-interval-ms:3600000}") + public void fetchMissingDocuments() { + List candidates = diagnosticOrderRepo.findOrdersNeedingDocuments(); + logger.info("Document back-fill tick: {} order(s) needing documents", candidates.size()); + if (candidates.isEmpty()) return; + + // X-ray and TrueNat are handled in this one job but are separate vendor endpoints: each is pinged + // once, before its first order, and its orders are skipped this tick if it's down (or drops mid-tick), + // without holding up the other. + Map vendorUp = new HashMap<>(); + int received = 0; + int skipped = 0; + for (DiagnosticOrder order : candidates) { + try { + DiagnosticOrderType orderType = DiagnosticOrderType.fromCode(order.getOrderType()); + String vendorKey = order.getProviderCode() + ":" + vendorGroup(orderType); + if (!vendorUp.computeIfAbsent(vendorKey, k -> isVendorUp(order.getProviderCode(), orderType))) { + skipped++; + continue; + } + try { + if (diagnosticOrderService.fetchMissingDocuments(order)) received++; + } catch (ResourceAccessException e) { + logger.error("Vendor {} unreachable fetching documents for orderId={} — skipping its remaining orders this tick: {}", + vendorKey, order.getId(), e.getMessage()); + vendorUp.put(vendorKey, false); + } + } catch (Exception e) { + logger.error("Document fetch failed for orderId={}: {}", order.getId(), e.getMessage()); + } + } + logger.info("Document back-fill: documents received for {} of {} order(s), {} skipped (vendor down)", + received, candidates.size(), skipped); + } + + // MTB and MTB_PLUS share the TrueNat endpoint, so they share one health check. + private static String vendorGroup(DiagnosticOrderType orderType) { + return orderType == DiagnosticOrderType.XRAY_CHEST ? "XRAY" : "TRUENAT"; + } + + private boolean isVendorUp(String providerCode, DiagnosticOrderType orderType) { + try { + boolean up = providerFactory.getProvider(providerCode).checkHealth(orderType); + if (!up) { + logger.warn("{} {} vendor ping failed — skipping its document back-fill this tick", + providerCode, vendorGroup(orderType)); + } + return up; + } catch (Exception e) { + logger.warn("No usable provider {} for {} document back-fill: {}", providerCode, orderType, e.getMessage()); + return false; + } + } + // Auto-closure of outstanding orders at the daily cutoff is disabled for now — orders are no longer // closed automatically. Uncomment this job (and expire() below) to re-enable it. // @Scheduled(cron = "${diagnostic.poll.expiry-cron:0 50 23 * * *}") diff --git a/src/main/java/com/iemr/flw/service/impl/DynamicFormResponseServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DynamicFormResponseServiceImpl.java index b14ab50c..78742f5e 100644 --- a/src/main/java/com/iemr/flw/service/impl/DynamicFormResponseServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DynamicFormResponseServiceImpl.java @@ -98,6 +98,7 @@ public class DynamicFormResponseServiceImpl implements DynamicFormResponseServic private final JwtUtil jwtUtil; private final CampConfigService campConfigService; private final ConsentRefusalEvaluator consentRefusalEvaluator; + private final ConditionalAnswerPruner conditionalAnswerPruner; @Override @Transactional @@ -273,6 +274,9 @@ private FormResponseDTO processSections( o -> o.getSectionQuestion().getQuestionId(), Collectors.toMap(QuestionOption::getOptionValue, Function.identity()))); + Map> childrenByParent = + conditionalAnswerPruner.loadChildrenByParent(version.getVersionId()); + List sectionDTOs = new ArrayList<>(); for (SectionAnswerRequest sectionReq : request.getSections()) { if (sectionReq.getSectionUuid() == null) { @@ -310,6 +314,7 @@ private FormResponseDTO processSections( sectionReq.getAnswers(), questionMap, optionsByQuestion, + childrenByParent, actor, vanID, parkingPlaceID); @@ -368,10 +373,18 @@ private List processAnswers( List answers, Map questionMap, Map> optionsByQuestion, + Map> childrenByParent, String actor, Integer vanID, Integer parkingPlaceID) { + // Pass 1: clear old answers of every received question and its SHOW_QUESTION descendants, + // so children hidden by an edited parent don't keep stale answers. Done up-front so a + // parent listed after its child can't wipe the child's freshly inserted answer. + conditionalAnswerPruner.deleteWithDescendants( + sectionResponseId, answeredQuestionIds(answers, questionMap), childrenByParent); + + // Pass 2: insert the received answers List results = new ArrayList<>(); for (QuestionAnswerRequest answer : answers) { @@ -392,9 +405,6 @@ private List processAnswers( continue; } - // Delete any existing answers for this question in this section (handles re-saves) - questionResponseRepo.deleteByQuestionIdAndSectionResponseId(questionId, sectionResponseId); - if (type == QuestionType.RADIO || type == QuestionType.CHECKBOX || type == QuestionType.DROPDOWN) { if (answer.getOptionValue() != null) { QuestionOption opt = resolveOption( @@ -445,6 +455,15 @@ private List processAnswers( return results; } + /** Ids of the non-DISPLAY questions in the request; unknown/null uuids are left to processAnswers to reject. */ + private Set answeredQuestionIds(List answers, Map questionMap) { + return answers.stream() + .map(a -> a.getQuestionUuid() == null ? null : questionMap.get(a.getQuestionUuid())) + .filter(q -> q != null && q.getQuestionType() != QuestionType.DISPLAY) + .map(SectionQuestion::getQuestionId) + .collect(Collectors.toSet()); + } + private QuestionOption resolveOption( Map> optionsByQuestion, Long questionId, diff --git a/src/main/java/com/iemr/flw/service/impl/FormResponseItemSaver.java b/src/main/java/com/iemr/flw/service/impl/FormResponseItemSaver.java index 9a6e0487..72e6ed9a 100644 --- a/src/main/java/com/iemr/flw/service/impl/FormResponseItemSaver.java +++ b/src/main/java/com/iemr/flw/service/impl/FormResponseItemSaver.java @@ -88,6 +88,7 @@ public class FormResponseItemSaver { private final JwtUtil jwtUtil; private final CampConfigService campConfigService; private final ConsentRefusalEvaluator consentRefusalEvaluator; + private final ConditionalAnswerPruner conditionalAnswerPruner; /** * Saves one form response in its own independent REQUIRES_NEW transaction. @@ -232,6 +233,9 @@ private FormResponseDTO processSections(FormResponse formResponse, FormResponseR o -> o.getSectionQuestion().getQuestionId(), Collectors.toMap(QuestionOption::getOptionValue, Function.identity()))); + Map> childrenByParent = + conditionalAnswerPruner.loadChildrenByParent(version.getVersionId()); + List sectionDTOs = new ArrayList<>(); for (SectionAnswerRequest sectionReq : req.getSections()) { if (sectionReq.getSectionUuid() == null) { @@ -267,6 +271,7 @@ private FormResponseDTO processSections(FormResponse formResponse, FormResponseR sectionReq.getAnswers(), questionMap, optionsByQuestion, + childrenByParent, actor, vanID, parkingPlaceID); @@ -324,10 +329,18 @@ private List processAnswers( List answers, Map questionMap, Map> optionsByQuestion, + Map> childrenByParent, String actor, Integer vanID, Integer parkingPlaceID) { + // Pass 1: clear old answers of every received question and its SHOW_QUESTION descendants, + // so children hidden by an edited parent don't keep stale answers. Done up-front so a + // parent listed after its child can't wipe the child's freshly inserted answer. + conditionalAnswerPruner.deleteWithDescendants( + sectionResponseId, answeredQuestionIds(answers, questionMap), childrenByParent); + + // Pass 2: insert the received answers List results = new ArrayList<>(); for (QuestionAnswerRequest answer : answers) { if (answer.getQuestionUuid() == null) { @@ -346,8 +359,6 @@ private List processAnswers( continue; } - questionResponseRepo.deleteByQuestionIdAndSectionResponseId(questionId, sectionResponseId); - if (type == QuestionType.RADIO || type == QuestionType.CHECKBOX || type == QuestionType.DROPDOWN) { if (answer.getOptionValue() != null) { QuestionOption opt = resolveOption(optionsByQuestion, questionId, @@ -398,6 +409,15 @@ private List processAnswers( return results; } + /** Ids of the non-DISPLAY questions in the request; unknown/null uuids are left to processAnswers to reject. */ + private Set answeredQuestionIds(List answers, Map questionMap) { + return answers.stream() + .map(a -> a.getQuestionUuid() == null ? null : questionMap.get(a.getQuestionUuid())) + .filter(q -> q != null && q.getQuestionType() != QuestionType.DISPLAY) + .map(SectionQuestion::getQuestionId) + .collect(Collectors.toSet()); + } + private QuestionOption resolveOption(Map> optionsByQuestion, Long questionId, String optionValue, String questionUuid) { Map opts = optionsByQuestion.get(questionId);