Subversion Repositories SmartDukaan

Rev

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