Subversion Repositories SmartDukaan

Rev

Rev 35369 | Rev 35411 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
21339 kshitij.so 1
package com.spice.profitmandi.web.controller;
2
 
3
import com.eclipsesource.json.Json;
4
import com.eclipsesource.json.JsonArray;
5
import com.eclipsesource.json.JsonObject;
6
import com.eclipsesource.json.JsonValue;
7
import com.google.gson.Gson;
21356 kshitij.so 8
import com.google.gson.reflect.TypeToken;
25010 amit.gupta 9
import com.mongodb.BasicDBObject;
24163 amit.gupta 10
import com.mongodb.DBObject;
21643 ashik.ali 11
import com.spice.profitmandi.common.enumuration.SchemeType;
21339 kshitij.so 12
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
33929 tejus.loha 13
import com.spice.profitmandi.common.model.BrandAndAddToCartEligibleModel;
21339 kshitij.so 14
import com.spice.profitmandi.common.model.ProfitMandiConstants;
22289 amit.gupta 15
import com.spice.profitmandi.common.model.UserInfo;
27030 amit.gupta 16
import com.spice.profitmandi.common.solr.SolrService;
21643 ashik.ali 17
import com.spice.profitmandi.common.web.client.RestClient;
22319 amit.gupta 18
import com.spice.profitmandi.common.web.util.ResponseSender;
30686 amit.gupta 19
import com.spice.profitmandi.dao.entity.catalog.*;
31507 tejbeer 20
import com.spice.profitmandi.dao.entity.dtr.WebListing;
30595 tejbeer 21
import com.spice.profitmandi.dao.entity.dtr.WebOffer;
33929 tejus.loha 22
import com.spice.profitmandi.dao.entity.fofo.*;
30669 amit.gupta 23
import com.spice.profitmandi.dao.entity.inventory.SaholicCISTable;
27032 amit.gupta 24
import com.spice.profitmandi.dao.entity.inventory.SaholicPOItem;
31572 tejbeer 25
import com.spice.profitmandi.dao.enumuration.dtr.WebListingSource;
31507 tejbeer 26
import com.spice.profitmandi.dao.enumuration.dtr.WebListingType;
31954 amit.gupta 27
import com.spice.profitmandi.dao.model.AmountModel;
30188 amit.gupta 28
import com.spice.profitmandi.dao.model.CreateOfferRequest;
22361 amit.gupta 29
import com.spice.profitmandi.dao.model.UserCart;
30686 amit.gupta 30
import com.spice.profitmandi.dao.repository.catalog.*;
32978 amit.gupta 31
import com.spice.profitmandi.dao.repository.dtr.*;
31625 tejbeer 32
import com.spice.profitmandi.dao.repository.fofo.CatalogFavouriteRepository;
34260 vikas.jang 33
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
26846 tejbeer 34
import com.spice.profitmandi.dao.repository.fofo.SuggestedPoDetailRepository;
26847 tejbeer 35
import com.spice.profitmandi.dao.repository.fofo.SuggestedPoRepository;
30669 amit.gupta 36
import com.spice.profitmandi.dao.repository.inventory.SaholicCISTableRepository;
33929 tejus.loha 37
import com.spice.profitmandi.dao.repository.onboarding.BrandCommitRepository;
23798 amit.gupta 38
import com.spice.profitmandi.service.authentication.RoleManager;
31507 tejbeer 39
import com.spice.profitmandi.service.catalog.BrandsService;
30686 amit.gupta 40
import com.spice.profitmandi.service.inventory.*;
31954 amit.gupta 41
import com.spice.profitmandi.service.pricecircular.PriceCircularItemModelNew;
30123 amit.gupta 42
import com.spice.profitmandi.service.pricecircular.PriceCircularModel;
43
import com.spice.profitmandi.service.pricecircular.PriceCircularService;
22287 amit.gupta 44
import com.spice.profitmandi.service.pricing.PricingService;
26695 amit.gupta 45
import com.spice.profitmandi.service.scheme.SchemeService;
21356 kshitij.so 46
import com.spice.profitmandi.web.res.DealBrands;
21339 kshitij.so 47
import com.spice.profitmandi.web.res.DealObjectResponse;
48
import com.spice.profitmandi.web.res.DealsResponse;
49
import io.swagger.annotations.ApiImplicitParam;
50
import io.swagger.annotations.ApiImplicitParams;
51
import io.swagger.annotations.ApiOperation;
30686 amit.gupta 52
import org.apache.commons.lang3.StringUtils;
53
import org.apache.http.conn.HttpHostConnectException;
54
import org.apache.logging.log4j.LogManager;
55
import org.apache.logging.log4j.Logger;
56
import org.json.JSONArray;
57
import org.json.JSONObject;
58
import org.springframework.beans.factory.annotation.Autowired;
59
import org.springframework.beans.factory.annotation.Value;
60
import org.springframework.http.HttpStatus;
61
import org.springframework.http.MediaType;
62
import org.springframework.http.ResponseEntity;
63
import org.springframework.stereotype.Controller;
64
import org.springframework.transaction.annotation.Transactional;
33929 tejus.loha 65
import org.springframework.web.bind.annotation.*;
21339 kshitij.so 66
 
30686 amit.gupta 67
import javax.servlet.http.HttpServletRequest;
31954 amit.gupta 68
import java.time.LocalDate;
31625 tejbeer 69
import java.time.LocalDateTime;
30686 amit.gupta 70
import java.util.*;
71
import java.util.concurrent.atomic.AtomicInteger;
72
import java.util.stream.Collectors;
73
 
