Subversion Repositories SmartDukaan

Rev

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