Subversion Repositories SmartDukaan

Rev

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