21339 kshitij.so 74
@Controller
22319 amit.gupta 75
@Transactional(rollbackFor = Throwable.class)
21339 kshitij.so 76
public class DealsController {
77
 
32339 tejbeer 78
    private static final Logger logger = LogManager.getLogger(DealsController.class);
79
    private static final List<Integer> TAG_IDS = Arrays.asList(4);
21339 kshitij.so 80
 
32339 tejbeer 81
    @Value("${python.api.host}")
82
    private String host;
23816 amit.gupta 83
 
32339 tejbeer 84
    @Value("${new.solr.url}")
85
    private String solrUrl;
26889 amit.gupta 86
 
32339 tejbeer 87
    @Value("${python.api.port}")
88
    private int port;
23816 amit.gupta 89
 
32339 tejbeer 90
    @Autowired
91
    RestClient restClient;
27051 amit.gupta 92
 
32339 tejbeer 93
    @Autowired
94
    SolrService solrService;
26889 amit.gupta 95
 
32339 tejbeer 96
    @Autowired
33873 ranu 97
    com.spice.profitmandi.web.services.SolrService webSolrService;
98
 
99
    @Autowired
32339 tejbeer 100
    InventoryService inventoryService;
26924 amit.gupta 101
 
32339 tejbeer 102
    // This is now unused as we are not supporting multiple companies.
103
    @Value("${gadgetCops.invoice.cc}")
104
    private String[] ccGadgetCopInvoiceTo;
22319 amit.gupta 105
 
32339 tejbeer 106
    @Autowired
107
    private PricingService pricingService;
23816 amit.gupta 108
 
32339 tejbeer 109
    @Autowired
110
    private CategoryRepository categoryRepository;
25010 amit.gupta 111
 
32339 tejbeer 112
    @Autowired
113
    private SchemeService schemeService;
26695 amit.gupta 114
 
32339 tejbeer 115
    @Autowired
116
    private SaholicInventoryService saholicInventoryService;
26889 amit.gupta 117
 
32339 tejbeer 118
    @Autowired
119
    private Mongo mongoClient;
25879 amit.gupta 120
 
32339 tejbeer 121
    @Autowired
122
    private ItemBucketService itemBucketService;
23816 amit.gupta 123
 
32339 tejbeer 124
    @Autowired
125
    private UserAccountRepository userAccountRepository;
27051 amit.gupta 126
 
32339 tejbeer 127
    @Autowired
128
    private FofoStoreRepository fofoStoreRepository;
23816 amit.gupta 129
 
32339 tejbeer 130
    @Autowired
131
    private ResponseSender<?> responseSender;
23816 amit.gupta 132
 
32339 tejbeer 133
    @Autowired
134
    private TagListingRepository tagListingRepository;
23816 amit.gupta 135
 
32339 tejbeer 136
    @Autowired
137
    private ItemRepository itemRepository;
138
    @Autowired
139
    private PriceCircularService priceCircularService;
23816 amit.gupta 140
 
32339 tejbeer 141
    @Autowired
142
    private RoleManager roleManagerService;
23816 amit.gupta 143
 
32339 tejbeer 144
    @Autowired
32978 amit.gupta 145
    private SuggestedPoDetailRepository suggestedPoDetailRepository;
26846 tejbeer 146
 
32339 tejbeer 147
    @Autowired
148
    private SuggestedPoRepository suggestedPoRepository;
26847 tejbeer 149
 
32339 tejbeer 150
    @Autowired
151
    private WebOfferRepository webOfferRepository;
30595 tejbeer 152
 
32339 tejbeer 153
    @Autowired
154
    private ComboModelRepository comboModelRepository;
30683 tejbeer 155
 
32339 tejbeer 156
    @Autowired
157
    private ComboMappedModelRepository comboMappedModelRepository;
30683 tejbeer 158
 
32339 tejbeer 159
    @Autowired
160
    private BrandsService brandsService;
31547 tejbeer 161
 
32339 tejbeer 162
    @Autowired
163
    private WebListingRepository webListingRepository;
31547 tejbeer 164
 
32339 tejbeer 165
    @Autowired
166
    private WebProductListingRepository webProductListingRepository;
31547 tejbeer 167
 
32339 tejbeer 168
    @Autowired
169
    private CatalogFavouriteRepository catalogFavouriteRepository;
31625 tejbeer 170
 
33929 tejus.loha 171
    @Autowired
172
    PartnerOnBoardingPanelRepository partnerOnBoardingPanelRepository;
173
 
174
    @Autowired
175
    PartnerDealerRepository partnerDealerRepository;
176
 
177
    @Autowired
178
    BrandCommitRepository brandCommitRepository;
179
 
180
    @Autowired
181
    CatalogRepository catalogRepository;
182
 
34260 vikas.jang 183
    @Autowired
184
    private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
185
 
32339 tejbeer 186
    List<String> filterableParams = Arrays.asList("brand");
24949 amit.gupta 187
 
32339 tejbeer 188
    @RequestMapping(value = "/fofo/buckets", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
189
    public ResponseEntity<?> getBuckets(HttpServletRequest request) throws ProfitMandiBusinessException {
190
        logger.info("Request " + request.getParameterMap());
191
        return responseSender.ok(itemBucketService.getBuckets(Optional.of(true)));
192
    }
25879 amit.gupta 193
 
32339 tejbeer 194
    @RequestMapping(value = "/fofo/bucket", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
195
    public ResponseEntity<?> getBucketDetails(HttpServletRequest request, @RequestParam int id) throws ProfitMandiBusinessException {
196
        List<ItemQuantityPojo> iqPojo = itemBucketService.getBucketDetails(id);
197
        Map<Integer, Integer> itemIdsQtyMap = iqPojo.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x.getQuantity()));
198
        Set<Integer> catalogIds = itemRepository.selectByIds(itemIdsQtyMap.keySet()).stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet());
199
        Map<String, String> params = new HashMap<>();
200
        List<String> mandatoryQ = new ArrayList<>();
201
        mandatoryQ.add(
202
                String.format("+catalogId_i:(%s) +{!parent which=\"id:catalog*\"}", StringUtils.join(catalogIds, " ")));
203
        params.put("start", "0");
204
        params.put("rows", "100");
205
        params.put("q", StringUtils.join(mandatoryQ, " "));
206
        params.put("fl", "*, [child parentFilter=id:catalog*]");
25879 amit.gupta 207
 
32339 tejbeer 208
        params.put("wt", "json");
209
        String response = null;
210
        try {
35410 amit 211
            response = restClient.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
32339 tejbeer 212
        } catch (HttpHostConnectException e) {
213
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
214
        }
215
        JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
216
        JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
217
        List<FofoCatalogResponse> dealResponse = getCatalogSingleSkuResponse(docs, itemIdsQtyMap, false);
26051 amit.gupta 218
 
32339 tejbeer 219
        Bucket bucket = itemBucketService.getBuckets(Optional.of(true)).stream().filter(x -> x.getId() == id).collect(Collectors.toList()).get(0);
220
        bucket.setFofoCatalogResponses(dealResponse);
221
        return responseSender.ok(bucket);
222
    }
25879 amit.gupta 223
 
32339 tejbeer 224
    @RequestMapping(value = "/fofo/suggestedPo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
225
    public ResponseEntity<?> getSuggestedPo(HttpServletRequest request, @RequestParam int id) throws ProfitMandiBusinessException {
34436 ranu 226
        int userId = (int) request.getAttribute("userId");
227
        UserCart uc = userAccountRepository.getUserCart(userId);
228
        int fofoId = uc.getUserId();
229
        SuggestedPo  suggestedPo = suggestedPoRepository.selectAllOpenPoByFofoId(fofoId).get(0);
230
        if(suggestedPo == null){
231
            throw new ProfitMandiBusinessException("", "", "Open po is not available in list");
232
        }
233
        List<SuggestedPoDetail> mpd = suggestedPoDetailRepository.selectByPoId(suggestedPo.getId());
32339 tejbeer 234
        Map<Integer, Integer> itemIdsQtyMap = mpd.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x.getQuantity()));
26846 tejbeer 235
 
32339 tejbeer 236
        Set<Integer> catalogIds = itemRepository.selectByIds(itemIdsQtyMap.keySet()).stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet());
35410 amit 237
                Map<String, String> params = new HashMap<>();
32339 tejbeer 238
        List<String> mandatoryQ = new ArrayList<>();
239
        mandatoryQ.add(
240
                String.format("+catalogId_i:(%s) +{!parent which=\"id:catalog*\"}", StringUtils.join(catalogIds, " ")));
241
        params.put("start", "0");
242
        params.put("rows", "100");
243
        params.put("q", StringUtils.join(mandatoryQ, " "));
244
        params.put("fl", "*, [child parentFilter=id:catalog*]");
26846 tejbeer 245
 
32339 tejbeer 246
        params.put("wt", "json");
247
        String response = null;
248
        try {
35410 amit 249
            response = restClient.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
32339 tejbeer 250
        } catch (HttpHostConnectException e) {
251
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
252
        }
253
        JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
254
        JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
255
        List<FofoCatalogResponse> dealResponse = getCatalogSingleSkuResponse(docs, itemIdsQtyMap, false);
26846 tejbeer 256
 
32339 tejbeer 257
        return responseSender.ok(dealResponse);
258
    }
26846 tejbeer 259
 
