From 769dede9b5cc12bb52de519b374110c20fe24b8d Mon Sep 17 00:00:00 2001 From: gaspar-dev Date: Sun, 1 Dec 2024 19:07:59 +0300 Subject: [PATCH 1/5] Added support to ensure GePG Request handless error from live --- .../icare/billing/BillingServiceImpl.java | 483 +++++++++++++----- .../module/icare/billing/dao/PaymentDAO.java | 2 +- .../billing/services/BillingService.java | 2 +- .../services/payment/gepg/BillTrxInf.java | 4 + .../services/payment/gepg/GEPGService.java | 11 +- .../web/controller/GepgBillingController.java | 7 +- 6 files changed, 386 insertions(+), 123 deletions(-) diff --git a/omods/core/api/src/main/java/org/openmrs/module/icare/billing/BillingServiceImpl.java b/omods/core/api/src/main/java/org/openmrs/module/icare/billing/BillingServiceImpl.java index 2c8f6416d..09090197f 100644 --- a/omods/core/api/src/main/java/org/openmrs/module/icare/billing/BillingServiceImpl.java +++ b/omods/core/api/src/main/java/org/openmrs/module/icare/billing/BillingServiceImpl.java @@ -34,6 +34,7 @@ import javax.naming.ConfigurationException; import java.io.IOException; +import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; @@ -774,7 +775,10 @@ public Map processGepgCallbackResponse(Map callb Map status = (Map) callbackData.get("Status"); Map feedbackData = (Map) callbackData.get("FeedbackData"); - + GlobalProperty globalProperty = new GlobalProperty(); + globalProperty.setProperty("gepg.callbackResponseData.icareConnect"); + globalProperty.setPropertyValue(callbackData.toString()); + administrationService.saveGlobalProperty(globalProperty); if (feedbackData.containsKey("gepgPmtSpInfo")) { Map gepgPmtSpInfo = (Map) feedbackData.get("gepgPmtSpInfo"); Map pymtTrxInf = (Map) gepgPmtSpInfo.get("PymtTrxInf"); @@ -897,6 +901,10 @@ public Map processGepgCallbackResponse(Map callb response.put("SystemAuth", systemAuth); response.put("AckData", ackData); + } else { + String requestId = status.containsKey("RequestId") ? (String) status.get("RequestId") : null; + return buildErrorResponse(response, systemAuth, ackData, requestId, + "Encounter an Error on response"); } } else { @@ -945,7 +953,7 @@ public List getAllPaymentsWithStatus() throws Exception { return paymentDAO.findByPaymentTypeId(paymentTypeId); } - public String fetchControlNumber(String requestId) throws Exception { + public String fetchControlNumber(Integer requestId) throws Exception { String controlNumber = null; long startTime = System.currentTimeMillis(); long timeout = 32000; @@ -971,133 +979,391 @@ public String fetchControlNumber(String requestId) throws Exception { } // create payload for GePG Control Number Generation + // @Override + // public Map createGePGPayload(Patient patient, + // List invoiceItems, + // Number totalBillAmount, + // Date billExpirlyDate, String personPhoneAttributeTypeUuid, String + // personEmailAttributeTypeUuid, + // String currency, + // String gepgAuthSignature, String GFSCodeConceptSourceMappingUuid, String + // spCode, String sytemCode, + // String serviceCode, String SpSysId, String subSpCode, String + // clientPrivateKey, String pkcs12Path, + // String pkcs12Password, String enginepublicKey, String billId) throws + // Exception { + // AdministrationService administrationService = + // Context.getAdministrationService(); + // // Validate inputs + // if (patient == null) { + // throw new IllegalArgumentException("Patient cannot be null"); + // } + // if (invoiceItems == null || invoiceItems.isEmpty()) { + // throw new IllegalArgumentException("Invoice items cannot be null or empty"); + // } + // if (currency == null) { + // throw new IllegalArgumentException("Currency cannot be null"); + // } + // if (gepgAuthSignature == null) { + // gepgAuthSignature = ""; + // } + // if (GFSCodeConceptSourceMappingUuid == null) { + // throw new IllegalArgumentException("GFS Code Concept Source Mapping UUID + // cannot be null"); + // } + // if (spCode == null || sytemCode == null || serviceCode == null || SpSysId == + // null || subSpCode == null) { + // String missingParams = ""; + // if (spCode == null) + // missingParams += "spCode "; + // if (sytemCode == null) + // missingParams += "systemCode "; + // if (serviceCode == null) + // missingParams += "serviceCode "; + // if (SpSysId == null) + // missingParams += "SpSysId "; + // if (subSpCode == null) + // missingParams += "subSpCode "; + // throw new IllegalArgumentException("Missing system parameters: " + + // missingParams.trim()); + // } + + // // Retrieve patient attributes + // String patientNames = patient.getGivenName() + " " + patient.getFamilyName(); + // String patientUuid = patient.getId().toString(); + // String patientPhoneNumber = ""; + // String email = ""; + // for (PersonAttribute attribute : patient.getAttributes()) { + // if (personPhoneAttributeTypeUuid != null + // && + // attribute.getAttributeType().getUuid().equals(personPhoneAttributeTypeUuid)) + // { + // patientPhoneNumber = attribute.getValue(); + // } else if (personEmailAttributeTypeUuid != null + // && + // attribute.getAttributeType().getUuid().equals(personEmailAttributeTypeUuid)) + // { + // email = attribute.getValue(); + // } + // } + + // // BillItems generation + + // BillItems billItems = new BillItems(); + + // for (InvoiceItem invoiceItem : invoiceItems) { + // Drug drug = invoiceItem.getItem().getDrug(); + // Concept concept = invoiceItem.getItem().getConcept(); + + // if (drug == null && concept == null) { + // throw new IllegalStateException("Concept can not be null for InvoiceItem" + + // drug + concept); + // } else if (concept != null) { + // for (ConceptMap conceptMap : concept.getConceptMappings()) { + // if (conceptMap.getConceptReferenceTerm().getConceptSource().getUuid() + // .equals(GFSCodeConceptSourceMappingUuid)) { + // String GFSCode = conceptMap.getConceptReferenceTerm().getCode(); + // billItems.getBillItem().add( + // new BillItem(invoiceItem.getItem().getId().toString(), "N", + // invoiceItem.getPrice().toString(), + // invoiceItem.getPrice().toString(), "0.0", GFSCode)); + // } else { + // throw new IllegalStateException( + // "Please verify GFS CODE concept mapping if configured in a correct way"); + // } + // } + // } else if (drug != null) { + // Concept drugConcept = drug.getConcept(); + // GlobalProperty globalProperty = new GlobalProperty(); + // for (ConceptMap conceptMap : drugConcept.getConceptMappings()) { + // if (conceptMap.getConceptReferenceTerm().getConceptSource().getUuid() + // .equals(GFSCodeConceptSourceMappingUuid)) { + // globalProperty.setProperty("iCare.gepg.DrugConcept.icareConnect"); + // globalProperty.setPropertyValue("if condition meet"); + // administrationService.saveGlobalProperty(globalProperty); + // String GFSCode = conceptMap.getConceptReferenceTerm().getCode(); + // billItems.getBillItem().add( + // new BillItem(invoiceItem.getItem().getId().toString(), "N", + // invoiceItem.getPrice().toString(), + // invoiceItem.getPrice().toString(), "0.0", GFSCode)); + // } else { + // throw new IllegalStateException( + // "Please verify GFS CODE concept mapping if configured in a correct way"); + // } + // } + // } + + // } + + // // Create and populate BillHdr + // BillHdr billHdr = new BillHdr(); + // billHdr.setSpCode(spCode); + // billHdr.setRtrRespFlg("true"); + + // // Create and populate BillTrxInf + // BillTrxInf billTrxInf = new BillTrxInf(); + // billTrxInf.setBillId(billId); + // billTrxInf.setSubSpCode(subSpCode); + // billTrxInf.setSpSysId(SpSysId); + // billTrxInf.setBillAmt(totalBillAmount.toString()); + // billTrxInf.setMiscAmt("0"); + // LocalDateTime now = LocalDateTime.now(); + // DateTimeFormatter formatter = + // DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"); + // String formattedNow = now.format(formatter); + // billTrxInf.setBillGenDt(formattedNow); + + // LocalDateTime expirationTime = now.plusHours(24); + // String formattedExpirationTime = expirationTime.format(formatter); + // billTrxInf.setBillExprDt(formattedExpirationTime); + // billTrxInf.setPyrId("40"); + // billTrxInf.setPyrName(patientNames.toUpperCase()); + // billTrxInf.setBillDesc("Hospital Bill Payments"); + // billTrxInf.setBillGenBy("UDSM Hospital"); + // billTrxInf.setBillApprBy(patientNames.toUpperCase()); + // billTrxInf.setPyrCellNum(patientPhoneNumber); + // billTrxInf.setPyrEmail(email); + // billTrxInf.setCcy(currency); + // billTrxInf.setBillEqvAmt(totalBillAmount.toString()); + // billTrxInf.setRemFlag("false"); + // billTrxInf.setBillPayOpt("2"); + // billTrxInf.setBillItems(billItems); + // // Create and populate RequestData + // // Save PaymentData before Reference Number (Control Number) + // RequestData requestData = new RequestData(); + // try { + // Integer billUuid = Integer.parseInt(billId); + // Invoice invoice = invoiceDAO.findById(billUuid); + // if (invoice == null) { + // throw new Exception("Invoice of this Bill id " + billId + " is not valid"); + + // } + + // String paymentTypeConceptUuid = administrationService + // .getGlobalProperty(ICareConfig.DEFAULT_PAYMENT_TYPE_VIA_CONTROL_NUMBER); + // if (paymentTypeConceptUuid == null) { + // throw new Exception("No default payment type based on control number"); + // } + + // Concept paymentType = + // Context.getConceptService().getConceptByUuid(paymentTypeConceptUuid); + // if (paymentType == null) { + // throw new Exception("Payment type concept not found for UUID: " + + // paymentTypeConceptUuid); + // } + + // Payment payment = new Payment(); + // payment.setPaymentType(paymentType); + // payment.setReferenceNumber(null); + // payment.setInvoice(invoice); + // payment.setReceivedBy("SYSTEM"); + // payment.setStatus(PaymentStatus.REQUESTED); + // payment.setCreator(Context.getAuthenticatedUser()); + // payment.setDateCreated(new Date()); + // this.paymentDAO.save(payment); + // Integer paymentId = payment.getId(); + // requestData.setRequestId(paymentId.toString()); + // } catch (Exception e) { + // throw new Exception("Failed to Save Payments Data: " + e.getMessage()); + // } + + // requestData.setBillHdr(billHdr); + // requestData.setBillTrxInf(billTrxInf); + + // // Create and populate SystemAuth + // SystemAuth systemAuth = new SystemAuth(); + // systemAuth.setSystemCode(sytemCode); + // systemAuth.setServiceCode(serviceCode); + + // // Create and return BillSubmissionRequest + // BillSubmissionRequest billRequest = new BillSubmissionRequest(); + // billRequest.setSystemAuth(systemAuth); + // billRequest.setRequestData(requestData); + + // // Serialize RequestData to JSON for signing + // String requestDataJson = new ObjectMapper().writeValueAsString(requestData); + + // // Save the payload in a global property + // GlobalProperty globalProperty = new GlobalProperty(); + // globalProperty.setProperty("gepg.requestDataJson.icareConnect"); + // globalProperty.setPropertyValue(requestDataJson); + // administrationService.saveGlobalProperty(globalProperty); + + // // Sign the request data + // String signature = SignatureUtils.signData(requestDataJson, + // clientPrivateKey); + // systemAuth.setSignature(signature); + + // Map result = new HashMap<>(); + // result.put("billRequest", billRequest); + // result.put("signature", signature); + + // return result; + // } @Override public Map createGePGPayload(Patient patient, List invoiceItems, - Number totalBillAmount, - Date billExpirlyDate, String personPhoneAttributeTypeUuid, String personEmailAttributeTypeUuid, - String currency, - String gepgAuthSignature, String GFSCodeConceptSourceMappingUuid, String spCode, String sytemCode, - String serviceCode, String SpSysId, String subSpCode, String clientPrivateKey, String pkcs12Path, + Number totalBillAmount, Date billExpirlyDate, String personPhoneAttributeTypeUuid, + String personEmailAttributeTypeUuid, String currency, String gepgAuthSignature, + String GFSCodeConceptSourceMappingUuid, String spCode, String sytemCode, String serviceCode, + String SpSysId, String subSpCode, String clientPrivateKey, String pkcs12Path, String pkcs12Password, String enginepublicKey, String billId) throws Exception { - AdministrationService administrationService = Context.getAdministrationService(); + // Validate inputs - if (patient == null) { - throw new IllegalArgumentException("Patient cannot be null"); - } - if (invoiceItems == null || invoiceItems.isEmpty()) { - throw new IllegalArgumentException("Invoice items cannot be null or empty"); - } - if (currency == null) { - throw new IllegalArgumentException("Currency cannot be null"); - } - if (gepgAuthSignature == null) { - gepgAuthSignature = ""; - } - if (GFSCodeConceptSourceMappingUuid == null) { - throw new IllegalArgumentException("GFS Code Concept Source Mapping UUID cannot be null"); - } - if (spCode == null || sytemCode == null || serviceCode == null || SpSysId == null || subSpCode == null) { - String missingParams = ""; - if (spCode == null) - missingParams += "spCode "; - if (sytemCode == null) - missingParams += "systemCode "; - if (serviceCode == null) - missingParams += "serviceCode "; - if (SpSysId == null) - missingParams += "SpSysId "; - if (subSpCode == null) - missingParams += "subSpCode "; - throw new IllegalArgumentException("Missing system parameters: " + missingParams.trim()); - } + validateInputs(patient, invoiceItems, currency, gepgAuthSignature, GFSCodeConceptSourceMappingUuid, + spCode, sytemCode, serviceCode, SpSysId, subSpCode); // Retrieve patient attributes + String patientId = patient.getPatientId().toString(); String patientNames = patient.getGivenName() + " " + patient.getFamilyName(); - String patientUuid = patient.getId().toString(); - String patientPhoneNumber = ""; - String email = ""; - for (PersonAttribute attribute : patient.getAttributes()) { - if (personPhoneAttributeTypeUuid != null - && attribute.getAttributeType().getUuid().equals(personPhoneAttributeTypeUuid)) { - patientPhoneNumber = attribute.getValue(); - } else if (personEmailAttributeTypeUuid != null - && attribute.getAttributeType().getUuid().equals(personEmailAttributeTypeUuid)) { - email = attribute.getValue(); - } - } + String patientPhoneNumber = getPatientPhoneNumber(patient, personPhoneAttributeTypeUuid); + String email = getPatientEmail(patient, personEmailAttributeTypeUuid); // BillItems generation + BillItems billItems = createBillItems(invoiceItems, GFSCodeConceptSourceMappingUuid); - BillItems billItems = new BillItems(); + // Create and populate BillHdr + BillHdr billHdr = createBillHdr(spCode); + + // Create and populate BillTrxInf + BillTrxInf billTrxInf = createBillTrxInf(totalBillAmount, patientNames, patientPhoneNumber, email, + currency, billId, billExpirlyDate, billItems, subSpCode, SpSysId, patientId); + + // Create and populate RequestData + RequestData requestData = createRequestData(billHdr, billTrxInf, billId); + + // Create and populate SystemAuth + SystemAuth systemAuth = createSystemAuth(sytemCode, serviceCode); + + // Create the BillSubmissionRequest + BillSubmissionRequest billRequest = new BillSubmissionRequest(); + billRequest.setSystemAuth(systemAuth); + billRequest.setRequestData(requestData); + // Serialize RequestData to JSON for signing + String requestDataJson = new ObjectMapper().writeValueAsString(requestData); + + // Sign the request data + String signature = SignatureUtils.signData(requestDataJson, clientPrivateKey); + systemAuth.setSignature(signature); + + // Return the result + Map result = new LinkedHashMap<>(); + result.put("billRequest", billRequest); + result.put("signature", signature); + + return result; + } + + // Validate the inputs + private void validateInputs(Patient patient, List invoiceItems, String currency, String gepgAuthSignature, + String GFSCodeConceptSourceMappingUuid, String spCode, String sytemCode, String serviceCode, String SpSysId, + String subSpCode) { + if (patient == null || invoiceItems == null || invoiceItems.isEmpty() || currency == null || spCode == null + || sytemCode == null || serviceCode == null || SpSysId == null || subSpCode == null) { + throw new IllegalArgumentException("Invalid system inputs provided."); + } + } + + // Retrieve the patient phone number + private String getPatientPhoneNumber(Patient patient, String personPhoneAttributeTypeUuid) { + for (PersonAttribute attribute : patient.getAttributes()) { + if (attribute.getAttributeType().getUuid().equals(personPhoneAttributeTypeUuid)) { + return attribute.getValue(); + } + } + return ""; + } + + // Retrieve the patient email + private String getPatientEmail(Patient patient, String personEmailAttributeTypeUuid) { + for (PersonAttribute attribute : patient.getAttributes()) { + if (attribute.getAttributeType().getUuid().equals(personEmailAttributeTypeUuid)) { + return attribute.getValue(); + } + } + return ""; + } + + // Create BillItems + private BillItems createBillItems(List invoiceItems, String GFSCodeConceptSourceMappingUuid) { + BillItems billItems = new BillItems(); for (InvoiceItem invoiceItem : invoiceItems) { Drug drug = invoiceItem.getItem().getDrug(); Concept concept = invoiceItem.getItem().getConcept(); - if (drug == null && concept == null) { throw new IllegalStateException("Concept can not be null for InvoiceItem" + drug + concept); } else if (concept != null) { for (ConceptMap conceptMap : concept.getConceptMappings()) { if (conceptMap.getConceptReferenceTerm().getConceptSource().getUuid() - .equals(GFSCodeConceptSourceMappingUuid)) { + .equals(GFSCodeConceptSourceMappingUuid)) { String GFSCode = conceptMap.getConceptReferenceTerm().getCode(); billItems.getBillItem().add( - new BillItem(invoiceItem.getItem().getId().toString(), "N", - invoiceItem.getPrice().toString(), - invoiceItem.getPrice().toString(), "0.0", GFSCode)); + new BillItem(invoiceItem.getItem().getId().toString(), "N", invoiceItem.getPrice().toString(), + invoiceItem.getPrice().toString(), "0.0", GFSCode)); } else { throw new IllegalStateException( - "Please verify GFS CODE concept mapping if configured in a correct way"); + "Please verify GFS CODE concept mapping if configured in a correct way"); } } } else if (drug != null) { Concept drugConcept = drug.getConcept(); - GlobalProperty globalProperty = new GlobalProperty(); for (ConceptMap conceptMap : drugConcept.getConceptMappings()) { if (conceptMap.getConceptReferenceTerm().getConceptSource().getUuid() - .equals(GFSCodeConceptSourceMappingUuid)) { - globalProperty.setProperty("iCare.gepg.DrugConcept.icareConnect"); - globalProperty.setPropertyValue("if condition meet"); - administrationService.saveGlobalProperty(globalProperty); + .equals(GFSCodeConceptSourceMappingUuid)) { + String GFSCode = conceptMap.getConceptReferenceTerm().getCode(); billItems.getBillItem().add( - new BillItem(invoiceItem.getItem().getId().toString(), "N", - invoiceItem.getPrice().toString(), - invoiceItem.getPrice().toString(), "0.0", GFSCode)); + new BillItem(invoiceItem.getItem().getId().toString(), "N", invoiceItem.getPrice().toString(), + invoiceItem.getPrice().toString(), "0.0", GFSCode)); } else { throw new IllegalStateException( - "Please verify GFS CODE concept mapping if configured in a correct way"); + "Please verify GFS CODE concept mapping if configured in a correct way"); } } } - } - - // Create and populate BillHdr + return billItems; + } + + // Create BillHdr + private BillHdr createBillHdr(String spCode) { BillHdr billHdr = new BillHdr(); billHdr.setSpCode(spCode); billHdr.setRtrRespFlg("true"); - - // Create and populate BillTrxInf + return billHdr; + } + + // format Date + private String formatDate(Date date) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); + return sdf.format(date); + } + + // Create BillTrxInf + private BillTrxInf createBillTrxInf(Number totalBillAmount, String patientNames, String patientPhoneNumber, + String email, String currency, String billId, Date billExpirlyDate, BillItems billItems, String subSpCode, + String SpSysId, String patientId) { + + Date now = new Date(); + + // Calculate 24 hours from BillGenDt + Calendar calendar = Calendar.getInstance(); + calendar.setTime(now); + calendar.add(Calendar.HOUR_OF_DAY, 24); + Date billExpiryDate = calendar.getTime(); BillTrxInf billTrxInf = new BillTrxInf(); billTrxInf.setBillId(billId); billTrxInf.setSubSpCode(subSpCode); billTrxInf.setSpSysId(SpSysId); billTrxInf.setBillAmt(totalBillAmount.toString()); billTrxInf.setMiscAmt("0"); - LocalDateTime now = LocalDateTime.now(); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"); - String formattedNow = now.format(formatter); - billTrxInf.setBillGenDt(formattedNow); - - LocalDateTime expirationTime = now.plusHours(24); - String formattedExpirationTime = expirationTime.format(formatter); - billTrxInf.setBillExprDt(formattedExpirationTime); - billTrxInf.setPyrId("40"); - billTrxInf.setPyrName(patientNames.toUpperCase()); + billTrxInf.setBillGenDt(formatDate(new Date())); + billTrxInf.setBillExprDt(formatDate(billExpiryDate)); + billTrxInf.setPyrId(patientId); + billTrxInf.setPyrName(patientNames); billTrxInf.setBillDesc("Hospital Bill Payments"); billTrxInf.setBillGenBy("UDSM Hospital"); - billTrxInf.setBillApprBy(patientNames.toUpperCase()); + billTrxInf.setBillApprBy("UDSM"); billTrxInf.setPyrCellNum(patientPhoneNumber); billTrxInf.setPyrEmail(email); billTrxInf.setCcy(currency); @@ -1105,7 +1371,12 @@ public Map createGePGPayload(Patient patient, List billTrxInf.setRemFlag("false"); billTrxInf.setBillPayOpt("2"); billTrxInf.setBillItems(billItems); - // Create and populate RequestData + return billTrxInf; + } + + // Create RequestData + private RequestData createRequestData(BillHdr billHdr, BillTrxInf billTrxInf, String billId) throws Exception { + AdministrationService administrationService = Context.getAdministrationService(); // Save PaymentData before Reference Number (Control Number) RequestData requestData = new RequestData(); try { @@ -1113,20 +1384,20 @@ public Map createGePGPayload(Patient patient, List Invoice invoice = invoiceDAO.findById(billUuid); if (invoice == null) { throw new Exception("Invoice of this Bill id " + billId + " is not valid"); - + } - + String paymentTypeConceptUuid = administrationService - .getGlobalProperty(ICareConfig.DEFAULT_PAYMENT_TYPE_VIA_CONTROL_NUMBER); + .getGlobalProperty(ICareConfig.DEFAULT_PAYMENT_TYPE_VIA_CONTROL_NUMBER); if (paymentTypeConceptUuid == null) { throw new Exception("No default payment type based on control number"); } - + Concept paymentType = Context.getConceptService().getConceptByUuid(paymentTypeConceptUuid); if (paymentType == null) { throw new Exception("Payment type concept not found for UUID: " + paymentTypeConceptUuid); } - + Payment payment = new Payment(); payment.setPaymentType(paymentType); payment.setReferenceNumber(null); @@ -1138,41 +1409,21 @@ public Map createGePGPayload(Patient patient, List this.paymentDAO.save(payment); Integer paymentId = payment.getId(); requestData.setRequestId(paymentId.toString()); - } catch (Exception e) { + } + catch (Exception e) { throw new Exception("Failed to Save Payments Data: " + e.getMessage()); } - requestData.setBillHdr(billHdr); requestData.setBillTrxInf(billTrxInf); - - // Create and populate SystemAuth + return requestData; + } + + // Create SystemAuth + private SystemAuth createSystemAuth(String sytemCode, String serviceCode) { SystemAuth systemAuth = new SystemAuth(); systemAuth.setSystemCode(sytemCode); systemAuth.setServiceCode(serviceCode); - - // Create and return BillSubmissionRequest - BillSubmissionRequest billRequest = new BillSubmissionRequest(); - billRequest.setSystemAuth(systemAuth); - billRequest.setRequestData(requestData); - - // Serialize RequestData to JSON for signing - String requestDataJson = new ObjectMapper().writeValueAsString(requestData); - - // Save the payload in a global property - GlobalProperty globalProperty = new GlobalProperty(); - globalProperty.setProperty("gepg.requestDataJson.icareConnect"); - globalProperty.setPropertyValue(requestDataJson); - administrationService.saveGlobalProperty(globalProperty); - - // Sign the request data - String signature = SignatureUtils.signData(requestDataJson, clientPrivateKey); - systemAuth.setSignature(signature); - - Map result = new HashMap<>(); - result.put("billRequest", billRequest); - result.put("signature", signature); - - return result; + return systemAuth; } @Override @@ -1181,7 +1432,7 @@ public String signatureData(String rowData) throws Exception { String clientPrivateKey = administrationService.getGlobalProperty(ICareConfig.CLIENT_PRIVATE_KEY); try { GlobalProperty globalProperty = new GlobalProperty(); - globalProperty.setProperty("gepg.callbackrowData.icareConnect"); + globalProperty.setProperty("gepg.signaturerowData.icareConnect"); globalProperty.setPropertyValue(rowData); administrationService.saveGlobalProperty(globalProperty); String signature = SignatureUtils.signData(rowData, clientPrivateKey); diff --git a/omods/core/api/src/main/java/org/openmrs/module/icare/billing/dao/PaymentDAO.java b/omods/core/api/src/main/java/org/openmrs/module/icare/billing/dao/PaymentDAO.java index 8c6b3a778..47165ea2c 100644 --- a/omods/core/api/src/main/java/org/openmrs/module/icare/billing/dao/PaymentDAO.java +++ b/omods/core/api/src/main/java/org/openmrs/module/icare/billing/dao/PaymentDAO.java @@ -52,7 +52,7 @@ public List findByPatientUuid(String patientUuid) { return query.list(); } - public String getReferenceNumberByRequestId(String requestId) { + public String getReferenceNumberByRequestId(Integer requestId) { DbSession session = this.getSession(); String queryStr = "SELECT p.referenceNumber FROM Payment p WHERE p.id = :requestId"; Query query = session.createQuery(queryStr); diff --git a/omods/core/api/src/main/java/org/openmrs/module/icare/billing/services/BillingService.java b/omods/core/api/src/main/java/org/openmrs/module/icare/billing/services/BillingService.java index b2aae4d51..84fd8ab16 100644 --- a/omods/core/api/src/main/java/org/openmrs/module/icare/billing/services/BillingService.java +++ b/omods/core/api/src/main/java/org/openmrs/module/icare/billing/services/BillingService.java @@ -86,7 +86,7 @@ public interface BillingService extends OpenmrsService { Map processGepgCallbackResponse(Map feedBack) throws Exception; - String fetchControlNumber(String requestId) throws Exception; + String fetchControlNumber(Integer requestId) throws Exception; List getAllPaymentsWithStatus() throws Exception; diff --git a/omods/core/api/src/main/java/org/openmrs/module/icare/billing/services/payment/gepg/BillTrxInf.java b/omods/core/api/src/main/java/org/openmrs/module/icare/billing/services/payment/gepg/BillTrxInf.java index 6916fd8b7..bf6e7e924 100644 --- a/omods/core/api/src/main/java/org/openmrs/module/icare/billing/services/payment/gepg/BillTrxInf.java +++ b/omods/core/api/src/main/java/org/openmrs/module/icare/billing/services/payment/gepg/BillTrxInf.java @@ -1,7 +1,11 @@ package org.openmrs.module.icare.billing.services.payment.gepg; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonProperty; +@JsonPropertyOrder({ "BillId", "SubSpCode", "SpSysId", "BillAmt", "MiscAmt", "BillExprDt", "PyrId", "PyrName", "BillDesc", + "BillGenDt", "BillGenBy", "BillApprBy", "PyrCellNum", "PyrEmail", "Ccy", "BillEqvAmt", "RemFlag", "BillPayOpt", + "BillItems" }) public class BillTrxInf { private String BillId; diff --git a/omods/core/api/src/main/java/org/openmrs/module/icare/billing/services/payment/gepg/GEPGService.java b/omods/core/api/src/main/java/org/openmrs/module/icare/billing/services/payment/gepg/GEPGService.java index 196b0f3b6..6a6c7e77d 100644 --- a/omods/core/api/src/main/java/org/openmrs/module/icare/billing/services/payment/gepg/GEPGService.java +++ b/omods/core/api/src/main/java/org/openmrs/module/icare/billing/services/payment/gepg/GEPGService.java @@ -25,7 +25,7 @@ public class GEPGService { private PaymentDAO paymentDAO; @Autowired - private BillingService billingService; + private BillingService billingService; private final Map> callbackResponses = new ConcurrentHashMap<>(); private final ObjectMapper objectMapper = new ObjectMapper(); @@ -46,7 +46,7 @@ public Map submitGepgRequest(String jsonPayload, String signatur // Write JSON payload try (OutputStream os = con.getOutputStream(); - BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"))) { + BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"))) { writer.write(jsonPayload); writer.flush(); } @@ -81,7 +81,9 @@ public Map submitGepgRequest(String jsonPayload, String signatur // Handle different ackCodes if ("R3001".equals(ackCode)) { - String controlNumber = billingService.fetchControlNumber(requestId); + Integer requestpaymentId = null; + requestpaymentId = Integer.parseInt(requestId); + String controlNumber = billingService.fetchControlNumber(requestpaymentId); // Save the payload in a global property AdministrationService administrationService = Context.getAdministrationService(); GlobalProperty globalProperty = new GlobalProperty(); @@ -89,7 +91,8 @@ public Map submitGepgRequest(String jsonPayload, String signatur globalProperty.setPropertyValue(controlNumber); administrationService.saveGlobalProperty(globalProperty); responseMap.put("status", "success"); - responseMap.put("controlNumber", controlNumber != null ? controlNumber : "Not found within timeout"); + responseMap.put("controlNumber", + controlNumber != null ? controlNumber : "Not found within timeout"); responseMap.put("ackCode", ackCode); responseMap.put("message", "Request processed successfully."); } else if ("CONS9005".equals(ackCode)) { diff --git a/omods/core/omod/src/main/java/org/openmrs/module/icare/web/controller/GepgBillingController.java b/omods/core/omod/src/main/java/org/openmrs/module/icare/web/controller/GepgBillingController.java index 0a9684cfe..883b2803d 100644 --- a/omods/core/omod/src/main/java/org/openmrs/module/icare/web/controller/GepgBillingController.java +++ b/omods/core/omod/src/main/java/org/openmrs/module/icare/web/controller/GepgBillingController.java @@ -233,8 +233,13 @@ public ResponseEntity handleCallback(HttpServletRequest request) { private ResponseEntity> generateErrorResponse(String errorMessage, String requestId) { Map errorResponse = new HashMap<>(); try { - // AckData as per your requested format + AdministrationService administrationService = Context.getAdministrationService(); + // Retrieve GePG user credentials + String gepgUsername = administrationService.getGlobalProperty(ICareConfig.GEPG_USERNAME); + String gepgPassword = administrationService.getGlobalProperty(ICareConfig.GEPG_PASSWORD); + Context.authenticate(gepgUsername, gepgPassword); + // AckData as per your requested format Map ackData = new HashMap<>(); ackData.put("Description", errorMessage); ackData.put("RequestId", requestId); From cad4f2e6c5a758df1be6caaaad032c863f990880 Mon Sep 17 00:00:00 2001 From: gaspar-dev Date: Mon, 2 Dec 2024 10:51:09 +0300 Subject: [PATCH 2/5] Added support to ensure GePG Request handless error from live --- .../patients-tabular-list/patients-tabular-list.component.ts | 2 +- ui/src/app/shared/resources/visits/services/visits.service.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ui/src/app/shared/components/patients-tabular-list/patients-tabular-list.component.ts b/ui/src/app/shared/components/patients-tabular-list/patients-tabular-list.component.ts index af15fad46..e0f7a1468 100644 --- a/ui/src/app/shared/components/patients-tabular-list/patients-tabular-list.component.ts +++ b/ui/src/app/shared/components/patients-tabular-list/patients-tabular-list.component.ts @@ -37,7 +37,7 @@ export class PatientsTabularListComponent implements OnInit, OnChanges { constructor( private visitService: VisitsService,) {} ngOnInit(): void { - console.log("payment type passed .....",this.paymentTypeSelected) + // console.log("payment type passed .....",this.paymentTypeSelected) this.dataSource = new MatTableDataSource( sanitizePatientsVisitsForTabularPatientListing( this.visits, diff --git a/ui/src/app/shared/resources/visits/services/visits.service.ts b/ui/src/app/shared/resources/visits/services/visits.service.ts index ba7443313..3f34a4d08 100755 --- a/ui/src/app/shared/resources/visits/services/visits.service.ts +++ b/ui/src/app/shared/resources/visits/services/visits.service.ts @@ -357,7 +357,7 @@ export class VisitsService { } // - console.log("url fired ...",`icare/visit?${parametersString.replace("&","" )}&startIndex=${startIndex}&limit=${limit}`); + // console.log("url fired ...",`icare/visit?${parametersString.replace("&","" )}&startIndex=${startIndex}&limit=${limit}`); return ( locationUuids?.length > 0 ? zip( From 2f6712e3900937ce2785305e13d8c7f8ed6c4e4e Mon Sep 17 00:00:00 2001 From: gaspar-dev Date: Mon, 2 Dec 2024 15:24:02 +0300 Subject: [PATCH 3/5] Added support to ensure GePG Request handless error from live --- .../icare/billing/BillingServiceImpl.java | 405 +++++++++--------- .../visits/services/visits.service.ts | 1 - 2 files changed, 211 insertions(+), 195 deletions(-) diff --git a/omods/core/api/src/main/java/org/openmrs/module/icare/billing/BillingServiceImpl.java b/omods/core/api/src/main/java/org/openmrs/module/icare/billing/BillingServiceImpl.java index 09090197f..ac6bc0673 100644 --- a/omods/core/api/src/main/java/org/openmrs/module/icare/billing/BillingServiceImpl.java +++ b/omods/core/api/src/main/java/org/openmrs/module/icare/billing/BillingServiceImpl.java @@ -42,43 +42,43 @@ import java.util.concurrent.TimeUnit; public class BillingServiceImpl extends BaseOpenmrsService implements BillingService { - + ICareDao dao; - + InvoiceDAO invoiceDAO; - + PaymentDAO paymentDAO; - + DiscountDAO discountDAO; - + public void setDao(ICareDao dao) { this.dao = dao; } - + public void setInvoiceDAO(InvoiceDAO invoiceDAO) { this.invoiceDAO = invoiceDAO; } - + public void setPaymentDAO(PaymentDAO paymentDAO) { this.paymentDAO = paymentDAO; } - + public void setDiscountDAO(DiscountDAO discountDAO) { this.discountDAO = discountDAO; } - + @Override public Invoice createInvoice(Invoice invoice) throws APIException { return this.invoiceDAO.save(invoice); } - + @Override public Invoice createInvoice(Encounter encounter) throws APIException { Invoice invoice = convertEncounterToInvoice(encounter); this.invoiceDAO.save(invoice); return invoice; } - + @Override public List getPendingInvoices(String patientUuid) { List invoices = this.invoiceDAO.findByPatientUuidAndPending(patientUuid); @@ -95,12 +95,12 @@ public List getPendingInvoices(String patientUuid) { return invoices; // return this.invoiceDAO.findByPatientUuid(patientUuid); } - + @Override public List getPatientsInvoices(String patientUuid) { return this.invoiceDAO.findByPatientUuid(patientUuid); } - + private InvoiceItem getInvoiceItem(OrderMetaData orderMetaData) { ItemPrice itemPrice = orderMetaData.getItemPrice(); InvoiceItem invoiceItem = new InvoiceItem(); @@ -116,13 +116,13 @@ private InvoiceItem getInvoiceItem(OrderMetaData orderMetaData) { } else { invoiceItem.setQuantity(1.0); } - + invoiceItem.setItem(itemPrice.getItem()); invoiceItem.setPrice(itemPrice.getPrice()); invoiceItem.setOrder(orderMetaData.getOrder()); return invoiceItem; } - + private InvoiceItem getTopUpInvoiceItem(OrderMetaData orderMetaData) { ItemPrice itemPrice = orderMetaData.getItemPrice(); if (itemPrice.getPayable() == null) { @@ -144,17 +144,18 @@ private InvoiceItem getTopUpInvoiceItem(OrderMetaData orderMetaData) { } else { invoiceItem.setQuantity(1.0); } - + invoiceItem.setItem(itemPrice.getItem()); invoiceItem.setPrice(itemPrice.getPayable()); invoiceItem.setOrder(orderMetaData.getOrder()); return invoiceItem; } - + @Override public Order processOrder(OrderMetaData orderMetaData, Double quantity) { - - List invoices = this.getInvoicesByVisitUuid(orderMetaData.getOrder().getEncounter().getVisit().getUuid()); + + List invoices = this + .getInvoicesByVisitUuid(orderMetaData.getOrder().getEncounter().getVisit().getUuid()); if (invoices.size() == 0) { Concept paymentModeConcept; if (!orderMetaData.getItemPrice().getPaymentType().getName().getName().toLowerCase().equals("cash")) { @@ -180,7 +181,7 @@ public Order processOrder(OrderMetaData orderMetaData, Doub Invoice invoice = new Invoice(); invoice.setPaymentMode(paymentModeConcept); invoice.setVisit(orderMetaData.getOrder().getEncounter().getVisit()); - + InvoiceItem invoiceItem = getInvoiceItem(orderMetaData); if (quantity != null) { invoiceItem.setQuantity(quantity); @@ -230,21 +231,22 @@ public Order processOrder(OrderMetaData orderMetaData, Doub existingInvoice.getInvoiceItems().add(invoiceItem); } } - + // Automatic discount creation for full exempted discounts List discountInvoiceItems = existingInvoice.getDiscountItems(); Boolean isFullExemptedCheck = false; - + if (discountInvoiceItems != null && discountInvoiceItems.size() > 0) { for (DiscountInvoiceItem discountItem : discountInvoiceItems) { if (discountItem.getDiscount() != null) { - if (discountItem.getDiscount().getExempted() != null && discountItem.getDiscount().getExempted()) { + if (discountItem.getDiscount().getExempted() != null + && discountItem.getDiscount().getExempted()) { isFullExemptedCheck = true; } } } } - + if (isFullExemptedCheck) { for (InvoiceItem invoiceItem : existingInvoice.getInvoiceItems()) { // Find the coresponding discount item @@ -269,12 +271,12 @@ public Order processOrder(OrderMetaData orderMetaData, Doub } return orderMetaData.getOrder(); } - + @Override public InvoiceItem getInvoiceItemByOrder(Order order) { return invoiceDAO.getInvoiceItemByOrderUuid(order.getUuid()); } - + @Override public SyncResult syncInsurance(String insurance) throws Exception { InsuranceService insuranceService = null; @@ -285,7 +287,7 @@ public SyncResult syncInsurance(String insurance) throws Exception { } return insuranceService.syncPriceList(); } - + @Override public List getInvoicesByVisitUuid(String visitUuid) { List invoices = this.invoiceDAO.findByVisitUuidAndPending(visitUuid); @@ -301,25 +303,26 @@ public List getInvoicesByVisitUuid(String visitUuid) { } return invoices; } - + @Override public Invoice getInvoiceDetailsByUuid(String uuid) { Invoice invoice = this.invoiceDAO.findByUuid(uuid); // TODO: Check for any discounts return invoice; } - + @Override public List getPatientPayments(String patientUuid) { return paymentDAO.findByPatientUuid(patientUuid); } - + @Override public Payment confirmPayment(Payment payment) throws Exception { Invoice invoice = invoiceDAO.findByUuid(payment.getInvoice().getUuid()); // TODO Payments should address particular item prices in the invoice payment.setInvoice(invoice); - Concept paymentType = Context.getService(ConceptService.class).getConceptByUuid(payment.getPaymentType().getUuid()); + Concept paymentType = Context.getService(ConceptService.class) + .getConceptByUuid(payment.getPaymentType().getUuid()); if (paymentType == null) { throw new Exception("Payment Type with id '" + payment.getPaymentType().getUuid() + "' does not exist."); } @@ -327,13 +330,13 @@ public Payment confirmPayment(Payment payment) throws Exception { throw new Exception("Reference number should not be null."); } payment.setPaymentType(paymentType); - + for (PaymentItem item : payment.getItems()) { item.setPayment(payment); InvoiceItem invoiceItem = null; for (InvoiceItem iI : invoice.getInvoiceItems()) { if (iI.getItem().getUuid().equals(item.getItem().getUuid()) - && iI.getOrder().getUuid().equals(item.getOrder().getUuid())) { + && iI.getOrder().getUuid().equals(item.getOrder().getUuid())) { invoiceItem = iI; } } @@ -348,7 +351,7 @@ public Payment confirmPayment(Payment payment) throws Exception { payment.setStatus(PaymentStatus.PAID); return this.paymentDAO.save(payment); } - + @Override public Discount discountInvoice(Discount discount) throws Exception { Concept discountCriteria = Context.getConceptService().getConceptByUuid(discount.getCriteria().getUuid()); @@ -370,9 +373,10 @@ public Discount discountInvoice(Discount discount) throws Exception { } Invoice invoice = invoiceDAO.findByUuid(discountInvoiceItem.getInvoice().getUuid()); if (invoice == null) { - throw new Exception("Invoice with id '" + discountInvoiceItem.getInvoice().getUuid() + "' does not exist."); + throw new Exception( + "Invoice with id '" + discountInvoiceItem.getInvoice().getUuid() + "' does not exist."); } - + DiscountInvoiceItem newItem = new DiscountInvoiceItem(); newItem.setItem(item); newItem.setInvoice(invoice); @@ -381,7 +385,7 @@ public Discount discountInvoice(Discount discount) throws Exception { newItems.add(newItem); } discount.setItems(newItems); - + if (discount.getAttachment() != null) { Obs obs = Context.getObsService().getObsByUuid(discount.getAttachment().getUuid()); if (obs == null) { @@ -390,21 +394,21 @@ public Discount discountInvoice(Discount discount) throws Exception { discount.setAttachment(obs); } // discount.setCreator(Context.getAuthenticatedUser()); - + return discountDAO.save(discount); } - + @Override public List getPatientDiscounts(String patientUuid) { return discountDAO.findByPatientUuid(patientUuid); } - + @Override public Concept createDiscountCriteria(Concept discountCriteria) { Concept newDiscountCriteria = Context.getConceptService().saveConcept(discountCriteria); return newDiscountCriteria; } - + @Override public VisitMetaData validateVisitMetaData(VisitWrapper visit) throws Exception { VisitMetaData visitMetaData = new VisitMetaData(); @@ -412,40 +416,40 @@ public VisitMetaData validateVisitMetaData(VisitWrapper visit) throws Exception String serviceAttribute = adminService.getGlobalProperty(ICareConfig.SERVICE_ATTRIBUTE); if (serviceAttribute == null) { throw new ConfigurationException("Attribute ID for billing is not set. Please set '" - + ICareConfig.SERVICE_ATTRIBUTE + "'"); + + ICareConfig.SERVICE_ATTRIBUTE + "'"); } String paymentSchemeAttribute = adminService.getGlobalProperty(ICareConfig.PAYMENT_SCHEME_ATTRIBUTE); if (paymentSchemeAttribute == null) { throw new ConfigurationException("Attribute ID for billing is not set. Please set '" - + ICareConfig.PAYMENT_SCHEME_ATTRIBUTE + "'"); + + ICareConfig.PAYMENT_SCHEME_ATTRIBUTE + "'"); } String paymentTypeAttribute = adminService.getGlobalProperty(ICareConfig.PAYMENT_TYPE_ATTRIBUTE); if (paymentTypeAttribute == null) { throw new ConfigurationException("Attribute ID for billing is not set. Please set '" - + ICareConfig.PAYMENT_TYPE_ATTRIBUTE + "'"); + + ICareConfig.PAYMENT_TYPE_ATTRIBUTE + "'"); } String registrationEncounterType = adminService.getGlobalProperty(ICareConfig.REGISTRATION_ENCOUNTER_TYPE); if (registrationEncounterType == null) { throw new ConfigurationException("Attribute ID for billing is not set. Please set '" - + ICareConfig.REGISTRATION_ENCOUNTER_TYPE + "'"); + + ICareConfig.REGISTRATION_ENCOUNTER_TYPE + "'"); } String registrationFeeConcept = adminService.getGlobalProperty(ICareConfig.REGISTRATION_FEE_CONCEPT); if (registrationFeeConcept == null) { throw new ConfigurationException("Attribute ID for registration is not set. Please set '" - + ICareConfig.REGISTRATION_FEE_CONCEPT + "'"); + + ICareConfig.REGISTRATION_FEE_CONCEPT + "'"); } String billingOrderTypeUuid = adminService.getGlobalProperty(ICareConfig.BILLING_ORDER_TYPE); if (billingOrderTypeUuid == null) { throw new ConfigurationException("Attribute ID for billing order type is not set. Please set '" - + ICareConfig.BILLING_ORDER_TYPE + "'"); + + ICareConfig.BILLING_ORDER_TYPE + "'"); } - + String consultationOrderTypeUuid = adminService.getGlobalProperty(ICareConfig.CONSULTATION_ORDER_TYPE); if (consultationOrderTypeUuid == null) { throw new ConfigurationException("Attribute ID for consultation order type is not set. Please set '" - + ICareConfig.CONSULTATION_ORDER_TYPE + "'"); + + ICareConfig.CONSULTATION_ORDER_TYPE + "'"); } - + // Validate the visit with required attributes if (visit.getServiceConceptUuid() == null) { throw new VisitInvalidException("Service has not been specified in the visit"); @@ -456,15 +460,16 @@ public VisitMetaData validateVisitMetaData(VisitWrapper visit) throws Exception ConceptService conceptService = Context.getService(ConceptService.class); Concept serviceConcept = visit.getServiceConcept(); if (serviceConcept == null) { - throw new VisitInvalidException("Service concept is not valid. Check the UUID '" + visit.getServiceConceptUuid() - + "'."); + throw new VisitInvalidException( + "Service concept is not valid. Check the UUID '" + visit.getServiceConceptUuid() + + "'."); } visitMetaData.setServiceConcept(serviceConcept); - + Concept paymentTypeConcept = visit.getPaymentType(); if (paymentTypeConcept == null) { throw new VisitInvalidException("Payment Type concept is not valid. Check the UUID '" - + visit.getPaymentTypeUuid() + "'."); + + visit.getPaymentTypeUuid() + "'."); } visitMetaData.setPaymentType(paymentTypeConcept); if (visit.isInsurance()) { @@ -475,13 +480,14 @@ public VisitMetaData validateVisitMetaData(VisitWrapper visit) throws Exception throw new VisitInvalidException("Insurance ID has not been specified in the visit"); } InsuranceService insuranceService = visit.getInsuranceService(); - + VerificationRequest verificationRequest = new VerificationRequest(); verificationRequest.setId(visit.getInsuranceID()); verificationRequest.setAuthorizationNumber(visit.getInsuranceAuthorizationNumber()); verificationRequest.setReferralNumber(visit.getInsuranceReferralNumber()); verificationRequest.setPaymentScheme(visit.getPaymentSchemeUuid()); - VisitType visitType = Context.getVisitService().getVisitTypeByUuid(visit.getVisit().getVisitType().getUuid()); + VisitType visitType = Context.getVisitService() + .getVisitTypeByUuid(visit.getVisit().getVisitType().getUuid()); verificationRequest.setVisitType(visitType); VerificationResponse verificationResponse = insuranceService.request(verificationRequest); if (verificationResponse.getAuthorizationStatus() == AuthorizationStatus.REJECTED) { @@ -489,14 +495,14 @@ public VisitMetaData validateVisitMetaData(VisitWrapper visit) throws Exception } visit.setInsuranceAuthorizationNumber(verificationResponse.getAuthorizationNumber()); visit.setPaymentSchemeUuid(verificationResponse.getPaymentScheme().getUuid()); - + if (visit.getPaymentSchemeUuid() == null) { throw new VisitInvalidException("Payment Schema has not been specified in the visit"); } Concept paymentSchemeConcept = verificationResponse.getPaymentScheme(); if (paymentSchemeConcept == null) { throw new VisitInvalidException("Payment Schema concept is not valid. Check the UUID '" - + visit.getPaymentSchemeUuid() + "'."); + + visit.getPaymentSchemeUuid() + "'."); } visitMetaData.setPaymentScheme(paymentSchemeConcept); } else { @@ -506,14 +512,15 @@ public VisitMetaData validateVisitMetaData(VisitWrapper visit) throws Exception Concept paymentSchemeConcept = conceptService.getConceptByUuid(visit.getPaymentSchemeUuid()); if (paymentSchemeConcept == null) { throw new VisitInvalidException("Payment Schema concept is not valid. Check the UUID '" - + visit.getPaymentSchemeUuid() + "'."); + + visit.getPaymentSchemeUuid() + "'."); } visitMetaData.setPaymentScheme(paymentSchemeConcept); } EncounterService encounterService = Context.getService(EncounterService.class); EncounterType encounterType = encounterService.getEncounterTypeByUuid(registrationEncounterType); if (encounterType == null) { - throw new APIException("Registration Encounter does not exist. Please see '" + registrationEncounterType + "'."); + throw new APIException( + "Registration Encounter does not exist. Please see '" + registrationEncounterType + "'."); } visitMetaData.setRegistrationEncounterType(encounterType); Concept feeConcept = conceptService.getConceptByUuid(registrationFeeConcept); @@ -521,78 +528,86 @@ public VisitMetaData validateVisitMetaData(VisitWrapper visit) throws Exception throw new APIException("Fee Concept does not exist. Please see UUID '" + registrationFeeConcept + "'."); } visitMetaData.setRegistrationFeeConcept(feeConcept); - + OrderService orderService = Context.getService(OrderService.class); OrderType billingOrderType = orderService.getOrderTypeByUuid(billingOrderTypeUuid); if (billingOrderType == null) { - throw new APIException("Billing order type does not exist. Please see UUID '" + billingOrderTypeUuid + "'."); + throw new APIException( + "Billing order type does not exist. Please see UUID '" + billingOrderTypeUuid + "'."); } visitMetaData.setBillingOrderType(billingOrderType); - + OrderType consultationOrderType = orderService.getOrderTypeByUuid(consultationOrderTypeUuid); if (consultationOrderType == null) { - throw new APIException("Consultation order type does not exist. Please see UUID '" + consultationOrderTypeUuid - + "'."); + throw new APIException( + "Consultation order type does not exist. Please see UUID '" + consultationOrderTypeUuid + + "'."); } visitMetaData.setConsultationOrderType(consultationOrderType); // Check the existance of Item Prices ICareService iCareService = Context.getService(ICareService.class); - ItemPrice serviceItemPrice = iCareService.getItemPriceByConceptId(serviceConcept.getId(), visit.getPaymentScheme() - .getId(), paymentTypeConcept.getId()); + ItemPrice serviceItemPrice = iCareService.getItemPriceByConceptId(serviceConcept.getId(), + visit.getPaymentScheme() + .getId(), + paymentTypeConcept.getId()); if (serviceItemPrice == null) { throw new VisitInvalidException("Service Fee:" + serviceConcept.getDisplayString() + "(" - + serviceConcept.getUuid() + ") " + "Payment Scheme:" - + visitMetaData.getPaymentScheme().getDisplayString() + "(" + visitMetaData.getPaymentScheme().getUuid() - + ") " + " Payment Type:" + paymentTypeConcept.getDisplayString() + "(" + paymentTypeConcept.getUuid() - + ") " + "is not a billable item"); + + serviceConcept.getUuid() + ") " + "Payment Scheme:" + + visitMetaData.getPaymentScheme().getDisplayString() + "(" + + visitMetaData.getPaymentScheme().getUuid() + + ") " + " Payment Type:" + paymentTypeConcept.getDisplayString() + "(" + + paymentTypeConcept.getUuid() + + ") " + "is not a billable item"); } visitMetaData.setServiceItemPrice(serviceItemPrice); - ItemPrice regItemPrice = iCareService.getItemPriceByConceptId(feeConcept.getId(), visitMetaData.getPaymentScheme() - .getId(), paymentTypeConcept.getId()); - + ItemPrice regItemPrice = iCareService.getItemPriceByConceptId(feeConcept.getId(), + visitMetaData.getPaymentScheme() + .getId(), + paymentTypeConcept.getId()); + if (regItemPrice == null) { throw new VisitInvalidException("Registration Fee:" + feeConcept.getUuid() + " Payment Scheme:" - + visitMetaData.getPaymentScheme().getUuid() + " Payment Type:" + paymentTypeConcept.getUuid() - + " is not a billable item"); + + visitMetaData.getPaymentScheme().getUuid() + " Payment Type:" + paymentTypeConcept.getUuid() + + " is not a billable item"); } visitMetaData.setRegistrationItemPrice(regItemPrice); return visitMetaData; } - + public void processVisit(VisitWrapper visitWrapper, VisitMetaData visitMetaData) throws VisitInvalidException, - ConfigurationException { - + ConfigurationException { + // Start Creating Invoice Patient patient = visitWrapper.getVisit().getPatient(); Invoice invoice = new Invoice(); invoice.setVisit(visitWrapper.getVisit()); // invoice.setPatient(patient); - + // Create a patient encounter at the registration EncounterService encounterService = Context.getService(EncounterService.class); Encounter encounter = new Encounter(); encounter.setVisit(visitWrapper.getVisit()); encounter.setPatient(patient); encounter.setEncounterDatetime(new Date()); - + AdministrationService adminService = Context.getService(AdministrationService.class); String registrationEncounterRoleId = adminService.getGlobalProperty(ICareConfig.REGISTRATION_ENCOUNTER_ROLE); if (registrationEncounterRoleId == null) { throw new ConfigurationException("Registration Encounter Role is not configured. Please check " - + ICareConfig.REGISTRATION_ENCOUNTER_ROLE + "."); + + ICareConfig.REGISTRATION_ENCOUNTER_ROLE + "."); } List providers = (List) Context.getService(ProviderService.class).getProvidersByPerson( - Context.getAuthenticatedUser().getPerson()); + Context.getAuthenticatedUser().getPerson()); encounter.setProvider(encounterService.getEncounterRoleByUuid(registrationEncounterRoleId), providers.get(0)); - + encounterService.getEncounterRoleByUuid(registrationEncounterRoleId); encounter.setEncounterType(visitMetaData.getRegistrationEncounterType()); visitWrapper.getVisit().addEncounter(encounter); encounterService.saveEncounter(encounter); - + // Get concepts for payment type and payment scheme to assosciate with item // price - + OrderService orderService = Context.getService(OrderService.class); VisitService visitService = Context.getService(VisitService.class); // List visits = visitService.getVisitsByPatient(patient); @@ -603,39 +618,39 @@ public void processVisit(VisitWrapper visitWrapper, VisitMetaData visitMetaData) if (patient.getDateCreated().after(newDate)) { // TODO Soft code the UUID for fee concept Concept feeConcept = visitMetaData.getRegistrationFeeConcept(); - + Order order = new Order(); order.setConcept(feeConcept); order.setPatient(patient); order.setEncounter(encounter); order.setOrderer(providers.get(0)); order.setOrderType(visitMetaData.getBillingOrderType()); - + OrderContext orderContext = new OrderContext(); - + // TODO Softcode to get the current care setting of the visit orderContext.setCareSetting(orderService.getCareSetting(1)); encounter.addOrder(order); orderService.saveOrder(order, orderContext); } - + // Get concepts for service Concept serviceConcept = visitMetaData.getServiceConcept(); - + Order order = new Order(); order.setConcept(serviceConcept); order.setPatient(patient); order.setEncounter(encounter); order.setOrderer(providers.get(0)); order.setOrderType(visitMetaData.getConsultationOrderType()); - + OrderContext orderContext = new OrderContext(); // TODO Softcode to get the current care setting of the visit orderContext.setCareSetting(orderService.getCareSetting(1)); encounter.addOrder(order); orderService.saveOrder(order, orderContext); } - + @Override public Visit createVisit(MethodInvocation invocation) throws Throwable { // Visit visit = (Visit) invocation.getArguments()[0]; @@ -651,11 +666,11 @@ public Visit createVisit(MethodInvocation invocation) throws Throwable { this.processVisit(visitWrapper, visitMetaData); return visitWrapper.getVisit(); } - + Invoice convertEncounterToInvoice(Encounter encounter) { Invoice invoice = new Invoice(); invoice.setVisit(encounter.getVisit()); - + List items = new ArrayList(); for (Order order : encounter.getOrders()) { InvoiceItem item = new InvoiceItem(); @@ -665,35 +680,35 @@ Invoice convertEncounterToInvoice(Encounter encounter) { invoice.setInvoiceItems(items); return invoice; } - + public Order createOrderForOngoingIPDPatients() throws Exception { - + Order newOrder = new Order(); OrderService orderService = Context.getService(OrderService.class); - + List visits = dao.getOpenAdmittedVisit(); - + for (Visit visit : visits) { Order order = new Order(); AdministrationService administrationService = Context.getService(AdministrationService.class); - + String bedOrderTypeUUID = administrationService.getGlobalProperty(ICareConfig.BED_ORDER_TYPE); if (bedOrderTypeUUID == null) { throw new ConfigurationException("Bed Order Type is not configured. Please check " - + ICareConfig.BED_ORDER_TYPE + "."); + + ICareConfig.BED_ORDER_TYPE + "."); } String bedOrderConceptUUID = administrationService.getGlobalProperty(ICareConfig.BED_ORDER_CONCEPT); if (bedOrderConceptUUID == null) { throw new ConfigurationException("Bed Order Concept is not configured. Please check " - + ICareConfig.BED_ORDER_CONCEPT + "."); + + ICareConfig.BED_ORDER_CONCEPT + "."); } - + OrderType bedOrderOrderType = Context.getOrderService().getOrderTypeByUuid(bedOrderTypeUUID); - + Provider provider = Context.getProviderService().getProvider(1); - + Concept concept = Context.getConceptService().getConceptByUuid(bedOrderConceptUUID); - + order.setPatient(visit.getPatient()); order.setAction(Order.Action.NEW); order.setCareSetting(orderService.getCareSettingByName("Inpatient")); @@ -706,37 +721,37 @@ public Order createOrderForOngoingIPDPatients() throws Exception { newOrder = orderService.saveOrder(order, orderContext); } return newOrder; - + } - + public Order createOrderForOngoingDeceasedPatients() throws Exception { - + Order newOrder = new Order(); OrderService orderService = Context.getService(OrderService.class); - + List visits = dao.getOpenVisitForDeceasedPatients(); - + for (Visit visit : visits) { Order order = new Order(); AdministrationService administrationService = Context.getService(AdministrationService.class); - + String cabinetOrderTypeUUID = administrationService.getGlobalProperty(ICareConfig.CABINET_ORDER_TYPE); if (cabinetOrderTypeUUID == null) { throw new ConfigurationException("Cabinet Order Type is not configured. Please check " - + ICareConfig.CABINET_ORDER_TYPE + "."); + + ICareConfig.CABINET_ORDER_TYPE + "."); } String cabinetOrderConceptUUID = administrationService.getGlobalProperty(ICareConfig.BED_ORDER_CONCEPT); if (cabinetOrderConceptUUID == null) { throw new ConfigurationException("Bed Order Concept is not configured. Please check " - + ICareConfig.CABINET_ORDER_CONCEPT + "."); + + ICareConfig.CABINET_ORDER_CONCEPT + "."); } - + OrderType cabinetOrderOrderType = Context.getOrderService().getOrderTypeByUuid(cabinetOrderTypeUUID); - + Provider provider = Context.getProviderService().getProvider(1); - + Concept concept = Context.getConceptService().getConceptByUuid(cabinetOrderConceptUUID); - + order.setPatient(visit.getPatient()); order.setAction(Order.Action.NEW); order.setCareSetting(orderService.getCareSettingByName("Deceasedpatient")); @@ -750,12 +765,13 @@ public Order createOrderForOngoingDeceasedPatients() throws Exception { } return newOrder; } - + @Override - public List getTotalAmountFromPaidInvoices(Date startDate, Date endDate, String provider) throws Exception { + public List getTotalAmountFromPaidInvoices(Date startDate, Date endDate, String provider) + throws Exception { return this.invoiceDAO.getTotalAmountFromPaidInvoices(startDate, endDate, provider); } - + @Override public Map processGepgCallbackResponse(Map callbackData) { @@ -829,7 +845,8 @@ public Map processGepgCallbackResponse(Map callb Map billTrxInf = (Map) gepgBillSubResp.get("BillTrxInf"); String billIdString = (String) billTrxInf.get("BillId"); - String payCntrNum = (String) billTrxInf.get("PayCntrNum"); + String payCntrNum = (String) billTrxInf.get("PayCtrNum"); + // String payCntrNum = (String) billTrxInf.get("PayCntrNum"); String requestId = status.containsKey("RequestId") ? (String) status.get("RequestId") : null; systemAuth.put("SystemCode", systemCode); @@ -917,47 +934,47 @@ public Map processGepgCallbackResponse(Map callb } return response; } - + // Helper method to build error response private Map buildErrorResponse(Map response, Map systemAuth, - Map ackData, String requestId, String errorMessage) { + Map ackData, String requestId, String errorMessage) { ackData.put("RequestId", requestId != null ? requestId : "Unknown Request"); ackData.put("SystemAckCode", "0"); ackData.put("Description", errorMessage); - + response.put("SystemAuth", systemAuth); response.put("AckData", ackData); - + return response; } - + @Override public List getAllPaymentsWithStatus() throws Exception { // Fetch the default payment type UUID from the administration service AdministrationService administrationService = Context.getAdministrationService(); String paymentTypeConceptUuid = administrationService - .getGlobalProperty(ICareConfig.DEFAULT_PAYMENT_TYPE_VIA_CONTROL_NUMBER); - + .getGlobalProperty(ICareConfig.DEFAULT_PAYMENT_TYPE_VIA_CONTROL_NUMBER); + if (paymentTypeConceptUuid == null || paymentTypeConceptUuid.isEmpty()) { throw new Exception("No default payment type UUID configured for control number."); } - + // Fetch the Concept by UUID Concept paymentType = Context.getConceptService().getConceptByUuid(paymentTypeConceptUuid); if (paymentType == null) { throw new Exception("Payment type concept not found for UUID: " + paymentTypeConceptUuid); } - + // Use the concept ID to retrieve payments by payment type Integer paymentTypeId = paymentType.getId(); return paymentDAO.findByPaymentTypeId(paymentTypeId); } - + public String fetchControlNumber(Integer requestId) throws Exception { String controlNumber = null; long startTime = System.currentTimeMillis(); long timeout = 32000; - + while (System.currentTimeMillis() - startTime < timeout) { controlNumber = paymentDAO.getReferenceNumberByRequestId(requestId); AdministrationService administrationService = Context.getAdministrationService(); @@ -970,14 +987,13 @@ public String fetchControlNumber(Integer requestId) throws Exception { } try { Thread.sleep(4000); - } - catch (InterruptedException e) { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } return controlNumber; } - + // create payload for GePG Control Number Generation // @Override // public Map createGePGPayload(Patient patient, @@ -1027,7 +1043,7 @@ public String fetchControlNumber(Integer requestId) throws Exception { // throw new IllegalArgumentException("Missing system parameters: " + // missingParams.trim()); // } - + // // Retrieve patient attributes // String patientNames = patient.getGivenName() + " " + patient.getFamilyName(); // String patientUuid = patient.getId().toString(); @@ -1046,15 +1062,15 @@ public String fetchControlNumber(Integer requestId) throws Exception { // email = attribute.getValue(); // } // } - + // // BillItems generation - + // BillItems billItems = new BillItems(); - + // for (InvoiceItem invoiceItem : invoiceItems) { // Drug drug = invoiceItem.getItem().getDrug(); // Concept concept = invoiceItem.getItem().getConcept(); - + // if (drug == null && concept == null) { // throw new IllegalStateException("Concept can not be null for InvoiceItem" + // drug + concept); @@ -1092,14 +1108,14 @@ public String fetchControlNumber(Integer requestId) throws Exception { // } // } // } - + // } - + // // Create and populate BillHdr // BillHdr billHdr = new BillHdr(); // billHdr.setSpCode(spCode); // billHdr.setRtrRespFlg("true"); - + // // Create and populate BillTrxInf // BillTrxInf billTrxInf = new BillTrxInf(); // billTrxInf.setBillId(billId); @@ -1112,7 +1128,7 @@ public String fetchControlNumber(Integer requestId) throws Exception { // DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"); // String formattedNow = now.format(formatter); // billTrxInf.setBillGenDt(formattedNow); - + // LocalDateTime expirationTime = now.plusHours(24); // String formattedExpirationTime = expirationTime.format(formatter); // billTrxInf.setBillExprDt(formattedExpirationTime); @@ -1136,22 +1152,22 @@ public String fetchControlNumber(Integer requestId) throws Exception { // Invoice invoice = invoiceDAO.findById(billUuid); // if (invoice == null) { // throw new Exception("Invoice of this Bill id " + billId + " is not valid"); - + // } - + // String paymentTypeConceptUuid = administrationService // .getGlobalProperty(ICareConfig.DEFAULT_PAYMENT_TYPE_VIA_CONTROL_NUMBER); // if (paymentTypeConceptUuid == null) { // throw new Exception("No default payment type based on control number"); // } - + // Concept paymentType = // Context.getConceptService().getConceptByUuid(paymentTypeConceptUuid); // if (paymentType == null) { // throw new Exception("Payment type concept not found for UUID: " + // paymentTypeConceptUuid); // } - + // Payment payment = new Payment(); // payment.setPaymentType(paymentType); // payment.setReferenceNumber(null); @@ -1166,38 +1182,38 @@ public String fetchControlNumber(Integer requestId) throws Exception { // } catch (Exception e) { // throw new Exception("Failed to Save Payments Data: " + e.getMessage()); // } - + // requestData.setBillHdr(billHdr); // requestData.setBillTrxInf(billTrxInf); - + // // Create and populate SystemAuth // SystemAuth systemAuth = new SystemAuth(); // systemAuth.setSystemCode(sytemCode); // systemAuth.setServiceCode(serviceCode); - + // // Create and return BillSubmissionRequest // BillSubmissionRequest billRequest = new BillSubmissionRequest(); // billRequest.setSystemAuth(systemAuth); // billRequest.setRequestData(requestData); - + // // Serialize RequestData to JSON for signing // String requestDataJson = new ObjectMapper().writeValueAsString(requestData); - + // // Save the payload in a global property // GlobalProperty globalProperty = new GlobalProperty(); // globalProperty.setProperty("gepg.requestDataJson.icareConnect"); // globalProperty.setPropertyValue(requestDataJson); // administrationService.saveGlobalProperty(globalProperty); - + // // Sign the request data // String signature = SignatureUtils.signData(requestDataJson, // clientPrivateKey); // systemAuth.setSignature(signature); - + // Map result = new HashMap<>(); // result.put("billRequest", billRequest); // result.put("signature", signature); - + // return result; // } @Override @@ -1253,17 +1269,18 @@ public Map createGePGPayload(Patient patient, List return result; } - + // Validate the inputs - private void validateInputs(Patient patient, List invoiceItems, String currency, String gepgAuthSignature, - String GFSCodeConceptSourceMappingUuid, String spCode, String sytemCode, String serviceCode, String SpSysId, - String subSpCode) { + private void validateInputs(Patient patient, List invoiceItems, String currency, + String gepgAuthSignature, + String GFSCodeConceptSourceMappingUuid, String spCode, String sytemCode, String serviceCode, String SpSysId, + String subSpCode) { if (patient == null || invoiceItems == null || invoiceItems.isEmpty() || currency == null || spCode == null - || sytemCode == null || serviceCode == null || SpSysId == null || subSpCode == null) { + || sytemCode == null || serviceCode == null || SpSysId == null || subSpCode == null) { throw new IllegalArgumentException("Invalid system inputs provided."); } } - + // Retrieve the patient phone number private String getPatientPhoneNumber(Patient patient, String personPhoneAttributeTypeUuid) { for (PersonAttribute attribute : patient.getAttributes()) { @@ -1273,7 +1290,7 @@ private String getPatientPhoneNumber(Patient patient, String personPhoneAttribut } return ""; } - + // Retrieve the patient email private String getPatientEmail(Patient patient, String personEmailAttributeTypeUuid) { for (PersonAttribute attribute : patient.getAttributes()) { @@ -1283,7 +1300,7 @@ private String getPatientEmail(Patient patient, String personEmailAttributeTypeU } return ""; } - + // Create BillItems private BillItems createBillItems(List invoiceItems, String GFSCodeConceptSourceMappingUuid) { BillItems billItems = new BillItems(); @@ -1295,36 +1312,38 @@ private BillItems createBillItems(List invoiceItems, String GFSCode } else if (concept != null) { for (ConceptMap conceptMap : concept.getConceptMappings()) { if (conceptMap.getConceptReferenceTerm().getConceptSource().getUuid() - .equals(GFSCodeConceptSourceMappingUuid)) { + .equals(GFSCodeConceptSourceMappingUuid)) { String GFSCode = conceptMap.getConceptReferenceTerm().getCode(); billItems.getBillItem().add( - new BillItem(invoiceItem.getItem().getId().toString(), "N", invoiceItem.getPrice().toString(), - invoiceItem.getPrice().toString(), "0.0", GFSCode)); + new BillItem(invoiceItem.getItem().getId().toString(), "N", + invoiceItem.getPrice().toString(), + invoiceItem.getPrice().toString(), "0.0", GFSCode)); } else { throw new IllegalStateException( - "Please verify GFS CODE concept mapping if configured in a correct way"); + "Please verify GFS CODE concept mapping if configured in a correct way"); } } } else if (drug != null) { Concept drugConcept = drug.getConcept(); for (ConceptMap conceptMap : drugConcept.getConceptMappings()) { if (conceptMap.getConceptReferenceTerm().getConceptSource().getUuid() - .equals(GFSCodeConceptSourceMappingUuid)) { - + .equals(GFSCodeConceptSourceMappingUuid)) { + String GFSCode = conceptMap.getConceptReferenceTerm().getCode(); billItems.getBillItem().add( - new BillItem(invoiceItem.getItem().getId().toString(), "N", invoiceItem.getPrice().toString(), - invoiceItem.getPrice().toString(), "0.0", GFSCode)); + new BillItem(invoiceItem.getItem().getId().toString(), "N", + invoiceItem.getPrice().toString(), + invoiceItem.getPrice().toString(), "0.0", GFSCode)); } else { throw new IllegalStateException( - "Please verify GFS CODE concept mapping if configured in a correct way"); + "Please verify GFS CODE concept mapping if configured in a correct way"); } } } } return billItems; } - + // Create BillHdr private BillHdr createBillHdr(String spCode) { BillHdr billHdr = new BillHdr(); @@ -1332,20 +1351,20 @@ private BillHdr createBillHdr(String spCode) { billHdr.setRtrRespFlg("true"); return billHdr; } - + // format Date private String formatDate(Date date) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); return sdf.format(date); } - + // Create BillTrxInf private BillTrxInf createBillTrxInf(Number totalBillAmount, String patientNames, String patientPhoneNumber, - String email, String currency, String billId, Date billExpirlyDate, BillItems billItems, String subSpCode, - String SpSysId, String patientId) { - + String email, String currency, String billId, Date billExpirlyDate, BillItems billItems, String subSpCode, + String SpSysId, String patientId) { + Date now = new Date(); - + // Calculate 24 hours from BillGenDt Calendar calendar = Calendar.getInstance(); calendar.setTime(now); @@ -1373,7 +1392,7 @@ private BillTrxInf createBillTrxInf(Number totalBillAmount, String patientNames, billTrxInf.setBillItems(billItems); return billTrxInf; } - + // Create RequestData private RequestData createRequestData(BillHdr billHdr, BillTrxInf billTrxInf, String billId) throws Exception { AdministrationService administrationService = Context.getAdministrationService(); @@ -1384,20 +1403,20 @@ private RequestData createRequestData(BillHdr billHdr, BillTrxInf billTrxInf, St Invoice invoice = invoiceDAO.findById(billUuid); if (invoice == null) { throw new Exception("Invoice of this Bill id " + billId + " is not valid"); - + } - + String paymentTypeConceptUuid = administrationService - .getGlobalProperty(ICareConfig.DEFAULT_PAYMENT_TYPE_VIA_CONTROL_NUMBER); + .getGlobalProperty(ICareConfig.DEFAULT_PAYMENT_TYPE_VIA_CONTROL_NUMBER); if (paymentTypeConceptUuid == null) { throw new Exception("No default payment type based on control number"); } - + Concept paymentType = Context.getConceptService().getConceptByUuid(paymentTypeConceptUuid); if (paymentType == null) { throw new Exception("Payment type concept not found for UUID: " + paymentTypeConceptUuid); } - + Payment payment = new Payment(); payment.setPaymentType(paymentType); payment.setReferenceNumber(null); @@ -1409,15 +1428,14 @@ private RequestData createRequestData(BillHdr billHdr, BillTrxInf billTrxInf, St this.paymentDAO.save(payment); Integer paymentId = payment.getId(); requestData.setRequestId(paymentId.toString()); - } - catch (Exception e) { + } catch (Exception e) { throw new Exception("Failed to Save Payments Data: " + e.getMessage()); } requestData.setBillHdr(billHdr); requestData.setBillTrxInf(billTrxInf); return requestData; } - + // Create SystemAuth private SystemAuth createSystemAuth(String sytemCode, String serviceCode) { SystemAuth systemAuth = new SystemAuth(); @@ -1425,7 +1443,7 @@ private SystemAuth createSystemAuth(String sytemCode, String serviceCode) { systemAuth.setServiceCode(serviceCode); return systemAuth; } - + @Override public String signatureData(String rowData) throws Exception { AdministrationService administrationService = Context.getAdministrationService(); @@ -1437,10 +1455,9 @@ public String signatureData(String rowData) throws Exception { administrationService.saveGlobalProperty(globalProperty); String signature = SignatureUtils.signData(rowData, clientPrivateKey); return signature; - } - catch (IOException e) { + } catch (IOException e) { throw new Exception("Error signing data due to I/O: " + e.getMessage(), e); } - + } } diff --git a/ui/src/app/shared/resources/visits/services/visits.service.ts b/ui/src/app/shared/resources/visits/services/visits.service.ts index 3f34a4d08..f6e542d66 100755 --- a/ui/src/app/shared/resources/visits/services/visits.service.ts +++ b/ui/src/app/shared/resources/visits/services/visits.service.ts @@ -356,7 +356,6 @@ export class VisitsService { parametersString += `&includeInactive=true`; } // - // console.log("url fired ...",`icare/visit?${parametersString.replace("&","" )}&startIndex=${startIndex}&limit=${limit}`); return ( locationUuids?.length > 0 From 150b4064def3666b6fb105a84577e24c23b0a96b Mon Sep 17 00:00:00 2001 From: gaspar-dev Date: Mon, 2 Dec 2024 16:58:43 +0300 Subject: [PATCH 4/5] Added support to ensure GePG Request handless error from live --- .../icare/billing/BillingServiceImpl.java | 408 +++++++++--------- 1 file changed, 196 insertions(+), 212 deletions(-) diff --git a/omods/core/api/src/main/java/org/openmrs/module/icare/billing/BillingServiceImpl.java b/omods/core/api/src/main/java/org/openmrs/module/icare/billing/BillingServiceImpl.java index ac6bc0673..b41fb8759 100644 --- a/omods/core/api/src/main/java/org/openmrs/module/icare/billing/BillingServiceImpl.java +++ b/omods/core/api/src/main/java/org/openmrs/module/icare/billing/BillingServiceImpl.java @@ -42,43 +42,43 @@ import java.util.concurrent.TimeUnit; public class BillingServiceImpl extends BaseOpenmrsService implements BillingService { - + ICareDao dao; - + InvoiceDAO invoiceDAO; - + PaymentDAO paymentDAO; - + DiscountDAO discountDAO; - + public void setDao(ICareDao dao) { this.dao = dao; } - + public void setInvoiceDAO(InvoiceDAO invoiceDAO) { this.invoiceDAO = invoiceDAO; } - + public void setPaymentDAO(PaymentDAO paymentDAO) { this.paymentDAO = paymentDAO; } - + public void setDiscountDAO(DiscountDAO discountDAO) { this.discountDAO = discountDAO; } - + @Override public Invoice createInvoice(Invoice invoice) throws APIException { return this.invoiceDAO.save(invoice); } - + @Override public Invoice createInvoice(Encounter encounter) throws APIException { Invoice invoice = convertEncounterToInvoice(encounter); this.invoiceDAO.save(invoice); return invoice; } - + @Override public List getPendingInvoices(String patientUuid) { List invoices = this.invoiceDAO.findByPatientUuidAndPending(patientUuid); @@ -95,12 +95,12 @@ public List getPendingInvoices(String patientUuid) { return invoices; // return this.invoiceDAO.findByPatientUuid(patientUuid); } - + @Override public List getPatientsInvoices(String patientUuid) { return this.invoiceDAO.findByPatientUuid(patientUuid); } - + private InvoiceItem getInvoiceItem(OrderMetaData orderMetaData) { ItemPrice itemPrice = orderMetaData.getItemPrice(); InvoiceItem invoiceItem = new InvoiceItem(); @@ -116,13 +116,13 @@ private InvoiceItem getInvoiceItem(OrderMetaData orderMetaData) { } else { invoiceItem.setQuantity(1.0); } - + invoiceItem.setItem(itemPrice.getItem()); invoiceItem.setPrice(itemPrice.getPrice()); invoiceItem.setOrder(orderMetaData.getOrder()); return invoiceItem; } - + private InvoiceItem getTopUpInvoiceItem(OrderMetaData orderMetaData) { ItemPrice itemPrice = orderMetaData.getItemPrice(); if (itemPrice.getPayable() == null) { @@ -144,18 +144,17 @@ private InvoiceItem getTopUpInvoiceItem(OrderMetaData orderMetaData) { } else { invoiceItem.setQuantity(1.0); } - + invoiceItem.setItem(itemPrice.getItem()); invoiceItem.setPrice(itemPrice.getPayable()); invoiceItem.setOrder(orderMetaData.getOrder()); return invoiceItem; } - + @Override public Order processOrder(OrderMetaData orderMetaData, Double quantity) { - - List invoices = this - .getInvoicesByVisitUuid(orderMetaData.getOrder().getEncounter().getVisit().getUuid()); + + List invoices = this.getInvoicesByVisitUuid(orderMetaData.getOrder().getEncounter().getVisit().getUuid()); if (invoices.size() == 0) { Concept paymentModeConcept; if (!orderMetaData.getItemPrice().getPaymentType().getName().getName().toLowerCase().equals("cash")) { @@ -181,7 +180,7 @@ public Order processOrder(OrderMetaData orderMetaData, Doub Invoice invoice = new Invoice(); invoice.setPaymentMode(paymentModeConcept); invoice.setVisit(orderMetaData.getOrder().getEncounter().getVisit()); - + InvoiceItem invoiceItem = getInvoiceItem(orderMetaData); if (quantity != null) { invoiceItem.setQuantity(quantity); @@ -231,22 +230,21 @@ public Order processOrder(OrderMetaData orderMetaData, Doub existingInvoice.getInvoiceItems().add(invoiceItem); } } - + // Automatic discount creation for full exempted discounts List discountInvoiceItems = existingInvoice.getDiscountItems(); Boolean isFullExemptedCheck = false; - + if (discountInvoiceItems != null && discountInvoiceItems.size() > 0) { for (DiscountInvoiceItem discountItem : discountInvoiceItems) { if (discountItem.getDiscount() != null) { - if (discountItem.getDiscount().getExempted() != null - && discountItem.getDiscount().getExempted()) { + if (discountItem.getDiscount().getExempted() != null && discountItem.getDiscount().getExempted()) { isFullExemptedCheck = true; } } } } - + if (isFullExemptedCheck) { for (InvoiceItem invoiceItem : existingInvoice.getInvoiceItems()) { // Find the coresponding discount item @@ -271,12 +269,12 @@ public Order processOrder(OrderMetaData orderMetaData, Doub } return orderMetaData.getOrder(); } - + @Override public InvoiceItem getInvoiceItemByOrder(Order order) { return invoiceDAO.getInvoiceItemByOrderUuid(order.getUuid()); } - + @Override public SyncResult syncInsurance(String insurance) throws Exception { InsuranceService insuranceService = null; @@ -287,7 +285,7 @@ public SyncResult syncInsurance(String insurance) throws Exception { } return insuranceService.syncPriceList(); } - + @Override public List getInvoicesByVisitUuid(String visitUuid) { List invoices = this.invoiceDAO.findByVisitUuidAndPending(visitUuid); @@ -303,26 +301,25 @@ public List getInvoicesByVisitUuid(String visitUuid) { } return invoices; } - + @Override public Invoice getInvoiceDetailsByUuid(String uuid) { Invoice invoice = this.invoiceDAO.findByUuid(uuid); // TODO: Check for any discounts return invoice; } - + @Override public List getPatientPayments(String patientUuid) { return paymentDAO.findByPatientUuid(patientUuid); } - + @Override public Payment confirmPayment(Payment payment) throws Exception { Invoice invoice = invoiceDAO.findByUuid(payment.getInvoice().getUuid()); // TODO Payments should address particular item prices in the invoice payment.setInvoice(invoice); - Concept paymentType = Context.getService(ConceptService.class) - .getConceptByUuid(payment.getPaymentType().getUuid()); + Concept paymentType = Context.getService(ConceptService.class).getConceptByUuid(payment.getPaymentType().getUuid()); if (paymentType == null) { throw new Exception("Payment Type with id '" + payment.getPaymentType().getUuid() + "' does not exist."); } @@ -330,13 +327,13 @@ public Payment confirmPayment(Payment payment) throws Exception { throw new Exception("Reference number should not be null."); } payment.setPaymentType(paymentType); - + for (PaymentItem item : payment.getItems()) { item.setPayment(payment); InvoiceItem invoiceItem = null; for (InvoiceItem iI : invoice.getInvoiceItems()) { if (iI.getItem().getUuid().equals(item.getItem().getUuid()) - && iI.getOrder().getUuid().equals(item.getOrder().getUuid())) { + && iI.getOrder().getUuid().equals(item.getOrder().getUuid())) { invoiceItem = iI; } } @@ -351,7 +348,7 @@ public Payment confirmPayment(Payment payment) throws Exception { payment.setStatus(PaymentStatus.PAID); return this.paymentDAO.save(payment); } - + @Override public Discount discountInvoice(Discount discount) throws Exception { Concept discountCriteria = Context.getConceptService().getConceptByUuid(discount.getCriteria().getUuid()); @@ -373,10 +370,9 @@ public Discount discountInvoice(Discount discount) throws Exception { } Invoice invoice = invoiceDAO.findByUuid(discountInvoiceItem.getInvoice().getUuid()); if (invoice == null) { - throw new Exception( - "Invoice with id '" + discountInvoiceItem.getInvoice().getUuid() + "' does not exist."); + throw new Exception("Invoice with id '" + discountInvoiceItem.getInvoice().getUuid() + "' does not exist."); } - + DiscountInvoiceItem newItem = new DiscountInvoiceItem(); newItem.setItem(item); newItem.setInvoice(invoice); @@ -385,7 +381,7 @@ public Discount discountInvoice(Discount discount) throws Exception { newItems.add(newItem); } discount.setItems(newItems); - + if (discount.getAttachment() != null) { Obs obs = Context.getObsService().getObsByUuid(discount.getAttachment().getUuid()); if (obs == null) { @@ -394,21 +390,21 @@ public Discount discountInvoice(Discount discount) throws Exception { discount.setAttachment(obs); } // discount.setCreator(Context.getAuthenticatedUser()); - + return discountDAO.save(discount); } - + @Override public List getPatientDiscounts(String patientUuid) { return discountDAO.findByPatientUuid(patientUuid); } - + @Override public Concept createDiscountCriteria(Concept discountCriteria) { Concept newDiscountCriteria = Context.getConceptService().saveConcept(discountCriteria); return newDiscountCriteria; } - + @Override public VisitMetaData validateVisitMetaData(VisitWrapper visit) throws Exception { VisitMetaData visitMetaData = new VisitMetaData(); @@ -416,40 +412,40 @@ public VisitMetaData validateVisitMetaData(VisitWrapper visit) throws Exception String serviceAttribute = adminService.getGlobalProperty(ICareConfig.SERVICE_ATTRIBUTE); if (serviceAttribute == null) { throw new ConfigurationException("Attribute ID for billing is not set. Please set '" - + ICareConfig.SERVICE_ATTRIBUTE + "'"); + + ICareConfig.SERVICE_ATTRIBUTE + "'"); } String paymentSchemeAttribute = adminService.getGlobalProperty(ICareConfig.PAYMENT_SCHEME_ATTRIBUTE); if (paymentSchemeAttribute == null) { throw new ConfigurationException("Attribute ID for billing is not set. Please set '" - + ICareConfig.PAYMENT_SCHEME_ATTRIBUTE + "'"); + + ICareConfig.PAYMENT_SCHEME_ATTRIBUTE + "'"); } String paymentTypeAttribute = adminService.getGlobalProperty(ICareConfig.PAYMENT_TYPE_ATTRIBUTE); if (paymentTypeAttribute == null) { throw new ConfigurationException("Attribute ID for billing is not set. Please set '" - + ICareConfig.PAYMENT_TYPE_ATTRIBUTE + "'"); + + ICareConfig.PAYMENT_TYPE_ATTRIBUTE + "'"); } String registrationEncounterType = adminService.getGlobalProperty(ICareConfig.REGISTRATION_ENCOUNTER_TYPE); if (registrationEncounterType == null) { throw new ConfigurationException("Attribute ID for billing is not set. Please set '" - + ICareConfig.REGISTRATION_ENCOUNTER_TYPE + "'"); + + ICareConfig.REGISTRATION_ENCOUNTER_TYPE + "'"); } String registrationFeeConcept = adminService.getGlobalProperty(ICareConfig.REGISTRATION_FEE_CONCEPT); if (registrationFeeConcept == null) { throw new ConfigurationException("Attribute ID for registration is not set. Please set '" - + ICareConfig.REGISTRATION_FEE_CONCEPT + "'"); + + ICareConfig.REGISTRATION_FEE_CONCEPT + "'"); } String billingOrderTypeUuid = adminService.getGlobalProperty(ICareConfig.BILLING_ORDER_TYPE); if (billingOrderTypeUuid == null) { throw new ConfigurationException("Attribute ID for billing order type is not set. Please set '" - + ICareConfig.BILLING_ORDER_TYPE + "'"); + + ICareConfig.BILLING_ORDER_TYPE + "'"); } - + String consultationOrderTypeUuid = adminService.getGlobalProperty(ICareConfig.CONSULTATION_ORDER_TYPE); if (consultationOrderTypeUuid == null) { throw new ConfigurationException("Attribute ID for consultation order type is not set. Please set '" - + ICareConfig.CONSULTATION_ORDER_TYPE + "'"); + + ICareConfig.CONSULTATION_ORDER_TYPE + "'"); } - + // Validate the visit with required attributes if (visit.getServiceConceptUuid() == null) { throw new VisitInvalidException("Service has not been specified in the visit"); @@ -460,16 +456,15 @@ public VisitMetaData validateVisitMetaData(VisitWrapper visit) throws Exception ConceptService conceptService = Context.getService(ConceptService.class); Concept serviceConcept = visit.getServiceConcept(); if (serviceConcept == null) { - throw new VisitInvalidException( - "Service concept is not valid. Check the UUID '" + visit.getServiceConceptUuid() - + "'."); + throw new VisitInvalidException("Service concept is not valid. Check the UUID '" + visit.getServiceConceptUuid() + + "'."); } visitMetaData.setServiceConcept(serviceConcept); - + Concept paymentTypeConcept = visit.getPaymentType(); if (paymentTypeConcept == null) { throw new VisitInvalidException("Payment Type concept is not valid. Check the UUID '" - + visit.getPaymentTypeUuid() + "'."); + + visit.getPaymentTypeUuid() + "'."); } visitMetaData.setPaymentType(paymentTypeConcept); if (visit.isInsurance()) { @@ -480,14 +475,13 @@ public VisitMetaData validateVisitMetaData(VisitWrapper visit) throws Exception throw new VisitInvalidException("Insurance ID has not been specified in the visit"); } InsuranceService insuranceService = visit.getInsuranceService(); - + VerificationRequest verificationRequest = new VerificationRequest(); verificationRequest.setId(visit.getInsuranceID()); verificationRequest.setAuthorizationNumber(visit.getInsuranceAuthorizationNumber()); verificationRequest.setReferralNumber(visit.getInsuranceReferralNumber()); verificationRequest.setPaymentScheme(visit.getPaymentSchemeUuid()); - VisitType visitType = Context.getVisitService() - .getVisitTypeByUuid(visit.getVisit().getVisitType().getUuid()); + VisitType visitType = Context.getVisitService().getVisitTypeByUuid(visit.getVisit().getVisitType().getUuid()); verificationRequest.setVisitType(visitType); VerificationResponse verificationResponse = insuranceService.request(verificationRequest); if (verificationResponse.getAuthorizationStatus() == AuthorizationStatus.REJECTED) { @@ -495,14 +489,14 @@ public VisitMetaData validateVisitMetaData(VisitWrapper visit) throws Exception } visit.setInsuranceAuthorizationNumber(verificationResponse.getAuthorizationNumber()); visit.setPaymentSchemeUuid(verificationResponse.getPaymentScheme().getUuid()); - + if (visit.getPaymentSchemeUuid() == null) { throw new VisitInvalidException("Payment Schema has not been specified in the visit"); } Concept paymentSchemeConcept = verificationResponse.getPaymentScheme(); if (paymentSchemeConcept == null) { throw new VisitInvalidException("Payment Schema concept is not valid. Check the UUID '" - + visit.getPaymentSchemeUuid() + "'."); + + visit.getPaymentSchemeUuid() + "'."); } visitMetaData.setPaymentScheme(paymentSchemeConcept); } else { @@ -512,15 +506,14 @@ public VisitMetaData validateVisitMetaData(VisitWrapper visit) throws Exception Concept paymentSchemeConcept = conceptService.getConceptByUuid(visit.getPaymentSchemeUuid()); if (paymentSchemeConcept == null) { throw new VisitInvalidException("Payment Schema concept is not valid. Check the UUID '" - + visit.getPaymentSchemeUuid() + "'."); + + visit.getPaymentSchemeUuid() + "'."); } visitMetaData.setPaymentScheme(paymentSchemeConcept); } EncounterService encounterService = Context.getService(EncounterService.class); EncounterType encounterType = encounterService.getEncounterTypeByUuid(registrationEncounterType); if (encounterType == null) { - throw new APIException( - "Registration Encounter does not exist. Please see '" + registrationEncounterType + "'."); + throw new APIException("Registration Encounter does not exist. Please see '" + registrationEncounterType + "'."); } visitMetaData.setRegistrationEncounterType(encounterType); Concept feeConcept = conceptService.getConceptByUuid(registrationFeeConcept); @@ -528,86 +521,78 @@ public VisitMetaData validateVisitMetaData(VisitWrapper visit) throws Exception throw new APIException("Fee Concept does not exist. Please see UUID '" + registrationFeeConcept + "'."); } visitMetaData.setRegistrationFeeConcept(feeConcept); - + OrderService orderService = Context.getService(OrderService.class); OrderType billingOrderType = orderService.getOrderTypeByUuid(billingOrderTypeUuid); if (billingOrderType == null) { - throw new APIException( - "Billing order type does not exist. Please see UUID '" + billingOrderTypeUuid + "'."); + throw new APIException("Billing order type does not exist. Please see UUID '" + billingOrderTypeUuid + "'."); } visitMetaData.setBillingOrderType(billingOrderType); - + OrderType consultationOrderType = orderService.getOrderTypeByUuid(consultationOrderTypeUuid); if (consultationOrderType == null) { - throw new APIException( - "Consultation order type does not exist. Please see UUID '" + consultationOrderTypeUuid - + "'."); + throw new APIException("Consultation order type does not exist. Please see UUID '" + consultationOrderTypeUuid + + "'."); } visitMetaData.setConsultationOrderType(consultationOrderType); // Check the existance of Item Prices ICareService iCareService = Context.getService(ICareService.class); - ItemPrice serviceItemPrice = iCareService.getItemPriceByConceptId(serviceConcept.getId(), - visit.getPaymentScheme() - .getId(), - paymentTypeConcept.getId()); + ItemPrice serviceItemPrice = iCareService.getItemPriceByConceptId(serviceConcept.getId(), visit.getPaymentScheme() + .getId(), paymentTypeConcept.getId()); if (serviceItemPrice == null) { throw new VisitInvalidException("Service Fee:" + serviceConcept.getDisplayString() + "(" - + serviceConcept.getUuid() + ") " + "Payment Scheme:" - + visitMetaData.getPaymentScheme().getDisplayString() + "(" - + visitMetaData.getPaymentScheme().getUuid() - + ") " + " Payment Type:" + paymentTypeConcept.getDisplayString() + "(" - + paymentTypeConcept.getUuid() - + ") " + "is not a billable item"); + + serviceConcept.getUuid() + ") " + "Payment Scheme:" + + visitMetaData.getPaymentScheme().getDisplayString() + "(" + visitMetaData.getPaymentScheme().getUuid() + + ") " + " Payment Type:" + paymentTypeConcept.getDisplayString() + "(" + paymentTypeConcept.getUuid() + + ") " + "is not a billable item"); } visitMetaData.setServiceItemPrice(serviceItemPrice); - ItemPrice regItemPrice = iCareService.getItemPriceByConceptId(feeConcept.getId(), - visitMetaData.getPaymentScheme() - .getId(), - paymentTypeConcept.getId()); - + ItemPrice regItemPrice = iCareService.getItemPriceByConceptId(feeConcept.getId(), visitMetaData.getPaymentScheme() + .getId(), paymentTypeConcept.getId()); + if (regItemPrice == null) { throw new VisitInvalidException("Registration Fee:" + feeConcept.getUuid() + " Payment Scheme:" - + visitMetaData.getPaymentScheme().getUuid() + " Payment Type:" + paymentTypeConcept.getUuid() - + " is not a billable item"); + + visitMetaData.getPaymentScheme().getUuid() + " Payment Type:" + paymentTypeConcept.getUuid() + + " is not a billable item"); } visitMetaData.setRegistrationItemPrice(regItemPrice); return visitMetaData; } - + public void processVisit(VisitWrapper visitWrapper, VisitMetaData visitMetaData) throws VisitInvalidException, - ConfigurationException { - + ConfigurationException { + // Start Creating Invoice Patient patient = visitWrapper.getVisit().getPatient(); Invoice invoice = new Invoice(); invoice.setVisit(visitWrapper.getVisit()); // invoice.setPatient(patient); - + // Create a patient encounter at the registration EncounterService encounterService = Context.getService(EncounterService.class); Encounter encounter = new Encounter(); encounter.setVisit(visitWrapper.getVisit()); encounter.setPatient(patient); encounter.setEncounterDatetime(new Date()); - + AdministrationService adminService = Context.getService(AdministrationService.class); String registrationEncounterRoleId = adminService.getGlobalProperty(ICareConfig.REGISTRATION_ENCOUNTER_ROLE); if (registrationEncounterRoleId == null) { throw new ConfigurationException("Registration Encounter Role is not configured. Please check " - + ICareConfig.REGISTRATION_ENCOUNTER_ROLE + "."); + + ICareConfig.REGISTRATION_ENCOUNTER_ROLE + "."); } List providers = (List) Context.getService(ProviderService.class).getProvidersByPerson( - Context.getAuthenticatedUser().getPerson()); + Context.getAuthenticatedUser().getPerson()); encounter.setProvider(encounterService.getEncounterRoleByUuid(registrationEncounterRoleId), providers.get(0)); - + encounterService.getEncounterRoleByUuid(registrationEncounterRoleId); encounter.setEncounterType(visitMetaData.getRegistrationEncounterType()); visitWrapper.getVisit().addEncounter(encounter); encounterService.saveEncounter(encounter); - + // Get concepts for payment type and payment scheme to assosciate with item // price - + OrderService orderService = Context.getService(OrderService.class); VisitService visitService = Context.getService(VisitService.class); // List visits = visitService.getVisitsByPatient(patient); @@ -618,39 +603,39 @@ public void processVisit(VisitWrapper visitWrapper, VisitMetaData visitMetaData) if (patient.getDateCreated().after(newDate)) { // TODO Soft code the UUID for fee concept Concept feeConcept = visitMetaData.getRegistrationFeeConcept(); - + Order order = new Order(); order.setConcept(feeConcept); order.setPatient(patient); order.setEncounter(encounter); order.setOrderer(providers.get(0)); order.setOrderType(visitMetaData.getBillingOrderType()); - + OrderContext orderContext = new OrderContext(); - + // TODO Softcode to get the current care setting of the visit orderContext.setCareSetting(orderService.getCareSetting(1)); encounter.addOrder(order); orderService.saveOrder(order, orderContext); } - + // Get concepts for service Concept serviceConcept = visitMetaData.getServiceConcept(); - + Order order = new Order(); order.setConcept(serviceConcept); order.setPatient(patient); order.setEncounter(encounter); order.setOrderer(providers.get(0)); order.setOrderType(visitMetaData.getConsultationOrderType()); - + OrderContext orderContext = new OrderContext(); // TODO Softcode to get the current care setting of the visit orderContext.setCareSetting(orderService.getCareSetting(1)); encounter.addOrder(order); orderService.saveOrder(order, orderContext); } - + @Override public Visit createVisit(MethodInvocation invocation) throws Throwable { // Visit visit = (Visit) invocation.getArguments()[0]; @@ -666,11 +651,11 @@ public Visit createVisit(MethodInvocation invocation) throws Throwable { this.processVisit(visitWrapper, visitMetaData); return visitWrapper.getVisit(); } - + Invoice convertEncounterToInvoice(Encounter encounter) { Invoice invoice = new Invoice(); invoice.setVisit(encounter.getVisit()); - + List items = new ArrayList(); for (Order order : encounter.getOrders()) { InvoiceItem item = new InvoiceItem(); @@ -680,35 +665,35 @@ Invoice convertEncounterToInvoice(Encounter encounter) { invoice.setInvoiceItems(items); return invoice; } - + public Order createOrderForOngoingIPDPatients() throws Exception { - + Order newOrder = new Order(); OrderService orderService = Context.getService(OrderService.class); - + List visits = dao.getOpenAdmittedVisit(); - + for (Visit visit : visits) { Order order = new Order(); AdministrationService administrationService = Context.getService(AdministrationService.class); - + String bedOrderTypeUUID = administrationService.getGlobalProperty(ICareConfig.BED_ORDER_TYPE); if (bedOrderTypeUUID == null) { throw new ConfigurationException("Bed Order Type is not configured. Please check " - + ICareConfig.BED_ORDER_TYPE + "."); + + ICareConfig.BED_ORDER_TYPE + "."); } String bedOrderConceptUUID = administrationService.getGlobalProperty(ICareConfig.BED_ORDER_CONCEPT); if (bedOrderConceptUUID == null) { throw new ConfigurationException("Bed Order Concept is not configured. Please check " - + ICareConfig.BED_ORDER_CONCEPT + "."); + + ICareConfig.BED_ORDER_CONCEPT + "."); } - + OrderType bedOrderOrderType = Context.getOrderService().getOrderTypeByUuid(bedOrderTypeUUID); - + Provider provider = Context.getProviderService().getProvider(1); - + Concept concept = Context.getConceptService().getConceptByUuid(bedOrderConceptUUID); - + order.setPatient(visit.getPatient()); order.setAction(Order.Action.NEW); order.setCareSetting(orderService.getCareSettingByName("Inpatient")); @@ -721,37 +706,37 @@ public Order createOrderForOngoingIPDPatients() throws Exception { newOrder = orderService.saveOrder(order, orderContext); } return newOrder; - + } - + public Order createOrderForOngoingDeceasedPatients() throws Exception { - + Order newOrder = new Order(); OrderService orderService = Context.getService(OrderService.class); - + List visits = dao.getOpenVisitForDeceasedPatients(); - + for (Visit visit : visits) { Order order = new Order(); AdministrationService administrationService = Context.getService(AdministrationService.class); - + String cabinetOrderTypeUUID = administrationService.getGlobalProperty(ICareConfig.CABINET_ORDER_TYPE); if (cabinetOrderTypeUUID == null) { throw new ConfigurationException("Cabinet Order Type is not configured. Please check " - + ICareConfig.CABINET_ORDER_TYPE + "."); + + ICareConfig.CABINET_ORDER_TYPE + "."); } String cabinetOrderConceptUUID = administrationService.getGlobalProperty(ICareConfig.BED_ORDER_CONCEPT); if (cabinetOrderConceptUUID == null) { throw new ConfigurationException("Bed Order Concept is not configured. Please check " - + ICareConfig.CABINET_ORDER_CONCEPT + "."); + + ICareConfig.CABINET_ORDER_CONCEPT + "."); } - + OrderType cabinetOrderOrderType = Context.getOrderService().getOrderTypeByUuid(cabinetOrderTypeUUID); - + Provider provider = Context.getProviderService().getProvider(1); - + Concept concept = Context.getConceptService().getConceptByUuid(cabinetOrderConceptUUID); - + order.setPatient(visit.getPatient()); order.setAction(Order.Action.NEW); order.setCareSetting(orderService.getCareSettingByName("Deceasedpatient")); @@ -765,13 +750,12 @@ public Order createOrderForOngoingDeceasedPatients() throws Exception { } return newOrder; } - + @Override - public List getTotalAmountFromPaidInvoices(Date startDate, Date endDate, String provider) - throws Exception { + public List getTotalAmountFromPaidInvoices(Date startDate, Date endDate, String provider) throws Exception { return this.invoiceDAO.getTotalAmountFromPaidInvoices(startDate, endDate, provider); } - + @Override public Map processGepgCallbackResponse(Map callbackData) { @@ -802,7 +786,7 @@ public Map processGepgCallbackResponse(Map callb Payment payment = this.paymentDAO.getPaymentByRequestId(Integer.parseInt(requestId)); if (payment != null) { - payment.setReferenceNumber((String) pymtTrxInf.get("PspReceiptNumber")); + payment.setReferenceNumber((String) pymtTrxInf.get("PayCtrNum")); payment.setBillAmount(Double.parseDouble((String) pymtTrxInf.get("BillAmt"))); payment.setPaidAmount(Double.parseDouble((String) pymtTrxInf.get("PaidAmt"))); LocalDateTime localDateTime = LocalDateTime.parse((String) pymtTrxInf.get("TrxDtTm")); @@ -845,8 +829,8 @@ public Map processGepgCallbackResponse(Map callb Map billTrxInf = (Map) gepgBillSubResp.get("BillTrxInf"); String billIdString = (String) billTrxInf.get("BillId"); - String payCntrNum = (String) billTrxInf.get("PayCtrNum"); - // String payCntrNum = (String) billTrxInf.get("PayCntrNum"); + + String payCntrNum = (String) billTrxInf.get("PayCntrNum"); String requestId = status.containsKey("RequestId") ? (String) status.get("RequestId") : null; systemAuth.put("SystemCode", systemCode); @@ -934,47 +918,47 @@ public Map processGepgCallbackResponse(Map callb } return response; } - + // Helper method to build error response private Map buildErrorResponse(Map response, Map systemAuth, - Map ackData, String requestId, String errorMessage) { + Map ackData, String requestId, String errorMessage) { ackData.put("RequestId", requestId != null ? requestId : "Unknown Request"); ackData.put("SystemAckCode", "0"); ackData.put("Description", errorMessage); - + response.put("SystemAuth", systemAuth); response.put("AckData", ackData); - + return response; } - + @Override public List getAllPaymentsWithStatus() throws Exception { // Fetch the default payment type UUID from the administration service AdministrationService administrationService = Context.getAdministrationService(); String paymentTypeConceptUuid = administrationService - .getGlobalProperty(ICareConfig.DEFAULT_PAYMENT_TYPE_VIA_CONTROL_NUMBER); - + .getGlobalProperty(ICareConfig.DEFAULT_PAYMENT_TYPE_VIA_CONTROL_NUMBER); + if (paymentTypeConceptUuid == null || paymentTypeConceptUuid.isEmpty()) { throw new Exception("No default payment type UUID configured for control number."); } - + // Fetch the Concept by UUID Concept paymentType = Context.getConceptService().getConceptByUuid(paymentTypeConceptUuid); if (paymentType == null) { throw new Exception("Payment type concept not found for UUID: " + paymentTypeConceptUuid); } - + // Use the concept ID to retrieve payments by payment type Integer paymentTypeId = paymentType.getId(); return paymentDAO.findByPaymentTypeId(paymentTypeId); } - + public String fetchControlNumber(Integer requestId) throws Exception { String controlNumber = null; long startTime = System.currentTimeMillis(); long timeout = 32000; - + while (System.currentTimeMillis() - startTime < timeout) { controlNumber = paymentDAO.getReferenceNumberByRequestId(requestId); AdministrationService administrationService = Context.getAdministrationService(); @@ -987,13 +971,14 @@ public String fetchControlNumber(Integer requestId) throws Exception { } try { Thread.sleep(4000); - } catch (InterruptedException e) { + } + catch (InterruptedException e) { Thread.currentThread().interrupt(); } } return controlNumber; } - + // create payload for GePG Control Number Generation // @Override // public Map createGePGPayload(Patient patient, @@ -1043,7 +1028,7 @@ public String fetchControlNumber(Integer requestId) throws Exception { // throw new IllegalArgumentException("Missing system parameters: " + // missingParams.trim()); // } - + // // Retrieve patient attributes // String patientNames = patient.getGivenName() + " " + patient.getFamilyName(); // String patientUuid = patient.getId().toString(); @@ -1062,15 +1047,15 @@ public String fetchControlNumber(Integer requestId) throws Exception { // email = attribute.getValue(); // } // } - + // // BillItems generation - + // BillItems billItems = new BillItems(); - + // for (InvoiceItem invoiceItem : invoiceItems) { // Drug drug = invoiceItem.getItem().getDrug(); // Concept concept = invoiceItem.getItem().getConcept(); - + // if (drug == null && concept == null) { // throw new IllegalStateException("Concept can not be null for InvoiceItem" + // drug + concept); @@ -1108,14 +1093,14 @@ public String fetchControlNumber(Integer requestId) throws Exception { // } // } // } - + // } - + // // Create and populate BillHdr // BillHdr billHdr = new BillHdr(); // billHdr.setSpCode(spCode); // billHdr.setRtrRespFlg("true"); - + // // Create and populate BillTrxInf // BillTrxInf billTrxInf = new BillTrxInf(); // billTrxInf.setBillId(billId); @@ -1128,7 +1113,7 @@ public String fetchControlNumber(Integer requestId) throws Exception { // DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"); // String formattedNow = now.format(formatter); // billTrxInf.setBillGenDt(formattedNow); - + // LocalDateTime expirationTime = now.plusHours(24); // String formattedExpirationTime = expirationTime.format(formatter); // billTrxInf.setBillExprDt(formattedExpirationTime); @@ -1152,22 +1137,22 @@ public String fetchControlNumber(Integer requestId) throws Exception { // Invoice invoice = invoiceDAO.findById(billUuid); // if (invoice == null) { // throw new Exception("Invoice of this Bill id " + billId + " is not valid"); - + // } - + // String paymentTypeConceptUuid = administrationService // .getGlobalProperty(ICareConfig.DEFAULT_PAYMENT_TYPE_VIA_CONTROL_NUMBER); // if (paymentTypeConceptUuid == null) { // throw new Exception("No default payment type based on control number"); // } - + // Concept paymentType = // Context.getConceptService().getConceptByUuid(paymentTypeConceptUuid); // if (paymentType == null) { // throw new Exception("Payment type concept not found for UUID: " + // paymentTypeConceptUuid); // } - + // Payment payment = new Payment(); // payment.setPaymentType(paymentType); // payment.setReferenceNumber(null); @@ -1182,38 +1167,38 @@ public String fetchControlNumber(Integer requestId) throws Exception { // } catch (Exception e) { // throw new Exception("Failed to Save Payments Data: " + e.getMessage()); // } - + // requestData.setBillHdr(billHdr); // requestData.setBillTrxInf(billTrxInf); - + // // Create and populate SystemAuth // SystemAuth systemAuth = new SystemAuth(); // systemAuth.setSystemCode(sytemCode); // systemAuth.setServiceCode(serviceCode); - + // // Create and return BillSubmissionRequest // BillSubmissionRequest billRequest = new BillSubmissionRequest(); // billRequest.setSystemAuth(systemAuth); // billRequest.setRequestData(requestData); - + // // Serialize RequestData to JSON for signing // String requestDataJson = new ObjectMapper().writeValueAsString(requestData); - + // // Save the payload in a global property // GlobalProperty globalProperty = new GlobalProperty(); // globalProperty.setProperty("gepg.requestDataJson.icareConnect"); // globalProperty.setPropertyValue(requestDataJson); // administrationService.saveGlobalProperty(globalProperty); - + // // Sign the request data // String signature = SignatureUtils.signData(requestDataJson, // clientPrivateKey); // systemAuth.setSignature(signature); - + // Map result = new HashMap<>(); // result.put("billRequest", billRequest); // result.put("signature", signature); - + // return result; // } @Override @@ -1269,18 +1254,17 @@ public Map createGePGPayload(Patient patient, List return result; } - + // Validate the inputs - private void validateInputs(Patient patient, List invoiceItems, String currency, - String gepgAuthSignature, - String GFSCodeConceptSourceMappingUuid, String spCode, String sytemCode, String serviceCode, String SpSysId, - String subSpCode) { + private void validateInputs(Patient patient, List invoiceItems, String currency, String gepgAuthSignature, + String GFSCodeConceptSourceMappingUuid, String spCode, String sytemCode, String serviceCode, String SpSysId, + String subSpCode) { if (patient == null || invoiceItems == null || invoiceItems.isEmpty() || currency == null || spCode == null - || sytemCode == null || serviceCode == null || SpSysId == null || subSpCode == null) { + || sytemCode == null || serviceCode == null || SpSysId == null || subSpCode == null) { throw new IllegalArgumentException("Invalid system inputs provided."); } } - + // Retrieve the patient phone number private String getPatientPhoneNumber(Patient patient, String personPhoneAttributeTypeUuid) { for (PersonAttribute attribute : patient.getAttributes()) { @@ -1290,7 +1274,7 @@ private String getPatientPhoneNumber(Patient patient, String personPhoneAttribut } return ""; } - + // Retrieve the patient email private String getPatientEmail(Patient patient, String personEmailAttributeTypeUuid) { for (PersonAttribute attribute : patient.getAttributes()) { @@ -1300,7 +1284,7 @@ private String getPatientEmail(Patient patient, String personEmailAttributeTypeU } return ""; } - + // Create BillItems private BillItems createBillItems(List invoiceItems, String GFSCodeConceptSourceMappingUuid) { BillItems billItems = new BillItems(); @@ -1312,38 +1296,36 @@ private BillItems createBillItems(List invoiceItems, String GFSCode } else if (concept != null) { for (ConceptMap conceptMap : concept.getConceptMappings()) { if (conceptMap.getConceptReferenceTerm().getConceptSource().getUuid() - .equals(GFSCodeConceptSourceMappingUuid)) { + .equals(GFSCodeConceptSourceMappingUuid)) { String GFSCode = conceptMap.getConceptReferenceTerm().getCode(); billItems.getBillItem().add( - new BillItem(invoiceItem.getItem().getId().toString(), "N", - invoiceItem.getPrice().toString(), - invoiceItem.getPrice().toString(), "0.0", GFSCode)); + new BillItem(invoiceItem.getItem().getId().toString(), "N", invoiceItem.getPrice().toString(), + invoiceItem.getPrice().toString(), "0.0", GFSCode)); } else { throw new IllegalStateException( - "Please verify GFS CODE concept mapping if configured in a correct way"); + "Please verify GFS CODE concept mapping if configured in a correct way"); } } } else if (drug != null) { Concept drugConcept = drug.getConcept(); for (ConceptMap conceptMap : drugConcept.getConceptMappings()) { if (conceptMap.getConceptReferenceTerm().getConceptSource().getUuid() - .equals(GFSCodeConceptSourceMappingUuid)) { - + .equals(GFSCodeConceptSourceMappingUuid)) { + String GFSCode = conceptMap.getConceptReferenceTerm().getCode(); billItems.getBillItem().add( - new BillItem(invoiceItem.getItem().getId().toString(), "N", - invoiceItem.getPrice().toString(), - invoiceItem.getPrice().toString(), "0.0", GFSCode)); + new BillItem(invoiceItem.getItem().getId().toString(), "N", invoiceItem.getPrice().toString(), + invoiceItem.getPrice().toString(), "0.0", GFSCode)); } else { throw new IllegalStateException( - "Please verify GFS CODE concept mapping if configured in a correct way"); + "Please verify GFS CODE concept mapping if configured in a correct way"); } } } } return billItems; } - + // Create BillHdr private BillHdr createBillHdr(String spCode) { BillHdr billHdr = new BillHdr(); @@ -1351,20 +1333,20 @@ private BillHdr createBillHdr(String spCode) { billHdr.setRtrRespFlg("true"); return billHdr; } - + // format Date private String formatDate(Date date) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); return sdf.format(date); } - + // Create BillTrxInf private BillTrxInf createBillTrxInf(Number totalBillAmount, String patientNames, String patientPhoneNumber, - String email, String currency, String billId, Date billExpirlyDate, BillItems billItems, String subSpCode, - String SpSysId, String patientId) { - + String email, String currency, String billId, Date billExpirlyDate, BillItems billItems, String subSpCode, + String SpSysId, String patientId) { + Date now = new Date(); - + // Calculate 24 hours from BillGenDt Calendar calendar = Calendar.getInstance(); calendar.setTime(now); @@ -1392,7 +1374,7 @@ private BillTrxInf createBillTrxInf(Number totalBillAmount, String patientNames, billTrxInf.setBillItems(billItems); return billTrxInf; } - + // Create RequestData private RequestData createRequestData(BillHdr billHdr, BillTrxInf billTrxInf, String billId) throws Exception { AdministrationService administrationService = Context.getAdministrationService(); @@ -1403,20 +1385,20 @@ private RequestData createRequestData(BillHdr billHdr, BillTrxInf billTrxInf, St Invoice invoice = invoiceDAO.findById(billUuid); if (invoice == null) { throw new Exception("Invoice of this Bill id " + billId + " is not valid"); - + } - + String paymentTypeConceptUuid = administrationService - .getGlobalProperty(ICareConfig.DEFAULT_PAYMENT_TYPE_VIA_CONTROL_NUMBER); + .getGlobalProperty(ICareConfig.DEFAULT_PAYMENT_TYPE_VIA_CONTROL_NUMBER); if (paymentTypeConceptUuid == null) { throw new Exception("No default payment type based on control number"); } - + Concept paymentType = Context.getConceptService().getConceptByUuid(paymentTypeConceptUuid); if (paymentType == null) { throw new Exception("Payment type concept not found for UUID: " + paymentTypeConceptUuid); } - + Payment payment = new Payment(); payment.setPaymentType(paymentType); payment.setReferenceNumber(null); @@ -1428,14 +1410,15 @@ private RequestData createRequestData(BillHdr billHdr, BillTrxInf billTrxInf, St this.paymentDAO.save(payment); Integer paymentId = payment.getId(); requestData.setRequestId(paymentId.toString()); - } catch (Exception e) { + } + catch (Exception e) { throw new Exception("Failed to Save Payments Data: " + e.getMessage()); } requestData.setBillHdr(billHdr); requestData.setBillTrxInf(billTrxInf); return requestData; } - + // Create SystemAuth private SystemAuth createSystemAuth(String sytemCode, String serviceCode) { SystemAuth systemAuth = new SystemAuth(); @@ -1443,7 +1426,7 @@ private SystemAuth createSystemAuth(String sytemCode, String serviceCode) { systemAuth.setServiceCode(serviceCode); return systemAuth; } - + @Override public String signatureData(String rowData) throws Exception { AdministrationService administrationService = Context.getAdministrationService(); @@ -1455,9 +1438,10 @@ public String signatureData(String rowData) throws Exception { administrationService.saveGlobalProperty(globalProperty); String signature = SignatureUtils.signData(rowData, clientPrivateKey); return signature; - } catch (IOException e) { + } + catch (IOException e) { throw new Exception("Error signing data due to I/O: " + e.getMessage(), e); } - + } } From e3c54a879c8c7b3bf41ca3fc2c9806de437f1084 Mon Sep 17 00:00:00 2001 From: gaspar-dev Date: Wed, 4 Dec 2024 11:22:43 +0300 Subject: [PATCH 5/5] Added support to avoid duplication on chiplist on issuing and requested --- .../store-pages/issuing-page/issuing-page.component.html | 2 +- .../requisition-page/requisition-page.component.html | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ui/src/app/shared/store-pages/issuing-page/issuing-page.component.html b/ui/src/app/shared/store-pages/issuing-page/issuing-page.component.html index 7cfcf7405..29ba6f168 100644 --- a/ui/src/app/shared/store-pages/issuing-page/issuing-page.component.html +++ b/ui/src/app/shared/store-pages/issuing-page/issuing-page.component.html @@ -10,7 +10,7 @@ mode="indeterminate" > - + - + - {{ store?.display }} + {{ store?.display }}