diff --git a/business-services/billing-service/src/main/java/org/egov/demand/service/BillServicev2.java b/business-services/billing-service/src/main/java/org/egov/demand/service/BillServicev2.java index 75b8b7ce294..74aa80058eb 100644 --- a/business-services/billing-service/src/main/java/org/egov/demand/service/BillServicev2.java +++ b/business-services/billing-service/src/main/java/org/egov/demand/service/BillServicev2.java @@ -239,7 +239,6 @@ public BillResponseV2 fetchBill(GenerateBillCriteria billCriteria, RequestInfoWr log.info( "If bills are empty" +bills.size()); //if(!billCriteria.getBusinessService().equalsIgnoreCase("WS") && !billCriteria.getBusinessService().equalsIgnoreCase("SW")) //if(!billCriteria.getBusinessService().equalsIgnoreCase("SW")) - if(!billCriteria.getBusinessService().equalsIgnoreCase("BPA.NC_SAN_FEE")) updateDemandsForexpiredBillDetails(billCriteria.getBusinessService(), billCriteria.getConsumerCode(), billCriteria.getTenantId(), requestInfoWrapper); return generateBill(billCriteria, requestInfo); } @@ -380,7 +379,7 @@ public BillResponseV2 generateBill(GenerateBillCriteria billCriteria, RequestInf consumerCodes.addAll(billCriteria.getConsumerCode()); DemandCriteria demandCriteria=new DemandCriteria(); - if(billCriteria.getBusinessService().equalsIgnoreCase("WS") || billCriteria.getBusinessService().equalsIgnoreCase("SW") || billCriteria.getBusinessService().equalsIgnoreCase("BPA.NC_SAN_FEE")) + if(billCriteria.getBusinessService().equalsIgnoreCase("WS") || billCriteria.getBusinessService().equalsIgnoreCase("SW")) demandCriteria = DemandCriteria.builder() .status(org.egov.demand.model.Demand.StatusEnum.ACTIVE.toString()) .businessService(billCriteria.getBusinessService()) diff --git a/core-services/egov-workflow-v2/src/main/java/org/egov/wf/repository/EscalationRepository.java b/core-services/egov-workflow-v2/src/main/java/org/egov/wf/repository/EscalationRepository.java index c5d342ca4f7..f4e044b7ce8 100644 --- a/core-services/egov-workflow-v2/src/main/java/org/egov/wf/repository/EscalationRepository.java +++ b/core-services/egov-workflow-v2/src/main/java/org/egov/wf/repository/EscalationRepository.java @@ -8,14 +8,11 @@ import org.springframework.jdbc.core.SingleColumnRowMapper; import org.springframework.stereotype.Component; -import lombok.extern.slf4j.Slf4j; - import java.util.ArrayList; import java.util.LinkedList; import java.util.List; @Component -@Slf4j public class EscalationRepository { @@ -46,8 +43,6 @@ public List getBusinessIds(EscalationSearchCriteria criteria){ else { query = queryBuilder.getEscalationQuery(criteria, preparedStmtList); } - log.info("query is"+query); - log.info("params are " +preparedStmtList.toString()); List businessIds = jdbcTemplate.query(query, preparedStmtList.toArray(), new SingleColumnRowMapper<>(String.class)); return businessIds; diff --git a/core-services/egov-workflow-v2/src/main/java/org/egov/wf/repository/querybuilder/EscalationQueryBuilder.java b/core-services/egov-workflow-v2/src/main/java/org/egov/wf/repository/querybuilder/EscalationQueryBuilder.java index f8591ddce2e..a6a6e32e5df 100644 --- a/core-services/egov-workflow-v2/src/main/java/org/egov/wf/repository/querybuilder/EscalationQueryBuilder.java +++ b/core-services/egov-workflow-v2/src/main/java/org/egov/wf/repository/querybuilder/EscalationQueryBuilder.java @@ -43,12 +43,12 @@ public String getEscalationQuery(EscalationSearchCriteria criteria, List preparedStmtList.add(criteria.getStatus()); if(criteria.getStateSlaExceededBy() != null){ - builder.append(" AND (select extract(epoch from current_timestamp)) * 1000 - wf.createdtime > ? "); + builder.append(" AND (select extract(epoch from current_timestamp)) * 1000 - wf.createdtime - wf.statesla > ? "); preparedStmtList.add(criteria.getStateSlaExceededBy()); } if(criteria.getBusinessSlaExceededBy() != null){ - builder.append(" AND (select extract(epoch from current_timestamp)) * 1000 - wf.createdtime > ? "); + builder.append(" AND (select extract(epoch from current_timestamp)) * 1000 - wf.createdtime - wf.businessservicesla > ? "); preparedStmtList.add(criteria.getBusinessSlaExceededBy()); } @@ -92,7 +92,7 @@ public String getEscalationQueryFiltered(EscalationSearchCriteria criteria,List< } if(criteria.getBusinessSlaExceededBy() != null){ - builder.append(" AND (select extract(epoch from current_timestamp)) * 1000 - wf.createdtime > ? "); + builder.append(" AND (select extract(epoch from current_timestamp)) * 1000 - wf.createdtime - wf.businessservicesla > ? "); preparedStmtList.add(criteria.getBusinessSlaExceededBy()); } diff --git a/core-services/egov-workflow-v2/src/main/java/org/egov/wf/service/EscalationService.java b/core-services/egov-workflow-v2/src/main/java/org/egov/wf/service/EscalationService.java index 7ec7ed90958..bbb01cb879e 100644 --- a/core-services/egov-workflow-v2/src/main/java/org/egov/wf/service/EscalationService.java +++ b/core-services/egov-workflow-v2/src/main/java/org/egov/wf/service/EscalationService.java @@ -123,8 +123,6 @@ private void processEscalation(RequestInfo requestInfo, Escalation escalation, L Integer numberOfBusinessIds = businessIds.size(); Integer batchSize = config.getEscalationBatchSize(); - log.info("Records to process"+numberOfBusinessIds); - for(int i = 0; i < numberOfBusinessIds; i = i + batchSize){ // Processing the businessIds in batches diff --git a/core-services/egov-workflow-v2/src/test/java/org/egov/wf/repository/querybuilder/EscalationQueryBuilderTest.java b/core-services/egov-workflow-v2/src/test/java/org/egov/wf/repository/querybuilder/EscalationQueryBuilderTest.java index b8ffde6e50d..42b0cce0594 100644 --- a/core-services/egov-workflow-v2/src/test/java/org/egov/wf/repository/querybuilder/EscalationQueryBuilderTest.java +++ b/core-services/egov-workflow-v2/src/test/java/org/egov/wf/repository/querybuilder/EscalationQueryBuilderTest.java @@ -1,96 +1,96 @@ -package org.egov.wf.repository.querybuilder; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.atLeast; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; - -import org.egov.wf.web.models.EscalationSearchCriteria; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -@ContextConfiguration(classes = {EscalationQueryBuilder.class}) -@ExtendWith(SpringExtension.class) -class EscalationQueryBuilderTest { - @Autowired - private EscalationQueryBuilder escalationQueryBuilder; - - - @Test - void testGetEscalationQuery() { - EscalationSearchCriteria escalationSearchCriteria = mock(EscalationSearchCriteria.class); - when(escalationSearchCriteria.getBusinessSlaExceededBy()).thenReturn(1L); - when(escalationSearchCriteria.getStateSlaExceededBy()).thenReturn(1L); - when(escalationSearchCriteria.getBusinessService()).thenReturn("Business Service"); - when(escalationSearchCriteria.getStatus()).thenReturn("Status"); - when(escalationSearchCriteria.getTenantId()).thenReturn("42"); - ArrayList objectList = new ArrayList<>(); - assertEquals( - "select businessId from ( SELECT *,RANK () OVER (PARTITION BY businessId ORDER BY createdtime DESC)" - + " rank_number FROM eg_wf_processinstance_v2 WHERE businessservice = ? AND tenantid= ? ) wf WHERE" - + " rank_number = 1 AND wf.status = ? AND (select extract(epoch from current_timestamp)) * 1000 -" - + " wf.createdtime > ? AND (select extract(epoch from current_timestamp)) * 1000 -" - + " wf.createdtime > ? ", - this.escalationQueryBuilder.getEscalationQuery(escalationSearchCriteria, objectList)); - verify(escalationSearchCriteria, atLeast(1)).getBusinessSlaExceededBy(); - verify(escalationSearchCriteria, atLeast(1)).getStateSlaExceededBy(); - verify(escalationSearchCriteria).getBusinessService(); - verify(escalationSearchCriteria).getStatus(); - verify(escalationSearchCriteria).getTenantId(); - assertEquals(5, objectList.size()); - } - - - @Test - void testGetEscalationQuerywithstatesla() { - EscalationSearchCriteria escalationSearchCriteria = mock(EscalationSearchCriteria.class); - when(escalationSearchCriteria.getBusinessSlaExceededBy()).thenReturn(null); - when(escalationSearchCriteria.getStateSlaExceededBy()).thenReturn(1L); - when(escalationSearchCriteria.getBusinessService()).thenReturn("Business Service"); - when(escalationSearchCriteria.getStatus()).thenReturn("Status"); - when(escalationSearchCriteria.getTenantId()).thenReturn("42"); - ArrayList objectList = new ArrayList<>(); - assertEquals( - "select businessId from ( SELECT *,RANK () OVER (PARTITION BY businessId ORDER BY createdtime DESC)" - + " rank_number FROM eg_wf_processinstance_v2 WHERE businessservice = ? AND tenantid= ? ) wf WHERE" - + " rank_number = 1 AND wf.status = ? AND (select extract(epoch from current_timestamp)) * 1000 -" - + " wf.createdtime > ? ", - this.escalationQueryBuilder.getEscalationQuery(escalationSearchCriteria, objectList)); - verify(escalationSearchCriteria).getBusinessSlaExceededBy(); - verify(escalationSearchCriteria, atLeast(1)).getStateSlaExceededBy(); - verify(escalationSearchCriteria).getBusinessService(); - verify(escalationSearchCriteria).getStatus(); - verify(escalationSearchCriteria).getTenantId(); - assertEquals(4, objectList.size()); - } - - @Test - void testGetEscalationQuerywithbusinessservicesla() { - EscalationSearchCriteria escalationSearchCriteria = mock(EscalationSearchCriteria.class); - when(escalationSearchCriteria.getBusinessSlaExceededBy()).thenReturn(1L); - when(escalationSearchCriteria.getStateSlaExceededBy()).thenReturn(null); - when(escalationSearchCriteria.getBusinessService()).thenReturn("Business Service"); - when(escalationSearchCriteria.getStatus()).thenReturn("Status"); - when(escalationSearchCriteria.getTenantId()).thenReturn("42"); - ArrayList objectList = new ArrayList<>(); - assertEquals( - "select businessId from ( SELECT *,RANK () OVER (PARTITION BY businessId ORDER BY createdtime DESC)" - + " rank_number FROM eg_wf_processinstance_v2 WHERE businessservice = ? AND tenantid= ? ) wf WHERE" - + " rank_number = 1 AND wf.status = ? AND (select extract(epoch from current_timestamp)) * 1000 -" - + " wf.createdtime > ? ", - this.escalationQueryBuilder.getEscalationQuery(escalationSearchCriteria, objectList)); - verify(escalationSearchCriteria, atLeast(1)).getBusinessSlaExceededBy(); - verify(escalationSearchCriteria).getStateSlaExceededBy(); - verify(escalationSearchCriteria).getBusinessService(); - verify(escalationSearchCriteria).getStatus(); - verify(escalationSearchCriteria).getTenantId(); - assertEquals(4, objectList.size()); - } -} - +package org.egov.wf.repository.querybuilder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; + +import org.egov.wf.web.models.EscalationSearchCriteria; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +@ContextConfiguration(classes = {EscalationQueryBuilder.class}) +@ExtendWith(SpringExtension.class) +class EscalationQueryBuilderTest { + @Autowired + private EscalationQueryBuilder escalationQueryBuilder; + + + @Test + void testGetEscalationQuery() { + EscalationSearchCriteria escalationSearchCriteria = mock(EscalationSearchCriteria.class); + when(escalationSearchCriteria.getBusinessSlaExceededBy()).thenReturn(1L); + when(escalationSearchCriteria.getStateSlaExceededBy()).thenReturn(1L); + when(escalationSearchCriteria.getBusinessService()).thenReturn("Business Service"); + when(escalationSearchCriteria.getStatus()).thenReturn("Status"); + when(escalationSearchCriteria.getTenantId()).thenReturn("42"); + ArrayList objectList = new ArrayList<>(); + assertEquals( + "select businessId from ( SELECT *,RANK () OVER (PARTITION BY businessId ORDER BY createdtime DESC)" + + " rank_number FROM eg_wf_processinstance_v2 WHERE businessservice = ? AND tenantid= ? ) wf WHERE" + + " rank_number = 1 AND wf.status = ? AND (select extract(epoch from current_timestamp)) * 1000 -" + + " wf.createdtime - wf.statesla > ? AND (select extract(epoch from current_timestamp)) * 1000 -" + + " wf.createdtime - wf.businessservicesla > ? ", + this.escalationQueryBuilder.getEscalationQuery(escalationSearchCriteria, objectList)); + verify(escalationSearchCriteria, atLeast(1)).getBusinessSlaExceededBy(); + verify(escalationSearchCriteria, atLeast(1)).getStateSlaExceededBy(); + verify(escalationSearchCriteria).getBusinessService(); + verify(escalationSearchCriteria).getStatus(); + verify(escalationSearchCriteria).getTenantId(); + assertEquals(5, objectList.size()); + } + + + @Test + void testGetEscalationQuerywithstatesla() { + EscalationSearchCriteria escalationSearchCriteria = mock(EscalationSearchCriteria.class); + when(escalationSearchCriteria.getBusinessSlaExceededBy()).thenReturn(null); + when(escalationSearchCriteria.getStateSlaExceededBy()).thenReturn(1L); + when(escalationSearchCriteria.getBusinessService()).thenReturn("Business Service"); + when(escalationSearchCriteria.getStatus()).thenReturn("Status"); + when(escalationSearchCriteria.getTenantId()).thenReturn("42"); + ArrayList objectList = new ArrayList<>(); + assertEquals( + "select businessId from ( SELECT *,RANK () OVER (PARTITION BY businessId ORDER BY createdtime DESC)" + + " rank_number FROM eg_wf_processinstance_v2 WHERE businessservice = ? AND tenantid= ? ) wf WHERE" + + " rank_number = 1 AND wf.status = ? AND (select extract(epoch from current_timestamp)) * 1000 -" + + " wf.createdtime - wf.statesla > ? ", + this.escalationQueryBuilder.getEscalationQuery(escalationSearchCriteria, objectList)); + verify(escalationSearchCriteria).getBusinessSlaExceededBy(); + verify(escalationSearchCriteria, atLeast(1)).getStateSlaExceededBy(); + verify(escalationSearchCriteria).getBusinessService(); + verify(escalationSearchCriteria).getStatus(); + verify(escalationSearchCriteria).getTenantId(); + assertEquals(4, objectList.size()); + } + + @Test + void testGetEscalationQuerywithbusinessservicesla() { + EscalationSearchCriteria escalationSearchCriteria = mock(EscalationSearchCriteria.class); + when(escalationSearchCriteria.getBusinessSlaExceededBy()).thenReturn(1L); + when(escalationSearchCriteria.getStateSlaExceededBy()).thenReturn(null); + when(escalationSearchCriteria.getBusinessService()).thenReturn("Business Service"); + when(escalationSearchCriteria.getStatus()).thenReturn("Status"); + when(escalationSearchCriteria.getTenantId()).thenReturn("42"); + ArrayList objectList = new ArrayList<>(); + assertEquals( + "select businessId from ( SELECT *,RANK () OVER (PARTITION BY businessId ORDER BY createdtime DESC)" + + " rank_number FROM eg_wf_processinstance_v2 WHERE businessservice = ? AND tenantid= ? ) wf WHERE" + + " rank_number = 1 AND wf.status = ? AND (select extract(epoch from current_timestamp)) * 1000 -" + + " wf.createdtime - wf.businessservicesla > ? ", + this.escalationQueryBuilder.getEscalationQuery(escalationSearchCriteria, objectList)); + verify(escalationSearchCriteria, atLeast(1)).getBusinessSlaExceededBy(); + verify(escalationSearchCriteria).getStateSlaExceededBy(); + verify(escalationSearchCriteria).getBusinessService(); + verify(escalationSearchCriteria).getStatus(); + verify(escalationSearchCriteria).getTenantId(); + assertEquals(4, objectList.size()); + } +} + diff --git a/dx-services/requester-services-dx/src/main/java/org/egov/dx/service/eSignService.java b/dx-services/requester-services-dx/src/main/java/org/egov/dx/service/eSignService.java index e35a0dc18ce..9f0c387720f 100644 --- a/dx-services/requester-services-dx/src/main/java/org/egov/dx/service/eSignService.java +++ b/dx-services/requester-services-dx/src/main/java/org/egov/dx/service/eSignService.java @@ -8,25 +8,27 @@ import java.net.HttpURLConnection; import java.net.URL; import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.Base64; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import javax.validation.Valid; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathFactory; import org.egov.dx.util.Configurations; import org.egov.dx.util.Utilities; -import org.egov.dx.web.models.FileResponse; + import org.egov.dx.web.models.RequestInfoWrapper; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; -import org.springframework.web.util.UriComponentsBuilder; import org.w3c.dom.Document; import com.emudhra.esign.ReturnDocument; @@ -34,17 +36,9 @@ import com.emudhra.esign.eSignInput; import com.emudhra.esign.eSignInputBuilder; import com.emudhra.esign.eSignServiceReturn; -import com.google.gson.Gson; -import lombok.extern.slf4j.Slf4j; -import okhttp3.MediaType; -import okhttp3.MultipartBody; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; @Service -@Slf4j public class eSignService { @Autowired @@ -91,7 +85,7 @@ public String processPDF(RequestInfoWrapper requestInfoWrapper) throws IOExcepti .setSignedBy("Manvi") //(mandatory) .setCoSign(true) .setAppearanceType(eSign.AppearanceType.StandardSignature) - .setPageTobeSigned(eSign.PageTobeSigned.First) + .setPageTobeSigned(eSign.PageTobeSigned.Even) .setCoordinates(eSign.Coordinates.TopLeft) .build(); @@ -124,9 +118,6 @@ public String getEsignedPDF(HttpServletRequest request, HttpServletResponse resp InputStream xmlStream; String xml = ""; String txnref = null; - byte[] signedBytes = null; - String pdfPath=null; - try { // Get response from gateway xmlStream = request.getInputStream(); @@ -136,20 +127,21 @@ public String getEsignedPDF(HttpServletRequest request, HttpServletResponse resp String txn = new String(java.util.Base64.getDecoder().decode(txns.getBytes())); String[] strArr = txn.split("\\|"); - String txnId = strArr[0]; - - String xmlString = URLDecoder.decode(txnref); - xml = xmlString.split("&XML=")[1]; + String txnid = strArr[0]; + + eSign eSign = new eSign(configurations.getLicenceFile(), configurations.getPfxPath(), configurations.getPfxPassword(), configurations.getPfxAllias()); + eSignServiceReturn returnService = eSign.getStatus(txnid); + xml = returnService.getResponseXML(); Document doc = Utilities.convertStringToDocument(xml); XPath xPath = XPathFactory.newInstance().newXPath(); String status = Utilities.GetXpathValue(xPath, "/EsignResp/@status", doc); - txnId = Utilities.GetXpathValue(xPath, "/EsignResp/@txn", doc); + String txnId = Utilities.GetXpathValue(xPath, "/EsignResp/@txn", doc); + if ("1".equals(status)) { // complete signing - eSign eSign = new eSign(configurations.getLicenceFile(), configurations.getPfxPath(), configurations.getPfxPassword(), configurations.getPfxAllias()); eSignServiceReturn serviceReturn = eSign.getSigedDocument(xml, configurations.getTempFolder() + File.separator + txnId + ".sig"); // To convert signed pdf from base 64 encoded string to pdf file @@ -158,10 +150,8 @@ public String getEsignedPDF(HttpServletRequest request, HttpServletResponse resp int i = 0; for (ReturnDocument returnDocument : returnDocuments) { String pdfBase64 = returnDocument.getSignedDocument(); - System.out.println("Print" +pdfBase64); - signedBytes = esign.text.pdf.codec.Base64.decode(pdfBase64); - pdfPath = configurations.getOutputFolder() + File.separator + txnId + "_" + i + ".pdf"; - //String pdfPath = configurations.getS3Bucket() + File.separator + txnId + "_" + i + ".pdf"; + byte[] signedBytes = esign.text.pdf.codec.Base64.decode(pdfBase64); + String pdfPath = configurations.getOutputFolder() + File.separator + txnId + "_" + i + ".pdf"; try (FileOutputStream fos = new FileOutputStream(pdfPath)) { fos.write(signedBytes); } @@ -172,29 +162,8 @@ public String getEsignedPDF(HttpServletRequest request, HttpServletResponse resp } catch (Exception e) { e.printStackTrace(); } + return ("Document Signed and saved successfully"); - - OkHttpClient client = new OkHttpClient().newBuilder() - .build(); - RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM) - .addFormDataPart("tenantId","pg") - .addFormDataPart("module","TL") - .addFormDataPart("file",pdfPath, - RequestBody.create(MediaType.parse("application/pdf"), - new File(pdfPath))) - .build(); - Request request1 = new Request.Builder() - .url("https://upyog-test.niua.org/filestore/v1/files") - .method("POST", body) - .addHeader("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundaryf04Aqi5zqaexyYxK") - .build(); - - String responsee = client.newCall(request1).execute().body().string(); - log.info(responsee); - Gson gson = new Gson(); - FileResponse files = gson.fromJson(responsee , FileResponse.class); - - return files.getFiles().get(0).getFileStoreId(); } diff --git a/dx-services/requester-services-dx/src/main/java/org/egov/dx/util/Configurations.java b/dx-services/requester-services-dx/src/main/java/org/egov/dx/util/Configurations.java index d6fe257db6b..dad41132b92 100644 --- a/dx-services/requester-services-dx/src/main/java/org/egov/dx/util/Configurations.java +++ b/dx-services/requester-services-dx/src/main/java/org/egov/dx/util/Configurations.java @@ -90,16 +90,4 @@ public class Configurations { @Value("${esign.outputfolder}") private String outputFolder; - @Value("${esign.UIURL}") - private String uIURL; - -// @Value("${esign.tlredirecturl}") -// private String tlRedirectUrl; - -// @Value("${eSign.s3bucket}") -// private String s3Bucket; -// -// @Value("${api.documenthost}") -// private String documentHost; - } diff --git a/dx-services/requester-services-dx/src/main/java/org/egov/dx/web/controller/EsignController.java b/dx-services/requester-services-dx/src/main/java/org/egov/dx/web/controller/EsignController.java index 9f2fa9751db..c72434456dd 100644 --- a/dx-services/requester-services-dx/src/main/java/org/egov/dx/web/controller/EsignController.java +++ b/dx-services/requester-services-dx/src/main/java/org/egov/dx/web/controller/EsignController.java @@ -40,7 +40,6 @@ package org.egov.dx.web.controller; -import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.URISyntaxException; @@ -48,23 +47,18 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; -import org.springframework.http.MediaType; + import org.egov.common.contract.request.RequestInfo; import org.egov.dx.service.eSignService; -import org.egov.dx.util.Configurations; import org.egov.dx.web.models.ResponseInfoFactory; import org.egov.dx.web.models.RequestInfoWrapper; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.multipart.MultipartFile; -import org.springframework.web.util.UriComponentsBuilder; - import lombok.extern.slf4j.Slf4j; @@ -82,9 +76,6 @@ public class EsignController { @Autowired eSignService esignService; - @Autowired - Configurations configurations; - @RequestMapping("/process") public ResponseEntity processPDF(@Valid @RequestBody RequestInfoWrapper requestInfoWrapper) throws URISyntaxException { try { @@ -95,24 +86,12 @@ public ResponseEntity processPDF(@Valid @RequestBody RequestInfoWrapper } } @RequestMapping("/redirect") - public ResponseEntity getEsignedPDF(HttpServletRequest request, HttpServletResponse response) throws ServletException { + public ResponseEntity getEsignedPDF(HttpServletRequest request, HttpServletResponse response) throws ServletException { try { - //byte[] byteArray = esignService.getEsignedPDF( request, response); - - String ff = esignService.getEsignedPDF( request, response); - - HttpHeaders httpHeaders = new HttpHeaders(); -// httpHeaders.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=report.pdf"); -// httpHeaders.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PDF_VALUE); - StringBuilder redirectURL = new StringBuilder(); - redirectURL.append(configurations.getUIURL()+"?filestore="+ff); - httpHeaders.setLocation(UriComponentsBuilder.fromHttpUrl(redirectURL.toString()) - .queryParams(null).build().encode().toUri()); - return new ResponseEntity<>(httpHeaders, HttpStatus.FOUND); - - + String responseUrl = esignService.getEsignedPDF( request, response); + return new ResponseEntity<>(responseUrl, HttpStatus.OK); } catch (IOException e) { - return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR); + return new ResponseEntity<>("Error processing PDF: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } } } diff --git a/dx-services/requester-services-dx/src/main/java/org/egov/dx/web/models/FIleRequest.java b/dx-services/requester-services-dx/src/main/java/org/egov/dx/web/models/FIleRequest.java deleted file mode 100644 index 57208473abd..00000000000 --- a/dx-services/requester-services-dx/src/main/java/org/egov/dx/web/models/FIleRequest.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.egov.dx.web.models; - -import javax.validation.Valid; -import javax.validation.constraints.NotNull; - -import org.egov.common.contract.request.RequestInfo; - -import com.fasterxml.jackson.annotation.JsonProperty; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Data -@Builder -@NoArgsConstructor -@AllArgsConstructor -public class FIleRequest { - - - @JsonProperty("RequestInfo") - @NotNull - private RequestInfo requestInfo; - - @JsonProperty("TokenReq") - @Valid - private TokenReq tokenReq; - -} diff --git a/dx-services/requester-services-dx/src/main/java/org/egov/dx/web/models/FileResponse.java b/dx-services/requester-services-dx/src/main/java/org/egov/dx/web/models/FileResponse.java deleted file mode 100644 index 6c2ed8a969e..00000000000 --- a/dx-services/requester-services-dx/src/main/java/org/egov/dx/web/models/FileResponse.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.egov.dx.web.models; - -import java.util.List; - -import javax.validation.Valid; - -import org.egov.common.contract.response.ResponseInfo; - -import com.fasterxml.jackson.annotation.JsonProperty; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Data -@Builder -@NoArgsConstructor -@AllArgsConstructor -public class FileResponse { - - @JsonProperty("ResponseInfo") - private ResponseInfo responseInfo=null; - - - @JsonProperty("files") - @Valid - private List files=null; - } diff --git a/dx-services/requester-services-dx/src/main/java/org/egov/dx/web/models/Files.java b/dx-services/requester-services-dx/src/main/java/org/egov/dx/web/models/Files.java deleted file mode 100644 index 309afe656e9..00000000000 --- a/dx-services/requester-services-dx/src/main/java/org/egov/dx/web/models/Files.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.egov.dx.web.models; - -import javax.validation.constraints.NotNull; - -import com.fasterxml.jackson.annotation.JsonProperty; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Data -@Builder -@NoArgsConstructor -@AllArgsConstructor -public class Files { - - - @JsonProperty("fileStoreId") - @NotNull - private String fileStoreId; - - @JsonProperty("tenantId") - @NotNull - private String tenantId; - } diff --git a/dx-services/requester-services-dx/src/main/java/org/egov/dx/web/models/ResponseInfo.java b/dx-services/requester-services-dx/src/main/java/org/egov/dx/web/models/ResponseInfo.java deleted file mode 100644 index 2afb64e6099..00000000000 --- a/dx-services/requester-services-dx/src/main/java/org/egov/dx/web/models/ResponseInfo.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.egov.dx.web.models; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonValue; -import lombok.*; -import org.springframework.validation.annotation.Validated; - -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; - -/** - * ResponseInfo should be used to carry metadata information about the response from the server. apiId, ver and msgId in ResponseInfo should always correspond to the same values in respective request's RequestInfo. - */ -@Validated -@javax.annotation.Generated(value = "org.egov.codegen.SpringBootCodegen", date = "2018-06-05T12:58:12.679+05:30") - -@Getter -@Setter -@AllArgsConstructor -@NoArgsConstructor -@Builder -public class ResponseInfo { - - @JsonProperty("apiId") - @NotNull - @Size(max = 128) - private String apiId = null; - - @JsonProperty("ver") - @NotNull - @Size(max = 32) - private String ver = null; - - @JsonProperty("ts") - @NotNull - private Long ts = null; - - @JsonProperty("resMsgId") - @Size(max = 256) - private String resMsgId = null; - - @JsonProperty("msgId") - @Size(max = 256) - private String msgId = null; - -} - diff --git a/dx-services/requester-services-dx/src/main/resources/application.properties b/dx-services/requester-services-dx/src/main/resources/application.properties index 34a3d5a3740..db1b6760251 100644 --- a/dx-services/requester-services-dx/src/main/resources/application.properties +++ b/dx-services/requester-services-dx/src/main/resources/application.properties @@ -46,3 +46,4 @@ esign.UIURL=https://upyog-test.niua.org/digit-ui/employee/tl/common #File Store Id #egov.filestore.host=http://egov-filestore:8080/ #sw.fileStore.link=filestore/v1/files/url?tenantId=pg&fileStoreIds=$f + diff --git a/edcr/service/egov/egov-edcr-extract/src/main/java/org/egov/edcr/feature/FarExtract.java b/edcr/service/egov/egov-edcr-extract/src/main/java/org/egov/edcr/feature/FarExtract.java index 2f2060d4631..cafa33e12af 100644 --- a/edcr/service/egov/egov-edcr-extract/src/main/java/org/egov/edcr/feature/FarExtract.java +++ b/edcr/service/egov/egov-edcr-extract/src/main/java/org/egov/edcr/feature/FarExtract.java @@ -536,7 +536,7 @@ private void extractFloorHeight(PlanDetail pl, Block block, Floor floor) { String floorHeightLayerName = layerNames.getLayerName("LAYER_NAME_BLOCK_NAME_PREFIX") + block.getNumber() + "_" + layerNames.getLayerName("LAYER_NAME_FLOOR_NAME_PREFIX") + floor.getNumber() + "_" + layerNames.getLayerName("LAYER_NAME_FLOOR_HEIGHT_PREFIX"); - List flrHeights = Util.getListOfDimensionValueByLayer(pl, floorHeightLayerName); + // List flrHeights = Util.getListOfDimensionValueByLayer(pl, floorHeightLayerName); // String isStiltFloor = Util.getMtextByLayerName(pl.getDoc(), floorHeightLayerName, "STILT_FLR_HT"); // // if (!isBlank(isStiltFloor)) { @@ -566,11 +566,11 @@ private void extractFloorHeight(PlanDetail pl, Block block, Floor floor) { // } // // - if (!flrHeights.isEmpty()) { - floor.setFloorHeights(flrHeights); - } else { - pl.addError(FLOOR_HEIGHT_DESC, getLocaleMessage(OBJECTNOTDEFINED, FLOOR_HEIGHT_DESC + floor.getNumber())); - } +// if (!flrHeights.isEmpty()) { +// floor.setFloorHeights(flrHeights); +// } else { +// pl.addError(FLOOR_HEIGHT_DESC, getLocaleMessage(OBJECTNOTDEFINED, FLOOR_HEIGHT_DESC + floor.getNumber())); +// } } @Override diff --git a/edcr/service/egov/egov-edcr/src/main/java/org/egov/edcr/feature/AdditionalFeature.java b/edcr/service/egov/egov-edcr/src/main/java/org/egov/edcr/feature/AdditionalFeature.java index 9feb20c1edc..4fd35305d3f 100644 --- a/edcr/service/egov/egov-edcr/src/main/java/org/egov/edcr/feature/AdditionalFeature.java +++ b/edcr/service/egov/egov-edcr/src/main/java/org/egov/edcr/feature/AdditionalFeature.java @@ -78,7 +78,7 @@ public class AdditionalFeature extends FeatureProcess { private static final Logger LOG = LogManager.getLogger(AdditionalFeature.class); - private static final String RULE_38 = "4.4.4 (ii)"; + private static final String RULE_38 = "38"; private static final String RULE_39 = "39"; private static final String RULE = "5.2.1"; private static final String RULE_41_I_B = "41-i-b"; @@ -376,7 +376,7 @@ private void validateHeightOfFloors(Plan pl, HashMap errors) { String maxPermissibleFloorHeight = StringUtils.EMPTY; minRequiredFloorHeight = "2.75" + DcrConstants.IN_METER; - maxPermissibleFloorHeight = "4.40" + DcrConstants.IN_METER; + //maxPermissibleFloorHeight = "4.40" + DcrConstants.IN_METER; floor.setIsStiltFloor(false); if(floor.getIsStiltFloor() == false) { diff --git a/edcr/service/egov/egov-edcr/src/main/java/org/egov/edcr/feature/Balcony.java b/edcr/service/egov/egov-edcr/src/main/java/org/egov/edcr/feature/Balcony.java index 2a63e964338..416216052f6 100644 --- a/edcr/service/egov/egov-edcr/src/main/java/org/egov/edcr/feature/Balcony.java +++ b/edcr/service/egov/egov-edcr/src/main/java/org/egov/edcr/feature/Balcony.java @@ -69,7 +69,7 @@ public class Balcony extends FeatureProcess { private static final Logger LOG = LogManager.getLogger(Balcony.class); private static final String FLOOR = "Floor"; - private static final String RULE45_IV = "4.4.4 (iii)"; + private static final String RULE45_IV = "45-iv"; private static final String WIDTH_BALCONY_DESCRIPTION = "Minimum width for balcony %s"; private static final BigDecimal ONE_POINTNINEONE = BigDecimal.valueOf(0.91); diff --git a/edcr/service/egov/egov-edcr/src/main/java/org/egov/edcr/feature/GeneralStair.java b/edcr/service/egov/egov-edcr/src/main/java/org/egov/edcr/feature/GeneralStair.java index b96a9f838f5..7de8264fa41 100644 --- a/edcr/service/egov/egov-edcr/src/main/java/org/egov/edcr/feature/GeneralStair.java +++ b/edcr/service/egov/egov-edcr/src/main/java/org/egov/edcr/feature/GeneralStair.java @@ -1,7 +1,6 @@ package org.egov.edcr.feature; import java.math.BigDecimal; -import java.math.RoundingMode; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; @@ -51,20 +50,10 @@ public Plan validate(Plan plan) { @Override public Plan process(Plan plan) { - - // validate(planDetail); HashMap errors = new HashMap<>(); blk: for (Block block : plan.getBlocks()) { int generalStairCount = 0; - int totalLandings = 0; - int totalFlights = 0; - BigDecimal riserHeigt = BigDecimal.ZERO; - BigDecimal flrHt = BigDecimal.ZERO; - BigDecimal totalLandingWidth = BigDecimal.ZERO; - BigDecimal totalFlightWidth = BigDecimal.ZERO; - BigDecimal totalRisers = BigDecimal.ZERO; - BigDecimal totalSteps = BigDecimal.ZERO; if (block.getBuilding() != null) { /* @@ -106,16 +95,6 @@ public Plan process(Plan plan) { scrutinyDetailLanding.addColumnHeading(5, PROVIDED); scrutinyDetailLanding.addColumnHeading(6, STATUS); scrutinyDetailLanding.setKey("Block_" + block.getNumber() + "_" + "General Stair - Mid landing"); - - ScrutinyDetail scrutinyDetail4 = new ScrutinyDetail(); - scrutinyDetail4.addColumnHeading(1, RULE_NO); - scrutinyDetail4.addColumnHeading(2, FLOOR); - scrutinyDetail4.addColumnHeading(3, DESCRIPTION); - scrutinyDetail4.addColumnHeading(4, PERMISSIBLE); - scrutinyDetail4.addColumnHeading(5, PROVIDED); - scrutinyDetail4.addColumnHeading(6, STATUS); - scrutinyDetail4.setKey("Block_" + block.getNumber() + "_" + "General Stair - Riser Height"); - OccupancyTypeHelper mostRestrictiveOccupancyType = block.getBuilding() != null ? block.getBuilding().getMostRestrictiveFarHelper() @@ -130,7 +109,6 @@ public Plan process(Plan plan) { // BigDecimal floorSize = block.getBuilding().getFloorsAboveGround(); for (Floor floor : floors) { if (!floor.getTerrace()) { - boolean isTypicalRepititiveFloor = false; Map typicalFloorValues = Util.getTypicalFloorValues(block, floor, @@ -143,42 +121,6 @@ public Plan process(Plan plan) { if (!generalStairs.isEmpty()) { for (org.egov.common.entity.edcr.GeneralStair generalStair : generalStairs) { - - flrHt = generalStair.getFloorHeight(); - System.out.println("flrHt___" + flrHt); - List landings1 = generalStair.getLandings(); - totalLandings += landings1.size(); - - List flights = generalStair.getFlights(); - totalFlights += flights.size(); - - for (Flight flight : flights) { - - - BigDecimal risers = flight.getNoOfRises(); - totalRisers = totalRisers.add(risers); - } - System.out.println("total totalRisers " + totalRisers); - - // Sum the landing widths - for (StairLanding landing : landings1) { - List widths = landing.getWidths(); - if (!widths.isEmpty()) { - BigDecimal landingWidth = widths.stream().reduce(BigDecimal::min).get(); - totalLandingWidth = totalLandingWidth.add(landingWidth); // Add to total - } - } - - - System.out.println("total landings " + totalLandingWidth); - - totalSteps = totalRisers.add(totalLandingWidth); - - System.out.println("total totalSteps " + totalSteps); - - - - { validateFlight(plan, errors, block, scrutinyDetail2, scrutinyDetail3, scrutinyDetailRise, mostRestrictiveOccupancyType, floor, typicalFloorValues, @@ -202,9 +144,7 @@ public Plan process(Plan plan) { } } - } - } else { if (floor.getNumber() != generalStairCount) { @@ -234,8 +174,6 @@ public Plan process(Plan plan) { }} - - if ( !stairAbsent.isEmpty()) { for (String error : stairAbsent) { @@ -296,7 +234,6 @@ private void validateLanding(Plan plan, Block block, ScrutinyDetail scrutinyDeta scrutinyDetailLanding); } } - System.out.println("minn" + minWidth); }else { errors.put( "General Stair landing width not defined in block " + block.getNumber() + " floor " @@ -306,28 +243,22 @@ private void validateLanding(Plan plan, Block block, ScrutinyDetail scrutinyDeta + floor.getNumber() + " stair " + generalStair.getNumber()); plan.addErrors(errors); - } - } - } private void validateFlight(Plan plan, HashMap errors, Block block, ScrutinyDetail scrutinyDetail2, ScrutinyDetail scrutinyDetail3, ScrutinyDetail scrutinyDetailRise, OccupancyTypeHelper mostRestrictiveOccupancyType, Floor floor, Map typicalFloorValues, org.egov.common.entity.edcr.GeneralStair generalStair, int generalStairCount) { if (!generalStair.getFlights().isEmpty()) { - for (Flight flight : generalStair.getFlights()) { - List flightPolyLines = flight.getFlights(); List flightLengths = flight.getLengthOfFlights(); List flightWidths = flight.getWidthOfFlights(); BigDecimal noOfRises = flight.getNoOfRises(); Boolean flightPolyLineClosed = flight.getFlightClosed(); - - //flight.getNumber(); + BigDecimal minTread = BigDecimal.ZERO; BigDecimal minFlightWidth = BigDecimal.ZERO; String flightLayerName = String.format(DxfFileConstants.LAYER_STAIR_FLIGHT, @@ -397,10 +328,8 @@ private void validateFlight(Plan plan, HashMap errors, Block blo } } - } else { -// if(floor.getNumber() != generalStairCount - 1) - { //This condition because in top most floor stairs are not mandatory for punjab, + if(floor.getNumber() != generalStairCount - 1) { //This condition because in top most floor stairs are not mandatory for punjab, //so removing the error if stairs are not defined in top mist floor String error = String.format(FLIGHT_NOT_DEFINED_DESCRIPTION, block.getNumber(), floor.getNumber()); errors.put(error, error); diff --git a/edcr/service/egov/egov-edcr/src/main/java/org/egov/edcr/feature/HeightOfRoom.java b/edcr/service/egov/egov-edcr/src/main/java/org/egov/edcr/feature/HeightOfRoom.java index b48bb98cff4..512ad10a80d 100644 --- a/edcr/service/egov/egov-edcr/src/main/java/org/egov/edcr/feature/HeightOfRoom.java +++ b/edcr/service/egov/egov-edcr/src/main/java/org/egov/edcr/feature/HeightOfRoom.java @@ -82,7 +82,6 @@ public class HeightOfRoom extends FeatureProcess { private static final String RULE = "4.4.4"; - private static final String RULE1 = "4.4.4 (ix)"; private static final String SUBRULE_41_II_B = "41-ii-b"; private static final String RULE_AC_DESC = "Minimum height of ac room"; @@ -311,92 +310,104 @@ else if (G.equalsIgnoreCase(mostRestrictiveOccupancy.getType().getCode())) } } + if (floor.getRegularRooms() != null && floor.getRegularRooms().size() > 0) { - List residentialRoomHeights = new ArrayList<>(); - List heights = new ArrayList<>(); - List rooms = new ArrayList<>(); - - boolean roomWithMinArea9_2Exists = false; // Flag to check if any room has minimum area of 9.2 - boolean roomWithMinWidth2_4Exists = false; // Flag to check if any room has minimum width of 2.4 - - for (Room room : floor.getRegularRooms()) { - - if (room.getHeights() != null) - heights.addAll(room.getHeights()); - if (room.getRooms() != null) - rooms.addAll(room.getRooms()); - - for (Measurement measurement : room.getRooms()) { - measurement.setRoomNumber(room.getNumber()); - } - } - - for (RoomHeight roomHeight : heights) { - if (heightOfRoomFeaturesColor.get(color) == roomHeight.getColorCode()) { - residentialRoomHeights.add(roomHeight.getHeight()); - } - } - - BigDecimal roomArea; - BigDecimal roomWidth; - - for (Measurement room : rooms) { - - // Set the area and width thresholds based on whether the min area and width have been satisfied - minimumArea = roomWithMinArea9_2Exists ? MINIMUM_AREA_7_5 : MINIMUM_AREA_9_2; - minWidth = roomWithMinWidth2_4Exists ? MINIMUM_WIDTH_2_1 : MINIMUM_WIDTH_2_4; - maxArea = MAXIMUM_AREA_46_45; - - roomArea = room.getArea().setScale(2, BigDecimal.ROUND_HALF_UP); - roomWidth = room.getWidth().setScale(2, BigDecimal.ROUND_HALF_UP); - - // Update flags if the current room meets the higher thresholds - if (roomArea.compareTo(MINIMUM_AREA_9_2) >= 0) { - roomWithMinArea9_2Exists = true; - } - if (roomWidth.compareTo(MINIMUM_WIDTH_2_4) >= 0) { - roomWithMinWidth2_4Exists = true; - } - - // Perform the validation and generate the report - if (roomArea.compareTo(minimumArea) >= 0 && roomWidth.compareTo(minWidth) >= 0) { - setReportOutputDetails(pl, subRule, subRuleDesc, floor.getNumber().toString(), "" + room.getRoomNumber(), - "Area >= " + minimumArea + " , Width>= " + minWidth + "", - "Area = " + roomArea + ", Width = " + roomWidth, - Result.Accepted.getResultVal(), scrutinyDetail); - } else { - setReportOutputDetails(pl, subRule, subRuleDesc, floor.getNumber().toString(), "" + room.getRoomNumber(), - "Area >= " + minimumArea + " , Width>= " + minWidth + "", - "Area = " + roomArea + ", Width = " + roomWidth, - Result.Not_Accepted.getResultVal(), scrutinyDetail); - } - } - - if (!residentialRoomHeights.isEmpty()) { - BigDecimal minHeight = residentialRoomHeights.stream().reduce(BigDecimal::min).get(); - if (A.equalsIgnoreCase(mostRestrictiveOccupancy.getType().getCode())) { - minimumHeight = MINIMUM_HEIGHT_2_75; - Log.info("Minimum Residential Regular Room Height required is set to-------- : " + MINIMUM_HEIGHT_2_75); - } else { - minimumHeight = MINIMUM_HEIGHT_3; - } - - subRule = RULE; - subRuleDesc = RULE_REGULAR_DESC; - - boolean valid = false; - boolean isTypicalRepititiveFloor = false; - Map typicalFloorValues = ProcessHelper.getTypicalFloorValues(block, floor, isTypicalRepititiveFloor); - buildResult(pl, floor, minimumHeight, subRule, subRuleDesc, minHeight, valid, typicalFloorValues); - } else { - String layerName = String.format(LAYER_ROOM_HEIGHT, block.getNumber(), floor.getNumber(), "REGULAR_ROOM"); - errors.put(layerName, ROOM_HEIGHT_NOTDEFINED + layerName); - pl.addErrors(errors); - } - } + List residentialRoomHeights = new ArrayList<>(); + + List heights = new ArrayList<>(); + List rooms = new ArrayList<>(); + + for (Room room : floor.getRegularRooms()) { + + if (room.getHeights() != null) + heights.addAll(room.getHeights()); + if (room.getRooms() != null) + rooms.addAll(room.getRooms()); + + for (Measurement measurement : room.getRooms()) { + measurement.setRoomNumber(room.getNumber()); + } + } + for (RoomHeight roomHeight : heights) { + if (heightOfRoomFeaturesColor.get(color) == roomHeight.getColorCode()) { + residentialRoomHeights.add(roomHeight.getHeight()); + } + } + BigDecimal roomArea = BigDecimal.ZERO; + BigDecimal roomWidth = BigDecimal.ZERO; + + for (Measurement room : rooms) { + + + + + +// if (heightOfRoomFeaturesColor.get(color) == room.getColorCode()) { +// roomAreas.add(room.getArea()); +// roomWidths.add(room.getWidth()); +// +// } + minimumArea = MINIMUM_AREA_9_2; + minWidth = MINIMUM_WIDTH_2_7; + maxArea = MAXIMUM_AREA_46_45; + + roomArea = room.getArea().setScale(2, BigDecimal.ROUND_HALF_UP); + roomWidth = room.getWidth().setScale(2, BigDecimal.ROUND_HALF_UP); + + + if (roomArea.compareTo(minimumArea) >= 0 && roomWidth.compareTo(minWidth) >= 0) { + setReportOutputDetails(pl, subRule, subRuleDesc, floor.getNumber().toString(), "" + room.getRoomNumber() , + "Area >= " + minimumArea + " , Width>= " + minWidth + "", + "Area = " + roomArea + ", Width = " + roomWidth, + Result.Accepted.getResultVal(), scrutinyDetail); +// setReportOutputDetails(pl, subRule, subRuleDesc, floor.getNumber().toString(), +// minimumArea + DcrConstants.IN_METER, roomArea + DcrConstants.IN_METER, +// Result.Accepted.getResultVal(), scrutinyDetail1); + } else { + setReportOutputDetails(pl, subRule, subRuleDesc, floor.getNumber().toString(), "" + room.getRoomNumber(), + "Area >= " + minimumArea + " , Width>= " + minWidth + "", + "Area = " + roomArea + ", Width = " + roomWidth, + Result.Not_Accepted.getResultVal(), scrutinyDetail); +// setReportOutputDetails(pl, subRule, subRuleDesc, floor.getNumber().toString(), +// minimumArea + DcrConstants.IN_METER, roomArea + DcrConstants.IN_METER, +// Result.Not_Accepted.getResultVal(), scrutinyDetail1); + } + } + + if (!residentialRoomHeights.isEmpty()) { + BigDecimal minHeight = residentialRoomHeights.stream().reduce(BigDecimal::min) + .get(); + // Added by Bimal to check minimum height for residential rooms only + if (A.equalsIgnoreCase(mostRestrictiveOccupancy.getType().getCode())) { + minimumHeight = MINIMUM_HEIGHT_2_75; + + Log.info("Minimum Residential Regular Room Height required is set to-------- : " + + MINIMUM_HEIGHT_2_75); + } + + else + minimumHeight = MINIMUM_HEIGHT_3; + + subRule = RULE; + subRuleDesc = RULE_REGULAR_DESC; + + boolean valid = false; + boolean isTypicalRepititiveFloor = false; + Map typicalFloorValues = ProcessHelper.getTypicalFloorValues(block, + floor, isTypicalRepititiveFloor); + buildResult(pl, floor, minimumHeight, subRule, subRuleDesc, minHeight, valid, + typicalFloorValues); + } else { + String layerName = String.format(LAYER_ROOM_HEIGHT, block.getNumber(), + floor.getNumber(), "REGULAR_ROOM"); + errors.put(layerName, ROOM_HEIGHT_NOTDEFINED + layerName); + pl.addErrors(errors); + } + + } if (!roomAreas.isEmpty()) { totalArea = roomAreas.stream().reduce(BigDecimal.ZERO, BigDecimal::add); @@ -613,12 +624,12 @@ else if (roomAreas.size() > 1) { if (requiredVentilationArea.compareTo(BigDecimal.ZERO) != 0 && combinedArea.compareTo(BigDecimal.ZERO) != 0) { if (combinedArea.compareTo(requiredVentilationArea) >= 0) { - setReportOutputDetails(pl, RULE1, subRuleDesc1, floor.getNumber().toString(), "" + room.getNumber(), + setReportOutputDetails(pl, subRule, subRuleDesc1, floor.getNumber().toString(), "" + room.getNumber(), "Ventilation Required >= " + requiredVentilationArea, "Area provided = " + combinedArea, Result.Accepted.getResultVal(), scrutinyDetail4); } else { - setReportOutputDetails(pl, RULE1, subRuleDesc1, floor.getNumber().toString(), "" + room.getNumber(), + setReportOutputDetails(pl, subRule, subRuleDesc1, floor.getNumber().toString(), "" + room.getNumber(), "Ventilation Required >= " + requiredVentilationArea, "Area Provided = " + combinedArea, Result.Not_Accepted.getResultVal(), scrutinyDetail4); diff --git a/frontend/micro-ui/web/docker/Dockerfile b/frontend/micro-ui/web/docker/Dockerfile index 084181bf45e..42644eb0259 100644 --- a/frontend/micro-ui/web/docker/Dockerfile +++ b/frontend/micro-ui/web/docker/Dockerfile @@ -4,7 +4,7 @@ RUN apk add --no-cache git>2.30.0 RUN yarn add @upyog/digit-ui-libraries@1.7.0-beta.5 RUN yarn add @upyog/digit-ui-module-pt@1.7.0-beta.4 RUN yarn add @upyog/digit-ui-module-fsm@1.7.0-beta.18 -RUN yarn add @upyog/digit-ui-module-tl@1.7.0-beta.8 +RUN yarn add @upyog/digit-ui-module-tl@1.7.0-beta.9 RUN yarn add @upyog/digit-ui-module-dss@1.7.0-beta.4 RUN yarn add @upyog/digit-ui-module-mcollect@1.7.0-beta.4 RUN yarn add @upyog/digit-ui-module-pgr@1.7.0-beta.6 @@ -21,7 +21,7 @@ RUN yarn add @upyog-niua/upyog-ui-module-ptr@1.0.8 RUN yarn add @upyog/digit-ui-react-components@1.7.0-beta.4 ARG WORK_DIR WORKDIR /app -ENV NODE_OPTIONS "--max-old-space-size=4096" +ENV NODE_OPTIONS "--max-old-space-size=8192" ENV GENERATE_SOURCEMAP "false" COPY ${WORK_DIR} . @@ -30,7 +30,7 @@ RUN ls -lah #RUN node web/envs.js RUN cd web/ \ && node envs.js \ - && node -e 'console.log(v8.getHeapStatistics().heap_size_limit/(4096*4096))' \ + && node -e 'console.log(v8.getHeapStatistics().heap_size_limit/(8192*8192))' \ && ./install-deps.sh \ && yarn install \ && yarn build diff --git a/frontend/micro-ui/web/micro-ui-internals/example/devpackage.json b/frontend/micro-ui/web/micro-ui-internals/example/devpackage.json index 7491dd742ca..7c88dac13ba 100644 --- a/frontend/micro-ui/web/micro-ui-internals/example/devpackage.json +++ b/frontend/micro-ui/web/micro-ui-internals/example/devpackage.json @@ -20,7 +20,7 @@ "@upyog/digit-ui-module-pgr":"1.7.0-beta.6", "@upyog/digit-ui-module-pt":"1.7.0-beta.4", "@upyog/digit-ui-module-receipts":"1.7.0-beta.3", - "@upyog/digit-ui-module-tl":"1.7.0-beta.8", + "@upyog/digit-ui-module-tl":"1.7.0-beta.9", "@upyog/digit-ui-module-ws":"1.7.0-beta.12", "@upyog-niua/upyog-ui-module-ptr":"1.0.8", "@upyog/digit-ui-module-commonpt":"1.7.0-beta.4", diff --git a/frontend/micro-ui/web/micro-ui-internals/example/package.json b/frontend/micro-ui/web/micro-ui-internals/example/package.json index 2cee6c50781..b2a90f84e78 100644 --- a/frontend/micro-ui/web/micro-ui-internals/example/package.json +++ b/frontend/micro-ui/web/micro-ui-internals/example/package.json @@ -20,7 +20,7 @@ "@upyog/digit-ui-module-pgr": "1.7.0-beta.6", "@upyog/digit-ui-module-pt": "1.7.0-beta.4", "@upyog/digit-ui-module-receipts": "1.7.0-beta.3", - "@upyog/digit-ui-module-tl": "1.7.0-beta.8", + "@upyog/digit-ui-module-tl": "1.7.0-beta.9", "@upyog/digit-ui-module-ws": "1.7.0-beta.12", "@upyog/digit-ui-module-bills": "^1.7.0-beta.3", "@upyog/digit-ui-module-commonpt": "1.7.0-beta.4", diff --git a/frontend/micro-ui/web/micro-ui-internals/package.json b/frontend/micro-ui/web/micro-ui-internals/package.json index 6c245dfddf9..01e68e5e973 100644 --- a/frontend/micro-ui/web/micro-ui-internals/package.json +++ b/frontend/micro-ui/web/micro-ui-internals/package.json @@ -93,4 +93,4 @@ "**/@babel/preset-env": "7.14.0", "**/@babel/plugin-transform-modules-commonjs": "7.14.0" } -} \ No newline at end of file +} diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/obps/src/pageComponents/OwnerDetails.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/obps/src/pageComponents/OwnerDetails.js index c240fade84d..7abdba96b04 100644 --- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/obps/src/pageComponents/OwnerDetails.js +++ b/frontend/micro-ui/web/micro-ui-internals/packages/modules/obps/src/pageComponents/OwnerDetails.js @@ -425,45 +425,45 @@ const OwnerDetails = ({ t, config, onSelect, userType, formData }) => { } payload.additionalDetails.isSelfCertificationRequired = isSelfCertificationRequired.toString(); // create BPA call - if(isSelfCertificationRequired===true && formData?.data.occupancyType==="Residential" && (parsedArchitectName=="ARCHITECT" || parsedArchitectName=="ENGINEER"|| parsedArchitectName=="DESIGNER" || parsedArchitectName=="SUPERVISOR")){ - if(formData?.data.edcrDetails.planDetail.blocks[0].building.buildingHeight > 15){ - alert("Height should not be more than 15 metres"); - } - //converting plot area which is in square meters to square yards by multiplying 1.196 - else if((parsedArchitectName=="ARCHITECT" || parsedArchitectName=="ENGINEER") && (formData?.data.edcrDetails.planDetail.planInformation.plotArea*1.19599) >500){ - alert("Architect/Engineer can apply for area less then 500 sq. yards. in self declaration") - } - else if((parsedArchitectName=="DESIGNER" || parsedArchitectName=="SUPERVISOR") && (formData?.data.edcrDetails.planDetail.planInformation.plotArea*1.19599)>250){ - alert("Designer/Supervisor can apply for area less then 500 sq. yards. in self declaration") - } - else{ - Digit.OBPSService.create({ BPA: payload }, tenantId) - .then((result, err) => { - if (result?.BPA?.length > 0) { - result?.BPA?.[0]?.landInfo?.owners?.forEach(owner => { - owner.gender = { code: owner.gender, active: true, i18nKey: `COMMON_GENDER_${owner.gender}` } - }); - result.BPA[0].owners = { ...owner, owners: result?.BPA?.[0]?.landInfo?.owners, ownershipCategory: ownershipCategory }; - result.BPA[0].address = result?.BPA?.[0]?.landInfo?.address; - result.BPA[0].address.city = formData.address.city; - result.BPA[0].address.locality = formData.address.locality; - result.BPA[0].placeName = formData?.address?.placeName; - result.BPA[0].data = formData.data; - result.BPA[0].BlockIds = getBlockIds(result.BPA[0].landInfo.unit); - result.BPA[0].subOccupancy= formData?.subOccupancy; - result.BPA[0].uiFlow = formData?.uiFlow; - setIsDisable(false); - onSelect("", result.BPA[0], "", true); - } - }) - .catch((e) => { - setIsDisable(false); - setShowToast({ key: "true", error: true, message: e?.response?.data?.Errors[0]?.message }); - }); - } + // if(isSelfCertificationRequired===true && formData?.data.occupancyType==="Residential" && (parsedArchitectName=="ARCHITECT" || parsedArchitectName=="ENGINEER"|| parsedArchitectName=="DESIGNER" || parsedArchitectName=="SUPERVISOR")){ + // if(formData?.data.edcrDetails.planDetail.blocks[0].building.buildingHeight > 15){ + // alert("Height should not be more than 15 metres"); + // } + // //converting plot area which is in square meters to square yards by multiplying 1.196 + // else if((parsedArchitectName=="ARCHITECT" || parsedArchitectName=="ENGINEER") && (formData?.data.edcrDetails.planDetail.planInformation.plotArea*1.19599) >500){ + // alert("Architect/Engineer can apply for area less then 500 sq. yards. in self declaration") + // } + // else if((parsedArchitectName=="DESIGNER" || parsedArchitectName=="SUPERVISOR") && (formData?.data.edcrDetails.planDetail.planInformation.plotArea*1.19599)>250){ + // alert("Designer/Supervisor can apply for area less then 500 sq. yards. in self declaration") + // } + // else{ + // Digit.OBPSService.create({ BPA: payload }, tenantId) + // .then((result, err) => { + // if (result?.BPA?.length > 0) { + // result?.BPA?.[0]?.landInfo?.owners?.forEach(owner => { + // owner.gender = { code: owner.gender, active: true, i18nKey: `COMMON_GENDER_${owner.gender}` } + // }); + // result.BPA[0].owners = { ...owner, owners: result?.BPA?.[0]?.landInfo?.owners, ownershipCategory: ownershipCategory }; + // result.BPA[0].address = result?.BPA?.[0]?.landInfo?.address; + // result.BPA[0].address.city = formData.address.city; + // result.BPA[0].address.locality = formData.address.locality; + // result.BPA[0].placeName = formData?.address?.placeName; + // result.BPA[0].data = formData.data; + // result.BPA[0].BlockIds = getBlockIds(result.BPA[0].landInfo.unit); + // result.BPA[0].subOccupancy= formData?.subOccupancy; + // result.BPA[0].uiFlow = formData?.uiFlow; + // setIsDisable(false); + // onSelect("", result.BPA[0], "", true); + // } + // }) + // .catch((e) => { + // setIsDisable(false); + // setShowToast({ key: "true", error: true, message: e?.response?.data?.Errors[0]?.message }); + // }); + // } - } - else{ + // } + // else{ Digit.OBPSService.create({ BPA: payload }, tenantId) .then((result, err) => { if (result?.BPA?.length > 0) { @@ -487,7 +487,7 @@ const OwnerDetails = ({ t, config, onSelect, userType, formData }) => { setIsDisable(false); setShowToast({ key: "true", error: true, message: e?.response?.data?.Errors[0]?.message }); }); - } + // } } else { onSelect(config.key, ownerStep); } diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/tl/package.json b/frontend/micro-ui/web/micro-ui-internals/packages/modules/tl/package.json index 6debeda134c..4df60477e3c 100644 --- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/tl/package.json +++ b/frontend/micro-ui/web/micro-ui-internals/packages/modules/tl/package.json @@ -1,6 +1,6 @@ { "name": "@upyog/digit-ui-module-tl", - "version": "1.7.0-beta.8", + "version": "1.7.0-beta.9", "license": "MIT", "main": "dist/index.js", "module": "dist/index.modern.js", diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/tl/src/Module.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/tl/src/Module.js index e63255d445b..5c2e6a33d94 100644 --- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/tl/src/Module.js +++ b/frontend/micro-ui/web/micro-ui-internals/packages/modules/tl/src/Module.js @@ -55,7 +55,7 @@ import RenewTrade from "./pages/citizen/Renewal/renewTrade"; import SearchTradeComponent from "./pages/citizen/SearchTrade"; import SelectTradeUnitsInitial from "./pageComponents/SelectTradeUnitsInitial"; import TLTradeUnitsEmployeeInitial from "./pageComponents/TLTradeUnitsEmployeeInitial"; - +import CommonRedirect from "./pageComponents/CommonRedirect" import CitizenApp from "./pages/citizen"; import EmployeeApp from "./pages/employee"; @@ -153,6 +153,7 @@ const componentsToRegister = { SelectOtherTradeDetails, SelectTradeUnitsInitial, TLTradeUnitsEmployeeInitial, + CommonRedirect }; export const initTLComponents = () => { diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/tl/src/pageComponents/CommonRedirect.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/tl/src/pageComponents/CommonRedirect.js index 6a6d017f442..a0ad8d6c071 100644 --- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/tl/src/pageComponents/CommonRedirect.js +++ b/frontend/micro-ui/web/micro-ui-internals/packages/modules/tl/src/pageComponents/CommonRedirect.js @@ -1,14 +1,33 @@ -import React, { useState } from "react"; -import { FormStep, RadioOrSelect, RadioButtons } from "@upyog/digit-ui-react-components"; - -const CommonRedirect = ({ }) => { - - return ( - -
- Hello World -
-
- ); +import React, { useEffect, useState } from "react"; + +const CommonRedirect = () => { + const [receipt, setReceipt] = useState(""); + const tenantId = Digit.ULBService.getCurrentTenantId(); + + useEffect(() => { + const fetchReceipt = async () => { + if (window.location.href.includes("filestore")) { + const filestoreId = window?.location?.href?.split("filestore=")[1]; + const receiptFile = await Digit.PaymentService.printReciept(tenantId, { fileStoreIds: filestoreId }); + setReceipt(receiptFile); + } + }; + + fetchReceipt(); + }, []); + + useEffect(() => { + const openReceipt = () => { + const filestoreId = window?.location?.href.split("filestore=")[1]; + if (receipt?.[filestoreId]) { + window.open(receipt[filestoreId], "_blank"); + } + }; + + openReceipt(); + }, [receipt]); + + return E Signed PDF Downloaded; }; -export default SelectAccessories; \ No newline at end of file + +export default CommonRedirect; diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/tl/src/pages/employee/ApplicationDetails.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/tl/src/pages/employee/ApplicationDetails.js index dd7c4fc0b66..e7d2ef3e5e7 100644 --- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/tl/src/pages/employee/ApplicationDetails.js +++ b/frontend/micro-ui/web/micro-ui-internals/packages/modules/tl/src/pages/employee/ApplicationDetails.js @@ -256,7 +256,7 @@ const ApplicationDetails = () => { const TLcertificatefile = await Digit.PaymentService.generatePdf(tenantId, { Licenses: res?.Licenses }, "tlcertificate"); const receiptFile = await Digit.PaymentService.printReciept(tenantId, { fileStoreIds: TLcertificatefile.filestoreIds[0] }); fetchDigiLockerDocuments(receiptFile[TLcertificatefile.filestoreIds[0]]) - window.open(receiptFile[TLcertificatefile.filestoreIds[0]], "_blank"); + //window.open(receiptFile[TLcertificatefile.filestoreIds[0]], "_blank"); setIsDisplayDownloadMenu(false) } const [isDisplayDownloadMenu, setIsDisplayDownloadMenu] = useState(false); diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/tl/src/pages/employee/index.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/tl/src/pages/employee/index.js index 4eb670c52b5..acb146fbaf4 100644 --- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/tl/src/pages/employee/index.js +++ b/frontend/micro-ui/web/micro-ui-internals/packages/modules/tl/src/pages/employee/index.js @@ -156,7 +156,7 @@ const EmployeeApp = ({ path, url, userType }) => { const ReNewApplication = Digit?.ComponentRegistryService?.getComponent('TLReNewApplication'); const Response = Digit?.ComponentRegistryService?.getComponent('TLResponse'); const Search = Digit?.ComponentRegistryService?.getComponent('TLSearch'); - + const CommonRedirect = Digit?.ComponentRegistryService?.getComponent('CommonRedirect') return ( @@ -189,7 +189,7 @@ const EmployeeApp = ({ path, url, userType }) => { )} /> } /> - } /> + } /> } /> } /> } /> diff --git a/frontend/micro-ui/web/package.json b/frontend/micro-ui/web/package.json index 76409f61f32..3d05489de5c 100644 --- a/frontend/micro-ui/web/package.json +++ b/frontend/micro-ui/web/package.json @@ -73,4 +73,4 @@ "not dead", "not op_mini all" ] -} \ No newline at end of file +} diff --git a/frontend/micro-ui/web/src/App.js b/frontend/micro-ui/web/src/App.js index 0f65f1aa2e8..3e687bc5e1e 100644 --- a/frontend/micro-ui/web/src/App.js +++ b/frontend/micro-ui/web/src/App.js @@ -68,8 +68,7 @@ const enabledModules = [ "BillAmendment", "FireNoc", "Birth", - "Death", - "PTR" + "Death" ]; window.Digit.ComponentRegistryService.setupRegistry({ ...paymentConfigs, diff --git a/municipal-services/bpa-services/src/main/java/org/egov/bpa/validator/BPAValidator.java b/municipal-services/bpa-services/src/main/java/org/egov/bpa/validator/BPAValidator.java index b677c07a819..e513b59addb 100755 --- a/municipal-services/bpa-services/src/main/java/org/egov/bpa/validator/BPAValidator.java +++ b/municipal-services/bpa-services/src/main/java/org/egov/bpa/validator/BPAValidator.java @@ -640,10 +640,10 @@ public void validateApplication(BPARequest bpaRequest) if(height.intValue()>15) throw new CustomException(null,"Height should not be more than 15 metres"); -// if((obj.get("typeOfArchitect").toString().equalsIgnoreCase("ARCHITECT") || obj.get("typeOfArchitect").toString().equalsIgnoreCase("ENGINEER")) && area.intValue()>500) -// throw new CustomException(null,"Architect/Engineer can apply for area less then 500 sq. yards. in self declaration"); -// if((obj.get("typeOfArchitect").toString().equalsIgnoreCase("DESIGNER") || obj.get("typeOfArchitect").toString().equalsIgnoreCase("SUPERVISOR")) && area.intValue()>250) -// throw new CustomException(null,"Designer/Supervisor can apply for area less then 500 sq. yards. in self declaration"); + if((obj.get("typeOfArchitect").toString().equalsIgnoreCase("ARCHITECT") || obj.get("typeOfArchitect").toString().equalsIgnoreCase("ENGINEER")) && area.intValue()>500) + throw new CustomException(null,"Architect/Engineer can apply for area less then 500 sq. yards. in self declaration"); + if((obj.get("typeOfArchitect").toString().equalsIgnoreCase("DESIGNER") || obj.get("typeOfArchitect").toString().equalsIgnoreCase("SUPERVISOR")) && area.intValue()>250) + throw new CustomException(null,"Designer/Supervisor can apply for area less then 500 sq. yards. in self declaration"); } if (obj.get("riskType")!= null ) diff --git a/municipal-services/tl-services/src/main/java/org/egov/tl/repository/builder/TLQueryBuilder.java b/municipal-services/tl-services/src/main/java/org/egov/tl/repository/builder/TLQueryBuilder.java index 3e069f10619..4937e830f60 100644 --- a/municipal-services/tl-services/src/main/java/org/egov/tl/repository/builder/TLQueryBuilder.java +++ b/municipal-services/tl-services/src/main/java/org/egov/tl/repository/builder/TLQueryBuilder.java @@ -1,433 +1,427 @@ -package org.egov.tl.repository.builder; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import lombok.extern.slf4j.Slf4j; -import org.egov.tl.config.TLConfiguration; -import org.egov.tl.util.TLConstants; -import org.egov.tl.web.models.*; -import org.egov.tracer.model.CustomException; -import org.postgresql.util.PGobject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.dao.DataAccessException; -import org.springframework.stereotype.Component; -import org.springframework.util.CollectionUtils; - -import java.io.IOException; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.*; - -@Slf4j -@Component -public class TLQueryBuilder { - - private TLConfiguration config; - - @Autowired - public TLQueryBuilder(TLConfiguration config) { - this.config = config; - } - - private static final String INNER_JOIN_STRING = " INNER JOIN "; - private static final String LEFT_OUTER_JOIN_STRING = " LEFT OUTER JOIN "; - - @Value("${egov.receipt.businessserviceTL}") - private String businessServiceTL; - - - @Value("${egov.receipt.businessserviceBPA}") - private String businessServiceBPA; - - @Value("${renewal.pending.interval}") - private long renewalPeriod; - - private static final String QUERY = "SELECT tl.*,tld.*,tlunit.*,tlacc.*,tlowner.*," + - "tladdress.*,tlapldoc.*,tlverdoc.*,tlownerdoc.*,tlinsti.*,tl.id as tl_id,tl.tenantid as tl_tenantId,tl.lastModifiedTime as " + - "tl_lastModifiedTime,tl.createdBy as tl_createdBy,tl.lastModifiedBy as tl_lastModifiedBy,tl.createdTime as " + - "tl_createdTime,tl.filestoreid as tl_fileStoreId,tld.id as tld_id,tladdress.id as tl_ad_id,tld.createdBy as tld_createdBy," + - "tlowner.id as tlowner_uuid,tlowner.active as useractive,tlowner.additionalDetails as oadditionaldetails, " + - "tld.createdTime as tld_createdTime,tld.lastModifiedBy as tld_lastModifiedBy,tld.createdTime as " + - "tld_createdTime,tlunit.id as tl_un_id,tlunit.tradeType as tl_un_tradeType,tlunit.uom as tl_un_uom,tlunit.active as tl_un_active," + - "tlunit.uomvalue as tl_un_uomvalue,tlacc.id as tl_acc_id,tlacc.uom as tl_acc_uom,tlacc.uomvalue as tl_acc_uomvalue,tlacc.active as tl_acc_active," + - "tlapldoc.id as tl_ap_doc_id,tlapldoc.documenttype as tl_ap_doc_documenttype,tlapldoc.filestoreid as tl_ap_doc_filestoreid,tlapldoc.active as tl_ap_doc_active," + - "tlverdoc.id as tl_ver_doc_id,tlverdoc.documenttype as tl_ver_doc_documenttype,tlverdoc.filestoreid as tl_ver_doc_filestoreid,tlverdoc.active as tl_ver_doc_active," + - "tlownerdoc.userid as docuserid,tlownerdoc.tradeLicenseDetailId as doctradelicensedetailid,tlownerdoc.id as ownerdocid,"+ - "tlownerdoc.documenttype as ownerdocType,tlownerdoc.filestoreid as ownerfileStoreId,tlownerdoc.documentuid as ownerdocuid,tlownerdoc.active as ownerdocactive," + - " tlinsti.id as instiid,tlinsti.name as authorisedpersonname,tlinsti.type as institutiontype,tlinsti.tenantid as institenantId,tlinsti.active as instiactive, "+ - " tlinsti.instituionname as instiinstituionname, tlinsti.contactno as insticontactno, tlinsti.organisationregistrationno as instiorganisationregistrationno, tlinsti.address as instiaddress FROM eg_tl_tradelicense tl" - +INNER_JOIN_STRING - +"eg_tl_tradelicensedetail tld ON tld.tradelicenseid = tl.id" - +INNER_JOIN_STRING - +"eg_tl_address tladdress ON tladdress.tradelicensedetailid = tld.id" - +INNER_JOIN_STRING - +"eg_tl_owner tlowner ON tlowner.tradelicensedetailid = tld.id" - +INNER_JOIN_STRING - +"eg_tl_tradeunit tlunit ON tlunit.tradelicensedetailid = tld.id" - +LEFT_OUTER_JOIN_STRING - +"eg_tl_accessory tlacc ON tlacc.tradelicensedetailid = tld.id" - +LEFT_OUTER_JOIN_STRING - +"eg_tl_document_owner tlownerdoc ON tlownerdoc.userid = tlowner.id" - +LEFT_OUTER_JOIN_STRING - +"eg_tl_applicationdocument tlapldoc ON tlapldoc.tradelicensedetailid = tld.id" - +LEFT_OUTER_JOIN_STRING - +"eg_tl_verificationdocument tlverdoc ON tlverdoc.tradelicensedetailid = tld.id" - +LEFT_OUTER_JOIN_STRING - +"eg_tl_institution tlinsti ON tlinsti.tradelicensedetailid = tld.id "; - - - private final String paginationWrapper = "SELECT * FROM " + - "(SELECT *, DENSE_RANK() OVER (ORDER BY tl_lastModifiedTime DESC , tl_id) offset_ FROM " + - "({})" + - " result) result_offset " + - "WHERE offset_ > ? AND offset_ <= ?"; - - private final String countWrapper = "SELECT COUNT(DISTINCT(tl_id)) FROM ({INTERNAL_QUERY}) as license_count"; - - public static final String TENANTIDQUERY="select distinct(tenantid) from eg_tl_tradelicense"; - - - - - - public String getTLSearchQuery(TradeLicenseSearchCriteria criteria, List preparedStmtList, boolean isCount) { - - StringBuilder builder = new StringBuilder(QUERY); - - addBusinessServiceClause(criteria,preparedStmtList,builder); - - - if(criteria.getAccountId()!=null){ - addClauseIfRequired(preparedStmtList,builder); - builder.append(" tl.accountid = ? "); - preparedStmtList.add(criteria.getAccountId()); - - List ownerIds = criteria.getOwnerIds(); - if(!CollectionUtils.isEmpty(ownerIds)) { - builder.append(" OR (tlowner.id IN (").append(createQuery(ownerIds)).append(")"); - addToPreparedStatement(preparedStmtList,ownerIds); - addBusinessServiceClause(criteria,preparedStmtList,builder); - builder.append(" AND tlowner.active = ? )"); - preparedStmtList.add(true); - } - } - - else { - - if (criteria.getTenantId() != null) { - addClauseIfRequired(preparedStmtList, builder); - builder.append(" tl.tenantid=? "); - preparedStmtList.add(criteria.getTenantId()); - } - List ids = criteria.getIds(); - if (!CollectionUtils.isEmpty(ids)) { - addClauseIfRequired(preparedStmtList, builder); - builder.append(" tl.id IN (").append(createQuery(ids)).append(")"); - addToPreparedStatement(preparedStmtList, ids); - } - - List ownerIds = criteria.getOwnerIds(); - if (!CollectionUtils.isEmpty(ownerIds)) { - addClauseIfRequired(preparedStmtList, builder); - builder.append(" (tlowner.id IN (").append(createQuery(ownerIds)).append(")"); - addToPreparedStatement(preparedStmtList, ownerIds); - addClauseIfRequired(preparedStmtList, builder); - builder.append(" tlowner.active = ? ) "); - preparedStmtList.add(true); - } - - if (criteria.getApplicationNumber() != null) { - List applicationNumber = Arrays.asList(criteria.getApplicationNumber().split(",")); - addClauseIfRequired(preparedStmtList, builder); - builder.append(" LOWER(tl.applicationnumber) IN (").append(createQuery(applicationNumber)).append(")"); - addToPreparedStatement(preparedStmtList, applicationNumber); - } - - List status = criteria.getStatus(); - if (!CollectionUtils.isEmpty(status)) { - addClauseIfRequired(preparedStmtList, builder); - builder.append(" LOWER(tl.status) IN (").append(createQuery(status)).append(")"); - addToPreparedStatement(preparedStmtList, status); - } - - if (criteria.getApplicationType() != null) { - addClauseIfRequired(preparedStmtList, builder); - builder.append(" tl.applicationtype = ? "); - preparedStmtList.add(criteria.getApplicationType()); - } - - List licenseNumbers = criteria.getLicenseNumbers(); - if (!CollectionUtils.isEmpty(licenseNumbers)) { - addClauseIfRequired(preparedStmtList, builder); - builder.append(" LOWER(tl.licensenumber) IN (").append(createQuery(licenseNumbers)).append(")"); - addToPreparedStatement(preparedStmtList, licenseNumbers); - } - -// if (criteria.getLicenseNumber() != null) { -// addClauseIfRequired(preparedStmtList, builder); -// builder.append(" tl.licensenumber = ? "); -// preparedStmtList.add(criteria.getLicenseNumber()); -// } - - if (criteria.getOldLicenseNumber() != null) { - addClauseIfRequired(preparedStmtList, builder); - builder.append(" tl.oldlicensenumber = ? "); - preparedStmtList.add(criteria.getOldLicenseNumber()); - } - - if (criteria.getFromDate() != null) { - addClauseIfRequired(preparedStmtList, builder); - builder.append(" tl.applicationDate >= ? "); - preparedStmtList.add(criteria.getFromDate()); - } - - if (criteria.getToDate() != null) { - addClauseIfRequired(preparedStmtList, builder); - builder.append(" tl.applicationDate <= ? "); - preparedStmtList.add(criteria.getToDate()); - } - - - if (criteria.getValidTo() != null) { - addClauseIfRequired(preparedStmtList, builder); - builder.append(" tl.validTo <= ? "); - preparedStmtList.add(criteria.getValidTo()); - } - - - if(criteria.getRenewalPending()!=null && criteria.getRenewalPending()) { - - addRenewalCriteria(builder,preparedStmtList,criteria); - - } - - if(criteria.getLocality() != null) { - addClauseIfRequired(preparedStmtList, builder); - builder.append(" tladdress.locality = ? "); - preparedStmtList.add(criteria.getLocality()); - } - - if(criteria.getTradeName() != null) { - addClauseIfRequired(preparedStmtList, builder); - builder.append(" LOWER(tl.tradename) = LOWER(?) "); - preparedStmtList.add(criteria.getTradeName()); - } - - if (criteria.getOwnerName() != null) { - addClauseIfRequired(preparedStmtList, builder); - builder.append(" LOWER (tlowner.additionaldetails ->> 'ownerName') LIKE ? "); - preparedStmtList.add('%' +criteria.getOwnerName().toLowerCase()+ '%'); - } - - if (criteria.getIssuedFrom() != null) { - addClauseIfRequired(preparedStmtList, builder); - builder.append(" tl.issueddate >= ? "); - preparedStmtList.add(criteria.getIssuedFrom()); - } - - if (criteria.getIssuedTo() != null) { - addClauseIfRequired(preparedStmtList, builder); - builder.append(" tl.issueddate <= ? "); - preparedStmtList.add(criteria.getIssuedTo()); - } - - if (criteria.getTradeType() != null) { - addClauseIfRequired(preparedStmtList, builder); - builder.append(" tlunit.tradetype LIKE ? "); - preparedStmtList.add(criteria.getTradeType().split("\\.")[0]+"%"); - } - - } - - // enrichCriteriaForUpdateSearch(builder,preparedStmtList,criteria); - - if(!isCount) { - return addPaginationWrapper(builder.toString(),preparedStmtList,criteria); - } - - else { - return addCountWrapper(builder.toString()); - } - } - - - private void addRenewalCriteria(StringBuilder builder, List preparedStmtList, TradeLicenseSearchCriteria criteria) { - - addClauseIfRequired(preparedStmtList, builder); - builder.append(" (( tl.validTo <= ? "); - preparedStmtList.add(System.currentTimeMillis()+renewalPeriod); - - addClauseIfRequired(preparedStmtList, builder); - builder.append(" (( (tl.status IN (?,?)) "); - preparedStmtList.add(TLConstants.STATUS_APPROVED); - preparedStmtList.add(TLConstants.STATUS_EXPIRED); - - addClauseIfRequired(preparedStmtList, builder); - - /* SELECT NewTL applications which do not have any renewal applications yet */ - builder.append(" (tl.licensenumber NOT IN (SELECT licensenumber from eg_tl_tradelicense WHERE UPPER(applicationtype) = ? AND licensenumber IS NOT NULL) OR ("); - - /*SELECT applications which have application type as renewal, and having the latest financial year among all the renewal application - * for that particular license number*/ - builder.append(" tl.applicationtype = ? and ? > tl.financialyear AND tl.financialyear = (select max(financialyear) from eg_tl_tradelicense where licensenumber=tl.licensenumber) )))"); - - /* SELECT applications which are manually expired after their real expiry date, and which is having the latest financial year from among all the applications for that particular license number*/ - builder.append(" OR ( tl.status = ? AND tl.financialyear = (select max(financialyear) from eg_tl_tradelicense where licensenumber=tl.licensenumber) ))) "); - - /* SELECT those applications for which there exist a rejected application for the current financial year, and financial year of this application should be just before that of the rejected application*/ - builder.append("OR ( tl.financialyear= (select max(financialyear) from eg_tl_tradelicense where licensenumber=tl.licensenumber and licensenumber in ( select licensenumber from eg_tl_tradelicense where status=? and financialyear=? ) and status<>? ) "); - - /*set status (approved) and validTo(before current timestamp) conditions*/ - builder.append(" AND (tl.status IN (?,?) ) AND tl.validTo <= ? ) ) "); - - preparedStmtList.add(TLConstants.APPLICATION_TYPE_RENEWAL); - preparedStmtList.add(TLConstants.APPLICATION_TYPE_RENEWAL); - preparedStmtList.add(Integer.toString(Calendar.getInstance().get(Calendar.YEAR))); - preparedStmtList.add(TLConstants.STATUS_MANUALLYEXPIRED); - preparedStmtList.add(TLConstants.STATUS_REJECTED); - preparedStmtList.add(criteria.getFinancialYear()); - preparedStmtList.add(TLConstants.STATUS_REJECTED); - preparedStmtList.add(TLConstants.STATUS_APPROVED); - preparedStmtList.add(TLConstants.STATUS_EXPIRED); - preparedStmtList.add(System.currentTimeMillis()+renewalPeriod); - - } - - private String addCountWrapper(String query) { - - String finalQuery = countWrapper.replace("{INTERNAL_QUERY}",query ); - return finalQuery; - } - - - private void addBusinessServiceClause(TradeLicenseSearchCriteria criteria,List preparedStmtList,StringBuilder builder){ - if ((criteria.getBusinessService() == null) || (businessServiceTL.equals(criteria.getBusinessService()))) { - addClauseIfRequired(preparedStmtList, builder); - builder.append(" (tl.businessservice=? or tl.businessservice isnull) "); - preparedStmtList.add(businessServiceTL); - } else if (businessServiceBPA.equals(criteria.getBusinessService())) { - addClauseIfRequired(preparedStmtList, builder); - builder.append(" tl.businessservice=? "); - preparedStmtList.add(businessServiceBPA); - } - } - - private String createQuery(List ids) { - StringBuilder builder = new StringBuilder(); - int length = ids.size(); - for( int i = 0; i< length; i++){ - builder.append(" LOWER(?)"); - if(i != length -1) builder.append(","); - } - return builder.toString(); - } - - private void addToPreparedStatement(List preparedStmtList,List ids) - { - ids.forEach(id ->{ preparedStmtList.add(id);}); - } - - - private String addPaginationWrapper(String query,List preparedStmtList, - TradeLicenseSearchCriteria criteria){ - int limit = config.getDefaultLimit(); - int offset = config.getDefaultOffset(); - String finalQuery = paginationWrapper.replace("{}",query); - - if(criteria.getLimit()!=null && criteria.getLimit()<=config.getMaxSearchLimit()) - limit = criteria.getLimit(); - - if(criteria.getLimit()!=null && criteria.getLimit()>config.getMaxSearchLimit()) - limit = config.getMaxSearchLimit(); - - if(criteria.getOffset()!=null) - offset = criteria.getOffset(); - - preparedStmtList.add(offset); - preparedStmtList.add(limit+offset); - - return finalQuery; - } - - - private static void addClauseIfRequired(List values, StringBuilder queryString) { - if (values.isEmpty()) - queryString.append(" WHERE "); - else { - queryString.append(" AND"); - } - } - - public String getTLPlainSearchQuery(TradeLicenseSearchCriteria criteria, List preparedStmtList) { - StringBuilder builder = new StringBuilder(QUERY); - - List ids = criteria.getIds(); - if (!CollectionUtils.isEmpty(ids)) { - addClauseIfRequired(preparedStmtList,builder); - builder.append(" tl.id IN (").append(createQuery(ids)).append(")"); - addToPreparedStatement(preparedStmtList, ids); - } - - return addPaginationWrapper(builder.toString(), preparedStmtList, criteria); - - } - - public String getApplicationsCountQuery(TradeLicenseSearchCriteria criteria, List preparedStmtList, String applicationType) { - - StringBuilder query = new StringBuilder(""); - - if(criteria.getAccountId()!=null) { - query.append("select count(*) from eg_tl_tradelicense where tenantid = (select tl.tenantid from eg_tl_tradelicense tl INNER JOIN eg_tl_tradelicensedetail tld ON tld.tradelicenseid = tl.id INNER JOIN eg_tl_owner tlowner on tlowner.tradelicensedetailid = tld.id where tl.accountid=? "); - preparedStmtList.add(criteria.getAccountId()); - - List ownerIds = criteria.getOwnerIds(); - - if(!CollectionUtils.isEmpty(ownerIds)) { - - query.append(" OR (tlowner.id IN (").append(createQuery(ownerIds)).append(")"); - addToPreparedStatement(preparedStmtList,ownerIds); - - query.append(" AND tlowner.active = ? )"); - preparedStmtList.add(true); - } - - query.append("and tl.businessservice= ? limit 1) and createdtime> ? AND applicationtype= ? "); - - preparedStmtList.add(TLConstants.TRADE_LICENSE_MODULE_CODE); - - - } - - else if(criteria.getTenantId()!=null) { - query.append("select count(*) from eg_tl_tradelicense where tenantid = ? and createdtime > ? AND applicationtype= ? "); - preparedStmtList.add(criteria.getTenantId()); - } - - // In order to get data of last 12 months, the months variables is pre-configured in application properties - int months = Integer.valueOf(config.getNumberOfMonths()) ; - - Calendar calendar = Calendar.getInstance(); - - // To subtract 12 months from current time, we are adding -12 to the calendar instance, as subtract function is not in-built - calendar.add(Calendar.MONTH, -1*months); - - // Converting the timestamp to milliseconds and adding it to prepared statement list - preparedStmtList.add(calendar.getTimeInMillis()); - - preparedStmtList.add(applicationType); - - addClauseIfRequired(preparedStmtList, query); - query.append(" businessservice = ? "); - preparedStmtList.add(TLConstants.TRADE_LICENSE_MODULE_CODE); - - - return query.toString(); - - - } - - - - -} \ No newline at end of file +package org.egov.tl.repository.builder; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; +import org.egov.tl.config.TLConfiguration; +import org.egov.tl.util.TLConstants; +import org.egov.tl.web.models.*; +import org.egov.tracer.model.CustomException; +import org.postgresql.util.PGobject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DataAccessException; +import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; + +import java.io.IOException; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.*; + +@Slf4j +@Component +public class TLQueryBuilder { + + private TLConfiguration config; + + @Autowired + public TLQueryBuilder(TLConfiguration config) { + this.config = config; + } + + private static final String INNER_JOIN_STRING = " INNER JOIN "; + private static final String LEFT_OUTER_JOIN_STRING = " LEFT OUTER JOIN "; + + @Value("${egov.receipt.businessserviceTL}") + private String businessServiceTL; + + + @Value("${egov.receipt.businessserviceBPA}") + private String businessServiceBPA; + + @Value("${renewal.pending.interval}") + private long renewalPeriod; + + private static final String QUERY = "SELECT tl.*,tld.*,tlunit.*,tlacc.*,tlowner.*," + + "tladdress.*,tlapldoc.*,tlverdoc.*,tlownerdoc.*,tlinsti.*,tl.id as tl_id,tl.tenantid as tl_tenantId,tl.lastModifiedTime as " + + "tl_lastModifiedTime,tl.createdBy as tl_createdBy,tl.lastModifiedBy as tl_lastModifiedBy,tl.createdTime as " + + "tl_createdTime,tl.filestoreid as tl_fileStoreId,tld.id as tld_id,tladdress.id as tl_ad_id,tld.createdBy as tld_createdBy," + + "tlowner.id as tlowner_uuid,tlowner.active as useractive,tlowner.additionalDetails as oadditionaldetails, " + + "tld.createdTime as tld_createdTime,tld.lastModifiedBy as tld_lastModifiedBy,tld.createdTime as " + + "tld_createdTime,tlunit.id as tl_un_id,tlunit.tradeType as tl_un_tradeType,tlunit.uom as tl_un_uom,tlunit.active as tl_un_active," + + "tlunit.uomvalue as tl_un_uomvalue,tlacc.id as tl_acc_id,tlacc.uom as tl_acc_uom,tlacc.uomvalue as tl_acc_uomvalue,tlacc.active as tl_acc_active," + + "tlapldoc.id as tl_ap_doc_id,tlapldoc.documenttype as tl_ap_doc_documenttype,tlapldoc.filestoreid as tl_ap_doc_filestoreid,tlapldoc.active as tl_ap_doc_active," + + "tlverdoc.id as tl_ver_doc_id,tlverdoc.documenttype as tl_ver_doc_documenttype,tlverdoc.filestoreid as tl_ver_doc_filestoreid,tlverdoc.active as tl_ver_doc_active," + + "tlownerdoc.userid as docuserid,tlownerdoc.tradeLicenseDetailId as doctradelicensedetailid,tlownerdoc.id as ownerdocid,"+ + "tlownerdoc.documenttype as ownerdocType,tlownerdoc.filestoreid as ownerfileStoreId,tlownerdoc.documentuid as ownerdocuid,tlownerdoc.active as ownerdocactive," + + " tlinsti.id as instiid,tlinsti.name as authorisedpersonname,tlinsti.type as institutiontype,tlinsti.tenantid as institenantId,tlinsti.active as instiactive, "+ + " tlinsti.instituionname as instiinstituionname, tlinsti.contactno as insticontactno, tlinsti.organisationregistrationno as instiorganisationregistrationno, tlinsti.address as instiaddress FROM eg_tl_tradelicense tl" + +INNER_JOIN_STRING + +"eg_tl_tradelicensedetail tld ON tld.tradelicenseid = tl.id" + +INNER_JOIN_STRING + +"eg_tl_address tladdress ON tladdress.tradelicensedetailid = tld.id" + +INNER_JOIN_STRING + +"eg_tl_owner tlowner ON tlowner.tradelicensedetailid = tld.id" + +INNER_JOIN_STRING + +"eg_tl_tradeunit tlunit ON tlunit.tradelicensedetailid = tld.id" + +LEFT_OUTER_JOIN_STRING + +"eg_tl_accessory tlacc ON tlacc.tradelicensedetailid = tld.id" + +LEFT_OUTER_JOIN_STRING + +"eg_tl_document_owner tlownerdoc ON tlownerdoc.userid = tlowner.id" + +LEFT_OUTER_JOIN_STRING + +"eg_tl_applicationdocument tlapldoc ON tlapldoc.tradelicensedetailid = tld.id" + +LEFT_OUTER_JOIN_STRING + +"eg_tl_verificationdocument tlverdoc ON tlverdoc.tradelicensedetailid = tld.id" + +LEFT_OUTER_JOIN_STRING + +"eg_tl_institution tlinsti ON tlinsti.tradelicensedetailid = tld.id "; + + + private final String paginationWrapper = "SELECT * FROM " + + "(SELECT *, DENSE_RANK() OVER (ORDER BY tl_lastModifiedTime DESC , tl_id) offset_ FROM " + + "({})" + + " result) result_offset " + + "WHERE offset_ > ? AND offset_ <= ?"; + + private final String countWrapper = "SELECT COUNT(DISTINCT(tl_id)) FROM ({INTERNAL_QUERY}) as license_count"; + + public static final String TENANTIDQUERY="select distinct(tenantid) from eg_tl_tradelicense"; + + + + + + public String getTLSearchQuery(TradeLicenseSearchCriteria criteria, List preparedStmtList, boolean isCount) { + + StringBuilder builder = new StringBuilder(QUERY); + + addBusinessServiceClause(criteria,preparedStmtList,builder); + + + if(criteria.getAccountId()!=null){ + addClauseIfRequired(preparedStmtList,builder); + builder.append(" tl.accountid = ? "); + preparedStmtList.add(criteria.getAccountId()); + + List ownerIds = criteria.getOwnerIds(); + if(!CollectionUtils.isEmpty(ownerIds)) { + builder.append(" OR (tlowner.id IN (").append(createQuery(ownerIds)).append(")"); + addToPreparedStatement(preparedStmtList,ownerIds); + addBusinessServiceClause(criteria,preparedStmtList,builder); + builder.append(" AND tlowner.active = ? )"); + preparedStmtList.add(true); + } + } + + else { + + if (criteria.getTenantId() != null) { + addClauseIfRequired(preparedStmtList, builder); + builder.append(" tl.tenantid=? "); + preparedStmtList.add(criteria.getTenantId()); + } + List ids = criteria.getIds(); + if (!CollectionUtils.isEmpty(ids)) { + addClauseIfRequired(preparedStmtList, builder); + builder.append(" tl.id IN (").append(createQuery(ids)).append(")"); + addToPreparedStatement(preparedStmtList, ids); + } + + List ownerIds = criteria.getOwnerIds(); + if (!CollectionUtils.isEmpty(ownerIds)) { + addClauseIfRequired(preparedStmtList, builder); + builder.append(" (tlowner.id IN (").append(createQuery(ownerIds)).append(")"); + addToPreparedStatement(preparedStmtList, ownerIds); + addClauseIfRequired(preparedStmtList, builder); + builder.append(" tlowner.active = ? ) "); + preparedStmtList.add(true); + } + + if (criteria.getApplicationNumber() != null) { + List applicationNumber = Arrays.asList(criteria.getApplicationNumber().split(",")); + addClauseIfRequired(preparedStmtList, builder); + builder.append(" LOWER(tl.applicationnumber) IN (").append(createQuery(applicationNumber)).append(")"); + addToPreparedStatement(preparedStmtList, applicationNumber); + } + + List status = criteria.getStatus(); + if (!CollectionUtils.isEmpty(status)) { + addClauseIfRequired(preparedStmtList, builder); + builder.append(" LOWER(tl.status) IN (").append(createQuery(status)).append(")"); + addToPreparedStatement(preparedStmtList, status); + } + + if (criteria.getApplicationType() != null) { + addClauseIfRequired(preparedStmtList, builder); + builder.append(" tl.applicationtype = ? "); + preparedStmtList.add(criteria.getApplicationType()); + } + + List licenseNumbers = criteria.getLicenseNumbers(); + if (!CollectionUtils.isEmpty(licenseNumbers)) { + addClauseIfRequired(preparedStmtList, builder); + builder.append(" LOWER(tl.licensenumber) IN (").append(createQuery(licenseNumbers)).append(")"); + addToPreparedStatement(preparedStmtList, licenseNumbers); + } + +// if (criteria.getLicenseNumber() != null) { +// addClauseIfRequired(preparedStmtList, builder); +// builder.append(" tl.licensenumber = ? "); +// preparedStmtList.add(criteria.getLicenseNumber()); +// } + + if (criteria.getOldLicenseNumber() != null) { + addClauseIfRequired(preparedStmtList, builder); + builder.append(" tl.oldlicensenumber = ? "); + preparedStmtList.add(criteria.getOldLicenseNumber()); + } + + if (criteria.getFromDate() != null) { + addClauseIfRequired(preparedStmtList, builder); + builder.append(" tl.applicationDate >= ? "); + preparedStmtList.add(criteria.getFromDate()); + } + + if (criteria.getToDate() != null) { + addClauseIfRequired(preparedStmtList, builder); + builder.append(" tl.applicationDate <= ? "); + preparedStmtList.add(criteria.getToDate()); + } + + + if (criteria.getValidTo() != null) { + addClauseIfRequired(preparedStmtList, builder); + builder.append(" tl.validTo <= ? "); + preparedStmtList.add(criteria.getValidTo()); + } + + + if(criteria.getRenewalPending()!=null && criteria.getRenewalPending()) { + + addRenewalCriteria(builder,preparedStmtList,criteria); + + } + + if(criteria.getLocality() != null) { + addClauseIfRequired(preparedStmtList, builder); + builder.append(" tladdress.locality = ? "); + preparedStmtList.add(criteria.getLocality()); + } + + if(criteria.getTradeName() != null) { + addClauseIfRequired(preparedStmtList, builder); + builder.append(" LOWER(tl.tradename) = LOWER(?) "); + preparedStmtList.add(criteria.getTradeName()); + } + + if (criteria.getIssuedFrom() != null) { + addClauseIfRequired(preparedStmtList, builder); + builder.append(" tl.issueddate >= ? "); + preparedStmtList.add(criteria.getIssuedFrom()); + } + + if (criteria.getIssuedTo() != null) { + addClauseIfRequired(preparedStmtList, builder); + builder.append(" tl.issueddate <= ? "); + preparedStmtList.add(criteria.getIssuedTo()); + } + + if (criteria.getTradeType() != null) { + addClauseIfRequired(preparedStmtList, builder); + builder.append(" tlunit.tradetype LIKE ? "); + preparedStmtList.add(criteria.getTradeType().split("\\.")[0]+"%"); + } + + } + + // enrichCriteriaForUpdateSearch(builder,preparedStmtList,criteria); + + if(!isCount) { + return addPaginationWrapper(builder.toString(),preparedStmtList,criteria); + } + + else { + return addCountWrapper(builder.toString()); + } + } + + + private void addRenewalCriteria(StringBuilder builder, List preparedStmtList, TradeLicenseSearchCriteria criteria) { + + addClauseIfRequired(preparedStmtList, builder); + builder.append(" (( tl.validTo <= ? "); + preparedStmtList.add(System.currentTimeMillis()+renewalPeriod); + + addClauseIfRequired(preparedStmtList, builder); + builder.append(" (( (tl.status IN (?,?)) "); + preparedStmtList.add(TLConstants.STATUS_APPROVED); + preparedStmtList.add(TLConstants.STATUS_EXPIRED); + + addClauseIfRequired(preparedStmtList, builder); + + /* SELECT NewTL applications which do not have any renewal applications yet */ + builder.append(" (tl.licensenumber NOT IN (SELECT licensenumber from eg_tl_tradelicense WHERE UPPER(applicationtype) = ? AND licensenumber IS NOT NULL) OR ("); + + /*SELECT applications which have application type as renewal, and having the latest financial year among all the renewal application + * for that particular license number*/ + builder.append(" tl.applicationtype = ? and ? > tl.financialyear AND tl.financialyear = (select max(financialyear) from eg_tl_tradelicense where licensenumber=tl.licensenumber) )))"); + + /* SELECT applications which are manually expired after their real expiry date, and which is having the latest financial year from among all the applications for that particular license number*/ + builder.append(" OR ( tl.status = ? AND tl.financialyear = (select max(financialyear) from eg_tl_tradelicense where licensenumber=tl.licensenumber) ))) "); + + /* SELECT those applications for which there exist a rejected application for the current financial year, and financial year of this application should be just before that of the rejected application*/ + builder.append("OR ( tl.financialyear= (select max(financialyear) from eg_tl_tradelicense where licensenumber=tl.licensenumber and licensenumber in ( select licensenumber from eg_tl_tradelicense where status=? and financialyear=? ) and status<>? ) "); + + /*set status (approved) and validTo(before current timestamp) conditions*/ + builder.append(" AND (tl.status IN (?,?) ) AND tl.validTo <= ? ) ) "); + + preparedStmtList.add(TLConstants.APPLICATION_TYPE_RENEWAL); + preparedStmtList.add(TLConstants.APPLICATION_TYPE_RENEWAL); + preparedStmtList.add(Integer.toString(Calendar.getInstance().get(Calendar.YEAR))); + preparedStmtList.add(TLConstants.STATUS_MANUALLYEXPIRED); + preparedStmtList.add(TLConstants.STATUS_REJECTED); + preparedStmtList.add(criteria.getFinancialYear()); + preparedStmtList.add(TLConstants.STATUS_REJECTED); + preparedStmtList.add(TLConstants.STATUS_APPROVED); + preparedStmtList.add(TLConstants.STATUS_EXPIRED); + preparedStmtList.add(System.currentTimeMillis()+renewalPeriod); + + } + + private String addCountWrapper(String query) { + + String finalQuery = countWrapper.replace("{INTERNAL_QUERY}",query ); + return finalQuery; + } + + + private void addBusinessServiceClause(TradeLicenseSearchCriteria criteria,List preparedStmtList,StringBuilder builder){ + if ((criteria.getBusinessService() == null) || (businessServiceTL.equals(criteria.getBusinessService()))) { + addClauseIfRequired(preparedStmtList, builder); + builder.append(" (tl.businessservice=? or tl.businessservice isnull) "); + preparedStmtList.add(businessServiceTL); + } else if (businessServiceBPA.equals(criteria.getBusinessService())) { + addClauseIfRequired(preparedStmtList, builder); + builder.append(" tl.businessservice=? "); + preparedStmtList.add(businessServiceBPA); + } + } + + private String createQuery(List ids) { + StringBuilder builder = new StringBuilder(); + int length = ids.size(); + for( int i = 0; i< length; i++){ + builder.append(" LOWER(?)"); + if(i != length -1) builder.append(","); + } + return builder.toString(); + } + + private void addToPreparedStatement(List preparedStmtList,List ids) + { + ids.forEach(id ->{ preparedStmtList.add(id);}); + } + + + private String addPaginationWrapper(String query,List preparedStmtList, + TradeLicenseSearchCriteria criteria){ + int limit = config.getDefaultLimit(); + int offset = config.getDefaultOffset(); + String finalQuery = paginationWrapper.replace("{}",query); + + if(criteria.getLimit()!=null && criteria.getLimit()<=config.getMaxSearchLimit()) + limit = criteria.getLimit(); + + if(criteria.getLimit()!=null && criteria.getLimit()>config.getMaxSearchLimit()) + limit = config.getMaxSearchLimit(); + + if(criteria.getOffset()!=null) + offset = criteria.getOffset(); + + preparedStmtList.add(offset); + preparedStmtList.add(limit+offset); + + return finalQuery; + } + + + private static void addClauseIfRequired(List values, StringBuilder queryString) { + if (values.isEmpty()) + queryString.append(" WHERE "); + else { + queryString.append(" AND"); + } + } + + public String getTLPlainSearchQuery(TradeLicenseSearchCriteria criteria, List preparedStmtList) { + StringBuilder builder = new StringBuilder(QUERY); + + List ids = criteria.getIds(); + if (!CollectionUtils.isEmpty(ids)) { + addClauseIfRequired(preparedStmtList,builder); + builder.append(" tl.id IN (").append(createQuery(ids)).append(")"); + addToPreparedStatement(preparedStmtList, ids); + } + + return addPaginationWrapper(builder.toString(), preparedStmtList, criteria); + + } + + public String getApplicationsCountQuery(TradeLicenseSearchCriteria criteria, List preparedStmtList, String applicationType) { + + StringBuilder query = new StringBuilder(""); + + if(criteria.getAccountId()!=null) { + query.append("select count(*) from eg_tl_tradelicense where tenantid = (select tl.tenantid from eg_tl_tradelicense tl INNER JOIN eg_tl_tradelicensedetail tld ON tld.tradelicenseid = tl.id INNER JOIN eg_tl_owner tlowner on tlowner.tradelicensedetailid = tld.id where tl.accountid=? "); + preparedStmtList.add(criteria.getAccountId()); + + List ownerIds = criteria.getOwnerIds(); + + if(!CollectionUtils.isEmpty(ownerIds)) { + + query.append(" OR (tlowner.id IN (").append(createQuery(ownerIds)).append(")"); + addToPreparedStatement(preparedStmtList,ownerIds); + + query.append(" AND tlowner.active = ? )"); + preparedStmtList.add(true); + } + + query.append("and tl.businessservice= ? limit 1) and createdtime> ? AND applicationtype= ? "); + + preparedStmtList.add(TLConstants.TRADE_LICENSE_MODULE_CODE); + + + } + + else if(criteria.getTenantId()!=null) { + query.append("select count(*) from eg_tl_tradelicense where tenantid = ? and createdtime > ? AND applicationtype= ? "); + preparedStmtList.add(criteria.getTenantId()); + } + + // In order to get data of last 12 months, the months variables is pre-configured in application properties + int months = Integer.valueOf(config.getNumberOfMonths()) ; + + Calendar calendar = Calendar.getInstance(); + + // To subtract 12 months from current time, we are adding -12 to the calendar instance, as subtract function is not in-built + calendar.add(Calendar.MONTH, -1*months); + + // Converting the timestamp to milliseconds and adding it to prepared statement list + preparedStmtList.add(calendar.getTimeInMillis()); + + preparedStmtList.add(applicationType); + + addClauseIfRequired(preparedStmtList, query); + query.append(" businessservice = ? "); + preparedStmtList.add(TLConstants.TRADE_LICENSE_MODULE_CODE); + + + return query.toString(); + + + } + + + + +}