34436 ranu 260
    @RequestMapping(value = "/suggestedPo/status", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
32339 tejbeer 261
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
262
    @ApiOperation(value = "")
263
    public ResponseEntity<?> changeSuggestedPoStatus(HttpServletRequest request, @RequestParam int id) throws ProfitMandiBusinessException {
264
        SuggestedPo suggestedPo = suggestedPoRepository.selectById(id);
265
        suggestedPo.setStatus("closed");
33873 ranu 266
        //suggestedPo.setStatus(SuggestedPoStatus.valueOf("closed"));
26847 tejbeer 267
 
32339 tejbeer 268
        return responseSender.ok(true);
269
    }
26847 tejbeer 270
 
32339 tejbeer 271
    @RequestMapping(value = "/fofo/fovourites", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
272
    public ResponseEntity<?> getFavourites(HttpServletRequest request) throws Exception {
31625 tejbeer 273
 
32339 tejbeer 274
        int userId = (int) request.getAttribute("userId");
275
        UserCart uc = userAccountRepository.getUserCart(userId);
276
        int fofoId = uc.getUserId();
277
        List<FofoCatalogResponse> dealResponse = new ArrayList<>();
278
        Set<Integer> catalogIds = catalogFavouriteRepository.selectBypartnerId(fofoId).stream().map(x -> x.getCatalogId()).collect(Collectors.toSet());
279
        if (!catalogIds.isEmpty()) {
33929 tejus.loha 280
            dealResponse = webSolrService.dealResponse(catalogIds, fofoId);
32339 tejbeer 281
        }
282
        return responseSender.ok(dealResponse);
283
    }
31625 tejbeer 284
 
32339 tejbeer 285
    @RequestMapping(value = "/favourites/manage", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
286
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
287
    @ApiOperation(value = "")
288
    public ResponseEntity<?> mangeFavourites(HttpServletRequest request, @RequestParam int catalogId) throws ProfitMandiBusinessException {
31625 tejbeer 289
 
32339 tejbeer 290
        int userId = (int) request.getAttribute("userId");
291
        UserCart uc = userAccountRepository.getUserCart(userId);
292
        int fofoId = uc.getUserId();
31625 tejbeer 293
 
32339 tejbeer 294
        CatalogFavourite catalogFavourite = catalogFavouriteRepository.selectBypartnerAndCatalogId(fofoId, catalogId);
31625 tejbeer 295
 
32339 tejbeer 296
        if (catalogFavourite == null) {
297
            catalogFavourite = new CatalogFavourite();
298
            catalogFavourite.setCatalogId(catalogId);
299
            catalogFavourite.setFofoId(fofoId);
300
            catalogFavourite.setCreatedTimestamp(LocalDateTime.now());
301
            catalogFavouriteRepository.persist(catalogFavourite);
31625 tejbeer 302
 
32978 amit.gupta 303
        } else {
32339 tejbeer 304
            catalogFavouriteRepository.deleteByPartnerAndCatalogId(fofoId, catalogId);
305
        }
306
        return responseSender.ok(true);
307
    }
31625 tejbeer 308
 
33249 ranu 309
    private String getCommaSeparateTags(int userId) throws ProfitMandiBusinessException {
32339 tejbeer 310
        UserCart uc = userAccountRepository.getUserCart(userId);
311
        List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(uc.getUserId());
312
        List<String> strTagIds = new ArrayList<>();
313
        for (Integer tagId : tagIds) {
314
            strTagIds.add(String.valueOf(tagId));
315
        }
316
        return String.join(",", strTagIds);
317
    }
22273 amit.gupta 318
 
33575 amit.gupta 319
    @RequestMapping(value = "/fofo/similar-models/{modelId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
320
    public ResponseEntity<?> similarModels(HttpServletRequest httpServletRequest, @PathVariable int modelId) throws Throwable {
321
        UserInfo userInfo = (UserInfo) httpServletRequest.getAttribute("userInfo");
322
        //FofoStore fs = fofoStoreRepository.selectByRetailerId(userInfo.getRetailerId());
323
 
324
        JSONObject jsonObject = solrService.getContentByCatalogIds(Arrays.asList(modelId)).get(modelId);
325
 
326
        JSONArray similarModelsArray = jsonObject.getJSONArray("similarModels_ii");
327
        List<Integer> similarCatalogIds = new ArrayList<>();
328
        for (int j = 0; j < similarModelsArray.length(); j++) {
329
            similarCatalogIds.add(similarModelsArray.getInt(j));
330
        }
331
 
332
        Map<String, String> params = new HashMap<>();
333
        List<String> mandatoryQ = new ArrayList<>();
334
 
335
        mandatoryQ.add(String.format(
336
                "+{!parent which=\"catalogId_i:(" + StringUtils.join(similarCatalogIds, " ") + ")\"} AND active_b:true AND show_default_b:true"));
337
 
338
        params.put("q", StringUtils.join(mandatoryQ, " "));
339
        params.put("fl", "*, [child parentFilter=id:catalog* childFilter=active_b:true ]");
340
        params.put("wt", "json");
341
        params.put("rows", similarCatalogIds.size() + "");
342
        try {
343
            String response = restClient.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
344
            JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
345
            JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
33576 amit.gupta 346
            return responseSender.ok(this.getCatalogResponse(docs, false, userInfo.getRetailerId()).stream().filter(x -> x.isInStock()).collect(Collectors.toList()));
33575 amit.gupta 347
        } catch (HttpHostConnectException e) {
348
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
349
        }
350
    }
351
 
32339 tejbeer 352
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
353
    @RequestMapping(value = "/fofo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
33573 amit.gupta 354
    public ResponseEntity<?> getFofo(HttpServletRequest request, @RequestParam(value = "categoryId", required = false, defaultValue = "3") String categoryId, @RequestParam(value = "offset") int offset,
34024 vikas.jang 355
                                     @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 {
33543 amit.gupta 356
        List<FofoCatalogResponse> dealResponse;
32339 tejbeer 357
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
358
        FofoStore fs = fofoStoreRepository.selectByRetailerId(userInfo.getRetailerId());
359
        sort = "w" + fs.getWarehouseId() + "_i desc";
31548 tejbeer 360
 
32339 tejbeer 361
        logger.info("endPoint {}", endPoint);
34024 vikas.jang 362
        logger.info("group Column {}", group);
31552 tejbeer 363
 
32339 tejbeer 364
        if (endPoint != null && !endPoint.trim().isEmpty()) {
365
            WebListing webListing = webListingRepository.selectByUrl(endPoint);
366
            dealResponse = this.getDealResponses(userInfo, webListing, offset, limit);
31552 tejbeer 367
 
32339 tejbeer 368
        } else {
31552 tejbeer 369
 
32339 tejbeer 370
            dealResponse = this.getCatalogResponse(
35369 ranu 371
                    solrService.getSolrDocs(queryTerm, categoryId, offset, limit, sort, brand, subCategoryId, hotDeal, group,true), hotDeal, userInfo.getRetailerId());
32339 tejbeer 372
        }
33573 amit.gupta 373
 
374
        Map<Integer, List<Integer>> similarModelMap = dealResponse.stream().filter(x -> x.getSimilarModelIds() != null && x.getSimilarModelIds().size() > 0)
375
                .collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getSimilarModelIds()));
376
        Set<Integer> similarModelIds = similarModelMap.values().stream().flatMap(x -> x.stream()).collect(Collectors.toSet());
377
        logger.info("similarModelIds - {}", similarModelIds);
33575 amit.gupta 378
        if (similarModelIds.size() > 0) {
33573 amit.gupta 379
 
33576 amit.gupta 380
            Map<Integer, FofoCatalogResponse> similarCatalogResponsesMap = this.getSimpleDocs(fs, similarModelIds).stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));
33573 amit.gupta 381
            logger.info("Similar Catalog ResponseMap - {}", similarCatalogResponsesMap.keySet());
382
 
383
            for (FofoCatalogResponse deal : dealResponse) {
384
                if (similarModelMap.containsKey(deal.getCatalogId())) {
385
                    List<Integer> similarCatalogIds = similarModelMap.get(deal.getCatalogId());
386
                    logger.info("Similar Catalog Ids - {}", similarCatalogIds);
33575 amit.gupta 387
                    List<FofoCatalogResponse> similarModels = similarCatalogIds.stream().filter(x -> similarCatalogResponsesMap.containsKey(x)).map(x -> similarCatalogResponsesMap.get(x)).collect(Collectors.toList());
33573 amit.gupta 388
                    deal.setSimilarModels(similarModels);
389
                }
390
            }
391
        }
32339 tejbeer 392
        return responseSender.ok(dealResponse);
393
    }
25015 amit.gupta 394
 
33576 amit.gupta 395
    private List<FofoCatalogResponse> getSimpleDocs(FofoStore fofoStore, Set<Integer> catalogIds) throws Exception {
33575 amit.gupta 396
        List<FofoCatalogResponse> fofoCatalogResponses = new ArrayList<>();
397
 
398
 
399
        Map<String, String> params = new HashMap<>();
400
        List<String> mandatoryQ = new ArrayList<>();
401
 
402
        mandatoryQ.add(String.format(
403
                "+{!parent which=\"catalogId_i:(" + StringUtils.join(catalogIds, " ") + ")\"} AND active_b:true AND show_default_b:true"));
404
 
405
        params.put("q", StringUtils.join(mandatoryQ, " "));
406
        params.put("fl", "*, [child parentFilter=id:catalog* childFilter=active_b:true ]");
407
        params.put("wt", "json");
408
        params.put("rows", catalogIds.size() + "");
409
 
33576 amit.gupta 410
        String response = restClient.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
411
        JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
412
        JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
35410 amit 413
        int warehouseId = fofoStore.getWarehouseId();
33576 amit.gupta 414
        Map<Integer, List<SaholicPOItem>> poItemAvailabilityMap = saholicInventoryService.getSaholicPOItems().get(warehouseId);
35410 amit 415
 
416
        // Pre-fetch all itemIds for batch CIS query
417
        List<Integer> allItemIds = new ArrayList<>();
33576 amit.gupta 418
        for (int i = 0; i < docs.length(); i++) {
419
            JSONObject doc = docs.getJSONObject(i);
35410 amit 420
            if (doc.has("_childDocuments_")) {
421
                for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
422
                    allItemIds.add(doc.getJSONArray("_childDocuments_").getJSONObject(j).getInt("itemId_i"));
423
                }
424
            }
425
        }
426
        // Batch fetch CIS data
427
        Map<Integer, List<SaholicCISTable>> cisDataByItemId = saholicCISTableRepository
428
                .selectByItemWarehouse(allItemIds, warehouseId).stream()
429
                .collect(Collectors.groupingBy(SaholicCISTable::getItemId));
430
 
431
        for (int i = 0; i < docs.length(); i++) {
432
            JSONObject doc = docs.getJSONObject(i);
33576 amit.gupta 433
            FofoCatalogResponse fofoCatalogResponse = this.toFofoCatalogResponse(doc);
434
            if (doc.has("_childDocuments_")) {
435
                String modelColorClass = "grey";
436
                FofoAvailabilityInfo fdiAnyColour = null;
437
                // Iterating itemIds
438
                for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
439
                    JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
440
                    int itemId = childItem.getInt("itemId_i");
441
 
35410 amit 442
                    List<SaholicCISTable> currentAvailability = cisDataByItemId.getOrDefault(itemId, new ArrayList<>());
33576 amit.gupta 443
                    List<SaholicPOItem> poItemAvailability = null;
444
                    if (poItemAvailabilityMap != null) {
445
                        poItemAvailability = poItemAvailabilityMap.get(itemId);
446
                    }
447
 
448
                    for (SaholicCISTable saholicCISTable : currentAvailability) {
449
                        saholicCISTable.setWarehouseName(
450
                                ProfitMandiConstants.WAREHOUSE_MAP.get(saholicCISTable.getWarehouseFrom()));
451
                    }
452
 
453
 
454
                    String poColor = "grey";
455
                    boolean active = false;
456
                    if (currentAvailability != null && currentAvailability.stream().collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)) > 0) {
457
                        poColor = "green";
458
                        modelColorClass = "green";
459
                    } else if (poItemAvailability != null && poItemAvailability.stream().collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty)) > 0) {
460
                        if (currentAvailability != null && poItemAvailability.stream().collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty)) + currentAvailability.stream().collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)) <= 0) {
461
                            poColor = "grey";
462
                        } else {
463
                            poColor = "yellow";
464
                            if (!modelColorClass.equals("green")) {
465
                                modelColorClass = poColor;
466
                            }
467
                        }
