Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
15 kB
1
Indexable
Never
public OrganisationResultSetWithTotal findOrganisationFromES(String token, Integer pageIndex, Integer pageSize, String timeZone,
                                                                 OrganisationFilterDTO organisationFilterDTO, Boolean isGetAll) throws IOException, ServiceException
    {

        OrganisationResultSetWithTotal organisationResultSetWithTotal = new OrganisationResultSetWithTotal();
        boolean isCrmFilter = false;
        Enterprise enterprise = getEnterpriseFromToken(token);
        User user = getUserFromToken(token);
        ViettelCustomerFilterDTO viettelCustomerFilterDTO = organisationFilterDTO.getViettelCustomerFilterDTO();
        viettelCustomerFilterDTO.setManagerCode(user.getStaffCode());

//        RestHighLevelClient client = convertSearchFieldService.createESClient();
        String accountIndex = convertSearchFieldService.chooseIndex(ObjectType.ACCOUNT, enterprise.getUuid().toString());
        SearchRequest searchRequest = new SearchRequest(accountIndex);
        CountRequest countRequest = new CountRequest(accountIndex);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.from(pageIndex * pageSize);
        searchSourceBuilder.size(pageSize);
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery()
                .filter(QueryBuilders.matchQuery("enterprise_id.keyword", enterprise.getUuid().toString()).operator(Operator.AND))
                .filter(QueryBuilders.matchQuery("deleted", FALSE).operator(Operator.AND));

        String searchText = organisationFilterDTO.getFtsTerms();
        if (StringUtils.isNotEmpty(organisationFilterDTO.getFtsTerms()))
        {
            fullTextSearchQueryBuilderES(queryBuilder, searchText);
        }

        if (organisationFilterDTO.getRoleFilterType() != null)
        {
            switch (organisationFilterDTO.getRoleFilterType())
            {
                case "Person": // For Person, using UserId
                    queryBuilder = queryBuilder.filter(QueryBuilders.nestedQuery("user_account", QueryBuilders.matchQuery("user_account.user_id.keyword", organisationFilterDTO.getRoleFilterValue()).operator(Operator.AND), ScoreMode.Avg));
                    break;
                case "Unit": // This case for Unit, using UnitId
                    queryBuilder = queryBuilder.filter(QueryBuilders.nestedQuery("user_account", QueryBuilders.matchQuery("user_account.unit_id.keyword", organisationFilterDTO.getRoleFilterValue()).operator(Operator.AND), ScoreMode.Avg));
                    break;
            }
        }

        boolean ignoreOrderStatement = false;
        boolean isFilterFavorite = false;
        if (organisationFilterDTO.getCustomFilter() != null)
        {
            switch (organisationFilterDTO.getCustomFilter())
            {
                case "favorite":
                    isFilterFavorite = true;
//                    ignoreOrderStatement = true;
                    queryBuilder = queryBuilder.filter(QueryBuilders.nestedQuery(ORGANISATION_CUSTOM_DATA, QueryBuilders.boolQuery()
                            .must(QueryBuilders.boolQuery()
                                    .must(QueryBuilders.existsQuery(ORGANISATION_CUSTOM_DATA_USER_ID))
                                    .must(QueryBuilders.matchQuery(ORGANISATION_CUSTOM_DATA_USER_ID, user.getUuid().toString()).operator(Operator.AND)))
                            .must(QueryBuilders.matchQuery("organisation_custom_data.is_favorite", "true").operator(Operator.AND)), ScoreMode.Avg));
                    break;
                case "recent":
                    ignoreOrderStatement = true;
                    queryBuilder = queryBuilder.filter(QueryBuilders.nestedQuery(ORGANISATION_CUSTOM_DATA, QueryBuilders.boolQuery()
                            .must(QueryBuilders.boolQuery()
                                    .must(QueryBuilders.existsQuery(ORGANISATION_CUSTOM_DATA_USER_ID))
                                    .must(QueryBuilders.matchQuery(ORGANISATION_CUSTOM_DATA_USER_ID, user.getUuid().toString()).operator(Operator.AND)))
                            .must(QueryBuilders.existsQuery("organisation_custom_data.last_viewed")), ScoreMode.Avg));
                    FieldSortBuilder fieldSortBuilder = new FieldSortBuilder("organisation_custom_data.last_viewed");
                    fieldSortBuilder.setNestedFilter(QueryBuilders.matchQuery(ORGANISATION_CUSTOM_DATA_USER_ID, user.getUuid().toString()));
                    fieldSortBuilder.setNestedPath(ORGANISATION_CUSTOM_DATA);
                    fieldSortBuilder.order(SortOrder.DESC);

                    searchSourceBuilder.sort(fieldSortBuilder);
                    break;
                case "alphabetical":
                    ignoreOrderStatement = true;
                    searchSourceBuilder.sort(NAME_KEY_WORD, SortOrder.ASC);
                    break;
                case "active":
                default:
            }
        }

        BoolQueryBuilder queryBuilderForAS = new BoolQueryBuilder();
        if (!organisationFilterDTO.getSearchFieldDTOList().isEmpty())
        {
            queryBuilderForAS = convertSearchFieldService.convertToQueryES(ObjectType.ACCOUNT.toString(), organisationFilterDTO.getSearchFieldDTOList(), timeZone);
        }

        queryBuilder = queryBuilder.filter(queryBuilderForAS);

        List<String> vatNumbers = new ArrayList<>();
        if (!mockData)
        {
            if (viettelCustomerFilterDTO.getProgramId() != null)
            {
                List<String> isdnFromGboc = organisationCommonService.findIsdnFromGboc(viettelCustomerFilterDTO);
                if (CollectionUtils.isEmpty(isdnFromGboc))
                {
                    return organisationResultSetWithTotal;
                }
                if ((viettelCustomerFilterDTO.getStartDate() != null && viettelCustomerFilterDTO.getEndDate() != null))
                {
                    InputLazyCustomerForSalesBoxExt inputLazyCustomerForSalesBoxExt = organisationCommonService.genInputLazyCustomerForSalesboxExt(user, isdnFromGboc, viettelCustomerFilterDTO);
                    vatNumbers.addAll(organisationCommonService.findIsdnFromCrm(inputLazyCustomerForSalesBoxExt, pageIndex, pageSize));
                    isCrmFilter = true;
                    organisationResultSetWithTotal.setTotalCount((long) organisationCommonService.countCustomerFromCrm(inputLazyCustomerForSalesBoxExt));
                }
                else
                {
                    vatNumbers.addAll(isdnFromGboc);
                }
            }
            else
            {
                if (viettelCustomerFilterDTO.getServiceType() != null || CollectionUtils.isNotEmpty(viettelCustomerFilterDTO.getServiceTypeList()))
                {
                    InputLazyCustomerForSalesBoxExt inputLazyCustomerForSalesBoxExt = organisationCommonService.genInputLazyCustomerForSalesboxExt(user, null, viettelCustomerFilterDTO);
                    vatNumbers.addAll(organisationCommonService.findIsdnFromCrm(inputLazyCustomerForSalesBoxExt, pageIndex, pageSize));
                    isCrmFilter = true;
                    organisationResultSetWithTotal.setTotalCount((long) organisationCommonService.countCustomerFromCrm(inputLazyCustomerForSalesBoxExt));
                }
            }
            if (isCrmFilter && CollectionUtils.isEmpty(vatNumbers))
            {
                return organisationResultSetWithTotal;
            }
        }

        if (StringUtils.isNotBlank(viettelCustomerFilterDTO.getTaxBusCust()))
        {
            vatNumbers.add(viettelCustomerFilterDTO.getTaxBusCust());
        }
        if (!vatNumbers.isEmpty())
        {
            queryBuilder.filter(QueryBuilders.termsQuery("vat_number.keyword", vatNumbers.stream()
                    .filter(org.apache.commons.lang3.StringUtils::isNotBlank).collect(Collectors.toList())));
        }
        if (StringUtils.isNotBlank(viettelCustomerFilterDTO.getProvince()))
        {
            BoolQueryBuilder filterByLocation = QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("province", viettelCustomerFilterDTO.getProvince()).operator(Operator.AND));

            if (StringUtils.isNotBlank(viettelCustomerFilterDTO.getDistrict()))
            {
                filterByLocation.must(QueryBuilders.matchQuery("district", viettelCustomerFilterDTO.getDistrict()).operator(Operator.AND));
            }
            if (StringUtils.isNotBlank(viettelCustomerFilterDTO.getPrecinct()))
            {
                filterByLocation.must(QueryBuilders.matchQuery("precinct", viettelCustomerFilterDTO.getPrecinct()).operator(Operator.AND));
            }

            queryBuilder.filter(filterByLocation);
        }
        if (!StringUtils.isBlank(viettelCustomerFilterDTO.getCustName()))
        {
            queryBuilder.filter(QueryBuilders.boolQuery()
                    .should(QueryBuilders.regexpQuery("name.key_word", ".*" + viettelCustomerFilterDTO.getCustName() + ".*"))
                    .should(QueryBuilders.regexpQuery("full_name.keyword", ".*" + viettelCustomerFilterDTO.getCustName() + ".*")));
        }

        if (!viettelCustomerFilterDTO.getMainBusiness().isEmpty())
        {
            queryBuilder = queryBuilder.filter(QueryBuilders.nestedQuery("custom_field", QueryBuilders.boolQuery()
                    .must(QueryBuilders.termsQuery("custom_field.cf_option_value_id.keyword", viettelCustomerFilterDTO.getMainBusiness()))
                    .must(QueryBuilders.matchQuery("custom_field.cf_is_checked", "true").operator(Operator.AND)), ScoreMode.Avg));
        }

        if (!StringUtils.isBlank(viettelCustomerFilterDTO.getBusinessTypeId()))
        {
            queryBuilder = queryBuilder.filter(QueryBuilders.matchQuery("type_id", viettelCustomerFilterDTO.getBusinessTypeId()));
        }

        if (!ignoreOrderStatement)
        {
            switch (organisationFilterDTO.getOrderBy())
            {
                case "numberActiveProspect":
                    searchSourceBuilder.sort("number_active_prospect", SortOrder.DESC);
                    searchSourceBuilder.sort(NAME_KEY_WORD);
                    break;
                case "numberTeamMember":
                    searchSourceBuilder.sort("number_team_member", SortOrder.DESC);
                    searchSourceBuilder.sort(NAME_KEY_WORD);
                    break;
                case "profit":
                    searchSourceBuilder.sort("won_profit", SortOrder.DESC);
                    searchSourceBuilder.sort(NAME_KEY_WORD);
                    break;
                case "grossPipe":
                    searchSourceBuilder.sort("gross_pipeline", SortOrder.DESC);
                    searchSourceBuilder.sort(NAME_KEY_WORD);
                    break;
                case "weightedPipe":
                    searchSourceBuilder.sort("net_pipeline", SortOrder.DESC);
                    searchSourceBuilder.sort(NAME_KEY_WORD);
                    break;
                case "nextMeeting":
                    searchSourceBuilder.sort("next_meeting_date", SortOrder.ASC);
                    searchSourceBuilder.sort(NAME_KEY_WORD);
                    break;
                case "nextTask":
                    searchSourceBuilder.sort("next_task_date", SortOrder.ASC);
                    searchSourceBuilder.sort(NAME_KEY_WORD);
                    break;
                case "Alphabetical":
                    searchSourceBuilder.sort(NAME_KEY_WORD, SortOrder.ASC);
                    break;
                case "latest":
                    searchSourceBuilder.sort("communication_history_latest.ch_start_date", SortOrder.DESC);
                    searchSourceBuilder.sort(NAME_KEY_WORD, SortOrder.ASC);
                    break;
                case "type":
                    searchSourceBuilder.sort("type_name.keyword", SortOrder.ASC);
                    searchSourceBuilder.sort(NAME_KEY_WORD, SortOrder.ASC);
                    break;
                case "industry":
                    searchSourceBuilder.sort("industry_name.keyword", SortOrder.ASC);
                    searchSourceBuilder.sort(NAME_KEY_WORD, SortOrder.ASC);
                    break;
                case "owner":
                    searchSourceBuilder.sort("owner_first_name.keyword", SortOrder.ASC);
                    searchSourceBuilder.sort("owner_last_name.keyword", SortOrder.ASC);
                    break;
                case "closedSales":
                default:
                    searchSourceBuilder.sort("order_intake", SortOrder.DESC);
                    searchSourceBuilder.sort(NAME_KEY_WORD, SortOrder.ASC);
            }
        }

        searchSourceBuilder.query(queryBuilder);
        searchRequest.source(searchSourceBuilder);
        countRequest.source(searchSourceBuilder);

        try
        {
            RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
            SearchResponse searchResponse = client.search(searchRequest, builder.build());
            CountResponse countResponse = client.count(countRequest, builder.build());

            SearchHit[] results = searchResponse.getHits().getHits();
            List<OrganisationElasticResponse> responseList = Arrays.stream(results).map(hit -> {
                String source = hit.getSourceAsString();
                OrganisationElasticResponse organisation = new OrganisationElasticResponse();
                try
                {
                    organisation = objectMapper.readValue(source, OrganisationElasticResponse.class);
                }
                catch (IOException e)
                {
                    logger.error("error mapping response: ", e);
                }
                return organisation;
            }).collect(Collectors.toList());
            List<OrganisationResultSet> organisationResultSetList;

            if (isFilterFavorite)
            {
                organisationResultSetList = responseList.stream().map(response -> response.convertToOrganisationResultSet(response, organisationFilterDTO.getRoleFilterValue(), organisationFilterDTO.getRoleFilterType(), user.getUuid().toString(), true)).collect(Collectors.toList());
            }
            else
            {
                organisationResultSetList = responseList.stream().map(response -> response.convertToOrganisationResultSet(response, organisationFilterDTO.getRoleFilterValue(), organisationFilterDTO.getRoleFilterType(), user.getUuid().toString(), false)).collect(Collectors.toList());
            }

            if (!isCrmFilter)
            {
                organisationResultSetWithTotal.setTotalCount(countResponse.getCount());
            }
            organisationResultSetWithTotal.setOrganisationResultSetList(organisationResultSetList);
        }
        catch (java.io.IOException e)
        {
            logger.info(e);
            e.getLocalizedMessage();
        }


        return organisationResultSetWithTotal;
    }