Subversion Repositories SmartDukaan

Rev

Rev 37247 | 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.BrandAndAddToCartEligibleModel;
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.WebListing;
import com.spice.profitmandi.dao.entity.dtr.WebOffer;
import com.spice.profitmandi.dao.entity.fofo.*;
import com.spice.profitmandi.dao.entity.inventory.SaholicCISTable;
import com.spice.profitmandi.dao.entity.inventory.SaholicPOItem;
import com.spice.profitmandi.dao.enumuration.dtr.WebListingSource;
import com.spice.profitmandi.dao.enumuration.dtr.WebListingType;
import com.spice.profitmandi.dao.model.AmountModel;
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.*;
import com.spice.profitmandi.dao.repository.fofo.CatalogFavouriteRepository;
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
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.dao.repository.onboarding.BrandCommitRepository;
import com.spice.profitmandi.service.authentication.RoleManager;
import com.spice.profitmandi.service.catalog.BrandsService;
import com.spice.profitmandi.service.integrations.pinelabs.PinelabsAffordabilityService;
import com.spice.profitmandi.service.integrations.pinelabs.PinelabsDeviceService;
import com.spice.profitmandi.service.integrations.pinelabs.PinelabsOfferCacheService;
import com.spice.profitmandi.service.integrations.pinelabs.dto.DownpaymentDetailsRequest;
import com.spice.profitmandi.service.integrations.pinelabs.dto.DownpaymentDetailsResponse;
import com.spice.profitmandi.service.integrations.pinelabs.dto.ImeiValidationResponse;
import com.spice.profitmandi.service.integrations.pinelabs.dto.OfferDiscoveryRequest;
import com.spice.profitmandi.service.integrations.pinelabs.dto.OfferDiscoveryResponse;
import com.spice.profitmandi.service.integrations.pinelabs.dto.OfferValidateRequest;
import com.spice.profitmandi.service.integrations.pinelabs.dto.OfferValidateResponse;
import com.spice.profitmandi.service.integrations.pinelabs.dto.PineLablsCreateOfferRequest;
import com.spice.profitmandi.service.integrations.pinelabs.dto.CreateOfferResponse;
import com.spice.profitmandi.service.integrations.pinelabs.dto.Tenure;
import com.spice.profitmandi.service.inventory.*;
import com.spice.profitmandi.service.pricecircular.PriceCircularItemModelNew;
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.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
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);
    private static final List<Integer> TAG_IDS = Arrays.asList(4);

    @Value("${python.api.host}")
    private String host;

    @Value("${new.solr.url}")
    private String solrUrl;

    @Value("${python.api.port}")
    private int port;

    @Autowired
    RestClient restClient;

    @Autowired
    SolrService solrService;

    @Autowired
    com.spice.profitmandi.web.services.SolrService webSolrService;

    @Autowired
    com.spice.profitmandi.web.services.HotDealEnrichmentService hotDealEnrichmentService;

    @Autowired
    com.spice.profitmandi.dao.repository.catalog.ModelHotDealRepository modelHotDealRepository;

    @Autowired
    private com.spice.profitmandi.web.services.PartnerSolrClient partnerSolrClient;

    @Autowired
    PinelabsAffordabilityService pinelabsAffordabilityService;

    @Autowired
    PinelabsDeviceService pinelabsDeviceService;

    // This is now unused as we are not supporting multiple companies.
    @Value("${gadgetCops.invoice.cc}")
    private String[] ccGadgetCopInvoiceTo;

    @Autowired
    private PricingService pricingService;

    @Autowired
    private CategoryRepository categoryRepository;

    @Autowired
    private SchemeService schemeService;

    @Autowired
    private SaholicInventoryService saholicInventoryService;

    @Autowired
    private Mongo mongoClient;

    @Autowired
    private ItemBucketService itemBucketService;

    @Autowired
    private UserAccountRepository userAccountRepository;

    @Autowired
    private FofoStoreRepository fofoStoreRepository;

    @Autowired
    private ResponseSender<?> responseSender;

    @Autowired
    private TagListingRepository tagListingRepository;

    @Autowired
    private ItemRepository itemRepository;
    @Autowired
    private PriceCircularService priceCircularService;

    @Autowired
    private RoleManager roleManagerService;

    @Autowired
    private SuggestedPoDetailRepository suggestedPoDetailRepository;

    @Autowired
    private SuggestedPoRepository suggestedPoRepository;

    @Autowired
    private WebOfferRepository webOfferRepository;

    @Autowired
    private ComboModelRepository comboModelRepository;

    @Autowired
    private PinelabsOfferCacheService pinelabsOfferCacheService;

    @Autowired
    private BrandsService brandsService;

    @Autowired
    private BrandsRepository brandsRepository;

    @Autowired
    private WebListingRepository webListingRepository;

    @Autowired
    private WebProductListingRepository webProductListingRepository;

    @Autowired
    private CatalogFavouriteRepository catalogFavouriteRepository;

    @Autowired
    PartnerOnBoardingPanelRepository partnerOnBoardingPanelRepository;

    @Autowired
    PartnerDealerRepository partnerDealerRepository;

    @Autowired
    BrandCommitRepository brandCommitRepository;

    @Autowired
    CatalogRepository catalogRepository;

    @Autowired
    private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;

    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());
        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");
        int fofoId = userAccountRepository.getUserCart((int) request.getAttribute("userId")).getUserId();
        JSONArray docs = partnerSolrClient.selectDocs(params, fofoId);
        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 {
        int userId = (int) request.getAttribute("userId");
        UserCart uc = userAccountRepository.getUserCart(userId);
        int fofoId = uc.getUserId();
        SuggestedPo  suggestedPo = suggestedPoRepository.selectAllOpenPoByFofoId(fofoId).get(0);
        if(suggestedPo == null){
            throw new ProfitMandiBusinessException("", "", "Open po is not available in list");
        }
        List<SuggestedPoDetail> mpd = suggestedPoDetailRepository.selectByPoId(suggestedPo.getId());
        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());
                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");
        JSONArray docs = partnerSolrClient.selectDocs(params, fofoId);
        List<FofoCatalogResponse> dealResponse = getCatalogSingleSkuResponse(docs, itemIdsQtyMap, false);

        return responseSender.ok(dealResponse);
    }

    @RequestMapping(value = "/suggestedPo/status", method = RequestMethod.GET, 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");
        //suggestedPo.setStatus(SuggestedPoStatus.valueOf("closed"));

        return responseSender.ok(true);
    }

    @RequestMapping(value = "/fofo/fovourites", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> getFavourites(HttpServletRequest request) throws Exception {

        int userId = (int) request.getAttribute("userId");
        UserCart uc = userAccountRepository.getUserCart(userId);
        int fofoId = uc.getUserId();
        List<FofoCatalogResponse> dealResponse = new ArrayList<>();
        Set<Integer> catalogIds = catalogFavouriteRepository.selectBypartnerId(fofoId).stream().map(x -> x.getCatalogId()).collect(Collectors.toSet());
        if (!catalogIds.isEmpty()) {
            dealResponse = webSolrService.dealResponse(catalogIds, fofoId);
            hotDealEnrichmentService.enrich(dealResponse);
        }
        return responseSender.ok(dealResponse);
    }

    @RequestMapping(value = "/favourites/manage", 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<?> mangeFavourites(HttpServletRequest request, @RequestParam int catalogId) throws ProfitMandiBusinessException {

        int userId = (int) request.getAttribute("userId");
        UserCart uc = userAccountRepository.getUserCart(userId);
        int fofoId = uc.getUserId();

        CatalogFavourite catalogFavourite = catalogFavouriteRepository.selectBypartnerAndCatalogId(fofoId, catalogId);

        if (catalogFavourite == null) {
            catalogFavourite = new CatalogFavourite();
            catalogFavourite.setCatalogId(catalogId);
            catalogFavourite.setFofoId(fofoId);
            catalogFavourite.setCreatedTimestamp(LocalDateTime.now());
            catalogFavouriteRepository.persist(catalogFavourite);

        } else {
            catalogFavouriteRepository.deleteByPartnerAndCatalogId(fofoId, catalogId);
        }
        return responseSender.ok(true);
    }

    private String getCommaSeparateTags(int userId) throws ProfitMandiBusinessException {
        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);
    }

    @RequestMapping(value = "/fofo/similar-models/{modelId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> similarModels(HttpServletRequest httpServletRequest, @PathVariable int modelId) throws Throwable {
        UserInfo userInfo = (UserInfo) httpServletRequest.getAttribute("userInfo");
        //FofoStore fs = fofoStoreRepository.selectByRetailerId(userInfo.getRetailerId());

        JSONObject jsonObject = solrService.getContentByCatalogIds(Arrays.asList(modelId)).get(modelId);

        JSONArray similarModelsArray = jsonObject.getJSONArray("similarModels_ii");
        List<Integer> similarCatalogIds = new ArrayList<>();
        for (int j = 0; j < similarModelsArray.length(); j++) {
            similarCatalogIds.add(similarModelsArray.getInt(j));
        }

        Map<String, String> params = new HashMap<>();
        List<String> mandatoryQ = new ArrayList<>();

        mandatoryQ.add(String.format(
                "+{!parent which=\"catalogId_i:(" + StringUtils.join(similarCatalogIds, " ") + ")\"} AND active_b:true AND show_default_b:true"));

        params.put("q", StringUtils.join(mandatoryQ, " "));
        params.put("fl", "*, [child parentFilter=id:catalog* childFilter=active_b:true ]");
        params.put("wt", "json");
        params.put("rows", similarCatalogIds.size() + "");
        JSONArray docs = partnerSolrClient.selectDocs(params, userInfo.getRetailerId());
        return responseSender.ok(this.getCatalogResponse(docs, false, userInfo.getRetailerId()).stream().filter(x -> x.isInStock()).collect(Collectors.toList()));
    }

    @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") int offset,
         @RequestParam(value = "limit") int 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, @RequestParam(value = "endPoint", required = false) String endPoint,@RequestParam(value = "group", required = false) boolean group) throws Throwable {
        // Band-aid for URL '+' decode issue on brand names.
        // Front-end sends `brand=Ai+`. Depending on where along the request path the
        // '+' is decoded, the servlet may receive "Ai " (trailing space) or just "Ai"
        // (plus dropped entirely by the SPA before the request goes out).
        // Strategy: if the received value doesn't exist as a real brand in catalog.brand,
        // try appending '+' and see if THAT exists — if so, use it. Zero regression risk
        // for real brand names because the fallback only fires on unknown values.
        logger.info("getFofo received brand='{}' (len={})",
                brand, brand == null ? -1 : brand.length());
        if (brand != null && !brand.trim().isEmpty()) {
            String probe = brand.replaceAll("\\s+$", "");
            try {
                if (brandsRepository.selectByBrand(brand) == null
                        && (probe.equals(brand) || brandsRepository.selectByBrand(probe) == null)) {
                    String withPlus = probe + "+";
                    if (brandsRepository.selectByBrand(withPlus) != null) {
                        logger.info("getFofo brand fallback: '{}' -> '{}'", brand, withPlus);
                        brand = withPlus;
                    }
                }
            } catch (Exception e) {
                logger.warn("getFofo brand fallback lookup failed for '{}': {}", brand, e.getMessage());
            }
        }
        List<FofoCatalogResponse> dealResponse;
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
        FofoStore fs = fofoStoreRepository.selectByRetailerId(userInfo.getRetailerId());
        sort = "w" + fs.getWarehouseId() + "_i desc";

        logger.info("endPoint {}", endPoint);
        logger.info("group Column {}", group);

        if (endPoint != null && !endPoint.trim().isEmpty()) {
            WebListing webListing = webListingRepository.selectByUrl(endPoint);
            dealResponse = this.getDealResponses(userInfo, fs, webListing, offset, limit);

        } else if (hotDeal) {
            // Hot deals are sourced from catalog.model_hot_deal (date-windowed, curated),
            // not the legacy Solr hot_deal_b flag
            List<Integer> hotDealCatalogIds = modelHotDealRepository.selectAllActive(java.time.LocalDate.now())
                    .stream().map(com.spice.profitmandi.dao.entity.catalog.ModelHotDeal::getCatalogItemId)
                    .distinct().collect(Collectors.toList());
            if (hotDealCatalogIds.isEmpty()) {
                dealResponse = new ArrayList<>();
            } else {
                dealResponse = this.getCatalogResponse(
                        solrService.getSolrDocs(queryTerm, categoryId, offset, limit, sort, brand, subCategoryId, false, group, true,
                                brandsService.restrictedBrands(userInfo.getRetailerId()), hotDealCatalogIds), false, userInfo.getRetailerId());
            }
        } else {

            dealResponse = this.getCatalogResponse(
                    solrService.getSolrDocs(queryTerm, categoryId, offset, limit, sort, brand, subCategoryId, hotDeal, group, true,
                            brandsService.restrictedBrands(userInfo.getRetailerId())), hotDeal, userInfo.getRetailerId());
        }
        hotDealEnrichmentService.enrich(dealResponse);

        Map<Integer, List<Integer>> similarModelMap = dealResponse.stream().filter(x -> x.getSimilarModelIds() != null && x.getSimilarModelIds().size() > 0)
                .collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getSimilarModelIds()));
        Set<Integer> similarModelIds = similarModelMap.values().stream().flatMap(x -> x.stream()).collect(Collectors.toSet());
        logger.info("similarModelIds - {}", similarModelIds);
        if (similarModelIds.size() > 0) {

            Map<Integer, FofoCatalogResponse> similarCatalogResponsesMap = this.getSimpleDocs(fs, similarModelIds).stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));
            logger.info("Similar Catalog ResponseMap - {}", similarCatalogResponsesMap.keySet());

            for (FofoCatalogResponse deal : dealResponse) {
                if (similarModelMap.containsKey(deal.getCatalogId())) {
                    List<Integer> similarCatalogIds = similarModelMap.get(deal.getCatalogId());
                    logger.info("Similar Catalog Ids - {}", similarCatalogIds);
                    List<FofoCatalogResponse> similarModels = similarCatalogIds.stream().filter(x -> similarCatalogResponsesMap.containsKey(x)).map(x -> similarCatalogResponsesMap.get(x)).collect(Collectors.toList());
                    deal.setSimilarModels(similarModels);
                }
            }
        }
        return responseSender.ok(dealResponse);
    }

    private List<FofoCatalogResponse> getSimpleDocs(FofoStore fofoStore, Set<Integer> catalogIds) throws Exception {
        List<FofoCatalogResponse> fofoCatalogResponses = new ArrayList<>();


        Map<String, String> params = new HashMap<>();
        List<String> mandatoryQ = new ArrayList<>();

        mandatoryQ.add(String.format(
                "+{!parent which=\"catalogId_i:(" + StringUtils.join(catalogIds, " ") + ")\"} AND active_b:true AND show_default_b:true"));

        params.put("q", StringUtils.join(mandatoryQ, " "));
        params.put("fl", "*, [child parentFilter=id:catalog* childFilter=active_b:true ]");
        params.put("wt", "json");
        params.put("rows", catalogIds.size() + "");

        JSONArray docs = partnerSolrClient.selectDocs(params, fofoStore.getId());
        int warehouseId = fofoStore.getWarehouseId();
        Map<Integer, List<SaholicPOItem>> poItemAvailabilityMap = saholicInventoryService.getSaholicPOItems().get(warehouseId);

        // Pre-fetch all itemIds for batch CIS query
        List<Integer> allItemIds = new ArrayList<>();
        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++) {
                    allItemIds.add(doc.getJSONArray("_childDocuments_").getJSONObject(j).getInt("itemId_i"));
                }
            }
        }
        // Batch fetch CIS data
        Map<Integer, List<SaholicCISTable>> cisDataByItemId = saholicCISTableRepository
                .selectByItemWarehouse(allItemIds, warehouseId).stream()
                .collect(Collectors.groupingBy(SaholicCISTable::getItemId));

        for (int i = 0; i < docs.length(); i++) {
            JSONObject doc = docs.getJSONObject(i);
            FofoCatalogResponse fofoCatalogResponse = this.toFofoCatalogResponse(doc);
            if (doc.has("_childDocuments_")) {
                String modelColorClass = "grey";
                FofoAvailabilityInfo fdiAnyColour = null;
                // Iterating itemIds
                for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
                    JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
                    int itemId = childItem.getInt("itemId_i");

                    List<SaholicCISTable> currentAvailability = cisDataByItemId.getOrDefault(itemId, new ArrayList<>());
                    List<SaholicPOItem> poItemAvailability = null;
                    if (poItemAvailabilityMap != null) {
                        poItemAvailability = poItemAvailabilityMap.get(itemId);
                    }

                    for (SaholicCISTable saholicCISTable : currentAvailability) {
                        saholicCISTable.setWarehouseName(
                                ProfitMandiConstants.WAREHOUSE_MAP.get(saholicCISTable.getWarehouseFrom()));
                    }


                    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.equals("green")) {
                                modelColorClass = poColor;
                            }
                        }
                    }

                }
                fofoCatalogResponse.setInStock(!modelColorClass.equals("grey"));
            }

            fofoCatalogResponses.add(fofoCatalogResponse);
        }

        return fofoCatalogResponses;
    }

    private FofoCatalogResponse toFofoCatalogResponse(JSONObject doc) {
        FofoCatalogResponse fofoCatalogResponse = new FofoCatalogResponse();
        fofoCatalogResponse.setCatalogId(doc.getInt("catalogId_i"));
        fofoCatalogResponse.setImageUrl(doc.getString("imageUrl_s"));
        fofoCatalogResponse.setTitle(doc.getString("title_s"));
        fofoCatalogResponse.setMop(doc.getFloat("mop_f"));
        fofoCatalogResponse.setDp(doc.getFloat("dp_f"));
        fofoCatalogResponse.setBrand(doc.getJSONArray("brand_ss").getString(0));
        return fofoCatalogResponse;
    }

    @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;
                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 = restClient.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 properties
        String uri = ProfitMandiConstants.URL_BRANDS;
                Map<String, String> params = new HashMap<>();
        params.put("category_id", category_id);
        List<DealBrands> dealBrandsResponse = null;
        try {
            response = restClient.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());

        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
        List<String> restrictedBrands = brandsService.restrictedBrands(userInfo.getRetailerId());
        dealBrandsResponse = dealBrandsResponse.stream().filter(x -> !restrictedBrands.contains(x.getBrand()))
                .collect(Collectors.toList());

        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 properties
        String uri = "getDealById/" + id;
        System.out.println("Unit deal " + uri);
                Map<String, String> params = new HashMap<>();
        DealsResponse dealsResponse = null;
        try {
            response = restClient.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());
                        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");
            JSONArray docs = partnerSolrClient.selectDocs(params, userInfo.getRetailerId());
            dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId());
        } else {
            return responseSender.badRequest(
                    new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
        }
        if (dealResponse.isEmpty()) {
            return responseSender.badRequest(
                    new ProfitMandiBusinessException("catalogId", id, "DEAL_NOT_FOUND"));
        }
        hotDealEnrichmentService.enrich(dealResponse);
        return responseSender.ok(dealResponse.get(0));
    }


    @RequestMapping(value = "/suggestedPoDeals", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> suggestedPoDeals(HttpServletRequest request,@RequestBody Set<Integer>catalogIds) throws Exception {

        int userId = (int) request.getAttribute("userId");
        UserCart uc = userAccountRepository.getUserCart(userId);
        int fofoId = uc.getUserId();
        List<FofoCatalogResponse> dealResponse = new ArrayList<>();
        if (!catalogIds.isEmpty()) {
            dealResponse = webSolrService.dealResponse(catalogIds, fofoId);
        }
        return responseSender.ok(dealResponse);
    }

    @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<BrandCatalog> brandsDisplay = brandsService.getBrandsToDisplay(categoryId);
        //List<DBObject> brandsDisplay = mongoClient.getMongoBrands(userInfo.getRetailerId(), userInfo.getEmail(), categoryId);
        return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
    }

    @RequestMapping(value = "/fofo/brandCatalog", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> getBrands(HttpServletRequest request,
                                       @RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
        logger.info("userInfo [{}]", userInfo);

        List<BrandCatalog> brandsDisplay = brandsService.getBrands(userInfo.getRetailerId(), userInfo.getEmail(), categoryId);
        List<String> restrictedBrands = brandsService.restrictedBrands(userInfo.getRetailerId());
        brandsDisplay = brandsDisplay.stream().filter(x -> !restrictedBrands.contains(x.getName()))
                .collect(Collectors.toList());
        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<>();
                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 = restClient.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("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 = "/fofo/categories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> getFofoCategories() {
        Map<Integer, Category> categoryMap = categoryRepository.selectAll();
        List<Map<String, Object>> result = new ArrayList<>();
        for (Category category : categoryMap.values()) {
            if (category.isStatus()) {
                Map<String, Object> cat = new HashMap<>();
                cat.put("id", category.getId());
                cat.put("label", category.getLabel());
                cat.put("displayName", category.getDisplayName());
                cat.put("parentCategoryId", category.getParentCategoryId());
                cat.put("marginOnly", category.isMarginOnly());
                result.add(cat);
            }
        }
        return responseSender.ok(result);
    }

    @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();
                String response;
        try {
            response = restClient.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);
    }

    // Fans out the per-listing Solr HTTP calls only; every DB access stays on the request
    // thread because the Hibernate session is thread-bound. Pool size matches the
    // RestClient per-route connection limit.
    private static final ExecutorService SOLR_EXECUTOR = Executors.newFixedThreadPool(8, r -> {
        Thread t = new Thread(r, "partner-listing-solr");
        t.setDaemon(true);
        return t;
    });

    @RequestMapping(value = "/partner/listing", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> getPartnersListing(HttpServletRequest request) throws Exception {
        List<WebListing> webListings = webListingRepository.selectAllWebListingByType(Optional.of(true), WebListingSource.partner);
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
        int fofoId = userInfo.getRetailerId();
        FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);

        // Build every listing's Solr query on the request thread; the brand exclusion is
        // partner-scoped, so resolve it once instead of per listing.
        String exclusionFq = SolrService.brandExclusionFq(brandsService.restrictedBrands(fofoId));
        List<ListingQuery> queries = new ArrayList<>();
        for (WebListing webListing : webListings) {
            ListingQuery query = buildListingQuery(webListing, fs.getWarehouseId(), 0, 20);
            if (query.params != null && exclusionFq != null) {
                query.params.put("fq", exclusionFq);
            }
            queries.add(query);
        }

        Map<Integer, CompletableFuture<JSONArray>> futures = new HashMap<>();
        for (int i = 0; i < queries.size(); i++) {
            Map<String, String> params = queries.get(i).params;
            if (params != null) {
                futures.put(i, CompletableFuture.supplyAsync(() -> {
                    try {
                        return partnerSolrClient.selectDocsRaw(params);
                    } catch (ProfitMandiBusinessException e) {
                        throw new CompletionException(e);
                    }
                }, SOLR_EXECUTOR));
            }
        }

        Map<Integer, JSONArray> docsByListing = new HashMap<>();
        Set<Integer> allCatalogIds = new LinkedHashSet<>();
        Set<Integer> allItemIds = new LinkedHashSet<>();
        for (Map.Entry<Integer, CompletableFuture<JSONArray>> entry : futures.entrySet()) {
            JSONArray docs;
            try {
                docs = entry.getValue().join();
            } catch (CompletionException e) {
                throw e.getCause() instanceof Exception ? (Exception) e.getCause() : e;
            }
            docsByListing.put(entry.getKey(), docs);
            allCatalogIds.addAll(extractCatalogIds(docs));
            allItemIds.addAll(extractItemIds(docs));
        }

        CatalogBatchData batch = allItemIds.isEmpty() ? null
                : buildCatalogBatchData(fofoId, fs.getWarehouseId(), new ArrayList<>(allCatalogIds), new ArrayList<>(allItemIds));

        for (int i = 0; i < queries.size(); i++) {
            ListingQuery query = queries.get(i);
            JSONArray docs = docsByListing.get(i);
            List<FofoCatalogResponse> dealResponse;
            if (docs == null || batch == null) {
                dealResponse = new ArrayList<>();
            } else {
                dealResponse = buildCatalogResponses(docs, false, fofoId, batch);
                if (query.webProducts != null && query.webListing.getUrl().equals("new-launches")) {
                    List<Integer> webProductsFinal = query.webProducts;
                    dealResponse = dealResponse.stream().sorted(Comparator.comparing(x -> webProductsFinal.indexOf(x.getCatalogId()))).collect(Collectors.toList());
                }
            }
            query.webListing.setFofoCatalogResponses(dealResponse);
        }
        return responseSender.ok(webListings);
    }

    private List<FofoCatalogResponse> getDealResponses(UserInfo userInfo, FofoStore fs, WebListing webListing, int offset, int limit) throws Exception {
        ListingQuery query = buildListingQuery(webListing, fs.getWarehouseId(), offset, limit);
        if (query.params == null) {
            return new ArrayList<>();
        }
        JSONArray docs = partnerSolrClient.selectDocs(query.params, userInfo.getRetailerId());
        List<FofoCatalogResponse> dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId());

        if (query.webProducts != null && webListing.getUrl().equals("new-launches")) {
            List<Integer> webProductsFinal = query.webProducts;
            dealResponse = dealResponse.stream().sorted(Comparator.comparing(x -> webProductsFinal.indexOf(x.getCatalogId()))).collect(Collectors.toList());
        }

        return dealResponse;
    }

    /** Solr query for one web listing; params is null when a curated listing has no ranked products. */
    private static class ListingQuery {
        WebListing webListing;
        Map<String, String> params;
        List<Integer> webProducts;
    }

    private ListingQuery buildListingQuery(WebListing webListing, int warehouseId, int offset, int limit) {
        ListingQuery query = new ListingQuery();
        query.webListing = webListing;

        Map<String, String> params = new HashMap<>();
        List<String> mandatoryQ = new ArrayList<>();
        params.put("sort", "w" + warehouseId + "_i desc");

        if (webListing.getType().equals(WebListingType.solr)) {
            mandatoryQ.add(String.format("+{!parent which=\"" + webListing.getSolrQuery() + "\"} AND active_b:true AND show_default_b:true"));
        } else {
            query.webProducts = webProductListingRepository.selectAllByWebListingId(webListing.getId(), offset, limit).stream().filter(x -> x.getRank() > 0).map(x -> x.getEntityId()).collect(Collectors.toList());

            if (query.webProducts.size() == 0) {
                return query;
            }

            mandatoryQ.add(String.format(
                    "+{!parent which=\"catalogId_i:(" + StringUtils.join(query.webProducts, " ") + ")\"} AND active_b:true AND show_default_b:true"));
        }
        params.put("q", StringUtils.join(mandatoryQ, " "));
        params.put("fl", "*, [child parentFilter=id:catalog* childFilter=active_b:true ]");

        params.put("start", String.valueOf(offset));
        params.put("rows", String.valueOf(limit));
        params.put("wt", "json");
        query.params = params;
        return query;
    }

    @Autowired
    private SaholicCISTableRepository saholicCISTableRepository;

    private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal, int fofoId) throws Exception {
        List<Integer> itemIds = extractItemIds(docs);
        if (itemIds.isEmpty()) {
            return new ArrayList<>();
        }
        int warehouseId = fofoStoreRepository.selectByRetailerId(fofoId).getWarehouseId();
        CatalogBatchData batch = buildCatalogBatchData(fofoId, warehouseId, extractCatalogIds(docs), itemIds);
        return buildCatalogResponses(docs, hotDeal, fofoId, batch);
    }

    private List<Integer> extractItemIds(JSONArray docs) {
        List<Integer> itemIds = new ArrayList<>();
        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++) {
                    itemIds.add(doc.getJSONArray("_childDocuments_").getJSONObject(j).getInt("itemId_i"));
                }
            }
        }
        return itemIds;
    }

    private List<Integer> extractCatalogIds(JSONArray docs) {
        List<Integer> catalogIds = new ArrayList<>();
        for (int i = 0; i < docs.length(); i++) {
            catalogIds.add(docs.getJSONObject(i).getInt("catalogId_i"));
        }
        return catalogIds;
    }

    /** Partner-level data shared by every catalog response built in one request. */
    private static class CatalogBatchData {
        int warehouseId;
        Map<Integer, List<SaholicPOItem>> poItemAvailabilityMap;
        Map<Integer, Integer> partnerStockAvailabilityMap;
        Set<Integer> favouriteCatalogIds;
        Map<Integer, List<WebOffer>> webOffersMap;
        Map<Integer, List<ComboModel>> comboModelsByCatalogId;
        Map<Integer, PriceCircularItemModelNew> priceCircularItemModelMap;
        Map<Integer, List<CreateOfferRequest>> schemeOffersByCatalogId;
        Map<Integer, List<SaholicCISTable>> cisDataByItemId;
        Map<Integer, Item> itemMap;
        Map<Integer, Float> cashbackMap;
    }

    private CatalogBatchData buildCatalogBatchData(int fofoId, int warehouseId, List<Integer> catalogIds, List<Integer> itemIds) throws Exception {
        CatalogBatchData batch = new CatalogBatchData();
        batch.warehouseId = warehouseId;
        batch.poItemAvailabilityMap = saholicInventoryService.getSaholicPOItems().get(warehouseId);

        batch.priceCircularItemModelMap = new HashMap<>();
        batch.schemeOffersByCatalogId = new HashMap<>();
        if (catalogIds.size() > 0) {
            PriceCircularModel priceCircularModel = priceCircularService.getPriceCircularByOffer(fofoId, catalogIds, LocalDate.now());
            List<CreateOfferRequest> allSchemOffers = priceCircularModel.getOffers();

            List<PriceCircularItemModelNew> priceCircularItemModelNews = priceCircularModel.getPriceCircularItemModelNews();
            if (priceCircularItemModelNews != null) {
                batch.priceCircularItemModelMap = priceCircularItemModelNews.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));
            }
            // Filter null slab payouts and align the surviving ones with the offer list exactly
            // once per catalog. The models are shared when a catalog appears in more than one
            // listing, and the iterator.remove() below breaks the index alignment on a second pass.
            for (PriceCircularItemModelNew model : batch.priceCircularItemModelMap.values()) {
                if (model.getSlabPayouts() == null) {
                    continue;
                }
                List<CreateOfferRequest> schemeOffers = new ArrayList<>();
                Iterator<Map<Integer, AmountModel>> iterator = model.getSlabPayouts().iterator();
                int iteratorCount = 0;
                while (iterator.hasNext()) {
                    Map<Integer, AmountModel> slabPayoutMap = iterator.next();
                    if (slabPayoutMap != null) {
                        schemeOffers.add(allSchemOffers.get(iteratorCount));
                    } else {
                        iterator.remove();
                    }
                    iteratorCount++;
                }
                batch.schemeOffersByCatalogId.put(model.getCatalogId(), schemeOffers);
            }
        }

        if (fofoId > 0) {
            batch.partnerStockAvailabilityMap = currentInventorySnapshotRepository.selectItemsStock(fofoId).stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
        }
        batch.favouriteCatalogIds = catalogFavouriteRepository.selectBypartnerId(fofoId).stream()
                .map(CatalogFavourite::getCatalogId)
                .collect(Collectors.toSet());

        batch.cisDataByItemId = saholicCISTableRepository
                .selectByItemWarehouse(itemIds, warehouseId).stream()
                .collect(Collectors.groupingBy(SaholicCISTable::getItemId));

        batch.itemMap = itemRepository.selectByIds(new HashSet<>(itemIds)).stream()
                .collect(Collectors.toMap(Item::getId, x -> x));

        batch.cashbackMap = schemeService.getCatalogSchemeCashBack(fofoId, catalogIds);

        batch.webOffersMap = webOfferRepository.selectAllActiveOffers();

        batch.comboModelsByCatalogId = comboModelRepository.selectByWarehouseId(warehouseId)
                .stream().collect(Collectors.groupingBy(ComboModel::getCatalogId));
        return batch;
    }

    private List<FofoCatalogResponse> buildCatalogResponses(JSONArray docs, boolean hotDeal, int fofoId, CatalogBatchData batch) throws Exception {
        List<FofoCatalogResponse> dealResponse = new ArrayList<>();
        int warehouseId = batch.warehouseId;
        Map<Integer, List<SaholicPOItem>> poItemAvailabilityMap = batch.poItemAvailabilityMap;
        Map<Integer, Integer> partnerStockAvailabilityMap = batch.partnerStockAvailabilityMap;
        Set<Integer> favouriteCatalogIds = batch.favouriteCatalogIds;
        Map<Integer, List<WebOffer>> webOffersMap = batch.webOffersMap;
        Map<Integer, List<ComboModel>> comboModelsByCatalogId = batch.comboModelsByCatalogId;
        Map<Integer, PriceCircularItemModelNew> priceCircularItemModelMap = batch.priceCircularItemModelMap;
        Map<Integer, List<SaholicCISTable>> cisDataByItemId = batch.cisDataByItemId;
        Map<Integer, Item> itemMap = batch.itemMap;
        Map<Integer, Float> cashbackMap = batch.cashbackMap;

        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"));
            fofoCatalogResponse.setSuperCatalogTitle(doc.getString("superCatalog_s"));
            fofoCatalogResponse.setSuperCatalogId(doc.getInt("superCatalog_i"));
            fofoCatalogResponse.setSuperCatalogVariants(doc.getString("superCatalogVariants_s"));

            // optional, since default is false
            fofoCatalogResponse.setFavourite(favouriteCatalogIds.contains(fofoCatalogResponse.getCatalogId()));
            List<WebOffer> webOffers = webOffersMap.get(fofoCatalogResponse.getCatalogId());

            //logger.info("webOffers {}", webOffers);
            if (webOffers != null && webOffers.size() > 0) {
                fofoCatalogResponse.setWebOffers(webOffers);
                fofoCatalogResponse.setOffers(webOffers.stream().map(x -> x.getTitle()).collect(Collectors.toList()));
            }

            /*Map<Integer, OfferDiscoveryResponse> pineResponse = pinelabsOfferCacheService.getCachedOffersForItems(fofoCatalogResponse.getItems().stream().map(x -> (int) x.getItem_id()).collect(Collectors.toList()));
            if (pineResponse != null && pineResponse.size() > 0) {
                fofoCatalogResponse.setPineOffers(pineResponse);
            }*/

            List<ComboModel> comboModels = comboModelsByCatalogId.get(fofoCatalogResponse.getCatalogId());

            //logger.info("comboModels {}", comboModels);

            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("label_ss")) {
                JSONArray arr = doc.getJSONArray("label_ss");
                Set<String> labels = new HashSet<String>();
                for (int j = 0; j < arr.length(); j++) {
                    labels.add(arr.getString(j));
                }

                fofoCatalogResponse.setLabels(new ArrayList<>(labels));

            }
            if (doc.has("similarModels_ii")) {
                JSONArray similarModelsArray = doc.getJSONArray("similarModels_ii");
                List<Integer> similarCatalogIds = new ArrayList<>();
                for (int j = 0; j < similarModelsArray.length(); j++) {
                    similarCatalogIds.add(similarModelsArray.getInt(j));
                }
                fofoCatalogResponse.setSimilarModelIds(similarCatalogIds);
            }

            if (doc.has("_childDocuments_")) {
                String modelColorClass = "grey";
                FofoAvailabilityInfo fdiAnyColour = null;
                // Iterating itemIds
                for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
                    PriceCircularItemModelNew 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");
                    int partnerAvailability = partnerStockAvailabilityMap.get(itemId) == null ? 0 : partnerStockAvailabilityMap.get(itemId);
                    if (!fofoAvailabilityInfoMap.containsKey(itemId)) {
                        OfferDiscoveryResponse offers = pinelabsOfferCacheService.getCachedOfferForItem(itemId);
                        FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
                        fdi.setOffers(offers);
                        List<SaholicCISTable> currentAvailability = cisDataByItemId.getOrDefault(itemId, new ArrayList<>());
                        List<SaholicPOItem> poItemAvailability = null;
                        if (poItemAvailabilityMap != null) {
                            poItemAvailability = poItemAvailabilityMap.get(itemId);
                        }

                        if (priceCircularItemModel != null) {
                            fdi.setNlc((float) priceCircularItemModel.getNetNlc());
                        }

                        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) {
                            for (SaholicPOItem saholicPOItem : poItemAvailability) {
                                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 (!"green".equals(modelColorClass)) {
                                    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.setBrand((String) doc.getJSONArray("brand_ss").get(0));
                        fdi.setCategoryId(doc.getInt("subCategoryId_i"));
                        fdi.setTagId(childItem.getInt("tagId_i"));
                        fdi.setItem_id(itemId);
                        fdi.setCatalog_id(doc.getInt("catalogId_i"));
                        Float cashBack = cashbackMap.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);
                            }
                            fdi.setPartnerAvailability(partnerAvailability);
                        } else {
                            // Lets consider that its out of stock
                            fdi.setAvailability(400);
                            Item item = itemMap.get(itemId);
                            // In case its tampered glass moq should be
                            if (item != null && item.getCategoryId() == 10020) {
                                fdi.setMinBuyQuantity(5);
                            }
                        }
                        fdi.setQuantityStep(1);
                        fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 400));
                        fofoAvailabilityInfoMap.put(itemId, fdi);
                    }
                }
                if (fdiAnyColour != null) {
                    fdiAnyColour.setColorClass(modelColorClass);
                }
                fofoCatalogResponse.setInStock(!modelColorClass.equals("grey"));
            }
            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())) {
                    PriceCircularItemModelNew priceCircularItemModel = priceCircularItemModelMap.get(fofoCatalogResponse.getCatalogId());
                    List<CreateOfferRequest> schemeOffers = batch.schemeOffersByCatalogId.get(fofoCatalogResponse.getCatalogId());
                    if (schemeOffers != null) {
                        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 {
        List<FofoCatalogResponse> dealResponse = new ArrayList<>();
        List<Integer> tagIds = Arrays.asList(4);

        Map<Integer, TagListing> itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemFilter.keySet(), new HashSet<>(tagIds)).stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x));

        // Pre-fetch all items (batch query instead of N+1)
        Map<Integer, Item> itemMap = itemRepository.selectByIds(itemFilter.keySet()).stream()
                .collect(Collectors.toMap(Item::getId, 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);
                    fdi.setCatalog_id(doc.getInt("catalogId_i"));
                    Item item = itemMap.get(itemId);
                    // In case its tampered glass moq should be 5
                    if (item != null && 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);
    }

    @RequestMapping(value = "/checkCombo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> checkCombo(HttpServletRequest request, @RequestParam int catalogId,
                                        @RequestParam int warehouseId, @RequestParam int qty) throws Exception {
        boolean isCombo = false;
        ComboModel comboModel = comboModelRepository.selectByCatalogIdWarehouseIdAndQty(catalogId, warehouseId, qty);
        if (comboModel != null) {
            isCombo = true;
        }

        return responseSender.ok(isCombo);
    }

    @GetMapping(value = "/partner/wodCompleteBrands", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> getWodcompletBrands(HttpServletRequest request) throws Exception {
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
        BrandAndAddToCartEligibleModel brandAndAddToCartEligibleModel = brandsService.wodcompletBrands(userInfo.getRetailerId());
        return responseSender.ok(brandAndAddToCartEligibleModel);
    }

    @RequestMapping(value = "/pinelabs/offers", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> getPineLabsOffers(@RequestBody OfferDiscoveryRequest offerDiscoveryRequest) {
        logger.info("pinelabs offers {}", offerDiscoveryRequest);
        OfferDiscoveryResponse pineLabsOffers = pinelabsAffordabilityService.discoverOffers(offerDiscoveryRequest);
        logger.info("pinelabs offers response {}", pineLabsOffers);
        return responseSender.ok(pineLabsOffers);
    }

    @RequestMapping(value = "/pinelabs/offers/cache", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> cachePineLabsOffers() {
        pinelabsOfferCacheService.cacheAllItemOffers();
        return responseSender.ok("PineLabs offers cache initiated");
    }

    @RequestMapping(value = "/pinelabs/offers/{itemId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> pineLabsOfferById(@PathVariable int itemId) {
        List<Integer> itemIds = new ArrayList<>();
        itemIds.add(itemId);
        Map<Integer, Map<String, List<Tenure>>> pineLabsOffers = pinelabsOfferCacheService.getGroupedCachedOffersForItems(itemIds);
        return responseSender.ok(pineLabsOffers);
    }

    @RequestMapping(value = "/pinelabs/offers/downpayment", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> getPineLabsDownpaymentDetails(@RequestBody DownpaymentDetailsRequest request) {
        logger.info("pinelabs downpayment details request");
        DownpaymentDetailsResponse response = pinelabsAffordabilityService.getDownpaymentDetails(request);
        return responseSender.ok(response);
    }

    @RequestMapping(value = "/pinelabs/offers/cardless", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> getPineLabsCardlessOffers(@RequestBody OfferDiscoveryRequest offerDiscoveryRequest) {
        logger.info("pinelabs cardless discovery request {}", offerDiscoveryRequest);
        OfferDiscoveryResponse response = pinelabsAffordabilityService.discoverCardlessOffers(offerDiscoveryRequest);
        return responseSender.ok(response);
    }

    @RequestMapping(value = "/pinelabs/offers/validate", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> validatePineLabsOffer(@RequestBody OfferValidateRequest request) {
        logger.info("pinelabs offer validate request");
        OfferValidateResponse response = pinelabsAffordabilityService.validateOffer(request);
        return responseSender.ok(response);
    }

    @RequestMapping(value = "/pinelabs/offers/create", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> createPineLabsOffer(@RequestBody PineLablsCreateOfferRequest request) {
        logger.info("pinelabs create offer request for orderId {}", request.getOrderId());
        CreateOfferResponse response = pinelabsAffordabilityService.createOffer(request);
        return responseSender.ok(response);
    }

    @RequestMapping(value = "/pinelabs/imei/{orderId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> validateImei(@PathVariable String orderId, @RequestBody Map<String, String> body) {
        String imei = body.get("imei");
        logger.info("pinelabs IMEI validation for orderId {} imei {}", orderId, imei);
        ImeiValidationResponse response = pinelabsDeviceService.validateImei(orderId, imei);
        return responseSender.ok(response);
    }

}