468
                    }
469
 
470
                }
471
                fofoCatalogResponse.setInStock(!modelColorClass.equals("grey"));
33575 amit.gupta 472
            }
33576 amit.gupta 473
 
474
            fofoCatalogResponses.add(fofoCatalogResponse);
33575 amit.gupta 475
        }
33576 amit.gupta 476
 
33575 amit.gupta 477
        return fofoCatalogResponses;
478
    }
479
 
480
    private FofoCatalogResponse toFofoCatalogResponse(JSONObject doc) {
481
        FofoCatalogResponse fofoCatalogResponse = new FofoCatalogResponse();
482
        fofoCatalogResponse.setCatalogId(doc.getInt("catalogId_i"));
483
        fofoCatalogResponse.setImageUrl(doc.getString("imageUrl_s"));
484
        fofoCatalogResponse.setTitle(doc.getString("title_s"));
485
        fofoCatalogResponse.setMop(doc.getFloat("mop_f"));
486
        fofoCatalogResponse.setDp(doc.getFloat("dp_f"));
487
        fofoCatalogResponse.setBrand(doc.getJSONArray("brand_ss").getString(0));
488
        return fofoCatalogResponse;
489
    }
490
 
32339 tejbeer 491
    @RequestMapping(value = "/online-deals", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
492
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
493
    @ApiOperation(value = "Get online deals")
33575 amit.gupta 494
    public ResponseEntity<?> getOnlineDeals(HttpServletRequest request, @RequestParam(value = "categoryId") String
495
            categoryId, @RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String
496
                                                    limit, @RequestParam(value = "sort", required = false) String
497
                                                    sort, @RequestParam(value = "direction", required = false) String
498
                                                    direction, @RequestParam(value = "filterData", required = false) String filterData) throws Throwable {
32339 tejbeer 499
        logger.info("Request " + request.getParameterMap());
500
        String response = null;
501
        int userId = (int) request.getAttribute("userId");
22289 amit.gupta 502
 
32339 tejbeer 503
        String uri = "/deals/" + userId;
35410 amit 504
                Map<String, String> params = new HashMap<>();
32339 tejbeer 505
        params.put("offset", offset);
506
        params.put("limit", limit);
507
        params.put("categoryId", categoryId);
508
        params.put("direction", direction);
509
        params.put("sort", sort);
510
        params.put("source", "online");
511
        params.put("filterData", filterData);
512
        /*
513
         * if (userInfo.getRoleNames().contains(RoleType.FOFO.toString())) {
514
         * params.put("tag_ids", getCommaSeparateTags(userId)); }
515
         */
516
        List<Object> responseObject = new ArrayList<>();
517
        try {
35410 amit 518
            response = restClient.get(SchemeType.HTTP, host, port, uri, params);
32339 tejbeer 519
        } catch (HttpHostConnectException e) {
520
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
521
        }
22931 ashik.ali 522
 
32339 tejbeer 523
        JsonArray result_json = Json.parse(response).asArray();
524
        for (JsonValue j : result_json) {
525
            // logger.info("res " + j.asArray());
526
            List<Object> innerObject = new ArrayList<>();
527
            for (JsonValue jsonObject : j.asArray()) {
528
                innerObject.add(toDealObject(jsonObject.asObject()));
529
            }
530
            if (innerObject.size() > 0) {
531
                responseObject.add(innerObject);
532
            }
533
        }
534
        return responseSender.ok(responseObject);
535
    }
22272 amit.gupta 536
 
32339 tejbeer 537
    private Object toDealObject(JsonObject jsonObject) {
538
        if (jsonObject.get("dealObject") != null && jsonObject.get("dealObject").asInt() == 1) {
539
            return new Gson().fromJson(jsonObject.toString(), DealObjectResponse.class);
540
        }
541
        return new Gson().fromJson(jsonObject.toString(), DealsResponse.class);
542
    }
22319 amit.gupta 543
 
32339 tejbeer 544
    @RequestMapping(value = ProfitMandiConstants.URL_BRANDS, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
545
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
546
    @ApiOperation(value = "Get brand list and count for category")
33575 amit.gupta 547
    public ResponseEntity<?> getBrands(HttpServletRequest request, @RequestParam(value = "category_id") String
548
            category_id) throws ProfitMandiBusinessException {
32339 tejbeer 549
        logger.info("Request " + request.getParameterMap());
550
        String response = null;
551
        // TODO: move to properties
552
        String uri = ProfitMandiConstants.URL_BRANDS;
35410 amit 553
                Map<String, String> params = new HashMap<>();
32339 tejbeer 554
        params.put("category_id", category_id);
555
        List<DealBrands> dealBrandsResponse = null;
556
        try {
35410 amit 557
            response = restClient.get(SchemeType.HTTP, host, port, uri, params);
32339 tejbeer 558
        } catch (HttpHostConnectException e) {
559
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
560
        }
23816 amit.gupta 561
 
32339 tejbeer 562
        dealBrandsResponse = new Gson().fromJson(response, new TypeToken<List<DealBrands>>() {
563
        }.getType());
23022 ashik.ali 564
 
32339 tejbeer 565
        return responseSender.ok(dealBrandsResponse);
566
    }
22319 amit.gupta 567
 
32339 tejbeer 568
    @RequestMapping(value = ProfitMandiConstants.URL_UNIT_DEAL, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
569
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
570
    @ApiOperation(value = "Get unit deal object")
33575 amit.gupta 571
    public ResponseEntity<?> getUnitDeal(HttpServletRequest request, @PathVariable(value = "id") long id) throws
572
            ProfitMandiBusinessException {
32339 tejbeer 573
        String response = null;
574
        // TODO: move to properties
575
        String uri = "getDealById/" + id;
576
        System.out.println("Unit deal " + uri);
35410 amit 577
                Map<String, String> params = new HashMap<>();
32339 tejbeer 578
        DealsResponse dealsResponse = null;
579
        try {
35410 amit 580
            response = restClient.get(SchemeType.HTTP, host, port, uri, params);
32339 tejbeer 581
        } catch (HttpHostConnectException e) {
582
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
583
        }
23816 amit.gupta 584
 
32339 tejbeer 585
        JsonObject result_json = Json.parse(response).asObject();
586
        if (!result_json.isEmpty()) {
587
            dealsResponse = new Gson().fromJson(response, DealsResponse.class);
588
            Iterator<AvailabilityInfo> iter = dealsResponse.getAvailabilityInfo().iterator();
589
            while (iter.hasNext()) {
590
                AvailabilityInfo ai = iter.next();
591
                if (ai.getAvailability() <= 0)
592
                    iter.remove();
593
            }
594
        }
595
        return responseSender.ok(dealsResponse);
596
    }
23816 amit.gupta 597
 
32339 tejbeer 598
    @RequestMapping(value = "/partnerdeals/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
599
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
600
    @ApiOperation(value = "Get unit deal object")
33575 amit.gupta 601
    public ResponseEntity<?> getUnitFocoDeal(HttpServletRequest request, @PathVariable(value = "id") long id) throws
602
            Exception {
32339 tejbeer 603
        List<FofoCatalogResponse> dealResponse = new ArrayList<>();
604
        List<Integer> tagIds = Arrays.asList(4);
605
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
606
        if (roleManagerService.isPartner(userInfo.getRoleIds())) {
607
            String categoryId = "(3 OR 6)";
608
            UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
35410 amit 609
                        Map<String, String> params = new HashMap<>();
32339 tejbeer 610
            List<String> mandatoryQ = new ArrayList<>();
611
            String catalogString = "catalog" + id;
24091 tejbeer 612
 
32339 tejbeer 613
            mandatoryQ.add(String.format("+(categoryId_i:%s) +(id:%s) +{!parent which=\"id:%s\"} tagId_i:(%s)", categoryId, catalogString, catalogString, StringUtils.join(tagIds, " ")));
24149 amit.gupta 614
 
32339 tejbeer 615
            params.put("q", StringUtils.join(mandatoryQ, " "));
616
            params.put("fl", "*, [child parentFilter=id:catalog*]");
617
            params.put("sort", "rank_i asc, create_s desc");
618
            params.put("wt", "json");
619
            String response = null;
620
            try {
35410 amit 621
                response = restClient.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
32339 tejbeer 622
            } catch (HttpHostConnectException e) {
623
                throw new ProfitMandiBusinessException("", "", "Could not connect to host");
624
            }
625
            JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
626
            JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
627
            dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId());
628
        } else {
629
            return responseSender.badRequest(
630
                    new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
631
        }
632
        return responseSender.ok(dealResponse.get(0));
633
    }
24091 tejbeer 634
 
34436 ranu 635
 
636
    @RequestMapping(value = "/suggestedPoDeals", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
637
    public ResponseEntity<?> suggestedPoDeals(HttpServletRequest request,@RequestBody Set<Integer>catalogIds) throws Exception {
638
 
639
        int userId = (int) request.getAttribute("userId");
640
        UserCart uc = userAccountRepository.getUserCart(userId);
641
        int fofoId = uc.getUserId();
642
        List<FofoCatalogResponse> dealResponse = new ArrayList<>();
643
        if (!catalogIds.isEmpty()) {
644
            dealResponse = webSolrService.dealResponse(catalogIds, fofoId);
645
        }
646
        return responseSender.ok(dealResponse);
647
    }
648
 
32339 tejbeer 649
    @RequestMapping(value = "/fofo/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
33575 amit.gupta 650
    public ResponseEntity<?> getBrandsToDisplay(HttpServletRequest request,
651
                                                @RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {
32339 tejbeer 652
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
653
        logger.info("userInfo [{}]", userInfo);
32717 ranu 654
        List<BrandCatalog> brandsDisplay = brandsService.getBrandsToDisplay(categoryId);
655
        //List<DBObject> brandsDisplay = mongoClient.getMongoBrands(userInfo.getRetailerId(), userInfo.getEmail(), categoryId);
32339 tejbeer 656
        return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
657
    }
25879 amit.gupta 658
 
32339 tejbeer 659
    @RequestMapping(value = "/fofo/brandCatalog", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
33575 amit.gupta 660
    public ResponseEntity<?> getBrands(HttpServletRequest request,
661
                                       @RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {
32339 tejbeer 662
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
663
        logger.info("userInfo [{}]", userInfo);
31507 tejbeer 664
 
32339 tejbeer 665
        List<BrandCatalog> brandsDisplay = brandsService.getBrands(userInfo.getRetailerId(), userInfo.getEmail(), categoryId);
666
        return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
667
    }
31507 tejbeer 668
 
32339 tejbeer 669
    @RequestMapping(value = "/fofo/accessory/all-categories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
670
    public ResponseEntity<?> getSubCategoriesToDisplay(HttpServletRequest request) throws Exception {
671
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
672
        logger.info("userInfo [{}]", userInfo);
673
        List<DBObject> subCategoriesDisplay = this.getSubCategoriesToDisplay();
674
        return new ResponseEntity<>(subCategoriesDisplay, HttpStatus.OK);
675
    }
23816 amit.gupta 676
 
32339 tejbeer 677
    private List<DBObject> getSubCategoriesToDisplay() throws Exception {
678
        List<DBObject> subCategories = new ArrayList<>();
35410 amit 679
                Map<String, String> params = new HashMap<>();
32339 tejbeer 680
        params.put("q", "categoryId_i:6");
681
        params.put("group", "true");
682
        params.put("group.field", "subCategoryId_i");
683
        params.put("wt", "json");
684
        params.put("rows", "50");
685
        params.put("fl", "subCategoryId_i");
686
        String response = null;
687
        try {
35410 amit 688
            response = restClient.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
32339 tejbeer 689
        } catch (HttpHostConnectException e) {
690
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
691
        }
692
        JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("grouped");
693
        JSONArray groups = solrResponseJSONObj.getJSONObject("subCategoryId_i").getJSONArray("groups");
694
        List<Integer> categoryIds = new ArrayList<>();
695
        for (int i = 0; i < groups.length(); i++) {
696
            JSONObject groupObject = groups.getJSONObject(i);
697
            int subCategoryId = groupObject.getInt("groupValue");
698
            int quantity = groupObject.getJSONObject("doclist").getInt("numFound");
699
            categoryIds.add(subCategoryId);
700
        }
25015 amit.gupta 701
 
32339 tejbeer 702
        List<Category> categories = categoryRepository.selectByIds(categoryIds);
703
        AtomicInteger i = new AtomicInteger(0);
704
        categories.forEach(x -> {
705
            DBObject dbObject = new BasicDBObject();
706
            dbObject.put("name", x.getLabel());
707
            dbObject.put("subCategoryId", x.getId());
708
            dbObject.put("rank", i.incrementAndGet());
709
            dbObject.put("categoryId", 6);
710
            dbObject.put("url", "https://images.smartdukaan.com/uploads/campaigns/" + x.getId() + ".png");
711
            subCategories.add(dbObject);
712
        });
25015 amit.gupta 713
 
32339 tejbeer 714
        return subCategories;
25015 amit.gupta 715
 
32339 tejbeer 716
    }
25010 amit.gupta 717
 
32339 tejbeer 718
    @RequestMapping(value = "/banners/{bannerType}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
719
    public ResponseEntity<?> getBanners(@PathVariable String bannerType) {
720
        return new ResponseEntity<>(mongoClient.getBannersByType(bannerType), HttpStatus.OK);
721
    }
23816 amit.gupta 722
 
32339 tejbeer 723
    @RequestMapping(value = "/deals/subCategories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
724
    public ResponseEntity<?> getSubcategoriesToDisplay() {
725
        return new ResponseEntity<>(mongoClient.getSubcategoriesToDisplay(), HttpStatus.OK);
726
    }
23816 amit.gupta 727
 
32339 tejbeer 728
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
729
    @RequestMapping(value = "/deals/skus/{skus}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
730
    public ResponseEntity<?> getDealsBySkus(@PathVariable String skus) throws ProfitMandiBusinessException {
731
        StringBuffer sb = new StringBuffer("/getDealsForNotification/");
732
        String uri = sb.append(skus).toString();
35410 amit 733
                String response;
32339 tejbeer 734
        try {
35410 amit 735
            response = restClient.get(SchemeType.HTTP, host, port, uri, new HashMap<>());
32339 tejbeer 736
        } catch (HttpHostConnectException e) {
737
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
738
        }
739
        JsonArray result_json = Json.parse(response).asArray();
740
        List<Object> responseObject = new ArrayList<>();
741
        for (JsonValue j : result_json) {
742
            // logger.info("res " + j.asArray());
743
            List<Object> innerObject = new ArrayList<>();
744
            for (JsonValue jsonObject : j.asArray()) {
745
                innerObject.add(toDealObject(jsonObject.asObject()));
746
            }
747
            if (innerObject.size() > 0) {
748
                responseObject.add(innerObject);
749
            }
750
        }
751
        return responseSender.ok(responseObject);
752
    }
21339 kshitij.so 753
 
32339 tejbeer 754
    @RequestMapping(value = "/partner/listing", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
755
    public ResponseEntity<?> getPartnersListing(HttpServletRequest request) throws Exception {
756
        List<WebListing> webListings = webListingRepository.selectAllWebListingByType(Optional.of(true), WebListingSource.partner);
757
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
34786 aman.kumar 758
 
32339 tejbeer 759
        for (WebListing webListing : webListings) {
34786 aman.kumar 760
//            catalogFavouriteList.contains(webListing.getId())?
33573 amit.gupta 761
            webListing.setFofoCatalogResponses(getDealResponses(userInfo, webListing, 0, 20));
34786 aman.kumar 762
//            List<FofoCatalogResponse> responseList= new ArrayList<>();
32339 tejbeer 763
        }
764
        return responseSender.ok(webListings);
765
    }
31547 tejbeer 766
 
33576 amit.gupta 767
    private List<FofoCatalogResponse> getDealResponses(UserInfo userInfo, WebListing webListing, int offset,
768
                                                       int limit) throws Exception {
31572 tejbeer 769
 
35410 amit 770
                Map<String, String> params = new HashMap<>();
32339 tejbeer 771
        List<String> mandatoryQ = new ArrayList<>();
31670 tejbeer 772
 
32339 tejbeer 773
        FofoStore fs = fofoStoreRepository.selectByRetailerId(userInfo.getRetailerId());
774
        params.put("sort", "w" + fs.getWarehouseId() + "_i desc");
31576 tejbeer 775
 
32339 tejbeer 776
        List<Integer> webProducts = null;
777
        if (webListing.getType().equals(WebListingType.solr)) {
778
            logger.info("solrtype {}", webListing.getSolrQuery());
779
            mandatoryQ.add(String.format("+{!parent which=\"" + webListing.getSolrQuery() + "\"} AND active_b:true AND show_default_b:true"));
780
        } else {
781
            logger.info("solrtype2 {}", webListing.getSolrQuery());
31675 tejbeer 782
 
33573 amit.gupta 783
            webProducts = webProductListingRepository.selectAllByWebListingId(webListing.getId(), offset, limit).stream().filter(x -> x.getRank() > 0).map(x -> x.getEntityId()).collect(Collectors.toList());
31572 tejbeer 784
 
32339 tejbeer 785
            if (webProducts.size() == 0) {
786
                return new ArrayList<>();
787
            }
31572 tejbeer 788
 
32339 tejbeer 789
            mandatoryQ.add(String.format(
33575 amit.gupta 790
                    "+{!parent which=\"catalogId_i:(" + StringUtils.join(webProducts, " ") + ")\"} AND active_b:true AND show_default_b:true"));
31642 tejbeer 791
 
32339 tejbeer 792
        }
793
        params.put("q", StringUtils.join(mandatoryQ, " "));
794
        params.put("fl", "*, [child parentFilter=id:catalog* childFilter=active_b:true ]");
31612 tejbeer 795
 
32339 tejbeer 796
        params.put("start", String.valueOf(offset));
797
        params.put("rows", String.valueOf(limit));
798
        params.put("wt", "json");
799
        String response = null;
800
        try {
35410 amit 801
            response = restClient.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
32339 tejbeer 802
        } catch (HttpHostConnectException e) {
803
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
804
        }
805
        JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
806
        JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
807
        List<FofoCatalogResponse> dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId());
31671 tejbeer 808
 
32339 tejbeer 809
        if (webProducts != null && webListing.getUrl().equals("new-launches")) {
810
            List<Integer> webProductsFinal = webProducts;
811
            dealResponse = dealResponse.stream().sorted(Comparator.comparing(x -> webProductsFinal.indexOf(x.getCatalogId()))).collect(Collectors.toList());
31671 tejbeer 812
 
32339 tejbeer 813
        }
31547 tejbeer 814
 
32339 tejbeer 815
        return dealResponse;
816
    }
30669 amit.gupta 817
 
32339 tejbeer 818
    @Autowired
819
    private SaholicCISTableRepository saholicCISTableRepository;
27053 amit.gupta 820
 
33575 amit.gupta 821
    private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal, int fofoId) throws
822
            Exception {
32339 tejbeer 823
        List<FofoCatalogResponse> dealResponse = new ArrayList<>();
824
        List<Integer> tagIds = Arrays.asList(4);
825
        List<Integer> itemIds = new ArrayList<>();
34260 vikas.jang 826
        Map<Integer, Integer> partnerStockAvailabilityMap = null;
32339 tejbeer 827
        if (docs.length() > 0) {
828
            for (int i = 0; i < docs.length(); i++) {
829
                JSONObject doc = docs.getJSONObject(i);
830
                if (doc.has("_childDocuments_")) {
831
                    for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
832
                        JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
833
                        int itemId = childItem.getInt("itemId_i");
834
                        itemIds.add(itemId);
835
                    }
836
                }
837
            }
838
            if (itemIds.size() == 0) {
839
                return dealResponse;
840
            }
841
        }
842
        // get warehouse Id
843
        int warehouseId = fofoStoreRepository.selectByRetailerId(fofoId).getWarehouseId();
844
        Map<Integer, List<SaholicPOItem>> poItemAvailabilityMap = saholicInventoryService.getSaholicPOItems().get(warehouseId);
845
        List<Integer> catalogIds = new ArrayList<>();
846
        for (int i = 0; i < docs.length(); i++) {
847
            JSONObject doc = docs.getJSONObject(i);
848
            catalogIds.add(doc.getInt("catalogId_i"));
849
        }
850
        List<CreateOfferRequest> allSchemOffers = null;
851
        Map<Integer, PriceCircularItemModelNew> priceCircularItemModelMap = new HashMap<>();
852
        if (catalogIds.size() > 0) {
853
            PriceCircularModel priceCircularModel = priceCircularService.getPriceCircularByOffer(fofoId, catalogIds, LocalDate.now());
854
            allSchemOffers = priceCircularModel.getOffers();
30188 amit.gupta 855
 
32339 tejbeer 856
            List<PriceCircularItemModelNew> priceCircularItemModelNews = priceCircularModel.getPriceCircularItemModelNews();
857
            if (priceCircularItemModelNews != null) {
858
                priceCircularItemModelMap = priceCircularItemModelNews.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));
859
            }
860
        }
31629 tejbeer 861
 
33575 amit.gupta 862
        /*List<CatalogFavourite> catalogFavourites = catalogFavouriteRepository.selectBypartnerId(fofoId);
32339 tejbeer 863
        List<Integer> catalogFavouriteIds = new ArrayList<>();
864
        if (!catalogFavourites.isEmpty()) {
865
            catalogFavouriteIds = catalogFavourites.stream().map(x -> x.getCatalogId()).collect(Collectors.toList());
866
        }
31629 tejbeer 867
 
32339 tejbeer 868
        if (!catalogFavourites.isEmpty()) {
869
            catalogFavourites.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));
33575 amit.gupta 870
        }*/
30595 tejbeer 871
 
34260 vikas.jang 872
        if (fofoId > 0) {
873
            partnerStockAvailabilityMap = currentInventorySnapshotRepository.selectItemsStock(fofoId).stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
874
            logger.info("partnerStockAvailabilityMap: {}",partnerStockAvailabilityMap);
875
        }
34786 aman.kumar 876
        List<CatalogFavourite> catalogFavouriteList = catalogFavouriteRepository.selectBypartnerId(fofoId);
877
        Set<Integer> favouriteCatalogIds = catalogFavouriteList.stream()
878
                .map(CatalogFavourite::getCatalogId)
879
                .collect(Collectors.toSet());
35410 amit 880
 
881
        // Pre-fetch CIS data for all items (batch query instead of N+1)
882
        Map<Integer, List<SaholicCISTable>> cisDataByItemId = saholicCISTableRepository
883
                .selectByItemWarehouse(itemIds, warehouseId).stream()
884
                .collect(Collectors.groupingBy(SaholicCISTable::getItemId));
885
 
886
        // Pre-fetch all Items (batch query instead of N+1)
887
        Map<Integer, Item> itemMap = itemRepository.selectByIds(new HashSet<>(itemIds)).stream()
888
                .collect(Collectors.toMap(Item::getId, x -> x));
889
 
890
        // Pre-fetch cashback data for all catalogs (batch query instead of N+1)
891
        Map<Integer, Float> cashbackMap = schemeService.getCatalogSchemeCashBack(fofoId, catalogIds);
892
 
893
        // Pre-fetch web offers (call once instead of inside loop)
894
        Map<Integer, List<WebOffer>> webOffersMap = webOfferRepository.selectAllActiveOffers();
895
 
896
        // Pre-fetch combo models (call once instead of inside loop)
897
        Map<Integer, List<ComboModel>> comboModelsByCatalogId = comboModelRepository.selectByWarehouseId(warehouseId)
898
                .stream().collect(Collectors.groupingBy(ComboModel::getCatalogId));
899
 
32339 tejbeer 900
        for (int i = 0; i < docs.length(); i++) {
901
            Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
902
            JSONObject doc = docs.getJSONObject(i);
903
            FofoCatalogResponse fofoCatalogResponse = new FofoCatalogResponse();
904
            fofoCatalogResponse.setCatalogId(doc.getInt("catalogId_i"));
905
            fofoCatalogResponse.setImageUrl(doc.getString("imageUrl_s"));
906
            fofoCatalogResponse.setTitle(doc.getString("title_s"));
33975 tejus.loha 907
            fofoCatalogResponse.setSuperCatalogTitle(doc.getString("superCatalog_s"));
908
            fofoCatalogResponse.setSuperCatalogId(doc.getInt("superCatalog_i"));
909
            fofoCatalogResponse.setSuperCatalogVariants(doc.getString("superCatalogVariants_s"));
31629 tejbeer 910
 
34786 aman.kumar 911
            if (favouriteCatalogIds.contains(fofoCatalogResponse.getCatalogId())) {
32339 tejbeer 912
                fofoCatalogResponse.setFavourite(true);
34786 aman.kumar 913
            } else {
914
                fofoCatalogResponse.setFavourite(false); // optional, since default is false
915
            }
35410 amit 916
            List<WebOffer> webOffers = webOffersMap.get(fofoCatalogResponse.getCatalogId());
31612 tejbeer 917
 
33573 amit.gupta 918
            //logger.info("webOffers {}", webOffers);
32339 tejbeer 919
            if (webOffers != null && webOffers.size() > 0) {
920
                fofoCatalogResponse.setWebOffers(webOffers);
921
                fofoCatalogResponse.setOffers(webOffers.stream().map(x -> x.getTitle()).collect(Collectors.toList()));
30683 tejbeer 922
 
32339 tejbeer 923
            }
30683 tejbeer 924
 
35410 amit 925
            List<ComboModel> comboModels = comboModelsByCatalogId.get(fofoCatalogResponse.getCatalogId());
30683 tejbeer 926
 
33573 amit.gupta 927
            //logger.info("comboModels {}", comboModels);
32344 tejbeer 928
 
32339 tejbeer 929
            if (comboModels != null && comboModels.size() > 0) {
930
                fofoCatalogResponse.setComboModels(comboModels);
931
            }
30683 tejbeer 932
 
32339 tejbeer 933
            try {
934
                fofoCatalogResponse.setFeature(doc.getString("feature_s"));
935
            } catch (Exception e) {
936
                fofoCatalogResponse.setFeature(null);
937
                logger.info("Could not find Feature_s for {}", fofoCatalogResponse.getCatalogId());
938
            }
30683 tejbeer 939
 
32339 tejbeer 940
            fofoCatalogResponse.setBrand(doc.getJSONArray("brand_ss").getString(0));
941
            logger.info("labelss {}", doc.has("label_ss"));
30683 tejbeer 942
 
32339 tejbeer 943
            if (doc.has("label_ss")) {
944
                logger.info("label {}", doc.getJSONArray("label_ss"));
30683 tejbeer 945
 
32339 tejbeer 946
                JSONArray arr = doc.getJSONArray("label_ss");
947
                Set<String> labels = new HashSet<String>();
948
                for (int j = 0; j < arr.length(); j++) {
949
                    labels.add(arr.getString(j));
950
                }
31612 tejbeer 951
 
32339 tejbeer 952
                fofoCatalogResponse.setLabels(new ArrayList<>(labels));
31612 tejbeer 953
 
32339 tejbeer 954
            }
33573 amit.gupta 955
            if (doc.has("similarModels_ii")) {
956
                JSONArray similarModelsArray = doc.getJSONArray("similarModels_ii");
957
                List<Integer> similarCatalogIds = new ArrayList<>();
958
                for (int j = 0; j < similarModelsArray.length(); j++) {
959
                    similarCatalogIds.add(similarModelsArray.getInt(j));
960
                }
961
                fofoCatalogResponse.setSimilarModelIds(similarCatalogIds);
962
            }
31612 tejbeer 963
 
32339 tejbeer 964
            if (doc.has("_childDocuments_")) {
965
                String modelColorClass = "grey";
966
                FofoAvailabilityInfo fdiAnyColour = null;
967
                // Iterating itemIds
968
                for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
969
                    PriceCircularItemModelNew priceCircularItemModel = priceCircularItemModelMap.get(fofoCatalogResponse.getCatalogId());
970
                    JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
971
                    int itemId = childItem.getInt("itemId_i");
972
                    float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
34260 vikas.jang 973
                    int partnerAvailability = partnerStockAvailabilityMap.get(itemId) == null ? 0 : partnerStockAvailabilityMap.get(itemId);
32339 tejbeer 974
                    if (!fofoAvailabilityInfoMap.containsKey(itemId)) {
975
                        FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
35410 amit 976
                        List<SaholicCISTable> currentAvailability = cisDataByItemId.getOrDefault(itemId, new ArrayList<>());
32339 tejbeer 977
                        List<SaholicPOItem> poItemAvailability = null;
978
                        if (poItemAvailabilityMap != null) {
979
                            poItemAvailability = poItemAvailabilityMap.get(itemId);
980
                        }
31612 tejbeer 981
 
32339 tejbeer 982
                        if (priceCircularItemModel != null) {
33410 ranu 983
                            fdi.setNlc((float) priceCircularItemModel.getNetNlc());
32339 tejbeer 984
                        }
31612 tejbeer 985
 
32339 tejbeer 986
                        for (SaholicCISTable saholicCISTable : currentAvailability) {
987
                            saholicCISTable.setWarehouseName(
988
                                    ProfitMandiConstants.WAREHOUSE_MAP.get(saholicCISTable.getWarehouseFrom()));
989
                        }
31612 tejbeer 990
 
32339 tejbeer 991
                        Map<Integer, SaholicCISTable> map = currentAvailability.stream().collect(Collectors.toMap(SaholicCISTable::getWarehouseFrom, x -> x));
992
                        if (poItemAvailability != null) {
993
                            for (SaholicPOItem saholicPOItem : poItemAvailability) {
994
                                if (map.containsKey(saholicPOItem.getWarehouseFrom())) {
995
                                    map.get(saholicPOItem.getWarehouseFrom()).setPopendingQty(saholicPOItem.getUnfulfilledQty());
996
                                } else {
997
                                    SaholicCISTable saholicCISTable = new SaholicCISTable();
998
                                    saholicCISTable.setAvailability(0);
999
                                    saholicCISTable.setReserved(0);
1000
                                    saholicCISTable.setItemId(itemId);
1001
                                    saholicCISTable.setWarehouseId(warehouseId);
1002
                                    saholicCISTable.setPopendingQty(saholicPOItem.getUnfulfilledQty());
1003
                                    saholicCISTable.setWarehouseFrom(saholicPOItem.getWarehouseFrom());
1004
                                    saholicCISTable.setWarehouseName(
1005
                                            ProfitMandiConstants.WAREHOUSE_MAP.get(saholicPOItem.getWarehouseFrom()));
1006
                                    map.put(saholicPOItem.getWarehouseFrom(), saholicCISTable);
1007
                                }
1008
                            }
1009
                        }
1010
                        fdi.setSaholicCISTableList(new ArrayList<>(map.values()));
1011
                        String poColor = "grey";
1012
                        boolean active = false;
1013
                        if (currentAvailability != null && currentAvailability.stream().collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)) > 0) {
1014
                            poColor = "green";
1015
                            modelColorClass = "green";
32978 amit.gupta 1016
                        } else if (poItemAvailability != null && poItemAvailability.stream().collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty)) > 0) {
1017
                            if (currentAvailability != null && poItemAvailability.stream().collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty)) + currentAvailability.stream().collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)) <= 0) {
1018
                                poColor = "grey";
1019
                            } else {
1020
                                poColor = "yellow";
35410 amit 1021
                                if (!"green".equals(modelColorClass)) {
32978 amit.gupta 1022
                                    modelColorClass = poColor;
32339 tejbeer 1023
                                }
1024
                            }
32978 amit.gupta 1025
                        }
32339 tejbeer 1026
                        fdi.setColorClass(poColor);
1027
                        fdi.setSellingPrice(sellingPrice);
1028
                        fdi.setActive(active);
1029
                        fdi.setMrp(childItem.getDouble("mrp_f"));
1030
                        fdi.setMop((float) childItem.getDouble("mop_f"));
1031
                        fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
1032
                        if (fdi.getColor().equalsIgnoreCase("any colour")) {
1033
                            fdiAnyColour = fdi;
1034
                        }
33929 tejus.loha 1035
                        fdi.setBrand((String) doc.getJSONArray("brand_ss").get(0));
1036
                        fdi.setCategoryId(doc.getInt("subCategoryId_i"));
32339 tejbeer 1037
                        fdi.setTagId(childItem.getInt("tagId_i"));
1038
                        fdi.setItem_id(itemId);
34196 ranu 1039
                        fdi.setCatalog_id(doc.getInt("catalogId_i"));
35410 amit 1040
                        Float cashBack = cashbackMap.get(fofoCatalogResponse.getCatalogId());
32339 tejbeer 1041
                        cashBack = cashBack == null ? 0 : cashBack;
1042
                        fdi.setCashback(cashBack);
1043
                        fdi.setMinBuyQuantity(1);
1044
                        if (hotDeal) {
1045
                            if (currentAvailability != null) {
1046
                                fdi.setAvailability(currentAvailability.stream().collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)));
1047
                            } else {
1048
                                fdi.setAvailability(0);
1049
                            }
34260 vikas.jang 1050
                            fdi.setPartnerAvailability(partnerAvailability);
32339 tejbeer 1051
                        } else {
1052
                            // Lets consider that its out of stock
32591 amit.gupta 1053
                            fdi.setAvailability(400);
35410 amit 1054
                            Item item = itemMap.get(itemId);
32339 tejbeer 1055
                            // In case its tampered glass moq should be
35410 amit 1056
                            if (item != null && item.getCategoryId() == 10020) {
32339 tejbeer 1057
                                fdi.setMinBuyQuantity(5);
1058
                            }
1059
                        }
1060
                        fdi.setQuantityStep(1);
32590 amit.gupta 1061
                        fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 400));
32339 tejbeer 1062
                        fofoAvailabilityInfoMap.put(itemId, fdi);
1063
                    }
