Rev 30716 | Rev 31507 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed
package com.spice.profitmandi.web.controller;import com.eclipsesource.json.Json;import com.eclipsesource.json.JsonArray;import com.eclipsesource.json.JsonObject;import com.eclipsesource.json.JsonValue;import com.google.gson.Gson;import com.google.gson.reflect.TypeToken;import com.mongodb.BasicDBObject;import com.mongodb.DBObject;import com.spice.profitmandi.common.enumuration.SchemeType;import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;import com.spice.profitmandi.common.model.ProfitMandiConstants;import com.spice.profitmandi.common.model.UserInfo;import com.spice.profitmandi.common.solr.SolrService;import com.spice.profitmandi.common.web.client.RestClient;import com.spice.profitmandi.common.web.util.ResponseSender;import com.spice.profitmandi.dao.entity.catalog.*;import com.spice.profitmandi.dao.entity.dtr.WebOffer;import com.spice.profitmandi.dao.entity.fofo.FofoStore;import com.spice.profitmandi.dao.entity.fofo.SuggestedPo;import com.spice.profitmandi.dao.entity.fofo.SuggestedPoDetail;import com.spice.profitmandi.dao.entity.inventory.SaholicCISTable;import com.spice.profitmandi.dao.entity.inventory.SaholicPOItem;import com.spice.profitmandi.dao.model.CreateOfferRequest;import com.spice.profitmandi.dao.model.UserCart;import com.spice.profitmandi.dao.repository.catalog.*;import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;import com.spice.profitmandi.dao.repository.dtr.Mongo;import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;import com.spice.profitmandi.dao.repository.dtr.WebOfferRepository;import com.spice.profitmandi.dao.repository.fofo.SuggestedPoDetailRepository;import com.spice.profitmandi.dao.repository.fofo.SuggestedPoRepository;import com.spice.profitmandi.dao.repository.inventory.SaholicCISTableRepository;import com.spice.profitmandi.service.authentication.RoleManager;import com.spice.profitmandi.service.inventory.*;import com.spice.profitmandi.service.pricecircular.PriceCircularItemModel;import com.spice.profitmandi.service.pricecircular.PriceCircularModel;import com.spice.profitmandi.service.pricecircular.PriceCircularService;import com.spice.profitmandi.service.pricing.PricingService;import com.spice.profitmandi.service.scheme.SchemeService;import com.spice.profitmandi.web.res.DealBrands;import com.spice.profitmandi.web.res.DealObjectResponse;import com.spice.profitmandi.web.res.DealsResponse;import io.swagger.annotations.ApiImplicitParam;import io.swagger.annotations.ApiImplicitParams;import io.swagger.annotations.ApiOperation;import org.apache.commons.lang3.StringUtils;import org.apache.http.conn.HttpHostConnectException;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import org.json.JSONArray;import org.json.JSONObject;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.http.HttpStatus;import org.springframework.http.MediaType;import org.springframework.http.ResponseEntity;import org.springframework.stereotype.Controller;import org.springframework.transaction.annotation.Transactional;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import javax.servlet.http.HttpServletRequest;import java.util.*;import java.util.concurrent.atomic.AtomicInteger;import java.util.stream.Collectors;@Controller@Transactional(rollbackFor = Throwable.class)public class DealsController {private static final Logger logger = LogManager.getLogger(DealsController.class);@Value("${python.api.host}")private String host;@Value("${new.solr.url}")private String solrUrl;@Value("${python.api.port}")private int port;@AutowiredRestClient restClient;@AutowiredSolrService solrService;@AutowiredInventoryService inventoryService;// This is now unused as we are not supporting multiple companies.@Value("${gadgetCops.invoice.cc}")private String[] ccGadgetCopInvoiceTo;@Autowiredprivate PricingService pricingService;@Autowiredprivate CategoryRepository categoryRepository;@Autowiredprivate SchemeService schemeService;@Autowiredprivate SaholicInventoryService saholicInventoryService;@Autowiredprivate Mongo mongoClient;@Autowiredprivate ItemBucketService itemBucketService;@Autowiredprivate UserAccountRepository userAccountRepository;@Autowiredprivate FofoStoreRepository fofoStoreRepository;@Autowiredprivate ResponseSender<?> responseSender;@Autowiredprivate TagListingRepository tagListingRepository;@Autowiredprivate ItemRepository itemRepository;@Autowiredprivate PriceCircularService priceCircularService;@Autowiredprivate RoleManager roleManagerService;@Autowiredprivate SuggestedPoDetailRepository monthlyPoDetailRepository;@Autowiredprivate SuggestedPoRepository suggestedPoRepository;@Autowiredprivate WebOfferRepository webOfferRepository;@Autowiredprivate ComboModelRepository comboModelRepository;@Autowiredprivate ComboMappedModelRepository comboMappedModelRepository;List<String> filterableParams = Arrays.asList("brand");@RequestMapping(value = "/fofo/buckets", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)public ResponseEntity<?> getBuckets(HttpServletRequest request) throws ProfitMandiBusinessException {logger.info("Request " + request.getParameterMap());return responseSender.ok(itemBucketService.getBuckets(Optional.of(true)));}@RequestMapping(value = "/fofo/bucket", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)public ResponseEntity<?> getBucketDetails(HttpServletRequest request, @RequestParam int id)throws ProfitMandiBusinessException {List<ItemQuantityPojo> iqPojo = itemBucketService.getBucketDetails(id);Map<Integer, Integer> itemIdsQtyMap = iqPojo.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x.getQuantity()));Set<Integer> catalogIds = itemRepository.selectByIds(itemIdsQtyMap.keySet()).stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet());RestClient rc = new RestClient();Map<String, String> params = new HashMap<>();List<String> mandatoryQ = new ArrayList<>();mandatoryQ.add(String.format("+catalogId_i:(%s) +{!parent which=\"id:catalog*\"}", StringUtils.join(catalogIds, " ")));params.put("start", "0");params.put("rows", "100");params.put("q", StringUtils.join(mandatoryQ, " "));params.put("fl", "*, [child parentFilter=id:catalog*]");params.put("wt", "json");String response = null;try {response = rc.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);} catch (HttpHostConnectException e) {throw new ProfitMandiBusinessException("", "", "Could not connect to host");}JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");JSONArray docs = solrResponseJSONObj.getJSONArray("docs");List<FofoCatalogResponse> dealResponse = getCatalogSingleSkuResponse(docs, itemIdsQtyMap, false);Bucket bucket = itemBucketService.getBuckets(Optional.of(true)).stream().filter(x -> x.getId() == id).collect(Collectors.toList()).get(0);bucket.setFofoCatalogResponses(dealResponse);return responseSender.ok(bucket);}@RequestMapping(value = "/fofo/suggestedPo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)public ResponseEntity<?> getSuggestedPo(HttpServletRequest request, @RequestParam int id)throws ProfitMandiBusinessException {List<SuggestedPoDetail> mpd = monthlyPoDetailRepository.selectByPoId(id);Map<Integer, Integer> itemIdsQtyMap = mpd.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x.getQuantity()));Set<Integer> catalogIds = itemRepository.selectByIds(itemIdsQtyMap.keySet()).stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet());RestClient rc = new RestClient();Map<String, String> params = new HashMap<>();List<String> mandatoryQ = new ArrayList<>();mandatoryQ.add(String.format("+catalogId_i:(%s) +{!parent which=\"id:catalog*\"}", StringUtils.join(catalogIds, " ")));params.put("start", "0");params.put("rows", "100");params.put("q", StringUtils.join(mandatoryQ, " "));params.put("fl", "*, [child parentFilter=id:catalog*]");params.put("wt", "json");String response = null;try {response = rc.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);} catch (HttpHostConnectException e) {throw new ProfitMandiBusinessException("", "", "Could not connect to host");}JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");JSONArray docs = solrResponseJSONObj.getJSONArray("docs");List<FofoCatalogResponse> dealResponse = getCatalogSingleSkuResponse(docs, itemIdsQtyMap, false);return responseSender.ok(dealResponse);}@RequestMapping(value = "/suggestedPo/status", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)@ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})@ApiOperation(value = "")public ResponseEntity<?> changeSuggestedPoStatus(HttpServletRequest request, @RequestParam int id)throws ProfitMandiBusinessException {SuggestedPo suggestedPo = suggestedPoRepository.selectById(id);suggestedPo.setStatus("closed");return responseSender.ok(true);}private String getCommaSeparateTags(int userId) {UserCart uc = userAccountRepository.getUserCart(userId);List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(uc.getUserId());List<String> strTagIds = new ArrayList<>();for (Integer tagId : tagIds) {strTagIds.add(String.valueOf(tagId));}return String.join(",", strTagIds);}@ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})@RequestMapping(value = "/fofo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)public ResponseEntity<?> getFofo(HttpServletRequest request,@RequestParam(value = "categoryId", required = false, defaultValue = "3") String categoryId,@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,@RequestParam(value = "sort", required = false) String sort,@RequestParam(value = "brand", required = false) String brand,@RequestParam(value = "subCategoryId", required = false) int subCategoryId,@RequestParam(value = "q", required = false) String queryTerm,@RequestParam(value = "hotDeal", required = false) boolean hotDeal) throws Throwable {List<FofoCatalogResponse> dealResponse = new ArrayList<>();UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");FofoStore fs = fofoStoreRepository.selectByRetailerId(userInfo.getRetailerId());sort = "w" + fs.getWarehouseId() + "_i desc";dealResponse = this.getCatalogResponse(solrService.getSolrDocs(queryTerm, categoryId, offset, limit, sort, brand, subCategoryId, hotDeal),hotDeal, userInfo.getRetailerId());logger.info("log me");return responseSender.ok(dealResponse);}@RequestMapping(value = "/online-deals", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)@ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})@ApiOperation(value = "Get online deals")public ResponseEntity<?> getOnlineDeals(HttpServletRequest request,@RequestParam(value = "categoryId") String categoryId, @RequestParam(value = "offset") String offset,@RequestParam(value = "limit") String limit, @RequestParam(value = "sort", required = false) String sort,@RequestParam(value = "direction", required = false) String direction,@RequestParam(value = "filterData", required = false) String filterData) throws Throwable {logger.info("Request " + request.getParameterMap());String response = null;int userId = (int) request.getAttribute("userId");String uri = "/deals/" + userId;RestClient rc = new RestClient();Map<String, String> params = new HashMap<>();params.put("offset", offset);params.put("limit", limit);params.put("categoryId", categoryId);params.put("direction", direction);params.put("sort", sort);params.put("source", "online");params.put("filterData", filterData);/** if (userInfo.getRoleNames().contains(RoleType.FOFO.toString())) {* params.put("tag_ids", getCommaSeparateTags(userId)); }*/List<Object> responseObject = new ArrayList<>();try {response = rc.get(SchemeType.HTTP, host, port, uri, params);} catch (HttpHostConnectException e) {throw new ProfitMandiBusinessException("", "", "Could not connect to host");}JsonArray result_json = Json.parse(response).asArray();for (JsonValue j : result_json) {// logger.info("res " + j.asArray());List<Object> innerObject = new ArrayList<>();for (JsonValue jsonObject : j.asArray()) {innerObject.add(toDealObject(jsonObject.asObject()));}if (innerObject.size() > 0) {responseObject.add(innerObject);}}return responseSender.ok(responseObject);}private Object toDealObject(JsonObject jsonObject) {if (jsonObject.get("dealObject") != null && jsonObject.get("dealObject").asInt() == 1) {return new Gson().fromJson(jsonObject.toString(), DealObjectResponse.class);}return new Gson().fromJson(jsonObject.toString(), DealsResponse.class);}@RequestMapping(value = ProfitMandiConstants.URL_BRANDS, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)@ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})@ApiOperation(value = "Get brand list and count for category")public ResponseEntity<?> getBrands(HttpServletRequest request,@RequestParam(value = "category_id") String category_id) throws ProfitMandiBusinessException {logger.info("Request " + request.getParameterMap());String response = null;// TODO: move to propertiesString uri = ProfitMandiConstants.URL_BRANDS;RestClient rc = new RestClient();Map<String, String> params = new HashMap<>();params.put("category_id", category_id);List<DealBrands> dealBrandsResponse = null;try {response = rc.get(SchemeType.HTTP, host, port, uri, params);} catch (HttpHostConnectException e) {throw new ProfitMandiBusinessException("", "", "Could not connect to host");}dealBrandsResponse = new Gson().fromJson(response, new TypeToken<List<DealBrands>>() {}.getType());return responseSender.ok(dealBrandsResponse);}@RequestMapping(value = ProfitMandiConstants.URL_UNIT_DEAL, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)@ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})@ApiOperation(value = "Get unit deal object")public ResponseEntity<?> getUnitDeal(HttpServletRequest request, @PathVariable(value = "id") long id)throws ProfitMandiBusinessException {String response = null;// TODO: move to propertiesString uri = "getDealById/" + id;System.out.println("Unit deal " + uri);RestClient rc = new RestClient();Map<String, String> params = new HashMap<>();DealsResponse dealsResponse = null;try {response = rc.get(SchemeType.HTTP, host, port, uri, params);} catch (HttpHostConnectException e) {throw new ProfitMandiBusinessException("", "", "Could not connect to host");}JsonObject result_json = Json.parse(response).asObject();if (!result_json.isEmpty()) {dealsResponse = new Gson().fromJson(response, DealsResponse.class);Iterator<AvailabilityInfo> iter = dealsResponse.getAvailabilityInfo().iterator();while (iter.hasNext()) {AvailabilityInfo ai = iter.next();if (ai.getAvailability() <= 0)iter.remove();}}return responseSender.ok(dealsResponse);}@RequestMapping(value = "/partnerdeals/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)@ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})@ApiOperation(value = "Get unit deal object")public ResponseEntity<?> getUnitFocoDeal(HttpServletRequest request, @PathVariable(value = "id") long id)throws Exception {List<FofoCatalogResponse> dealResponse = new ArrayList<>();List<Integer> tagIds = Arrays.asList(4);UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");if (roleManagerService.isPartner(userInfo.getRoleIds())) {String categoryId = "(3 OR 6)";UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());RestClient rc = new RestClient();Map<String, String> params = new HashMap<>();List<String> mandatoryQ = new ArrayList<>();String catalogString = "catalog" + id;mandatoryQ.add(String.format("+(categoryId_i:%s) +(id:%s) +{!parent which=\"id:%s\"} tagId_i:(%s)",categoryId, catalogString, catalogString, StringUtils.join(tagIds, " ")));params.put("q", StringUtils.join(mandatoryQ, " "));params.put("fl", "*, [child parentFilter=id:catalog*]");params.put("sort", "rank_i asc, create_s desc");params.put("wt", "json");String response = null;try {response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);} catch (HttpHostConnectException e) {throw new ProfitMandiBusinessException("", "", "Could not connect to host");}JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");JSONArray docs = solrResponseJSONObj.getJSONArray("docs");dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId());} else {return responseSender.badRequest(new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));}return responseSender.ok(dealResponse.get(0));}@RequestMapping(value = "/fofo/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)public ResponseEntity<?> getBrandsToDisplay(HttpServletRequest request,@RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");logger.info("userInfo [{}]", userInfo);List<DBObject> brandsDisplay = mongoClient.getMongoBrands(userInfo.getRetailerId(), userInfo.getEmail(),categoryId);return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);}@RequestMapping(value = "/fofo/accessory/all-categories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)public ResponseEntity<?> getSubCategoriesToDisplay(HttpServletRequest request) throws Exception {UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");logger.info("userInfo [{}]", userInfo);List<DBObject> subCategoriesDisplay = this.getSubCategoriesToDisplay();return new ResponseEntity<>(subCategoriesDisplay, HttpStatus.OK);}private List<DBObject> getSubCategoriesToDisplay() throws Exception {List<DBObject> subCategories = new ArrayList<>();RestClient rc = new RestClient();Map<String, String> params = new HashMap<>();params.put("q", "categoryId_i:6");params.put("group", "true");params.put("group.field", "subCategoryId_i");params.put("wt", "json");params.put("rows", "50");params.put("fl", "subCategoryId_i");String response = null;try {response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);} catch (HttpHostConnectException e) {throw new ProfitMandiBusinessException("", "", "Could not connect to host");}JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("grouped");JSONArray groups = solrResponseJSONObj.getJSONObject("subCategoryId_i").getJSONArray("groups");List<Integer> categoryIds = new ArrayList<>();for (int i = 0; i < groups.length(); i++) {JSONObject groupObject = groups.getJSONObject(i);int subCategoryId = groupObject.getInt("groupValue");int quantity = groupObject.getJSONObject("doclist").getInt("numFound");categoryIds.add(subCategoryId);}List<Category> categories = categoryRepository.selectByIds(categoryIds);AtomicInteger i = new AtomicInteger(0);categories.forEach(x -> {DBObject dbObject = new BasicDBObject();dbObject.put("name", x.getLabel());dbObject.put("subCategoryId", x.getId());dbObject.put("rank", i.incrementAndGet());dbObject.put("categoryId", 6);dbObject.put("url", "https://images.smartdukaan.com/uploads/campaigns/" + x.getId() + ".png");subCategories.add(dbObject);});return subCategories;}@RequestMapping(value = "/banners/{bannerType}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)public ResponseEntity<?> getBanners(@PathVariable String bannerType) {return new ResponseEntity<>(mongoClient.getBannersByType(bannerType), HttpStatus.OK);}@RequestMapping(value = "/deals/subCategories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)public ResponseEntity<?> getSubcategoriesToDisplay() {return new ResponseEntity<>(mongoClient.getSubcategoriesToDisplay(), HttpStatus.OK);}@ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})@RequestMapping(value = "/deals/skus/{skus}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)public ResponseEntity<?> getDealsBySkus(@PathVariable String skus) throws ProfitMandiBusinessException {StringBuffer sb = new StringBuffer("/getDealsForNotification/");String uri = sb.append(skus).toString();RestClient rc = new RestClient();String response;try {response = rc.get(SchemeType.HTTP, host, port, uri, new HashMap<>());} catch (HttpHostConnectException e) {throw new ProfitMandiBusinessException("", "", "Could not connect to host");}JsonArray result_json = Json.parse(response).asArray();List<Object> responseObject = new ArrayList<>();for (JsonValue j : result_json) {// logger.info("res " + j.asArray());List<Object> innerObject = new ArrayList<>();for (JsonValue jsonObject : j.asArray()) {innerObject.add(toDealObject(jsonObject.asObject()));}if (innerObject.size() > 0) {responseObject.add(innerObject);}}return responseSender.ok(responseObject);}@Autowiredprivate SaholicCISTableRepository saholicCISTableRepository;private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal, int fofoId) throws Exception {List<FofoCatalogResponse> dealResponse = new ArrayList<>();List<Integer> tagIds = Arrays.asList(4);List<Integer> itemIds = new ArrayList<>();if (docs.length() > 0) {for (int i = 0; i < docs.length(); i++) {JSONObject doc = docs.getJSONObject(i);if (doc.has("_childDocuments_")) {for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);int itemId = childItem.getInt("itemId_i");itemIds.add(itemId);}}}if (itemIds.size() == 0) {return dealResponse;}}// get warehouse Idint warehouseId = fofoStoreRepository.selectByRetailerId(fofoId).getWarehouseId();Map<Integer, List<SaholicPOItem>> poItemAvailabilityMap = saholicInventoryService.getSaholicPOItems().get(warehouseId);List<Integer> catalogIds = new ArrayList<>();for (int i = 0; i < docs.length(); i++) {Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();JSONObject doc = docs.getJSONObject(i);catalogIds.add(doc.getInt("catalogId_i"));}List<CreateOfferRequest> allSchemOffers = null;Map<Integer, PriceCircularItemModel> priceCircularItemModelMap = new HashMap<>();if (catalogIds.size() > 0) {PriceCircularModel priceCircularModel = priceCircularService.getPriceCircularByOffer(fofoId, catalogIds);allSchemOffers = priceCircularModel.getOffers();List<PriceCircularItemModel> priceCircularItemModels = priceCircularModel.getPriceCircularItemModels();if (priceCircularItemModels != null) {priceCircularItemModelMap = priceCircularItemModels.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));}}for (int i = 0; i < docs.length(); i++) {Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();JSONObject doc = docs.getJSONObject(i);FofoCatalogResponse fofoCatalogResponse = new FofoCatalogResponse();fofoCatalogResponse.setCatalogId(doc.getInt("catalogId_i"));fofoCatalogResponse.setImageUrl(doc.getString("imageUrl_s"));fofoCatalogResponse.setTitle(doc.getString("title_s"));List<WebOffer> webOffers = webOfferRepository.selectAllActiveOffers().get(fofoCatalogResponse.getCatalogId());logger.info("webOffers {}", webOffers);if (webOffers != null && webOffers.size() > 0) {fofoCatalogResponse.setWebOffers(webOffers);}List<ComboModel> comboModels = comboModelRepository.selectByWarehouseId(warehouseId).stream().filter(x -> x.getCatalogId() == fofoCatalogResponse.getCatalogId()).collect(Collectors.toList());for (ComboModel comboModel : comboModels) {List<ComboMappedModel> mappedModels = comboMappedModelRepository.selectByComboId(comboModel.getId());comboModel.setComboMappedModels(mappedModels);}if (comboModels != null && comboModels.size() > 0) {fofoCatalogResponse.setComboModels(comboModels);}try {fofoCatalogResponse.setFeature(doc.getString("feature_s"));} catch (Exception e) {fofoCatalogResponse.setFeature(null);logger.info("Could not find Feature_s for {}", fofoCatalogResponse.getCatalogId());}fofoCatalogResponse.setBrand(doc.getJSONArray("brand_ss").getString(0));if (doc.has("_childDocuments_")) {String modelColorClass = "grey";FofoAvailabilityInfo fdiAnyColour = null;//Iterating itemIdsfor (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {PriceCircularItemModel priceCircularItemModel = priceCircularItemModelMap.get(fofoCatalogResponse.getCatalogId());JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);int itemId = childItem.getInt("itemId_i");float sellingPrice = (float) childItem.getDouble("sellingPrice_f");if (fofoAvailabilityInfoMap.containsKey(itemId)) {/*if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));fofoAvailabilityInfoMap.get(itemId).setNlc(priceCircularItemModel == null ? 0 : priceCircularItemModel.getNetPrice());}*/} else {FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();List<SaholicCISTable> currentAvailability = saholicCISTableRepository.selectByItemWarehouse(itemId, warehouseId);List<SaholicPOItem> poItemAvailability = null;if (poItemAvailabilityMap != null) {poItemAvailability = poItemAvailabilityMap.get(itemId);}fdi.setNlc(priceCircularItemModel == null ? 0 : priceCircularItemModel.getNetPrice());for (SaholicCISTable saholicCISTable : currentAvailability) {saholicCISTable.setWarehouseName(ProfitMandiConstants.WAREHOUSE_MAP.get(saholicCISTable.getWarehouseFrom()));}Map<Integer, SaholicCISTable> map = currentAvailability.stream().collect(Collectors.toMap(SaholicCISTable::getWarehouseFrom, x -> x));if (poItemAvailability != null) {if (fofoCatalogResponse.getCatalogId() == 1023522) {logger.info("currentAvailabilityMap --> {}", map);logger.info("currentAvailability --> {}", currentAvailability);logger.info("currentAvailabilitySum --> {}", currentAvailability.stream().collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)));}for (SaholicPOItem saholicPOItem : poItemAvailability) {if (fofoCatalogResponse.getCatalogId() == 1023522) {logger.info("SaholicPoItem {}", saholicPOItem);logger.info("Warehouse From - {}", map.get(saholicPOItem.getWarehouseFrom()));}if (map.containsKey(saholicPOItem.getWarehouseFrom())) {map.get(saholicPOItem.getWarehouseFrom()).setPopendingQty(saholicPOItem.getUnfulfilledQty());} else {SaholicCISTable saholicCISTable = new SaholicCISTable();saholicCISTable.setAvailability(0);saholicCISTable.setReserved(0);saholicCISTable.setItemId(itemId);saholicCISTable.setWarehouseId(warehouseId);saholicCISTable.setPopendingQty(saholicPOItem.getUnfulfilledQty());saholicCISTable.setWarehouseFrom(saholicPOItem.getWarehouseFrom());saholicCISTable.setWarehouseName(ProfitMandiConstants.WAREHOUSE_MAP.get(saholicPOItem.getWarehouseFrom()));map.put(saholicPOItem.getWarehouseFrom(), saholicCISTable);}}}fdi.setSaholicCISTableList(new ArrayList<>(map.values()));String poColor = "grey";boolean active = false;if (currentAvailability != null && currentAvailability.stream().collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)) > 0) {poColor = "green";modelColorClass = "green";} else if (poItemAvailability != null && poItemAvailability.stream().collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty)) > 0) {if (currentAvailability != null && poItemAvailability.stream().collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty))+ currentAvailability.stream().collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)) <= 0) {poColor = "grey";} else {poColor = "yellow";if (modelColorClass != "green") {modelColorClass = poColor;}}}fdi.setColorClass(poColor);fdi.setSellingPrice(sellingPrice);fdi.setActive(active);fdi.setMrp(childItem.getDouble("mrp_f"));fdi.setMop((float) childItem.getDouble("mop_f"));fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");if (fdi.getColor().equalsIgnoreCase("any colour")) {fdiAnyColour = fdi;}fdi.setTagId(childItem.getInt("tagId_i"));fdi.setItem_id(itemId);Float cashBack = schemeService.getCatalogSchemeCashBack().get(fofoCatalogResponse.getCatalogId());cashBack = cashBack == null ? 0 : cashBack;fdi.setCashback(cashBack);fdi.setMinBuyQuantity(1);if (hotDeal) {if (currentAvailability != null) {fdi.setAvailability(currentAvailability.stream().collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)));} else {fdi.setAvailability(0);}} else {// Lets consider that its out of stockfdi.setAvailability(100);Item item = null;try {item = itemRepository.selectById(itemId);} catch (Exception e) {e.printStackTrace();continue;}// In case its tampered glass moq should beif (item.getCategoryId() == 10020) {fdi.setMinBuyQuantity(5);}}fdi.setQuantityStep(1);fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));fofoAvailabilityInfoMap.put(itemId, fdi);}}if (fdiAnyColour != null) {fdiAnyColour.setColorClass(modelColorClass);}}if (fofoAvailabilityInfoMap.values().size() > 0) {List<FofoAvailabilityInfo> availabilityList = fofoAvailabilityInfoMap.values().stream().sorted(Comparator.comparing(FofoAvailabilityInfo::getAvailability).reversed()).collect(Collectors.toList());fofoCatalogResponse.setItems(availabilityList);if (priceCircularItemModelMap.containsKey(fofoCatalogResponse.getCatalogId())) {PriceCircularItemModel priceCircularItemModel = priceCircularItemModelMap.get(fofoCatalogResponse.getCatalogId());if (priceCircularItemModel.getSlabPayouts() != null) {List<CreateOfferRequest> schemeOffers = new ArrayList<>();List<Map<Integer, Long>> slabPayouts = priceCircularItemModel.getSlabPayouts();Iterator<Map<Integer, Long>> iterator = slabPayouts.iterator();int iteratorCount = 0;while (iterator.hasNext()) {Map<Integer, Long> slabPayoutMap = iterator.next();if (slabPayoutMap != null) {schemeOffers.add(allSchemOffers.get(iteratorCount));} else {iterator.remove();}iteratorCount++;}fofoCatalogResponse.setSchemeOffers(schemeOffers);}fofoCatalogResponse.setPriceCircularItemModel(priceCircularItemModel);}dealResponse.add(fofoCatalogResponse);}}return dealResponse;}private List<FofoCatalogResponse> getCatalogSingleSkuResponse(JSONArray docs, Map<Integer, Integer> itemFilter,boolean hotDeal) throws ProfitMandiBusinessException {Map<Integer, TagListing> itemTagListingMap = null;List<FofoCatalogResponse> dealResponse = new ArrayList<>();List<Integer> tagIds = Arrays.asList(4);itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemFilter.keySet(), new HashSet<>(tagIds)).stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x));for (int i = 0; i < docs.length(); i++) {Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();JSONObject doc = docs.getJSONObject(i);for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);int itemId = childItem.getInt("itemId_i");TagListing tl = itemTagListingMap.get(itemId);if (tl == null) {continue;}if (hotDeal) {if (!tl.isHotDeals()) {continue;}}float sellingPrice = (float) childItem.getDouble("sellingPrice_f");if (fofoAvailabilityInfoMap.containsKey(itemId)) {if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));}} else {FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));fdi.setMop((float) childItem.getDouble("mop_f"));fdi.setMop((float) tl.getMrp());fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");fdi.setTagId(childItem.getInt("tagId_i"));fdi.setItem_id(itemId);Item item = itemRepository.selectById(itemId);// In case its tampered glass moq should be 5if (item.getCategoryId() == 10020) {fdi.setMinBuyQuantity(10);} else {fdi.setMinBuyQuantity(1);}fdi.setAvailability(itemFilter.get(itemId));fdi.setQuantityStep(1);fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));fofoAvailabilityInfoMap.put(itemId, fdi);}}if (fofoAvailabilityInfoMap.values().size() > 0) {for (FofoAvailabilityInfo fofoAvailabilityInfo : fofoAvailabilityInfoMap.values()) {FofoCatalogResponse ffdr = new FofoCatalogResponse();ffdr.setCatalogId(doc.getInt("catalogId_i"));ffdr.setImageUrl(doc.getString("imageUrl_s"));ffdr.setTitle(doc.getString("title_s"));try {ffdr.setFeature(doc.getString("feature_s"));} catch (Exception e) {ffdr.setFeature(null);logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());}ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));ffdr.setItems(Arrays.asList(fofoAvailabilityInfo));dealResponse.add(ffdr);}}}return dealResponse;}@RequestMapping(value = "/combo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)public ResponseEntity<?> getBanners(@RequestParam int catalogId, @RequestParam int warehouseId) {List<ComboModel> comboModels = comboModelRepository.selectByCatalogIdAndWarehouseId(catalogId, warehouseId);return responseSender.ok(comboModels);}}