Subversion Repositories SmartDukaan

Rev

Rev 24163 | Rev 24577 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.web.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

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 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.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.web.client.RestClient;
import com.spice.profitmandi.common.web.util.ResponseSender;
import com.spice.profitmandi.dao.entity.catalog.Item;
import com.spice.profitmandi.dao.entity.catalog.TagListing;
import com.spice.profitmandi.dao.entity.inventory.ItemAvailabilityCache;
import com.spice.profitmandi.dao.model.UserCart;
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
import com.spice.profitmandi.dao.repository.dtr.Mongo;
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
import com.spice.profitmandi.dao.repository.inventory.ItemAvailabilityCacheRepository;
import com.spice.profitmandi.service.authentication.RoleManager;
import com.spice.profitmandi.service.pricing.PricingService;
import com.spice.profitmandi.web.res.AvailabilityInfo;
import com.spice.profitmandi.web.res.DealBrands;
import com.spice.profitmandi.web.res.DealObjectResponse;
import com.spice.profitmandi.web.res.DealsResponse;
import com.spice.profitmandi.web.res.FofoAvailabilityInfo;
import com.spice.profitmandi.web.res.FofoCatalogResponse;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@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("${python.api.port}")
        private int port;

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

        @Autowired
        private PricingService pricingService;

        @Autowired
        private Mongo mongoClient;

        @Autowired
        private UserAccountRepository userAccountRepository;

        @Autowired
        private ResponseSender<?> responseSender;

        @Autowired
        private TagListingRepository tagListingRepository;

        @Autowired
        private ItemRepository itemRepository;

        @Autowired
        private ItemAvailabilityCacheRepository itemAvailabilityCacheRepository;

        @Autowired
        private RoleManager roleManagerService;

        List<String> filterableParams = Arrays.asList("brand");
        public static final Map<String, List<String>> EMAIL_BLOCKED_BRANDS = new HashMap<>();
        
        static {
                EMAIL_BLOCKED_BRANDS.put("sachinindri2006@gmail.com", Arrays.asList("Vivo"));
                EMAIL_BLOCKED_BRANDS.put("akamboj828@gmail.com", Arrays.asList("Vivo"));
        }

        @RequestMapping(value = ProfitMandiConstants.URL_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 deals")
        public ResponseEntity<?> getDeals(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 ProfitMandiBusinessException {
                logger.info("Request " + request.getParameterMap());
                String response = null;
                int userId = (int) request.getAttribute("userId");

                // If pincode belongs to Specific warehouse marked
                // availability should be fetched for that warehouse only
                // show only skus belonging to that specific
                // else use normal flow
                UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
                // TODO: move to properties
                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("filterData", filterData);
                params.put("source", "deals");
                if (roleManagerService.isPartner(userInfo.getRoleIds())) {
                        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 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 OR 6)") 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 = "hotDeal", required = false) boolean hotDeal) throws Throwable {
                List<FofoCatalogResponse> dealResponse = new ArrayList<>();
                UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
                if (roleManagerService.isPartner(userInfo.getRoleIds())) {
                        UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
                        List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(uc.getUserId());
                        RestClient rc = new RestClient();
                        Map<String, String> params = new HashMap<>();
                        List<String> mandatoryQ = new ArrayList<>();
                        if (brand != null) {

                                mandatoryQ.add(
                                                String.format("+(categoryId_i:%s) +(brand_ss:%s) +{!parent which=\"brand_ss:%s\"} tagId_i:(%s)",
                                                                categoryId, brand, brand, StringUtils.join(tagIds, " ")));
                        } else if (hotDeal) {
                                mandatoryQ.add(String.format("+{!parent which=\"hot_deals_b=true\"} tagId_i:(%s)",
                                                StringUtils.join(tagIds, " ")));
                        } else {
                                mandatoryQ.add(
                                                String.format("+{!parent which=\"id:catalog*\"} tagId_i:(%s)", 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("start", String.valueOf(offset));
                        params.put("rows", String.valueOf(limit));
                        params.put("wt", "json");
                        String response = null;
                        try {
                                response = rc.get(SchemeType.HTTP, "dtr", 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, hotDeal);
                        if(EMAIL_BLOCKED_BRANDS.containsKey(userInfo.getEmail())) {
                                dealResponse.stream().filter(x->EMAIL_BLOCKED_BRANDS.get(userInfo.getEmail()).contains(x.getBrand()));
                        }
                } else {
                        return responseSender.badRequest(
                                        new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
                }
                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);
        }

        /*
         * @RequestMapping(value = "/direct-deals", method=RequestMethod.GET,produces =
         * MediaType.APPLICATION_JSON_VALUE)
         * 
         * @ApiImplicitParams({
         * 
         * @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true,
         * dataType = "string", paramType = "header") }) public ResponseEntity<?>
         * getDirectDeals(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 ){
         * 
         * return new ResponseEntity<>(profitMandiResponse,HttpStatus.OK); }
         */

        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;
                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 properties
                String 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();
                        }
                }
                /*
                 * final ProfitMandiResponse<?> profitMandiResponse = new
                 * ProfitMandiResponse<>(LocalDateTime.now(),
                 * request.getRequestURL().toString(), HttpStatus.OK.toString(), HttpStatus.OK,
                 * ResponseStatus.SUCCESS, dealsResponse);
                 */
                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 ProfitMandiBusinessException {
                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, "dtr", 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);
                } 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) {
                UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
                List<DBObject> brandsDisplay = mongoClient.getBrandsToDisplay(categoryId);
                if(EMAIL_BLOCKED_BRANDS.containsKey(userInfo.getEmail())) {
                        List<String> blockedBrands = EMAIL_BLOCKED_BRANDS.get(userInfo.getEmail());
                        brandsDisplay.stream().filter(x->{
                                return blockedBrands.contains(x.get("name").toString());
                        });
                }
                return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
        }

        @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);
        }

        private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal)
                        throws ProfitMandiBusinessException {
                Map<Integer, TagListing> itemTagListingMap = null;
                List<FofoCatalogResponse> dealResponse = new ArrayList<>();
                List<Integer> tagIds = Arrays.asList(4);
                if (docs.length() > 0) {
                        HashSet<Integer> itemsSet = new HashSet<>();
                        for (int i = 0; i < docs.length(); i++) {
                                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");
                                        itemsSet.add(itemId);
                                }
                        }
                        itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemsSet, 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);
                        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));

                        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 (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.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 5
                                        if (item.getCategoryId() == 10020) {
                                                fdi.setMinBuyQuantity(10);
                                        } else {
                                                fdi.setMinBuyQuantity(1);
                                        }
                                        if (hotDeal || !tl.isActive()) {

                                                int totalAvailability = 0; // Using item availability
                                                                                                        // cache for now but can be
                                                                                                        // changed to
                                                                                                        // use caching later.
                                                try {
                                                        ItemAvailabilityCache iac = itemAvailabilityCacheRepository.selectByItemId(itemId);
                                                        totalAvailability = iac.getTotalAvailability();
                                                        fdi.setAvailability(totalAvailability);
                                                } catch (Exception e) {
                                                        continue;
                                                }
                                                if (totalAvailability <= 0) {
                                                        continue;
                                                }
                                        } else {
                                                // For accessories item availability should at be ordered for Rs.1000
                                                if (item.getCategoryId() == 10020 || fdi.getSellingPrice() < 100) {
                                                        fdi.setAvailability((int) Math.ceil(1000 / fdi.getSellingPrice()));
                                                } else {
                                                        fdi.setAvailability(10);
                                                }
                                        }
                                        fdi.setQuantityStep(1);
                                        fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
                                        fofoAvailabilityInfoMap.put(itemId, fdi);
                                }
                        }
                        if (fofoAvailabilityInfoMap.values().size() > 0) {
                                ffdr.setItems(new ArrayList<FofoAvailabilityInfo>(fofoAvailabilityInfoMap.values()));
                                dealResponse.add(ffdr);
                        }
                }
                return dealResponse;

        }

}