1064
                }
1065
                if (fdiAnyColour != null) {
1066
                    fdiAnyColour.setColorClass(modelColorClass);
1067
                }
33576 amit.gupta 1068
                fofoCatalogResponse.setInStock(!modelColorClass.equals("grey"));
32339 tejbeer 1069
            }
1070
            if (fofoAvailabilityInfoMap.values().size() > 0) {
1071
                List<FofoAvailabilityInfo> availabilityList = fofoAvailabilityInfoMap.values().stream().sorted(Comparator.comparing(FofoAvailabilityInfo::getAvailability).reversed()).collect(Collectors.toList());
1072
                fofoCatalogResponse.setItems(availabilityList);
1073
                if (priceCircularItemModelMap.containsKey(fofoCatalogResponse.getCatalogId())) {
1074
                    PriceCircularItemModelNew priceCircularItemModel = priceCircularItemModelMap.get(fofoCatalogResponse.getCatalogId());
1075
                    if (priceCircularItemModel.getSlabPayouts() != null) {
1076
                        List<CreateOfferRequest> schemeOffers = new ArrayList<>();
1077
                        List<Map<Integer, AmountModel>> slabPayouts = priceCircularItemModel.getSlabPayouts();
1078
                        Iterator<Map<Integer, AmountModel>> iterator = slabPayouts.iterator();
1079
                        int iteratorCount = 0;
1080
                        while (iterator.hasNext()) {
1081
                            Map<Integer, AmountModel> slabPayoutMap = iterator.next();
1082
                            if (slabPayoutMap != null) {
1083
                                schemeOffers.add(allSchemOffers.get(iteratorCount));
1084
                            } else {
1085
                                iterator.remove();
1086
                            }
1087
                            iteratorCount++;
1088
                        }
1089
                        fofoCatalogResponse.setSchemeOffers(schemeOffers);
1090
                    }
1091
                    fofoCatalogResponse.setPriceCircularItemModel(priceCircularItemModel);
1092
                }
1093
                dealResponse.add(fofoCatalogResponse);
1094
            }
