diff --git a/accelerators/inbox/src/main/java/org/egov/inbox/repository/builder/V2/InboxQueryBuilder.java b/accelerators/inbox/src/main/java/org/egov/inbox/repository/builder/V2/InboxQueryBuilder.java index 4cd28e12c37..3477ba3974a 100644 --- a/accelerators/inbox/src/main/java/org/egov/inbox/repository/builder/V2/InboxQueryBuilder.java +++ b/accelerators/inbox/src/main/java/org/egov/inbox/repository/builder/V2/InboxQueryBuilder.java @@ -20,7 +20,6 @@ import static org.egov.inbox.util.InboxConstants.*; - @Slf4j @Component public class InboxQueryBuilder implements QueryBuilderInterface { @@ -31,54 +30,67 @@ public class InboxQueryBuilder implements QueryBuilderInterface { @Autowired private MDMSUtil mdmsUtil; - @Override public Map getESQuery(InboxRequest inboxRequest, Boolean isPaginationRequired) { - InboxQueryConfiguration configuration = mdmsUtil.getConfigFromMDMS(inboxRequest.getInbox().getTenantId(), inboxRequest.getInbox().getProcessSearchCriteria().getModuleName()); + InboxQueryConfiguration configuration = mdmsUtil.getConfigFromMDMS(inboxRequest.getInbox().getTenantId(), + inboxRequest.getInbox().getProcessSearchCriteria().getModuleName()); Map params = inboxRequest.getInbox().getModuleSearchCriteria(); Map baseEsQuery = getBaseESQueryBody(inboxRequest, isPaginationRequired); - if(isPaginationRequired) { - // Adds sort clause to the inbox ES query only in case pagination is present, else not + if (isPaginationRequired) { + // Adds sort clause to the inbox ES query only in case pagination is present, + // else not String sortClauseFieldPath = configuration.getSortParam().getPath(); - SortParam.Order sortOrder = inboxRequest.getInbox().getModuleSearchCriteria().containsKey(SORT_ORDER_CONSTANT) ? SortParam.Order.valueOf((String) inboxRequest.getInbox().getModuleSearchCriteria().get(SORT_ORDER_CONSTANT)) : configuration.getSortParam().getOrder(); + SortParam.Order sortOrder = inboxRequest.getInbox().getModuleSearchCriteria() + .containsKey(SORT_ORDER_CONSTANT) + ? SortParam.Order.valueOf( + (String) inboxRequest.getInbox().getModuleSearchCriteria().get(SORT_ORDER_CONSTANT)) + : configuration.getSortParam().getOrder(); addSortClauseToBaseQuery(baseEsQuery, sortClauseFieldPath, sortOrder); - // Adds source filter only when requesting for inbox items. List sourceFilterPathList = configuration.getSourceFilterPathList(); addSourceFilterToBaseQuery(baseEsQuery, sourceFilterPathList); } - Map innerBoolClause = (HashMap) ((HashMap) baseEsQuery.get(QUERY_KEY)).get(BOOL_KEY); + Map innerBoolClause = (HashMap) ((HashMap) baseEsQuery + .get(QUERY_KEY)).get(BOOL_KEY); List mustClauseList = (ArrayList) innerBoolClause.get(MUST_KEY); Map nameToPathMap = new HashMap<>(); Map nameToOperator = new HashMap<>(); - + System.out.println(baseEsQuery.toString()); configuration.getAllowedSearchCriteria().forEach(searchParam -> { nameToPathMap.put(searchParam.getName(), searchParam.getPath()); nameToOperator.put(searchParam.getName(), searchParam.getOperator()); }); - addModuleSearchCriteriaToBaseQuery(params, nameToPathMap, nameToOperator, mustClauseList); - addProcessSearchCriteriaToBaseQuery(inboxRequest.getInbox().getProcessSearchCriteria(), nameToPathMap, nameToOperator, mustClauseList); + addProcessSearchCriteriaToBaseQuery(inboxRequest.getInbox().getProcessSearchCriteria(), + nameToPathMap, + nameToOperator, mustClauseList); innerBoolClause.put(MUST_KEY, mustClauseList); - + log.info("Final ES Query after adding must clause: " + baseEsQuery.toString()); return baseEsQuery; } public Map getESQueryForSimpleSearch(SearchRequest searchRequest, Boolean isPaginationRequired) { - InboxQueryConfiguration configuration = mdmsUtil.getConfigFromMDMS(searchRequest.getIndexSearchCriteria().getTenantId(), searchRequest.getIndexSearchCriteria().getModuleName()); + InboxQueryConfiguration configuration = mdmsUtil.getConfigFromMDMS( + searchRequest.getIndexSearchCriteria().getTenantId(), + searchRequest.getIndexSearchCriteria().getModuleName()); Map params = searchRequest.getIndexSearchCriteria().getModuleSearchCriteria(); Map baseEsQuery = getBaseESQueryBody(searchRequest, isPaginationRequired); - if(isPaginationRequired) { - // Adds sort clause to the inbox ES query only in case pagination is present, else not + if (isPaginationRequired) { + // Adds sort clause to the inbox ES query only in case pagination is present, + // else not String sortClauseFieldPath = configuration.getSortParam().getPath(); - SortParam.Order sortOrder = searchRequest.getIndexSearchCriteria().getModuleSearchCriteria().containsKey(SORT_ORDER_CONSTANT) ? SortParam.Order.valueOf((String) searchRequest.getIndexSearchCriteria().getModuleSearchCriteria().get(SORT_ORDER_CONSTANT)) : configuration.getSortParam().getOrder(); + SortParam.Order sortOrder = searchRequest.getIndexSearchCriteria().getModuleSearchCriteria() + .containsKey(SORT_ORDER_CONSTANT) + ? SortParam.Order.valueOf((String) searchRequest.getIndexSearchCriteria() + .getModuleSearchCriteria().get(SORT_ORDER_CONSTANT)) + : configuration.getSortParam().getOrder(); addSortClauseToBaseQuery(baseEsQuery, sortClauseFieldPath, sortOrder); // Adds source filter only when requesting for inbox items. @@ -86,7 +98,8 @@ public Map getESQueryForSimpleSearch(SearchRequest searchRequest addSourceFilterToBaseQuery(baseEsQuery, sourceFilterPathList); } - Map innerBoolClause = (HashMap) ((HashMap) baseEsQuery.get(QUERY_KEY)).get(BOOL_KEY); + Map innerBoolClause = (HashMap) ((HashMap) baseEsQuery + .get(QUERY_KEY)).get(BOOL_KEY); List mustClauseList = (ArrayList) innerBoolClause.get(MUST_KEY); Map nameToPathMap = new HashMap<>(); @@ -105,11 +118,12 @@ public Map getESQueryForSimpleSearch(SearchRequest searchRequest } private void addSourceFilterToBaseQuery(Map baseEsQuery, List sourceFilterPathList) { - if(!CollectionUtils.isEmpty(sourceFilterPathList)) + if (!CollectionUtils.isEmpty(sourceFilterPathList)) baseEsQuery.put(SOURCE_KEY, sourceFilterPathList); } - private void addSortClauseToBaseQuery(Map baseEsQuery, String sortClauseFieldPath, SortParam.Order sortOrder) { + private void addSortClauseToBaseQuery(Map baseEsQuery, String sortClauseFieldPath, + SortParam.Order sortOrder) { List sortClause = new ArrayList<>(); Map innerSortOrderClause = new HashMap<>(); innerSortOrderClause.put(ORDER_KEY, sortOrder); @@ -119,82 +133,78 @@ private void addSortClauseToBaseQuery(Map baseEsQuery, String so baseEsQuery.put(SORT_KEY, sortClause); } - private void addProcessSearchCriteriaToBaseQuery(ProcessInstanceSearchCriteria processSearchCriteria, Map nameToPathMap, Map nameToOperator, List mustClauseList) { - if(!ObjectUtils.isEmpty(processSearchCriteria.getTenantId())){ - String key = "tenantId"; - Map mustClauseChild = null; - Map params = new HashMap<>(); - params.put(key, processSearchCriteria.getTenantId()); - mustClauseChild = (Map) prepareMustClauseChild(params, key, nameToPathMap, nameToOperator); - if(CollectionUtils.isEmpty(mustClauseChild)){ - log.info("Error occurred while preparing filter for must clause. Filter for key " + key + " will not be added."); - }else { - mustClauseList.add(mustClauseChild); - } - } + private void addProcessSearchCriteriaToBaseQuery(ProcessInstanceSearchCriteria processSearchCriteria, + Map nameToPathMap, Map nameToOperator, + List mustClauseList) { - if(!ObjectUtils.isEmpty(processSearchCriteria.getStatus())){ + if (!ObjectUtils.isEmpty(processSearchCriteria.getStatus())) { String key = "status"; Map mustClauseChild = null; Map params = new HashMap<>(); params.put(key, processSearchCriteria.getStatus()); mustClauseChild = (Map) prepareMustClauseChild(params, key, nameToPathMap, nameToOperator); - if(CollectionUtils.isEmpty(mustClauseChild)){ - log.info("Error occurred while preparing filter for must clause. Filter for key " + key + " will not be added."); - }else { + if (CollectionUtils.isEmpty(mustClauseChild)) { + log.info("Error occurred while preparing filter for must clause. Filter for key " + key + + " will not be added."); + } else { mustClauseList.add(mustClauseChild); } } - if(!ObjectUtils.isEmpty(processSearchCriteria.getAssignee())){ + if (!ObjectUtils.isEmpty(processSearchCriteria.getAssignee())) { String key = "assignee"; Map mustClauseChild = null; Map params = new HashMap<>(); params.put(key, processSearchCriteria.getAssignee()); mustClauseChild = (Map) prepareMustClauseChild(params, key, nameToPathMap, nameToOperator); - if(CollectionUtils.isEmpty(mustClauseChild)){ - log.info("Error occurred while preparing filter for must clause. Filter for key " + key + " will not be added."); - }else { + if (CollectionUtils.isEmpty(mustClauseChild)) { + log.info("Error occurred while preparing filter for must clause. Filter for key " + key + + " will not be added."); + } else { mustClauseList.add(mustClauseChild); } } - if(!ObjectUtils.isEmpty(processSearchCriteria.getFromDate())){ + if (!ObjectUtils.isEmpty(processSearchCriteria.getFromDate())) { String key = "fromDate"; Map mustClauseChild = null; Map params = new HashMap<>(); params.put(key, processSearchCriteria.getFromDate()); mustClauseChild = (Map) prepareMustClauseChild(params, key, nameToPathMap, nameToOperator); - if(CollectionUtils.isEmpty(mustClauseChild)){ - log.info("Error occurred while preparing filter for must clause. Filter for key " + key + " will not be added."); - }else { + if (CollectionUtils.isEmpty(mustClauseChild)) { + log.info("Error occurred while preparing filter for must clause. Filter for key " + key + + " will not be added."); + } else { mustClauseList.add(mustClauseChild); } } - if(!ObjectUtils.isEmpty(processSearchCriteria.getToDate())){ + if (!ObjectUtils.isEmpty(processSearchCriteria.getToDate())) { String key = "toDate"; Map mustClauseChild = null; Map params = new HashMap<>(); params.put(key, processSearchCriteria.getToDate()); mustClauseChild = (Map) prepareMustClauseChild(params, key, nameToPathMap, nameToOperator); - if(CollectionUtils.isEmpty(mustClauseChild)){ - log.info("Error occurred while preparing filter for must clause. Filter for key " + key + " will not be added."); - }else { + if (CollectionUtils.isEmpty(mustClauseChild)) { + log.info("Error occurred while preparing filter for must clause. Filter for key " + key + + " will not be added."); + } else { mustClauseList.add(mustClauseChild); } } } - - private void addModuleSearchCriteriaToBaseQuery(Map params, Map nameToPathMap, Map nameToOperator, List mustClauseList) { + private void addModuleSearchCriteriaToBaseQuery(Map params, Map nameToPathMap, + Map nameToOperator, List mustClauseList) { params.keySet().forEach(key -> { - if(!(key.equals(SORT_ORDER_CONSTANT) || key.equals(SORT_BY_CONSTANT))) { + if (!(key.equals(SORT_ORDER_CONSTANT) || key.equals(SORT_BY_CONSTANT))) { Map mustClauseChild = null; - mustClauseChild = (Map) prepareMustClauseChild(params, key, nameToPathMap, nameToOperator); + mustClauseChild = (Map) prepareMustClauseChild(params, key, nameToPathMap, + nameToOperator); if (CollectionUtils.isEmpty(mustClauseChild)) { - log.info("Error occurred while preparing filter for must clause. Filter for key " + key + " will not be added."); + log.info("Error occurred while preparing filter for must clause. Filter for key " + key + + " will not be added."); } else { mustClauseList.add(mustClauseChild); } @@ -214,7 +224,7 @@ public Map getNearingSlaCountQuery(InboxRequest inboxRequest, Lo Map baseEsQuery = getESQuery(inboxRequest, Boolean.FALSE); Long currenTimeInMillis = System.currentTimeMillis(); Long lteParam = currenTimeInMillis; - Long slotLimit = businessServiceSla - 40 * (businessServiceSla/100); + Long slotLimit = businessServiceSla - 40 * (businessServiceSla / 100); Long gteParam = currenTimeInMillis - slotLimit; appendNearingSlaCountClause(baseEsQuery, gteParam, lteParam); @@ -243,7 +253,7 @@ private void appendStatusCountAggsNode(Map baseEsQuery) { baseEsQuery.put("aggs", aggsNode); } - private Map getBaseESQueryBody(InboxRequest inboxRequest, Boolean isPaginationRequired){ + private Map getBaseESQueryBody(InboxRequest inboxRequest, Boolean isPaginationRequired) { Map baseEsQuery = new HashMap<>(); Map boolQuery = new HashMap<>(); Map mustClause = new HashMap<>(); @@ -254,7 +264,7 @@ private Map getBaseESQueryBody(InboxRequest inboxRequest, Boolea innerBoolBody.put("must", new ArrayList<>()); // Prepare base ES query - if(isPaginationRequired) { + if (isPaginationRequired) { baseEsQuery.put("from", inboxRequest.getInbox().getOffset()); baseEsQuery.put("size", inboxRequest.getInbox().getLimit()); } @@ -263,7 +273,7 @@ private Map getBaseESQueryBody(InboxRequest inboxRequest, Boolea return baseEsQuery; } - private Map getBaseESQueryBody(SearchRequest searchRequest, Boolean isPaginationRequired){ + private Map getBaseESQueryBody(SearchRequest searchRequest, Boolean isPaginationRequired) { Map baseEsQuery = new HashMap<>(); Map boolQuery = new HashMap<>(); @@ -273,7 +283,7 @@ private Map getBaseESQueryBody(SearchRequest searchRequest, Bool innerBoolBody.put("must", new ArrayList<>()); // Prepare base ES query - if(isPaginationRequired) { + if (isPaginationRequired) { baseEsQuery.put("from", searchRequest.getIndexSearchCriteria().getOffset()); baseEsQuery.put("size", searchRequest.getIndexSearchCriteria().getLimit()); } @@ -282,12 +292,13 @@ private Map getBaseESQueryBody(SearchRequest searchRequest, Bool return baseEsQuery; } - private Object prepareMustClauseChild(Map params, String key, Map nameToPathMap, Map nameToOperatorMap){ + private Object prepareMustClauseChild(Map params, String key, Map nameToPathMap, + Map nameToOperatorMap) { SearchParam.Operator operator = nameToOperatorMap.get(key); - if(operator == null || operator.equals(SearchParam.Operator.EQUAL)){ + if (operator == null || operator.equals(SearchParam.Operator.EQUAL)) { // Add terms clause in case the search criteria has a list of values - if(params.get(key) instanceof List){ + if (params.get(key) instanceof List) { Map termsClause = new HashMap<>(); termsClause.put("terms", new HashMap<>()); Map innerTermsClause = (Map) termsClause.get("terms"); @@ -295,25 +306,23 @@ private Object prepareMustClauseChild(Map params, String key, Ma return termsClause; } // Add term clause in case the search criteria has a single value - else{ + else { Map termClause = new HashMap<>(); termClause.put("term", new HashMap<>()); Map innerTermClause = (Map) termClause.get("term"); innerTermClause.put(addDataPathToSearchParamKey(key, nameToPathMap), params.get(key)); return termClause; } - } - else { + } else { Map rangeClause = new HashMap<>(); rangeClause.put("range", new HashMap<>()); Map innerTermClause = (Map) rangeClause.get("range"); Map comparatorMap = new HashMap<>(); - if (operator.equals(SearchParam.Operator.LTE)){ - comparatorMap.put("lte",params.get(key)); - } - else if (operator.equals(SearchParam.Operator.GTE)){ - comparatorMap.put("gte",params.get(key)); + if (operator.equals(SearchParam.Operator.LTE)) { + comparatorMap.put("lte", params.get(key)); + } else if (operator.equals(SearchParam.Operator.GTE)) { + comparatorMap.put("gte", params.get(key)); } innerTermClause.put(addDataPathToSearchParamKey(key, nameToPathMap), comparatorMap); return rangeClause; @@ -321,7 +330,7 @@ else if (operator.equals(SearchParam.Operator.GTE)){ } - private String addDataPathToSearchParamKey(String key, Map nameToPathMap){ + private String addDataPathToSearchParamKey(String key, Map nameToPathMap) { String path = nameToPathMap.get(key); diff --git a/accelerators/inbox/src/main/java/org/egov/inbox/service/V2/InboxServiceV2.java b/accelerators/inbox/src/main/java/org/egov/inbox/service/V2/InboxServiceV2.java index c67c7fa1607..441548164bd 100644 --- a/accelerators/inbox/src/main/java/org/egov/inbox/service/V2/InboxServiceV2.java +++ b/accelerators/inbox/src/main/java/org/egov/inbox/service/V2/InboxServiceV2.java @@ -58,39 +58,46 @@ public class InboxServiceV2 { @Autowired private HashService hashService; - /** * * @param inboxRequest * @return */ - public InboxResponse getInboxResponse(InboxRequest inboxRequest){ + public InboxResponse getInboxResponse(InboxRequest inboxRequest) { validator.validateSearchCriteria(inboxRequest); - InboxQueryConfiguration inboxQueryConfiguration = mdmsUtil.getConfigFromMDMS(inboxRequest.getInbox().getTenantId(), inboxRequest.getInbox().getProcessSearchCriteria().getModuleName()); - hashParamsWhereverRequiredBasedOnConfiguration(inboxRequest.getInbox().getModuleSearchCriteria(), inboxQueryConfiguration); + InboxQueryConfiguration inboxQueryConfiguration = mdmsUtil.getConfigFromMDMS( + inboxRequest.getInbox().getTenantId(), + inboxRequest.getInbox().getProcessSearchCriteria().getModuleName()); + hashParamsWhereverRequiredBasedOnConfiguration(inboxRequest.getInbox().getModuleSearchCriteria(), + inboxQueryConfiguration); List items = getInboxItems(inboxRequest, inboxQueryConfiguration.getIndex()); enrichProcessInstanceInInboxItems(items); - Integer totalCount = CollectionUtils.isEmpty(inboxRequest.getInbox().getProcessSearchCriteria().getStatus()) ? 0 : getTotalApplicationCount(inboxRequest, inboxQueryConfiguration.getIndex()); - List> statusCountMap = CollectionUtils.isEmpty(inboxRequest.getInbox().getProcessSearchCriteria().getStatus()) ? new ArrayList<>() : getStatusCountMap(inboxRequest, inboxQueryConfiguration.getIndex()); - Integer nearingSlaCount = CollectionUtils.isEmpty(inboxRequest.getInbox().getProcessSearchCriteria().getStatus()) ? 0 : getApplicationsNearingSlaCount(inboxRequest, inboxQueryConfiguration.getIndex()); - InboxResponse inboxResponse = InboxResponse.builder().items(items).totalCount(totalCount).statusMap(statusCountMap).nearingSlaCount(nearingSlaCount).build(); + Integer totalCount = getTotalApplicationCount(inboxRequest, inboxQueryConfiguration.getIndex()); + List> statusCountMap = getStatusCountMap(inboxRequest, + inboxQueryConfiguration.getIndex()); + Integer nearingSlaCount = CollectionUtils + .isEmpty(inboxRequest.getInbox().getProcessSearchCriteria().getStatus()) ? 0 + : getApplicationsNearingSlaCount(inboxRequest, inboxQueryConfiguration.getIndex()); + InboxResponse inboxResponse = InboxResponse.builder().items(items).totalCount(totalCount) + .statusMap(statusCountMap).nearingSlaCount(nearingSlaCount).build(); return inboxResponse; } - private void hashParamsWhereverRequiredBasedOnConfiguration(Map moduleSearchCriteria, InboxQueryConfiguration inboxQueryConfiguration) { + private void hashParamsWhereverRequiredBasedOnConfiguration(Map moduleSearchCriteria, + InboxQueryConfiguration inboxQueryConfiguration) { inboxQueryConfiguration.getAllowedSearchCriteria().forEach(searchParam -> { - if(!ObjectUtils.isEmpty(searchParam.getIsHashingRequired()) && searchParam.getIsHashingRequired()){ - if(moduleSearchCriteria.containsKey(searchParam.getName())){ - if(moduleSearchCriteria.get(searchParam.getName()) instanceof List){ + if (!ObjectUtils.isEmpty(searchParam.getIsHashingRequired()) && searchParam.getIsHashingRequired()) { + if (moduleSearchCriteria.containsKey(searchParam.getName())) { + if (moduleSearchCriteria.get(searchParam.getName()) instanceof List) { List hashedParams = new ArrayList<>(); ((List) moduleSearchCriteria.get(searchParam.getName())).forEach(object -> { hashedParams.add(hashService.getHashValue(object)); }); moduleSearchCriteria.put(searchParam.getName(), hashedParams); - }else{ + } else { Object hashedValue = hashService.getHashValue(moduleSearchCriteria.get(searchParam.getName())); moduleSearchCriteria.put(searchParam.getName(), hashedValue); } @@ -101,162 +108,221 @@ private void hashParamsWhereverRequiredBasedOnConfiguration(Map private void enrichProcessInstanceInInboxItems(List items) { /* - As part of the new inbox, having currentProcessInstance as part of the index is mandated. This has been - done to avoid having redundant network calls which could hog the performance. - */ + * As part of the new inbox, having currentProcessInstance as part of the index + * is mandated. This has been + * done to avoid having redundant network calls which could hog the performance. + */ items.forEach(item -> { - if(item.getBusinessObject().containsKey(CURRENT_PROCESS_INSTANCE_CONSTANT)) { - // Set process instance object in the native process instance field declared in the model inbox class. - ProcessInstance processInstance = mapper.convertValue(item.getBusinessObject().get(CURRENT_PROCESS_INSTANCE_CONSTANT), ProcessInstance.class); + if (item.getBusinessObject().containsKey(CURRENT_PROCESS_INSTANCE_CONSTANT)) { + // Set process instance object in the native process instance field declared in + // the model inbox class. + ProcessInstance processInstance = mapper.convertValue( + item.getBusinessObject().get(CURRENT_PROCESS_INSTANCE_CONSTANT), ProcessInstance.class); item.setProcessInstance(processInstance); - // Remove current process instance from business object in order to avoid having redundant data in response. + // Remove current process instance from business object in order to avoid having + // redundant data in response. item.getBusinessObject().remove(CURRENT_PROCESS_INSTANCE_CONSTANT); } }); } - private List getInboxItems(InboxRequest inboxRequest, String indexName){ + private List getInboxItems(InboxRequest inboxRequest, String indexName) { List businessServices = workflowService.getBusinessServices(inboxRequest); enrichActionableStatusesFromRole(inboxRequest, businessServices); - if(CollectionUtils.isEmpty(inboxRequest.getInbox().getProcessSearchCriteria().getStatus())){ - return new ArrayList<>(); - } + Map finalQueryBody = queryBuilder.getESQuery(inboxRequest, Boolean.TRUE); try { String q = mapper.writeValueAsString(finalQueryBody); - log.info("Query: "+q); - } - catch (Exception e){ + log.info("Query: " + q); + } catch (Exception e) { e.printStackTrace(); } StringBuilder uri = getURI(indexName, SEARCH_PATH); Object result = serviceRequestRepository.fetchResult(uri, finalQueryBody); List inboxItemsList = parseInboxItemsFromSearchResponse(result, businessServices); - log.info(result.toString()); + // log.info(result.toString()); return inboxItemsList; } + /************* ✨ Codeium Command ⭐ *************/ + /** + * This method takes in the inbox request and list of business services + * It fetches the actionable statuses for the given role and tenantId + * It then updates the inbox request with the actionable statuses + */ + /****** 203bf6c4-77e2-494a-bbba-dc1e36258155 *******/ private void enrichActionableStatusesFromRole(InboxRequest inboxRequest, List businessServices) { ProcessInstanceSearchCriteria processCriteria = inboxRequest.getInbox().getProcessSearchCriteria(); - String tenantId = inboxRequest.getInbox().getTenantId(); - processCriteria.setTenantId(tenantId); - HashMap StatusIdNameMap = workflowService.getActionableStatusesForRole(inboxRequest.getRequestInfo(), businessServices, + HashMap StatusIdNameMap = workflowService.getActionableStatusesForRole( + inboxRequest.getRequestInfo(), businessServices, inboxRequest.getInbox().getProcessSearchCriteria()); log.info(StatusIdNameMap.toString()); - List actionableStatusUuid = new ArrayList<>(); - if (StatusIdNameMap.values().size() > 0) { + List actionableStatus = new ArrayList<>(); + if (StatusIdNameMap.values().size() > 0 && processCriteria.getStatus() != null + && !processCriteria.getStatus().isEmpty()) { if (!CollectionUtils.isEmpty(processCriteria.getStatus())) { - processCriteria.getStatus().forEach(statusUuid -> { - if(StatusIdNameMap.keySet().contains(statusUuid)){ - actionableStatusUuid.add(statusUuid); + processCriteria.getStatus().forEach(status -> { + if (StatusIdNameMap.values().contains(status)) { + actionableStatus.add(status); } }); - inboxRequest.getInbox().getProcessSearchCriteria().setStatus(actionableStatusUuid); + inboxRequest.getInbox().getProcessSearchCriteria().setStatus(actionableStatus); } else { inboxRequest.getInbox().getProcessSearchCriteria().setStatus(new ArrayList<>(StatusIdNameMap.keySet())); } - }else{ + } else { inboxRequest.getInbox().getProcessSearchCriteria().setStatus(new ArrayList<>()); } } - public Integer getTotalApplicationCount(InboxRequest inboxRequest, String indexName){ + public Integer getTotalApplicationCount(InboxRequest inboxRequest, String indexName) { Map finalQueryBody = queryBuilder.getESQuery(inboxRequest, Boolean.FALSE); StringBuilder uri = getURI(indexName, COUNT_PATH); Map response = (Map) serviceRequestRepository.fetchResult(uri, finalQueryBody); Integer totalCount = 0; - if(response.containsKey(COUNT_CONSTANT)){ + if (response.containsKey(COUNT_CONSTANT)) { totalCount = (Integer) response.get(COUNT_CONSTANT); - }else{ + } else { throw new CustomException("INBOX_COUNT_ERR", "Error occurred while executing ES count query"); } return totalCount; } - public List> getStatusCountMap(InboxRequest inboxRequest, String indexName){ + public List> getStatusCountMap(InboxRequest inboxRequest, String indexName) { + List businessServices = workflowService.getBusinessServices(inboxRequest); + + HashMap StatusIdNameMap = workflowService.getActionableStatusesForRole( + inboxRequest.getRequestInfo(), businessServices, + inboxRequest.getInbox().getProcessSearchCriteria()); + log.info(StatusIdNameMap.toString()); + List actionableStatus = new ArrayList<>(); + // add keys + StatusIdNameMap.keySet().forEach(actionableStatus::add); Map finalQueryBody = queryBuilder.getStatusCountQuery(inboxRequest); + log.info("Query for status count: " + finalQueryBody.toString()); StringBuilder uri = getURI(indexName, SEARCH_PATH); Map response = (Map) serviceRequestRepository.fetchResult(uri, finalQueryBody); - Set actionableStatuses = new HashSet<>(inboxRequest.getInbox().getProcessSearchCriteria().getStatus()); - HashMap statusCountMap = parseStatusCountMapFromAggregationResponse(response, actionableStatuses); + Set actionableStatusHSet = new HashSet<>(actionableStatus); + HashMap statusCountMap = parseStatusCountMapFromAggregationResponse(response, + actionableStatusHSet); List> transformedStatusMap = transformStatusMap(inboxRequest, statusCountMap); return transformedStatusMap; } - private Long getApplicationServiceSla(Map businessServiceSlaMap, Map stateUuidSlaMap, Object data) { + private Long getApplicationServiceSla(Map businessServiceSlaMap, Map stateUuidSlaMap, + Object data) { - Long currentDate = System.currentTimeMillis(); //current time + Long currentDate = System.currentTimeMillis(); // current time Map auditDetails = (Map) ((Map) data).get(AUDIT_DETAILS_KEY); - String stateUuid = JsonPath.read(data, STATE_UUID_PATH); - if(stateUuidSlaMap.containsKey(stateUuid)){ + if (auditDetails == null) { + // Check if 'data' is indeed a Map + if (data instanceof Map) { + // Cast 'data' to Map + Map dataMap = (Map) data; + + // Iterate through the first level of the map + for (Map.Entry entry : dataMap.entrySet()) { + // Check if the value is a map and if it contains auditDetails at the second + // level + if (entry.getValue() instanceof Map) { + Map secondLevelMap = (Map) entry.getValue(); + if (secondLevelMap.containsKey("auditDetails")) { + auditDetails = (Map) secondLevelMap.get("auditDetails"); + break; // Found the first occurrence of auditDetails, no need to continue + } + } + } + } + } + String stateUuid = ""; + try { + stateUuid = JsonPath.read(data, STATE_UUID_PATH); + } catch (Exception e) { + log.warn(STATE_UUID_PATH + " not found in data: " + data); + return null; + } + if (stateUuidSlaMap.containsKey(stateUuid)) { if (!ObjectUtils.isEmpty(auditDetails.get(LAST_MODIFIED_TIME_KEY))) { Long lastModifiedTime = ((Number) auditDetails.get(LAST_MODIFIED_TIME_KEY)).longValue(); - return Long.valueOf(Math.round((stateUuidSlaMap.get(stateUuid) - (currentDate - lastModifiedTime)) / ((double) (24 * 60 * 60 * 1000)))); + return Long.valueOf(Math.round((stateUuidSlaMap.get(stateUuid) - (currentDate + - lastModifiedTime)) + / ((double) (24 * 60 * 60 * 1000)))); } - }else { + } else { if (!ObjectUtils.isEmpty(auditDetails.get(CREATED_TIME_KEY))) { Long createdTime = ((Number) auditDetails.get(CREATED_TIME_KEY)).longValue(); String businessService = JsonPath.read(data, BUSINESS_SERVICE_PATH); Long businessServiceSLA = businessServiceSlaMap.get(businessService); - return Long.valueOf(Math.round((businessServiceSLA - (currentDate - createdTime)) / ((double) (24 * 60 * 60 * 1000)))); + return Long.valueOf(Math + .round((businessServiceSLA - (currentDate - createdTime)) / ((double) (24 * + 60 * 60 * 1000)))); } } return null; } - private List> transformStatusMap(InboxRequest request,HashMap statusCountMap) { + private List> transformStatusMap(InboxRequest request, + HashMap statusCountMap) { - if(CollectionUtils.isEmpty(statusCountMap)) + if (CollectionUtils.isEmpty(statusCountMap)) return null; List businessServices = workflowService.getBusinessServices(request); - Map statusIdToBusinessServiceMap = workflowService.getStatusIdToBusinessServiceMap(businessServices); - Map statusIdToApplicationStatusMap = workflowService.getApplicationStatusIdToStatusMap(businessServices); + Map statusIdToBusinessServiceMap = workflowService + .getStatusIdToBusinessServiceMap(businessServices); + Map statusIdToApplicationStatusMap = workflowService + .getApplicationStatusIdToStatusMap(businessServices); Map statusIdToStateMap = workflowService.getStatusIdToStateMap(businessServices); - List> statusCountMapTransformed = new ArrayList<>(); + List> statusCountMapTransformed = new ArrayList<>(); - for(Map.Entry entry : statusCountMap.entrySet()){ + for (Map.Entry entry : statusCountMap.entrySet()) { String statusId = entry.getKey(); Integer count = (Integer) entry.getValue(); - HashMap map = new HashMap<>(); - map.put(COUNT_CONSTANT, count); - map.put(APPLICATION_STATUS_KEY,statusIdToApplicationStatusMap.get(statusId)); - map.put(BUSINESSSERVICE_KEY,statusIdToBusinessServiceMap.get(statusId)); - map.put(STATUSID_KEY, statusId); - map.put(STATE_KEY, statusIdToStateMap.get(statusId)); - statusCountMapTransformed.add(map); + if (statusIdToStateMap.get(statusId) != null) { + HashMap map = new HashMap<>(); + map.put(COUNT_CONSTANT, count); + map.put(APPLICATION_STATUS_KEY, statusIdToApplicationStatusMap.get(statusId)); + map.put(BUSINESSSERVICE_KEY, statusIdToBusinessServiceMap.get(statusId)); + map.put(STATUSID_KEY, statusId); + map.put(STATE_KEY, statusIdToStateMap.get(statusId)); + statusCountMapTransformed.add(map); + } } return statusCountMapTransformed; } - private HashMap parseStatusCountMapFromAggregationResponse(Map response, Set actionableStatuses) { + private HashMap parseStatusCountMapFromAggregationResponse(Map response, + Set actionableStatuses) { List> statusCountResponse = new ArrayList<>(); - if(!CollectionUtils.isEmpty((Map) response.get(AGGREGATIONS_KEY))){ - List> statusCountBuckets = JsonPath.read(response, STATUS_COUNT_AGGREGATIONS_BUCKETS_PATH); + if (!CollectionUtils.isEmpty((Map) response.get(AGGREGATIONS_KEY))) { + List> statusCountBuckets = JsonPath.read(response, + STATUS_COUNT_AGGREGATIONS_BUCKETS_PATH); HashMap statusCountMap = new HashMap<>(); + actionableStatuses.forEach(status -> { + statusCountMap.put(status, 0); + }); statusCountBuckets.forEach(bucket -> { - if(actionableStatuses.contains(bucket.get(KEY))) - statusCountMap.put((String)bucket.get(KEY), bucket.get(DOC_COUNT_KEY)); + statusCountMap.put((String) bucket.get(KEY), bucket.get(DOC_COUNT_KEY)); }); statusCountResponse.add(statusCountMap); } - if(CollectionUtils.isEmpty(statusCountResponse)) + if (CollectionUtils.isEmpty(statusCountResponse)) return null; return statusCountResponse.get(0); } private List parseInboxItemsFromSearchResponse(Object result, List businessServices) { - Map hits = (Map)((Map) result).get(HITS); + Map hits = (Map) ((Map) result).get(HITS); List> nestedHits = (List>) hits.get(HITS); - if(CollectionUtils.isEmpty(nestedHits)){ + if (CollectionUtils.isEmpty(nestedHits)) { return new ArrayList<>(); } @@ -264,19 +330,21 @@ private List parseInboxItemsFromSearchResponse(Object result, List stateUuidVsSlaMap = new HashMap<>(); businessServices.forEach(businessService -> { - businessServiceSlaMap.put(businessService.getBusinessService(),businessService.getBusinessServiceSla()); + businessServiceSlaMap.put(businessService.getBusinessService(), businessService.getBusinessServiceSla()); businessService.getStates().forEach(state -> { - if(!ObjectUtils.isEmpty(state.getSla())) + if (!ObjectUtils.isEmpty(state.getSla())) stateUuidVsSlaMap.put(state.getUuid(), state.getSla()); }); }); List inboxItemList = new ArrayList<>(); - nestedHits.forEach(hit ->{ + nestedHits.forEach(hit -> { Inbox inbox = new Inbox(); Map businessObject = (Map) hit.get(SOURCE_KEY); - inbox.setBusinessObject((Map)businessObject.get(DATA_KEY)); - Long serviceSla = getApplicationServiceSla(businessServiceSlaMap, stateUuidVsSlaMap, inbox.getBusinessObject()); inbox.getBusinessObject().put(SERVICESLA_KEY, serviceSla); + inbox.setBusinessObject((Map) businessObject.get(DATA_KEY)); + Long serviceSla = getApplicationServiceSla(businessServiceSlaMap, stateUuidVsSlaMap, + inbox.getBusinessObject()); + inbox.getBusinessObject().put(SERVICESLA_KEY, serviceSla); inboxItemList.add(inbox); }); return inboxItemList; @@ -292,15 +360,16 @@ public Integer getApplicationsNearingSlaCount(InboxRequest inboxRequest, String listOfUuids.add(state.getUuid()); }); businessServiceVsStateUuids.put(businessService.getBusinessService(), new HashSet<>(listOfUuids)); - businessServiceSlaMap.put(businessService.getBusinessService(),businessService.getBusinessServiceSla()); + businessServiceSlaMap.put(businessService.getBusinessService(), businessService.getBusinessServiceSla()); }); List uuidsInSearchCriteria = inboxRequest.getInbox().getProcessSearchCriteria().getStatus(); Map> businessServiceVsUuidsBasedOnSearchCriteria = new HashMap<>(); - // If status uuids are being passed in process search criteria, segregating them based on their business service - if(!CollectionUtils.isEmpty(uuidsInSearchCriteria)) { + // If status uuids are being passed in process search criteria, segregating them + // based on their business service + if (!CollectionUtils.isEmpty(uuidsInSearchCriteria)) { uuidsInSearchCriteria.forEach(uuid -> { businessServiceVsStateUuids.keySet().forEach(businessService -> { HashSet setOfUuids = businessServiceVsStateUuids.get(businessService); @@ -308,37 +377,37 @@ public Integer getApplicationsNearingSlaCount(InboxRequest inboxRequest, String if (businessServiceVsUuidsBasedOnSearchCriteria.containsKey(businessService)) { businessServiceVsUuidsBasedOnSearchCriteria.get(businessService).add(uuid); } else { - businessServiceVsUuidsBasedOnSearchCriteria.put(businessService, new ArrayList<>(Collections.singletonList(uuid))); + businessServiceVsUuidsBasedOnSearchCriteria.put(businessService, + new ArrayList<>(Collections.singletonList(uuid))); } } }); }); - }else{ + } else { businessServiceVsStateUuids.keySet().forEach(businessService -> { HashSet setOfUuids = businessServiceVsStateUuids.get(businessService); businessServiceVsUuidsBasedOnSearchCriteria.put(businessService, new ArrayList<>(setOfUuids)); }); } - - List businessServices = new ArrayList<>(businessServiceVsUuidsBasedOnSearchCriteria.keySet()); Integer totalCount = 0; // Fetch slot percentage only once here !!!!!!!!!! - - for(int i = 0; i < businessServices.size(); i++){ + for (int i = 0; i < businessServices.size(); i++) { String businessService = businessServices.get(i); Long businessServiceSla = businessServiceSlaMap.get(businessService); - inboxRequest.getInbox().getProcessSearchCriteria().setStatus(businessServiceVsUuidsBasedOnSearchCriteria.get(businessService)); + inboxRequest.getInbox().getProcessSearchCriteria() + .setStatus(businessServiceVsUuidsBasedOnSearchCriteria.get(businessService)); Map finalQueryBody = queryBuilder.getNearingSlaCountQuery(inboxRequest, businessServiceSla); StringBuilder uri = getURI(indexName, COUNT_PATH); - Map response = (Map) serviceRequestRepository.fetchResult(uri, finalQueryBody); + Map response = (Map) serviceRequestRepository.fetchResult(uri, + finalQueryBody); Integer currentCount = 0; - if(response.containsKey(COUNT_CONSTANT)){ + if (response.containsKey(COUNT_CONSTANT)) { currentCount = (Integer) response.get(COUNT_CONSTANT); - }else{ + } else { throw new CustomException("INBOX_COUNT_ERR", "Error occurred while executing ES count query"); } totalCount += currentCount; @@ -348,8 +417,7 @@ public Integer getApplicationsNearingSlaCount(InboxRequest inboxRequest, String } - - private StringBuilder getURI(String indexName, String endpoint){ + private StringBuilder getURI(String indexName, String endpoint) { StringBuilder uri = new StringBuilder(config.getIndexServiceHost()); uri.append(indexName); uri.append(endpoint); @@ -373,9 +441,8 @@ private List getDataFromSimpleSearch(SearchRequest searchRequest, String i Map finalQueryBody = queryBuilder.getESQueryForSimpleSearch(searchRequest, Boolean.TRUE); try { String q = mapper.writeValueAsString(finalQueryBody); - log.info("Query: "+q); - } - catch (Exception e){ + log.info("Query: " + q); + } catch (Exception e) { e.printStackTrace(); } StringBuilder uri = getURI(index, SEARCH_PATH); @@ -385,9 +452,9 @@ private List getDataFromSimpleSearch(SearchRequest searchRequest, String i } private List parseSearchResponseForSimpleSearch(Object result) { - Map hits = (Map)((Map) result).get(HITS); + Map hits = (Map) ((Map) result).get(HITS); List> nestedHits = (List>) hits.get(HITS); - if(CollectionUtils.isEmpty(nestedHits)){ + if (CollectionUtils.isEmpty(nestedHits)) { return new ArrayList<>(); } @@ -395,7 +462,7 @@ private List parseSearchResponseForSimpleSearch(Object result) { nestedHits.forEach(hit -> { Data data = new Data(); Map sourceObject = (Map) hit.get(SOURCE_KEY); - Map dataObject = (Map)sourceObject.get(DATA_KEY); + Map dataObject = (Map) sourceObject.get(DATA_KEY); List fields = getFieldsFromDataObject(dataObject); data.setFields(fields); dataList.add(data); @@ -414,7 +481,7 @@ private List getFieldsFromDataObject(Map dataObject) { field.setValue(flattenedDataObject.get(key)); listOfFields.add(field); }); - }catch (JsonProcessingException ex){ + } catch (JsonProcessingException ex) { throw new CustomException("EG_INBOX_GET_FIELDS_ERR", "Error while processing JSON."); } return listOfFields; diff --git a/accelerators/inbox/src/main/java/org/egov/inbox/service/WorkflowService.java b/accelerators/inbox/src/main/java/org/egov/inbox/service/WorkflowService.java index 9efabe3e3e7..6c2172779a5 100644 --- a/accelerators/inbox/src/main/java/org/egov/inbox/service/WorkflowService.java +++ b/accelerators/inbox/src/main/java/org/egov/inbox/service/WorkflowService.java @@ -19,10 +19,6 @@ import org.egov.inbox.util.FSMConstants; import org.egov.inbox.web.model.InboxRequest; import org.egov.inbox.web.model.RequestInfoWrapper; -import org.egov.inbox.web.model.workflow.BusinessService; -import org.egov.inbox.web.model.workflow.BusinessServiceResponse; -import org.egov.inbox.web.model.workflow.ProcessInstanceResponse; -import org.egov.inbox.web.model.workflow.ProcessInstanceSearchCriteria; import org.egov.tracer.model.CustomException; import org.egov.inbox.web.model.workflow.*; import org.springframework.beans.factory.annotation.Autowired; @@ -34,7 +30,10 @@ import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; + @Service +@Slf4j public class WorkflowService { private InboxConfiguration config; @@ -54,7 +53,7 @@ public WorkflowService(InboxConfiguration config, ServiceRequestRepository servi public Integer getProcessCount(String tenantId, RequestInfo requestInfo, ProcessInstanceSearchCriteria criteria) { List listOfBusinessServices = new ArrayList<>(criteria.getBusinessService()); Integer processCount = 0; - for(String businessSrv : listOfBusinessServices) { + for (String businessSrv : listOfBusinessServices) { criteria.setBusinessService(Collections.singletonList(businessSrv)); StringBuilder url = new StringBuilder(config.getWorkflowHost()); url.append(config.getProcessCountPath()); @@ -67,18 +66,20 @@ public Integer getProcessCount(String tenantId, RequestInfo requestInfo, Process try { response = mapper.convertValue(result, Integer.class); } catch (IllegalArgumentException e) { - throw new CustomException(ErrorConstants.PARSING_ERROR, "Failed to parse response of ProcessInstance Count"); + throw new CustomException(ErrorConstants.PARSING_ERROR, + "Failed to parse response of ProcessInstance Count"); } processCount += response; } criteria.setBusinessService(listOfBusinessServices); return processCount; } - - public Integer getNearingSlaProcessCount(String tenantId, RequestInfo requestInfo, ProcessInstanceSearchCriteria criteria) { + + public Integer getNearingSlaProcessCount(String tenantId, RequestInfo requestInfo, + ProcessInstanceSearchCriteria criteria) { List listOfBusinessServices = new ArrayList<>(criteria.getBusinessService()); Integer processCount = 0; - for(String businessSrv : listOfBusinessServices) { + for (String businessSrv : listOfBusinessServices) { criteria.setBusinessService(Collections.singletonList(businessSrv)); StringBuilder url = new StringBuilder(config.getWorkflowHost()); url.append(config.getNearingSlaProcessCountPath()); @@ -91,67 +92,74 @@ public Integer getNearingSlaProcessCount(String tenantId, RequestInfo requestInf try { response = mapper.convertValue(result, Integer.class); } catch (IllegalArgumentException e) { - throw new CustomException(ErrorConstants.PARSING_ERROR, "Failed to parse response of ProcessInstance Count"); + throw new CustomException(ErrorConstants.PARSING_ERROR, + "Failed to parse response of ProcessInstance Count"); } processCount += response; } criteria.setBusinessService(listOfBusinessServices); return processCount; } - - public List> getProcessStatusCount(RequestInfo requestInfo, - ProcessInstanceSearchCriteria criteria) { - List listOfBusinessServices = new ArrayList<>(criteria.getBusinessService()); - List> finalResponse = null; - for (String businessSrv : listOfBusinessServices) { - criteria.setBusinessService(Collections.singletonList(businessSrv)); - StringBuilder url = new StringBuilder(config.getWorkflowHost()); - url.append(config.getProcessStatusCountPath()); - criteria.setIsProcessCountCall(true); - // For BPA having large request, so that it was sending from the body - List roles = requestInfo.getUserInfo().getRoles().stream().map(Role::getCode).collect(Collectors.toList()); - if ((!ObjectUtils.isEmpty(criteria.getModuleName()) && !criteria.getModuleName().equalsIgnoreCase(BpaConstants.BPA)) - || (!ObjectUtils.isEmpty(criteria.getModuleName()) && - criteria.getModuleName().equalsIgnoreCase(BpaConstants.BPA) && !roles.contains(BpaConstants.CITIZEN))) - url = this.buildWorkflowUrl(criteria, url, Boolean.FALSE); - if (requestInfo.getUserInfo().getRoles().get(0).getCode().equals(FSMConstants.FSM_DSO)) { - url.append("&assignee=").append(requestInfo.getUserInfo().getUuid()); - } - - if (criteria != null && !ObjectUtils.isEmpty(criteria.getModuleName()) && criteria.getModuleName().equalsIgnoreCase(BpaConstants.BPA) - && roles.contains(BpaConstants.CITIZEN)) { - List inputBusinessSrvs = new ArrayList<>(criteria.getBusinessService()); - criteria.setBusinessService(null); - Map statusRequest = new HashMap<>(); - statusRequest.put("RequestInfo", requestInfo); - statusRequest.put("ProcessInstanceSearchCriteria", criteria); - finalResponse = (List>) serviceRequestRepository.fetchListResult(url, statusRequest); - criteria.setBusinessService(inputBusinessSrvs); - } else { - RequestInfoWrapper requestInfoWrapper = RequestInfoWrapper.builder().requestInfo(requestInfo).build(); - if (finalResponse == null) { - finalResponse = (List>) serviceRequestRepository.fetchListResult(url, - requestInfoWrapper); - } else { - finalResponse.addAll( - (List>) serviceRequestRepository.fetchListResult(url, requestInfoWrapper)); - } - } - } - criteria.setBusinessService(listOfBusinessServices); - return finalResponse; - } - + + public List> getProcessStatusCount(RequestInfo requestInfo, + ProcessInstanceSearchCriteria criteria) { + List listOfBusinessServices = new ArrayList<>(criteria.getBusinessService()); + List> finalResponse = null; + for (String businessSrv : listOfBusinessServices) { + criteria.setBusinessService(Collections.singletonList(businessSrv)); + StringBuilder url = new StringBuilder(config.getWorkflowHost()); + url.append(config.getProcessStatusCountPath()); + criteria.setIsProcessCountCall(true); + // For BPA having large request, so that it was sending from the body + List roles = requestInfo.getUserInfo().getRoles().stream().map(Role::getCode) + .collect(Collectors.toList()); + if ((!ObjectUtils.isEmpty(criteria.getModuleName()) + && !criteria.getModuleName().equalsIgnoreCase(BpaConstants.BPA)) + || (!ObjectUtils.isEmpty(criteria.getModuleName()) && + criteria.getModuleName().equalsIgnoreCase(BpaConstants.BPA) + && !roles.contains(BpaConstants.CITIZEN))) + url = this.buildWorkflowUrl(criteria, url, Boolean.FALSE); + if (requestInfo.getUserInfo().getRoles().get(0).getCode().equals(FSMConstants.FSM_DSO)) { + url.append("&assignee=").append(requestInfo.getUserInfo().getUuid()); + } + + if (criteria != null && !ObjectUtils.isEmpty(criteria.getModuleName()) + && criteria.getModuleName().equalsIgnoreCase(BpaConstants.BPA) + && roles.contains(BpaConstants.CITIZEN)) { + List inputBusinessSrvs = new ArrayList<>(criteria.getBusinessService()); + criteria.setBusinessService(null); + Map statusRequest = new HashMap<>(); + statusRequest.put("RequestInfo", requestInfo); + statusRequest.put("ProcessInstanceSearchCriteria", criteria); + finalResponse = (List>) serviceRequestRepository.fetchListResult(url, + statusRequest); + criteria.setBusinessService(inputBusinessSrvs); + } else { + RequestInfoWrapper requestInfoWrapper = RequestInfoWrapper.builder().requestInfo(requestInfo).build(); + if (finalResponse == null) { + finalResponse = (List>) serviceRequestRepository.fetchListResult(url, + requestInfoWrapper); + } else { + finalResponse.addAll( + (List>) serviceRequestRepository.fetchListResult(url, + requestInfoWrapper)); + } + } + } + criteria.setBusinessService(listOfBusinessServices); + return finalResponse; + } + public ProcessInstanceResponse getProcessInstance(ProcessInstanceSearchCriteria criteria, RequestInfo requestInfo) { StringBuilder url = new StringBuilder(config.getWorkflowHost()); - url.append( config.getProcessSearchPath()); + url.append(config.getProcessSearchPath()); url = this.buildWorkflowUrl(criteria, url, Boolean.FALSE); - if(requestInfo.getUserInfo().getRoles().get(0).getCode().equals(FSMConstants.FSM_DSO)) { - url.append("&assignee=").append( requestInfo.getUserInfo().getUuid()); - } + if (requestInfo.getUserInfo().getRoles().get(0).getCode().equals(FSMConstants.FSM_DSO)) { + url.append("&assignee=").append(requestInfo.getUserInfo().getUuid()); + } RequestInfoWrapper requestInfoWrapper = RequestInfoWrapper.builder().requestInfo(requestInfo).build(); Object result = serviceRequestRepository.fetchResult(url, requestInfoWrapper); - ProcessInstanceResponse resposne =null; + ProcessInstanceResponse resposne = null; try { resposne = mapper.convertValue(result, ProcessInstanceResponse.class); } catch (IllegalArgumentException e) { @@ -159,15 +167,16 @@ public ProcessInstanceResponse getProcessInstance(ProcessInstanceSearchCriteria } return resposne; } + /** * Get the workflow config for the given tenant * * @param tenantId - * id of the tenant + * id of the tenant * @param requestInfo - * The RequestInfo object of the request + * The RequestInfo object of the request * @param businessServiceName - * businessService code + * businessService code * @return BusinessService for the the given tenantId */ public BusinessService getBusinessService(String tenantId, RequestInfo requestInfo, String businessServceName) { @@ -183,13 +192,12 @@ public BusinessService getBusinessService(String tenantId, RequestInfo requestIn return response.getBusinessServices().get(0); } - - @Cacheable(value="businessServices") + @Cacheable(value = "businessServices") public List getBusinessServices(InboxRequest request) { - String tenantId = request.getInbox().getTenantId(); - RequestInfo requestInfo = request.getRequestInfo() ; + String tenantId = request.getInbox().getProcessSearchCriteria().getTenantId().split("\\.")[0]; + RequestInfo requestInfo = request.getRequestInfo(); List businessServicesCodes = request.getInbox().getProcessSearchCriteria().getBusinessService(); - String businessServiceList = String.join(",",businessServicesCodes); + String businessServiceList = String.join(",", businessServicesCodes); StringBuilder url = getSearchURLWithParams(tenantId, businessServiceList); RequestInfoWrapper requestInfoWrapper = RequestInfoWrapper.builder().requestInfo(requestInfo).build(); Object result = serviceRequestRepository.fetchResult(url, requestInfoWrapper); @@ -202,30 +210,27 @@ public List getBusinessServices(InboxRequest request) { return response.getBusinessServices(); } + public Map getStatusIdToBusinessServiceMap(List businessServices) { - public Map getStatusIdToBusinessServiceMap(List businessServices){ - - Map statusIdToBusinessServiceMap = new HashMap<>(); + Map statusIdToBusinessServiceMap = new HashMap<>(); businessServices.forEach(businessService -> { businessService.getStates().forEach(state -> { statusIdToBusinessServiceMap.put(state.getUuid(), businessService.getBusinessService()); - } - ); + }); }); return statusIdToBusinessServiceMap; } - public Map getApplicationStatusIdToStatusMap(List businessServices){ + public Map getApplicationStatusIdToStatusMap(List businessServices) { - Map statusIdToApplicationStatusMap = new HashMap<>(); + Map statusIdToApplicationStatusMap = new HashMap<>(); businessServices.forEach(businessService -> { businessService.getStates().forEach(state -> { statusIdToApplicationStatusMap.put(state.getUuid(), state.getApplicationStatus()); - } - ); + }); }); return statusIdToApplicationStatusMap; @@ -233,59 +238,61 @@ public Map getApplicationStatusIdToStatusMap(List getStatusIdToStateMap(List businessServices) { - Map statusIdToStateMap = new HashMap<>(); + Map statusIdToStateMap = new HashMap<>(); businessServices.forEach(businessService -> { businessService.getStates().forEach(state -> { - statusIdToStateMap.put(state.getUuid(), state.getState()); - } - ); + statusIdToStateMap.put(state.getUuid(), state.getState()); + }); }); return statusIdToStateMap; } - - private StringBuilder buildWorkflowUrl(ProcessInstanceSearchCriteria criteria, StringBuilder url,boolean noStatus) { + private StringBuilder buildWorkflowUrl(ProcessInstanceSearchCriteria criteria, StringBuilder url, + boolean noStatus) { url.append("?tenantId=").append(criteria.getTenantId()); - if(!CollectionUtils.isEmpty(criteria.getStatus()) && noStatus == Boolean.FALSE) { - url.append("&status=").append(StringUtils.arrayToDelimitedString(criteria.getStatus().toArray(),",")); + if (!CollectionUtils.isEmpty(criteria.getStatus()) && noStatus == Boolean.FALSE) { + url.append("&status=").append(StringUtils.arrayToDelimitedString(criteria.getStatus().toArray(), ",")); } - - if(!CollectionUtils.isEmpty(criteria.getBusinessIds())) { - url.append("&businessIds=").append(StringUtils.arrayToDelimitedString(criteria.getBusinessIds().toArray(),",")); + + if (!CollectionUtils.isEmpty(criteria.getBusinessIds())) { + url.append("&businessIds=") + .append(StringUtils.arrayToDelimitedString(criteria.getBusinessIds().toArray(), ",")); } - - if(!CollectionUtils.isEmpty(criteria.getIds())) { - url.append("&ids=").append(StringUtils.arrayToDelimitedString(criteria.getIds().toArray(),",")); + + if (!CollectionUtils.isEmpty(criteria.getIds())) { + url.append("&ids=").append(StringUtils.arrayToDelimitedString(criteria.getIds().toArray(), ",")); } - if(!StringUtils.isEmpty(criteria.getAssignee())) { - url.append("&assignee=").append( criteria.getAssignee()); + if (!StringUtils.isEmpty(criteria.getAssignee())) { + url.append("&assignee=").append(criteria.getAssignee()); } - if(criteria.getHistory() != null) { - url.append("&history=").append( criteria.getHistory()); + if (criteria.getHistory() != null) { + url.append("&history=").append(criteria.getHistory()); } - if(criteria.getFromDate() != null) { - url.append("&fromDate=").append( criteria.getFromDate()); + if (criteria.getFromDate() != null) { + url.append("&fromDate=").append(criteria.getFromDate()); } - if(criteria.getToDate() != null) { - url.append("&toDate=").append( criteria.getToDate()); + if (criteria.getToDate() != null) { + url.append("&toDate=").append(criteria.getToDate()); } - if(!StringUtils.isEmpty(criteria.getModuleName())) { - url.append("&moduleName=").append( criteria.getModuleName()); + if (!StringUtils.isEmpty(criteria.getModuleName())) { + url.append("&moduleName=").append(criteria.getModuleName()); } - if(criteria.getIsProcessCountCall() || ObjectUtils.isEmpty(criteria.getModuleName()) && !StringUtils.isEmpty(criteria.getBusinessService())) { - url.append("&businessService=").append( StringUtils.arrayToDelimitedString(criteria.getBusinessService().toArray(),",")); + if (criteria.getIsProcessCountCall() || ObjectUtils.isEmpty(criteria.getModuleName()) + && !StringUtils.isEmpty(criteria.getBusinessService())) { + url.append("&businessService=") + .append(StringUtils.arrayToDelimitedString(criteria.getBusinessService().toArray(), ",")); } - if(!StringUtils.isEmpty(criteria.getLimit())) { - url.append("&limit=").append( criteria.getLimit()); + if (!StringUtils.isEmpty(criteria.getLimit())) { + url.append("&limit=").append(criteria.getLimit()); } - if(!StringUtils.isEmpty(criteria.getOffset())) { - url.append("&offset=").append( criteria.getOffset()); + if (!StringUtils.isEmpty(criteria.getOffset())) { + url.append("&offset=").append(criteria.getOffset()); } - + return url; } @@ -293,127 +300,130 @@ private StringBuilder buildWorkflowUrl(ProcessInstanceSearchCriteria criteria, S * Creates url for search based on given tenantId * * @param tenantId - * The tenantId for which url is generated + * The tenantId for which url is generated * @return The search url */ private StringBuilder getSearchURLWithParams(String tenantId, String businessService) { StringBuilder url = new StringBuilder(config.getWorkflowHost()); - - - + if (businessService != null) { url.append(config.getBusinessServiceSearchPath()); url.append("?businessServices="); url.append(businessService); - } - + } + url.append("&tenantId="); url.append(tenantId); - + return url; } - + + /** + * Gets the list of status on which user from requestInfo can take action upon + * + * @param requestInfo The RequestInfo Object of the request + * @param businessServices List of all businessServices + * @return List of status on which user from requestInfo can take action upon + */ + + public HashMap getActionableStatusesForRole(RequestInfo requestInfo, + List businessServices, ProcessInstanceSearchCriteria criteria) { + + Map> tenantIdToUserRolesMap = getTenantIdToUserRolesMap(requestInfo); + Map> tenantIdToBuisnessSevicesMap = getTenantIdToBuisnessSevicesMap( + businessServices); + Map> stateToRoleMap = getStateToRoleMap(businessServices); + HashMap actionableStatuses = new HashMap<>(); + + for (Map.Entry> entry : tenantIdToUserRolesMap.entrySet()) { + + String statelevelTenantId = entry.getKey().split("\\.")[0]; + + if (entry.getKey().equals(criteria.getTenantId()) + || (entry.getValue().contains(FSMConstants.FSM_DSO) && entry.getKey().equals(statelevelTenantId))) { + List businessServicesByTenantId = new ArrayList(); + if (entry.getKey().split("\\.").length == 1) { + businessServicesByTenantId = tenantIdToBuisnessSevicesMap.get(criteria.getTenantId()); + } else { + businessServicesByTenantId = tenantIdToBuisnessSevicesMap.get(entry.getKey()); + } + if (businessServicesByTenantId != null) { + businessServicesByTenantId.forEach(service -> { + List states = service.getStates(); + states.forEach(state -> { + Set stateRoles = stateToRoleMap.get(state.getUuid()); + if (!CollectionUtils.isEmpty(stateRoles) + && !Collections.disjoint(stateRoles, entry.getValue())) { + actionableStatuses.put(state.getUuid(), state.getApplicationStatus()); + } + + }); + }); + } + + } + } + return actionableStatuses; + } + + /** + * Gets the map of tenantId to roles the user is assigned + * + * @param requestInfo RequestInfo of the request + * @return Map of tenantId to roles for user in the requestInfo + */ + public Map> getTenantIdToUserRolesMap(RequestInfo requestInfo) { + Map> tenantIdToUserRoles = new HashMap<>(); + requestInfo.getUserInfo().getRoles().forEach(role -> { + if (tenantIdToUserRoles.containsKey(role.getTenantId().split("\\.")[0])) { + tenantIdToUserRoles.get(role.getTenantId().split("\\.")[0]).add(role.getCode()); + } else { + List roleCodes = new LinkedList<>(); + roleCodes.add(role.getCode()); + tenantIdToUserRoles.put(role.getTenantId().split("\\.")[0], roleCodes); + } + + }); + log.info("tenantIdToUserRoles:" + tenantIdToUserRoles.toString()); + return tenantIdToUserRoles; + } + + public Map> getTenantIdToBuisnessSevicesMap(List businessServices) { + Map> tenantIdToBuisnessSevicesMap = new HashMap<>(); + businessServices.forEach(businessService -> { + if (tenantIdToBuisnessSevicesMap.containsKey(businessService.getTenantId())) { + tenantIdToBuisnessSevicesMap.get(businessService.getTenantId()).add(businessService); + } else { + List businessServiceList = new LinkedList<>(); + businessServiceList.add(businessService); + tenantIdToBuisnessSevicesMap.put(businessService.getTenantId(), businessServiceList); + } + }); + return tenantIdToBuisnessSevicesMap; + } + /** - * Gets the list of status on which user from requestInfo can take action upon - * @param requestInfo The RequestInfo Object of the request - * @param businessServices List of all businessServices - * @return List of status on which user from requestInfo can take action upon - */ - - public HashMap getActionableStatusesForRole(RequestInfo requestInfo, List businessServices,ProcessInstanceSearchCriteria criteria){ - - String tenantId; - List userRoleCodes; - Map> tenantIdToUserRolesMap = getTenantIdToUserRolesMap(requestInfo); - Map> tenantIdToBuisnessSevicesMap = getTenantIdToBuisnessSevicesMap(businessServices); - Map> stateToRoleMap = getStateToRoleMap(businessServices); - HashMap actionableStatuses = new HashMap<>(); - - for(Map.Entry> entry : tenantIdToUserRolesMap.entrySet()){ - - String statelevelTenantId=entry.getKey().split("\\.")[0]; - - if(entry.getKey().equals(criteria.getTenantId()) || (entry.getValue().contains(FSMConstants.FSM_DSO) && entry.getKey().equals(statelevelTenantId)) ){ - List businessServicesByTenantId = new ArrayList(); - if(entry.getKey().split("\\.").length==1){ - businessServicesByTenantId = tenantIdToBuisnessSevicesMap.get(criteria.getTenantId()); - }else{ - businessServicesByTenantId = tenantIdToBuisnessSevicesMap.get(entry.getKey()); - } - if(businessServicesByTenantId != null ) { - businessServicesByTenantId.forEach(service -> { - List states = service.getStates(); - states.forEach(state -> { - Set stateRoles = stateToRoleMap.get(state.getUuid()); - if(!CollectionUtils.isEmpty(stateRoles) && !Collections.disjoint(stateRoles,entry.getValue())){ - actionableStatuses.put(state.getUuid(), state.getApplicationStatus()); - } - - }); - }); - } - - } - } - return actionableStatuses; - } - - /** - * Gets the map of tenantId to roles the user is assigned - * @param requestInfo RequestInfo of the request - * @return Map of tenantId to roles for user in the requestInfo - */ - public Map> getTenantIdToUserRolesMap(RequestInfo requestInfo){ - Map> tenantIdToUserRoles = new HashMap<>(); - requestInfo.getUserInfo().getRoles().forEach(role -> { - if(tenantIdToUserRoles.containsKey(role.getTenantId())){ - tenantIdToUserRoles.get(role.getTenantId()).add(role.getCode()); - } - else { - List roleCodes = new LinkedList<>(); - roleCodes.add(role.getCode()); - tenantIdToUserRoles.put(role.getTenantId(),roleCodes); - } - - }); - return tenantIdToUserRoles; - } - - public Map> getTenantIdToBuisnessSevicesMap(List businessServices){ - Map> tenantIdToBuisnessSevicesMap = new HashMap<>(); - businessServices.forEach(businessService -> { - if(tenantIdToBuisnessSevicesMap.containsKey(businessService.getTenantId())){ - tenantIdToBuisnessSevicesMap.get(businessService.getTenantId()).add(businessService); - } - else { - List businessServiceList = new LinkedList<>(); - businessServiceList.add(businessService); - tenantIdToBuisnessSevicesMap.put(businessService.getTenantId(),businessServiceList); - } - }); - return tenantIdToBuisnessSevicesMap; - } - - /** - * Creates a map of status to roles who can take actions on it for all businessService - * @param businessServices The list of businessServices - * @return Map of status to roles which can take action on it for all businessService - */ - public Map> getStateToRoleMap(List businessServices){ - Map> stateToRolesMap = new HashMap<>(); - businessServices.forEach(businessService -> { - for(State state : businessService.getStates()){ - HashSet roles = new HashSet<>(); - if(!CollectionUtils.isEmpty(state.getActions())){ - state.getActions().forEach(action -> { - roles.addAll(action.getRoles()); - }); - } - stateToRolesMap.put(state.getUuid(),roles); - } - }); - return stateToRolesMap; - } - - + * Creates a map of status to roles who can take actions on it for all + * businessService + * + * @param businessServices The list of businessServices + * @return Map of status to roles which can take action on it for all + * businessService + */ + public Map> getStateToRoleMap(List businessServices) { + Map> stateToRolesMap = new HashMap<>(); + businessServices.forEach(businessService -> { + for (State state : businessService.getStates()) { + HashSet roles = new HashSet<>(); + if (!CollectionUtils.isEmpty(state.getActions())) { + state.getActions().forEach(action -> { + roles.addAll(action.getRoles()); + }); + } + stateToRolesMap.put(state.getUuid(), roles); + } + }); + return stateToRolesMap; + } + } diff --git a/accelerators/inbox/src/main/resources/application.properties b/accelerators/inbox/src/main/resources/application.properties index 407a655ee9b..27834b7a6eb 100644 --- a/accelerators/inbox/src/main/resources/application.properties +++ b/accelerators/inbox/src/main/resources/application.properties @@ -1,5 +1,5 @@ -server.context-path=/inbox -server.servlet.context-path=/inbox +server.context-path=/inbox-v2 +server.servlet.context-path=/inbox-v2 server.port=9011 app.timezone=GMT+5:30 @@ -102,7 +102,7 @@ egov.es.password=TUSYns9mEcRPy77n services.esindexer.host=http://localhost:9200/ egov.services.esindexer.host.search=/_search management.health.elasticsearch.enabled=false -parent.level.tenant.id=pb +parent.level.tenant.id=pg egov.internal.microservice.user.uuid=b5b2ac70-d347-4339-98f0-5349ce25f99f @@ -122,5 +122,5 @@ es.search.default.sort.order=desc inbox.water.search.allowed=true #state level tenant -state.level.tenant.id=pb -cache.expiry.minutes=10 \ No newline at end of file +state.level.tenant.id=pg +cache.expiry.minutes=10 diff --git a/build/build-config.yml b/build/build-config.yml index 40657af6ad4..69e2821e3f4 100644 --- a/build/build-config.yml +++ b/build/build-config.yml @@ -403,7 +403,7 @@ config: - name: "builds/Digit-Core/accelerators/inbox" build: - work-dir: "accelerators/inbox" - image-name: "inbox" + image-name: "inbox-v2" dockerfile: "build/maven/Dockerfile" - name: "builds/Digit-Core/core-services/service-request"