1095
        }
1096
        return dealResponse;
30686 amit.gupta 1097
 
32339 tejbeer 1098
    }
30693 amit.gupta 1099
 
33575 amit.gupta 1100
    private List<FofoCatalogResponse> getCatalogSingleSkuResponse(JSONArray
1101
                                                                          docs, Map<Integer, Integer> itemFilter, boolean hotDeal) throws ProfitMandiBusinessException {
32339 tejbeer 1102
        List<FofoCatalogResponse> dealResponse = new ArrayList<>();
1103
        List<Integer> tagIds = Arrays.asList(4);
24091 tejbeer 1104
 
33873 ranu 1105
        Map<Integer, TagListing> itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemFilter.keySet(), new HashSet<>(tagIds)).stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x));
24091 tejbeer 1106
 
35410 amit 1107
        // Pre-fetch all items (batch query instead of N+1)
1108
        Map<Integer, Item> itemMap = itemRepository.selectByIds(itemFilter.keySet()).stream()
1109
                .collect(Collectors.toMap(Item::getId, x -> x));
1110
 
32339 tejbeer 1111
        for (int i = 0; i < docs.length(); i++) {
1112
            Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
1113
            JSONObject doc = docs.getJSONObject(i);
26589 amit.gupta 1114
 
32339 tejbeer 1115
            for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
1116
                JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
1117
                int itemId = childItem.getInt("itemId_i");
1118
                TagListing tl = itemTagListingMap.get(itemId);
1119
                if (tl == null) {
1120
                    continue;
1121
                }
1122
                if (hotDeal) {
1123
                    if (!tl.isHotDeals()) {
1124
                        continue;
1125
                    }
1126
                }
1127
                float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
1128
                if (fofoAvailabilityInfoMap.containsKey(itemId)) {
1129
                    if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
1130
                        fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
1131
                        fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
1132
                    }
1133
                } else {
1134
                    FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
1135
                    fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
1136
                    fdi.setMop((float) childItem.getDouble("mop_f"));
1137
                    fdi.setMop((float) tl.getMrp());
1138
                    fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
1139
                    fdi.setTagId(childItem.getInt("tagId_i"));
1140
                    fdi.setItem_id(itemId);
34196 ranu 1141
                    fdi.setCatalog_id(doc.getInt("catalogId_i"));
35410 amit 1142
                    Item item = itemMap.get(itemId);
32339 tejbeer 1143
                    // In case its tampered glass moq should be 5
35410 amit 1144
                    if (item != null && item.getCategoryId() == 10020) {
32339 tejbeer 1145
                        fdi.setMinBuyQuantity(10);
1146
                    } else {
1147
                        fdi.setMinBuyQuantity(1);
1148
                    }
1149
                    fdi.setAvailability(itemFilter.get(itemId));
1150
                    fdi.setQuantityStep(1);
1151
                    fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
1152
                    fofoAvailabilityInfoMap.put(itemId, fdi);
1153
                }
1154
            }
1155
            if (fofoAvailabilityInfoMap.values().size() > 0) {
1156
                for (FofoAvailabilityInfo fofoAvailabilityInfo : fofoAvailabilityInfoMap.values()) {
1157
                    FofoCatalogResponse ffdr = new FofoCatalogResponse();
1158
                    ffdr.setCatalogId(doc.getInt("catalogId_i"));
1159
                    ffdr.setImageUrl(doc.getString("imageUrl_s"));
1160
                    ffdr.setTitle(doc.getString("title_s"));
1161
                    try {
1162
                        ffdr.setFeature(doc.getString("feature_s"));
1163
                    } catch (Exception e) {
1164
                        ffdr.setFeature(null);
1165
                        logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
1166
                    }
1167
                    ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
1168
                    ffdr.setItems(Arrays.asList(fofoAvailabilityInfo));
1169
                    dealResponse.add(ffdr);
1170
                }
1171
            }
1172
        }
1173
        return dealResponse;
25880 amit.gupta 1174
 
32339 tejbeer 1175
    }
25880 amit.gupta 1176
 
32339 tejbeer 1177
    @RequestMapping(value = "/combo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
1178
    public ResponseEntity<?> getBanners(@RequestParam int catalogId, @RequestParam int warehouseId) {
1179
        List<ComboModel> comboModels = comboModelRepository.selectByCatalogIdAndWarehouseId(catalogId, warehouseId);
1180
        return responseSender.ok(comboModels);
1181
    }
32344 tejbeer 1182
 
1183
    @RequestMapping(value = "/checkCombo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
33575 amit.gupta 1184
    public ResponseEntity<?> checkCombo(HttpServletRequest request, @RequestParam int catalogId,
1185
                                        @RequestParam int warehouseId, @RequestParam int qty) throws Exception {
32344 tejbeer 1186
        boolean isCombo = false;
1187
        ComboModel comboModel = comboModelRepository.selectByCatalogIdWarehouseIdAndQty(catalogId, warehouseId, qty);
1188
        if (comboModel != null) {
1189
            isCombo = true;
1190
        }
1191
 
1192
        return responseSender.ok(isCombo);
1193
    }
1194
 
33929 tejus.loha 1195
    @GetMapping(value = "/partner/wodCompleteBrands", produces = MediaType.APPLICATION_JSON_VALUE)
1196
    public ResponseEntity<?> getWodcompletBrands(HttpServletRequest request) throws Exception {
1197
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
34630 tejus.loha 1198
        BrandAndAddToCartEligibleModel brandAndAddToCartEligibleModel = brandsService.wodcompletBrands(userInfo.getRetailerId());
1199
        return responseSender.ok(brandAndAddToCartEligibleModel);
33929 tejus.loha 1200
 
1201
    }
1202
 
25967 amit.gupta 1203
}