Subversion Repositories SmartDukaan

Rev

Rev 33575 | Rev 33873 | 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");
33576 amit.gupta 346
            return responseSender.ok(this.getCatalogResponse(docs, false, userInfo.getRetailerId()).stream().filter(x -> x.isInStock()).collect(Collectors.toList()));
33575 amit.gupta 347
        } catch (HttpHostConnectException e) {
348
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
349
        }
350
    }
351
 
32339 tejbeer 352
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
353
    @RequestMapping(value = "/fofo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
33573 amit.gupta 354
    public ResponseEntity<?> getFofo(HttpServletRequest request, @RequestParam(value = "categoryId", required = false, defaultValue = "3") String categoryId, @RequestParam(value = "offset") int offset,
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
 
33576 amit.gupta 379
            Map<Integer, FofoCatalogResponse> similarCatalogResponsesMap = this.getSimpleDocs(fs, 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
 
33576 amit.gupta 394
    private List<FofoCatalogResponse> getSimpleDocs(FofoStore fofoStore, Set<Integer> catalogIds) throws Exception {
33575 amit.gupta 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
 
33576 amit.gupta 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
        int warehouseId = fofoStoreRepository.selectByRetailerId(fofoStore.getId()).getWarehouseId();
413
        Map<Integer, List<SaholicPOItem>> poItemAvailabilityMap = saholicInventoryService.getSaholicPOItems().get(warehouseId);
414
        for (int i = 0; i < docs.length(); i++) {
415
            JSONObject doc = docs.getJSONObject(i);
416
            FofoCatalogResponse fofoCatalogResponse = this.toFofoCatalogResponse(doc);
417
            if (doc.has("_childDocuments_")) {
418
                String modelColorClass = "grey";
419
                FofoAvailabilityInfo fdiAnyColour = null;
420
                // Iterating itemIds
421
                for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
422
                    JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
423
                    int itemId = childItem.getInt("itemId_i");
424
 
425
                    List<SaholicCISTable> currentAvailability = saholicCISTableRepository.selectByItemWarehouse(itemId, warehouseId);
426
                    List<SaholicPOItem> poItemAvailability = null;
427
                    if (poItemAvailabilityMap != null) {
428
                        poItemAvailability = poItemAvailabilityMap.get(itemId);
429
                    }
430
 
431
                    for (SaholicCISTable saholicCISTable : currentAvailability) {
432
                        saholicCISTable.setWarehouseName(
433
                                ProfitMandiConstants.WAREHOUSE_MAP.get(saholicCISTable.getWarehouseFrom()));
434
                    }
435
 
436
 
437
                    String poColor = "grey";
438
                    boolean active = false;
439
                    if (currentAvailability != null && currentAvailability.stream().collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)) > 0) {
440
                        poColor = "green";
441
                        modelColorClass = "green";
442
                    } else if (poItemAvailability != null && poItemAvailability.stream().collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty)) > 0) {
443
                        if (currentAvailability != null && poItemAvailability.stream().collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty)) + currentAvailability.stream().collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)) <= 0) {
444
                            poColor = "grey";
445
                        } else {
446
                            poColor = "yellow";
447
                            if (!modelColorClass.equals("green")) {
448
                                modelColorClass = poColor;
449
                            }
450
                        }
451
                    }
452
 
453
                }
454
                fofoCatalogResponse.setInStock(!modelColorClass.equals("grey"));
33575 amit.gupta 455
            }
33576 amit.gupta 456
 
457
            fofoCatalogResponses.add(fofoCatalogResponse);
33575 amit.gupta 458
        }
33576 amit.gupta 459
 
33575 amit.gupta 460
        return fofoCatalogResponses;
461
    }
462
 
463
    private FofoCatalogResponse toFofoCatalogResponse(JSONObject doc) {
464
        FofoCatalogResponse fofoCatalogResponse = new FofoCatalogResponse();
465
        fofoCatalogResponse.setCatalogId(doc.getInt("catalogId_i"));
466
        fofoCatalogResponse.setImageUrl(doc.getString("imageUrl_s"));
467
        fofoCatalogResponse.setTitle(doc.getString("title_s"));
468
        fofoCatalogResponse.setMop(doc.getFloat("mop_f"));
469
        fofoCatalogResponse.setDp(doc.getFloat("dp_f"));
470
        fofoCatalogResponse.setBrand(doc.getJSONArray("brand_ss").getString(0));
471
        return fofoCatalogResponse;
472
    }
473
 
32339 tejbeer 474
    @RequestMapping(value = "/online-deals", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
475
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
476
    @ApiOperation(value = "Get online deals")
33575 amit.gupta 477
    public ResponseEntity<?> getOnlineDeals(HttpServletRequest request, @RequestParam(value = "categoryId") String
478
            categoryId, @RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String
479
                                                    limit, @RequestParam(value = "sort", required = false) String
480
                                                    sort, @RequestParam(value = "direction", required = false) String
481
                                                    direction, @RequestParam(value = "filterData", required = false) String filterData) throws Throwable {
32339 tejbeer 482
        logger.info("Request " + request.getParameterMap());
483
        String response = null;
484
        int userId = (int) request.getAttribute("userId");
22289 amit.gupta 485
 
32339 tejbeer 486
        String uri = "/deals/" + userId;
487
        RestClient rc = new RestClient();
488
        Map<String, String> params = new HashMap<>();
489
        params.put("offset", offset);
490
        params.put("limit", limit);
491
        params.put("categoryId", categoryId);
492
        params.put("direction", direction);
493
        params.put("sort", sort);
494
        params.put("source", "online");
495
        params.put("filterData", filterData);
496
        /*
497
         * if (userInfo.getRoleNames().contains(RoleType.FOFO.toString())) {
498
         * params.put("tag_ids", getCommaSeparateTags(userId)); }
499
         */
500
        List<Object> responseObject = new ArrayList<>();
501
        try {
502
            response = rc.get(SchemeType.HTTP, host, port, uri, params);
503
        } catch (HttpHostConnectException e) {
504
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
505
        }
22931 ashik.ali 506
 
32339 tejbeer 507
        JsonArray result_json = Json.parse(response).asArray();
508
        for (JsonValue j : result_json) {
509
            // logger.info("res " + j.asArray());
510
            List<Object> innerObject = new ArrayList<>();
511
            for (JsonValue jsonObject : j.asArray()) {
512
                innerObject.add(toDealObject(jsonObject.asObject()));
513
            }
514
            if (innerObject.size() > 0) {
515
                responseObject.add(innerObject);
516
            }
517
        }
518
        return responseSender.ok(responseObject);
519
    }
22272 amit.gupta 520
 
32339 tejbeer 521
    private Object toDealObject(JsonObject jsonObject) {
522
        if (jsonObject.get("dealObject") != null && jsonObject.get("dealObject").asInt() == 1) {
523
            return new Gson().fromJson(jsonObject.toString(), DealObjectResponse.class);
524
        }
525
        return new Gson().fromJson(jsonObject.toString(), DealsResponse.class);
526
    }
22319 amit.gupta 527
 
32339 tejbeer 528
    @RequestMapping(value = ProfitMandiConstants.URL_BRANDS, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
529
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
530
    @ApiOperation(value = "Get brand list and count for category")
33575 amit.gupta 531
    public ResponseEntity<?> getBrands(HttpServletRequest request, @RequestParam(value = "category_id") String
532
            category_id) throws ProfitMandiBusinessException {
32339 tejbeer 533
        logger.info("Request " + request.getParameterMap());
534
        String response = null;
535
        // TODO: move to properties
536
        String uri = ProfitMandiConstants.URL_BRANDS;
537
        RestClient rc = new RestClient();
538
        Map<String, String> params = new HashMap<>();
539
        params.put("category_id", category_id);
540
        List<DealBrands> dealBrandsResponse = null;
541
        try {
542
            response = rc.get(SchemeType.HTTP, host, port, uri, params);
543
        } catch (HttpHostConnectException e) {
544
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
545
        }
23816 amit.gupta 546
 
32339 tejbeer 547
        dealBrandsResponse = new Gson().fromJson(response, new TypeToken<List<DealBrands>>() {
548
        }.getType());
23022 ashik.ali 549
 
32339 tejbeer 550
        return responseSender.ok(dealBrandsResponse);
551
    }
22319 amit.gupta 552
 
32339 tejbeer 553
    @RequestMapping(value = ProfitMandiConstants.URL_UNIT_DEAL, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
554
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
555
    @ApiOperation(value = "Get unit deal object")
33575 amit.gupta 556
    public ResponseEntity<?> getUnitDeal(HttpServletRequest request, @PathVariable(value = "id") long id) throws
557
            ProfitMandiBusinessException {
32339 tejbeer 558
        String response = null;
559
        // TODO: move to properties
560
        String uri = "getDealById/" + id;
561
        System.out.println("Unit deal " + uri);
562
        RestClient rc = new RestClient();
563
        Map<String, String> params = new HashMap<>();
564
        DealsResponse dealsResponse = null;
565
        try {
566
            response = rc.get(SchemeType.HTTP, host, port, uri, params);
567
        } catch (HttpHostConnectException e) {
568
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
569
        }
23816 amit.gupta 570
 
32339 tejbeer 571
        JsonObject result_json = Json.parse(response).asObject();
572
        if (!result_json.isEmpty()) {
573
            dealsResponse = new Gson().fromJson(response, DealsResponse.class);
574
            Iterator<AvailabilityInfo> iter = dealsResponse.getAvailabilityInfo().iterator();
575
            while (iter.hasNext()) {
576
                AvailabilityInfo ai = iter.next();
577
                if (ai.getAvailability() <= 0)
578
                    iter.remove();
579
            }
580
        }
581
        return responseSender.ok(dealsResponse);
582
    }
23816 amit.gupta 583
 
32339 tejbeer 584
    @RequestMapping(value = "/partnerdeals/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
585
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
586
    @ApiOperation(value = "Get unit deal object")
33575 amit.gupta 587
    public ResponseEntity<?> getUnitFocoDeal(HttpServletRequest request, @PathVariable(value = "id") long id) throws
588
            Exception {
32339 tejbeer 589
        List<FofoCatalogResponse> dealResponse = new ArrayList<>();
590
        List<Integer> tagIds = Arrays.asList(4);
591
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
592
        if (roleManagerService.isPartner(userInfo.getRoleIds())) {
593
            String categoryId = "(3 OR 6)";
594
            UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
595
            RestClient rc = new RestClient();
596
            Map<String, String> params = new HashMap<>();
597
            List<String> mandatoryQ = new ArrayList<>();
598
            String catalogString = "catalog" + id;
24091 tejbeer 599
 
32339 tejbeer 600
            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 601
 
32339 tejbeer 602
            params.put("q", StringUtils.join(mandatoryQ, " "));
603
            params.put("fl", "*, [child parentFilter=id:catalog*]");
604
            params.put("sort", "rank_i asc, create_s desc");
605
            params.put("wt", "json");
606
            String response = null;
607
            try {
33487 amit.gupta 608
                response = rc.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
32339 tejbeer 609
            } catch (HttpHostConnectException e) {
610
                throw new ProfitMandiBusinessException("", "", "Could not connect to host");
611
            }
612
            JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
613
            JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
614
            dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId());
615
        } else {
616
            return responseSender.badRequest(
617
                    new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
618
        }
619
        return responseSender.ok(dealResponse.get(0));
620
    }
24091 tejbeer 621
 
32339 tejbeer 622
    @RequestMapping(value = "/fofo/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
33575 amit.gupta 623
    public ResponseEntity<?> getBrandsToDisplay(HttpServletRequest request,
624
                                                @RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {
32339 tejbeer 625
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
626
        logger.info("userInfo [{}]", userInfo);
32717 ranu 627
        List<BrandCatalog> brandsDisplay = brandsService.getBrandsToDisplay(categoryId);
628
        //List<DBObject> brandsDisplay = mongoClient.getMongoBrands(userInfo.getRetailerId(), userInfo.getEmail(), categoryId);
32339 tejbeer 629
        return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
630
    }
25879 amit.gupta 631
 
32339 tejbeer 632
    @RequestMapping(value = "/fofo/brandCatalog", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
33575 amit.gupta 633
    public ResponseEntity<?> getBrands(HttpServletRequest request,
634
                                       @RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {
32339 tejbeer 635
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
636
        logger.info("userInfo [{}]", userInfo);
31507 tejbeer 637
 
32339 tejbeer 638
        List<BrandCatalog> brandsDisplay = brandsService.getBrands(userInfo.getRetailerId(), userInfo.getEmail(), categoryId);
639
        return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
640
    }
31507 tejbeer 641
 
32339 tejbeer 642
    @RequestMapping(value = "/fofo/accessory/all-categories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
643
    public ResponseEntity<?> getSubCategoriesToDisplay(HttpServletRequest request) throws Exception {
644
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
645
        logger.info("userInfo [{}]", userInfo);
646
        List<DBObject> subCategoriesDisplay = this.getSubCategoriesToDisplay();
647
        return new ResponseEntity<>(subCategoriesDisplay, HttpStatus.OK);
648
    }
23816 amit.gupta 649
 
32339 tejbeer 650
    private List<DBObject> getSubCategoriesToDisplay() throws Exception {
651
        List<DBObject> subCategories = new ArrayList<>();
652
        RestClient rc = new RestClient();
653
        Map<String, String> params = new HashMap<>();
654
        params.put("q", "categoryId_i:6");
655
        params.put("group", "true");
656
        params.put("group.field", "subCategoryId_i");
657
        params.put("wt", "json");
658
        params.put("rows", "50");
659
        params.put("fl", "subCategoryId_i");
660
        String response = null;
661
        try {
33487 amit.gupta 662
            response = rc.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
32339 tejbeer 663
        } catch (HttpHostConnectException e) {
664
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
665
        }
666
        JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("grouped");
667
        JSONArray groups = solrResponseJSONObj.getJSONObject("subCategoryId_i").getJSONArray("groups");
668
        List<Integer> categoryIds = new ArrayList<>();
669
        for (int i = 0; i < groups.length(); i++) {
670
            JSONObject groupObject = groups.getJSONObject(i);
671
            int subCategoryId = groupObject.getInt("groupValue");
672
            int quantity = groupObject.getJSONObject("doclist").getInt("numFound");
673
            categoryIds.add(subCategoryId);
674
        }
25015 amit.gupta 675
 
32339 tejbeer 676
        List<Category> categories = categoryRepository.selectByIds(categoryIds);
677
        AtomicInteger i = new AtomicInteger(0);
678
        categories.forEach(x -> {
679
            DBObject dbObject = new BasicDBObject();
680
            dbObject.put("name", x.getLabel());
681
            dbObject.put("subCategoryId", x.getId());
682
            dbObject.put("rank", i.incrementAndGet());
683
            dbObject.put("categoryId", 6);
684
            dbObject.put("url", "https://images.smartdukaan.com/uploads/campaigns/" + x.getId() + ".png");
685
            subCategories.add(dbObject);
686
        });
25015 amit.gupta 687
 
32339 tejbeer 688
        return subCategories;
25015 amit.gupta 689
 
32339 tejbeer 690
    }
25010 amit.gupta 691
 
32339 tejbeer 692
    @RequestMapping(value = "/banners/{bannerType}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
693
    public ResponseEntity<?> getBanners(@PathVariable String bannerType) {
694
        return new ResponseEntity<>(mongoClient.getBannersByType(bannerType), HttpStatus.OK);
695
    }
23816 amit.gupta 696
 
32339 tejbeer 697
    @RequestMapping(value = "/deals/subCategories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
698
    public ResponseEntity<?> getSubcategoriesToDisplay() {
699
        return new ResponseEntity<>(mongoClient.getSubcategoriesToDisplay(), HttpStatus.OK);
700
    }
23816 amit.gupta 701
 
32339 tejbeer 702
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
703
    @RequestMapping(value = "/deals/skus/{skus}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
704
    public ResponseEntity<?> getDealsBySkus(@PathVariable String skus) throws ProfitMandiBusinessException {
705
        StringBuffer sb = new StringBuffer("/getDealsForNotification/");
706
        String uri = sb.append(skus).toString();
707
        RestClient rc = new RestClient();
708
        String response;
709
        try {
710
            response = rc.get(SchemeType.HTTP, host, port, uri, new HashMap<>());
711
        } catch (HttpHostConnectException e) {
712
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
713
        }
714
        JsonArray result_json = Json.parse(response).asArray();
715
        List<Object> responseObject = new ArrayList<>();
716
        for (JsonValue j : result_json) {
717
            // logger.info("res " + j.asArray());
718
            List<Object> innerObject = new ArrayList<>();
719
            for (JsonValue jsonObject : j.asArray()) {
720
                innerObject.add(toDealObject(jsonObject.asObject()));
721
            }
722
            if (innerObject.size() > 0) {
723
                responseObject.add(innerObject);
724
            }
725
        }
726
        return responseSender.ok(responseObject);
727
    }
21339 kshitij.so 728
 
32339 tejbeer 729
    @RequestMapping(value = "/partner/listing", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
730
    public ResponseEntity<?> getPartnersListing(HttpServletRequest request) throws Exception {
731
        List<WebListing> webListings = webListingRepository.selectAllWebListingByType(Optional.of(true), WebListingSource.partner);
732
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
733
        for (WebListing webListing : webListings) {
31642 tejbeer 734
 
33573 amit.gupta 735
            webListing.setFofoCatalogResponses(getDealResponses(userInfo, webListing, 0, 20));
32339 tejbeer 736
        }
737
        return responseSender.ok(webListings);
738
    }
31547 tejbeer 739
 
33576 amit.gupta 740
    private List<FofoCatalogResponse> getDealResponses(UserInfo userInfo, WebListing webListing, int offset,
741
                                                       int limit) throws Exception {
31572 tejbeer 742
 
32339 tejbeer 743
        RestClient rc = new RestClient();
744
        Map<String, String> params = new HashMap<>();
745
        List<String> mandatoryQ = new ArrayList<>();
31670 tejbeer 746
 
32339 tejbeer 747
        FofoStore fs = fofoStoreRepository.selectByRetailerId(userInfo.getRetailerId());
31670 tejbeer 748
 
32339 tejbeer 749
        params.put("sort", "w" + fs.getWarehouseId() + "_i desc");
31576 tejbeer 750
 
32339 tejbeer 751
        List<Integer> webProducts = null;
752
        if (webListing.getType().equals(WebListingType.solr)) {
753
            logger.info("solrtype {}", webListing.getSolrQuery());
754
            mandatoryQ.add(String.format("+{!parent which=\"" + webListing.getSolrQuery() + "\"} AND active_b:true AND show_default_b:true"));
755
        } else {
756
            logger.info("solrtype2 {}", webListing.getSolrQuery());
31675 tejbeer 757
 
33573 amit.gupta 758
            webProducts = webProductListingRepository.selectAllByWebListingId(webListing.getId(), offset, limit).stream().filter(x -> x.getRank() > 0).map(x -> x.getEntityId()).collect(Collectors.toList());
31572 tejbeer 759
 
32339 tejbeer 760
            if (webProducts.size() == 0) {
761
                return new ArrayList<>();
762
            }
31572 tejbeer 763
 
32339 tejbeer 764
            mandatoryQ.add(String.format(
33575 amit.gupta 765
                    "+{!parent which=\"catalogId_i:(" + StringUtils.join(webProducts, " ") + ")\"} AND active_b:true AND show_default_b:true"));
31642 tejbeer 766
 
32339 tejbeer 767
        }
768
        params.put("q", StringUtils.join(mandatoryQ, " "));
769
        params.put("fl", "*, [child parentFilter=id:catalog* childFilter=active_b:true ]");
31612 tejbeer 770
 
32339 tejbeer 771
        params.put("start", String.valueOf(offset));
772
        params.put("rows", String.valueOf(limit));
773
        params.put("wt", "json");
774
        String response = null;
775
        try {
776
            response = rc.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
777
        } catch (HttpHostConnectException e) {
778
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
779
        }
780
        JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
781
        JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
782
        List<FofoCatalogResponse> dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId());
31671 tejbeer 783
 
32339 tejbeer 784
        if (webProducts != null && webListing.getUrl().equals("new-launches")) {
785
            List<Integer> webProductsFinal = webProducts;
786
            dealResponse = dealResponse.stream().sorted(Comparator.comparing(x -> webProductsFinal.indexOf(x.getCatalogId()))).collect(Collectors.toList());
31671 tejbeer 787
 
32339 tejbeer 788
        }
31547 tejbeer 789
 
32339 tejbeer 790
        return dealResponse;
791
    }
30669 amit.gupta 792
 
32339 tejbeer 793
    @Autowired
794
    private SaholicCISTableRepository saholicCISTableRepository;
27053 amit.gupta 795
 
33575 amit.gupta 796
    private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal, int fofoId) throws
797
            Exception {
32339 tejbeer 798
        List<FofoCatalogResponse> dealResponse = new ArrayList<>();
799
        List<Integer> tagIds = Arrays.asList(4);
800
        List<Integer> itemIds = new ArrayList<>();
801
        if (docs.length() > 0) {
802
            for (int i = 0; i < docs.length(); i++) {
803
                JSONObject doc = docs.getJSONObject(i);
804
                if (doc.has("_childDocuments_")) {
805
                    for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
806
                        JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
807
                        int itemId = childItem.getInt("itemId_i");
808
                        itemIds.add(itemId);
809
                    }
810
                }
811
            }
812
            if (itemIds.size() == 0) {
813
                return dealResponse;
814
            }
815
        }
816
        // get warehouse Id
817
        int warehouseId = fofoStoreRepository.selectByRetailerId(fofoId).getWarehouseId();
818
        Map<Integer, List<SaholicPOItem>> poItemAvailabilityMap = saholicInventoryService.getSaholicPOItems().get(warehouseId);
819
        List<Integer> catalogIds = new ArrayList<>();
820
        for (int i = 0; i < docs.length(); i++) {
821
            Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
822
            JSONObject doc = docs.getJSONObject(i);
823
            catalogIds.add(doc.getInt("catalogId_i"));
824
        }
825
        List<CreateOfferRequest> allSchemOffers = null;
826
        Map<Integer, PriceCircularItemModelNew> priceCircularItemModelMap = new HashMap<>();
827
        if (catalogIds.size() > 0) {
828
            PriceCircularModel priceCircularModel = priceCircularService.getPriceCircularByOffer(fofoId, catalogIds, LocalDate.now());
829
            allSchemOffers = priceCircularModel.getOffers();
30188 amit.gupta 830
 
32339 tejbeer 831
            List<PriceCircularItemModelNew> priceCircularItemModelNews = priceCircularModel.getPriceCircularItemModelNews();
832
            if (priceCircularItemModelNews != null) {
833
                priceCircularItemModelMap = priceCircularItemModelNews.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));
834
            }
835
        }
31629 tejbeer 836
 
33575 amit.gupta 837
        /*List<CatalogFavourite> catalogFavourites = catalogFavouriteRepository.selectBypartnerId(fofoId);
32339 tejbeer 838
        List<Integer> catalogFavouriteIds = new ArrayList<>();
839
        if (!catalogFavourites.isEmpty()) {
840
            catalogFavouriteIds = catalogFavourites.stream().map(x -> x.getCatalogId()).collect(Collectors.toList());
841
        }
31629 tejbeer 842
 
32339 tejbeer 843
        if (!catalogFavourites.isEmpty()) {
844
            catalogFavourites.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));
33575 amit.gupta 845
        }*/
30595 tejbeer 846
 
32339 tejbeer 847
        for (int i = 0; i < docs.length(); i++) {
848
            Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
849
            JSONObject doc = docs.getJSONObject(i);
850
            FofoCatalogResponse fofoCatalogResponse = new FofoCatalogResponse();
851
            fofoCatalogResponse.setCatalogId(doc.getInt("catalogId_i"));
852
            fofoCatalogResponse.setImageUrl(doc.getString("imageUrl_s"));
853
            fofoCatalogResponse.setTitle(doc.getString("title_s"));
31629 tejbeer 854
 
33575 amit.gupta 855
            /*if (catalogFavouriteIds.contains(fofoCatalogResponse.getCatalogId())) {
32339 tejbeer 856
                fofoCatalogResponse.setFavourite(true);
33575 amit.gupta 857
            }*/
30683 tejbeer 858
 
32339 tejbeer 859
            List<WebOffer> webOffers = webOfferRepository.selectAllActiveOffers().get(fofoCatalogResponse.getCatalogId());
31612 tejbeer 860
 
33573 amit.gupta 861
            //logger.info("webOffers {}", webOffers);
32339 tejbeer 862
            if (webOffers != null && webOffers.size() > 0) {
863
                fofoCatalogResponse.setWebOffers(webOffers);
864
                fofoCatalogResponse.setOffers(webOffers.stream().map(x -> x.getTitle()).collect(Collectors.toList()));
30683 tejbeer 865
 
32339 tejbeer 866
            }
30683 tejbeer 867
 
32339 tejbeer 868
            List<ComboModel> comboModels = comboModelRepository.selectByWarehouseId(warehouseId).stream().filter(x -> x.getCatalogId() == fofoCatalogResponse.getCatalogId()).collect(Collectors.toList());
30683 tejbeer 869
 
33573 amit.gupta 870
            //logger.info("comboModels {}", comboModels);
32344 tejbeer 871
 
32339 tejbeer 872
            if (comboModels != null && comboModels.size() > 0) {
873
                fofoCatalogResponse.setComboModels(comboModels);
874
            }
30683 tejbeer 875
 
32339 tejbeer 876
            try {
877
                fofoCatalogResponse.setFeature(doc.getString("feature_s"));
878
            } catch (Exception e) {
879
                fofoCatalogResponse.setFeature(null);
880
                logger.info("Could not find Feature_s for {}", fofoCatalogResponse.getCatalogId());
881
            }
30683 tejbeer 882
 
32339 tejbeer 883
            fofoCatalogResponse.setBrand(doc.getJSONArray("brand_ss").getString(0));
884
            logger.info("labelss {}", doc.has("label_ss"));
30683 tejbeer 885
 
32339 tejbeer 886
            if (doc.has("label_ss")) {
887
                logger.info("label {}", doc.getJSONArray("label_ss"));
30683 tejbeer 888
 
32339 tejbeer 889
                JSONArray arr = doc.getJSONArray("label_ss");
890
                Set<String> labels = new HashSet<String>();
891
                for (int j = 0; j < arr.length(); j++) {
892
                    labels.add(arr.getString(j));
893
                }
31612 tejbeer 894
 
32339 tejbeer 895
                fofoCatalogResponse.setLabels(new ArrayList<>(labels));
31612 tejbeer 896
 
32339 tejbeer 897
            }
33573 amit.gupta 898
            if (doc.has("similarModels_ii")) {
899
                JSONArray similarModelsArray = doc.getJSONArray("similarModels_ii");
900
                List<Integer> similarCatalogIds = new ArrayList<>();
901
                for (int j = 0; j < similarModelsArray.length(); j++) {
902
                    similarCatalogIds.add(similarModelsArray.getInt(j));
903
                }
904
                fofoCatalogResponse.setSimilarModelIds(similarCatalogIds);
905
            }
31612 tejbeer 906
 
32339 tejbeer 907
            if (doc.has("_childDocuments_")) {
908
                String modelColorClass = "grey";
909
                FofoAvailabilityInfo fdiAnyColour = null;
910
                // Iterating itemIds
911
                for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
912
                    PriceCircularItemModelNew priceCircularItemModel = priceCircularItemModelMap.get(fofoCatalogResponse.getCatalogId());
913
                    JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
914
                    int itemId = childItem.getInt("itemId_i");
915
                    float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
916
                    if (!fofoAvailabilityInfoMap.containsKey(itemId)) {
917
                        FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
918
                        List<SaholicCISTable> currentAvailability = saholicCISTableRepository.selectByItemWarehouse(itemId, warehouseId);
919
                        List<SaholicPOItem> poItemAvailability = null;
920
                        if (poItemAvailabilityMap != null) {
921
                            poItemAvailability = poItemAvailabilityMap.get(itemId);
922
                        }
31612 tejbeer 923
 
32339 tejbeer 924
                        if (priceCircularItemModel != null) {
33410 ranu 925
                            fdi.setNlc((float) priceCircularItemModel.getNetNlc());
32339 tejbeer 926
                        }
31612 tejbeer 927
 
32339 tejbeer 928
                        for (SaholicCISTable saholicCISTable : currentAvailability) {
929
                            saholicCISTable.setWarehouseName(
930
                                    ProfitMandiConstants.WAREHOUSE_MAP.get(saholicCISTable.getWarehouseFrom()));
931
                        }
31612 tejbeer 932
 
32339 tejbeer 933
                        Map<Integer, SaholicCISTable> map = currentAvailability.stream().collect(Collectors.toMap(SaholicCISTable::getWarehouseFrom, x -> x));
934
                        if (poItemAvailability != null) {
935
                            for (SaholicPOItem saholicPOItem : poItemAvailability) {
936
                                if (map.containsKey(saholicPOItem.getWarehouseFrom())) {
937
                                    map.get(saholicPOItem.getWarehouseFrom()).setPopendingQty(saholicPOItem.getUnfulfilledQty());
938
                                } else {
939
                                    SaholicCISTable saholicCISTable = new SaholicCISTable();
940
                                    saholicCISTable.setAvailability(0);
941
                                    saholicCISTable.setReserved(0);
942
                                    saholicCISTable.setItemId(itemId);
943
                                    saholicCISTable.setWarehouseId(warehouseId);
944
                                    saholicCISTable.setPopendingQty(saholicPOItem.getUnfulfilledQty());
945
                                    saholicCISTable.setWarehouseFrom(saholicPOItem.getWarehouseFrom());
946
                                    saholicCISTable.setWarehouseName(
947
                                            ProfitMandiConstants.WAREHOUSE_MAP.get(saholicPOItem.getWarehouseFrom()));
948
                                    map.put(saholicPOItem.getWarehouseFrom(), saholicCISTable);
949
                                }
950
                            }
951
                        }
952
                        fdi.setSaholicCISTableList(new ArrayList<>(map.values()));
953
                        String poColor = "grey";
954
                        boolean active = false;
955
                        if (currentAvailability != null && currentAvailability.stream().collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)) > 0) {
956
                            poColor = "green";
957
                            modelColorClass = "green";
32978 amit.gupta 958
                        } else if (poItemAvailability != null && poItemAvailability.stream().collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty)) > 0) {
959
                            if (currentAvailability != null && poItemAvailability.stream().collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty)) + currentAvailability.stream().collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)) <= 0) {
960
                                poColor = "grey";
961
                            } else {
962
                                poColor = "yellow";
963
                                if (modelColorClass != "green") {
964
                                    modelColorClass = poColor;
32339 tejbeer 965
                                }
966
                            }
32978 amit.gupta 967
                        }
32339 tejbeer 968
                        fdi.setColorClass(poColor);
969
                        fdi.setSellingPrice(sellingPrice);
970
                        fdi.setActive(active);
971
                        fdi.setMrp(childItem.getDouble("mrp_f"));
972
                        fdi.setMop((float) childItem.getDouble("mop_f"));
973
                        fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
974
                        if (fdi.getColor().equalsIgnoreCase("any colour")) {
975
                            fdiAnyColour = fdi;
976
                        }
977
                        fdi.setTagId(childItem.getInt("tagId_i"));
978
                        fdi.setItem_id(itemId);
32978 amit.gupta 979
                        Float cashBack = schemeService.getCatalogSchemeCashBack(fofoId, Arrays.asList(fofoCatalogResponse.getCatalogId())).get(fofoCatalogResponse.getCatalogId());
32339 tejbeer 980
                        cashBack = cashBack == null ? 0 : cashBack;
981
                        fdi.setCashback(cashBack);
982
                        fdi.setMinBuyQuantity(1);
983
                        if (hotDeal) {
984
                            if (currentAvailability != null) {
985
                                fdi.setAvailability(currentAvailability.stream().collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)));
986
                            } else {
987
                                fdi.setAvailability(0);
988
                            }
989
                        } else {
990
                            // Lets consider that its out of stock
32591 amit.gupta 991
                            fdi.setAvailability(400);
32339 tejbeer 992
                            Item item = null;
993
                            try {
994
                                item = itemRepository.selectById(itemId);
995
                            } catch (Exception e) {
996
                                e.printStackTrace();
997
                                continue;
998
                            }
999
                            // In case its tampered glass moq should be
1000
                            if (item.getCategoryId() == 10020) {
1001
                                fdi.setMinBuyQuantity(5);
1002
                            }
1003
                        }
1004
                        fdi.setQuantityStep(1);
32590 amit.gupta 1005
                        fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 400));
32339 tejbeer 1006
                        fofoAvailabilityInfoMap.put(itemId, fdi);
1007
                    }
1008
                }
1009
                if (fdiAnyColour != null) {
1010
                    fdiAnyColour.setColorClass(modelColorClass);
1011
                }
33576 amit.gupta 1012
                fofoCatalogResponse.setInStock(!modelColorClass.equals("grey"));
32339 tejbeer 1013
            }
1014
            if (fofoAvailabilityInfoMap.values().size() > 0) {
1015
                List<FofoAvailabilityInfo> availabilityList = fofoAvailabilityInfoMap.values().stream().sorted(Comparator.comparing(FofoAvailabilityInfo::getAvailability).reversed()).collect(Collectors.toList());
1016
                fofoCatalogResponse.setItems(availabilityList);
1017
                if (priceCircularItemModelMap.containsKey(fofoCatalogResponse.getCatalogId())) {
1018
                    PriceCircularItemModelNew priceCircularItemModel = priceCircularItemModelMap.get(fofoCatalogResponse.getCatalogId());
1019
                    if (priceCircularItemModel.getSlabPayouts() != null) {
1020
                        List<CreateOfferRequest> schemeOffers = new ArrayList<>();
1021
                        List<Map<Integer, AmountModel>> slabPayouts = priceCircularItemModel.getSlabPayouts();
1022
                        Iterator<Map<Integer, AmountModel>> iterator = slabPayouts.iterator();
1023
                        int iteratorCount = 0;
1024
                        while (iterator.hasNext()) {
1025
                            Map<Integer, AmountModel> slabPayoutMap = iterator.next();
1026
                            if (slabPayoutMap != null) {
1027
                                schemeOffers.add(allSchemOffers.get(iteratorCount));
1028
                            } else {
1029
                                iterator.remove();
1030
                            }
1031
                            iteratorCount++;
1032
                        }
1033
                        fofoCatalogResponse.setSchemeOffers(schemeOffers);
1034
                    }
1035
                    fofoCatalogResponse.setPriceCircularItemModel(priceCircularItemModel);
1036
                }
1037
                dealResponse.add(fofoCatalogResponse);
1038
            }
1039
        }
1040
        return dealResponse;
30686 amit.gupta 1041
 
32339 tejbeer 1042
    }
30693 amit.gupta 1043
 
33575 amit.gupta 1044
    private List<FofoCatalogResponse> getCatalogSingleSkuResponse(JSONArray
1045
                                                                          docs, Map<Integer, Integer> itemFilter, boolean hotDeal) throws ProfitMandiBusinessException {
32339 tejbeer 1046
        Map<Integer, TagListing> itemTagListingMap = null;
1047
        List<FofoCatalogResponse> dealResponse = new ArrayList<>();
1048
        List<Integer> tagIds = Arrays.asList(4);
24091 tejbeer 1049
 
32339 tejbeer 1050
        itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemFilter.keySet(), new HashSet<>(tagIds)).stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x));
24091 tejbeer 1051
 
32339 tejbeer 1052
        for (int i = 0; i < docs.length(); i++) {
1053
            Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
1054
            JSONObject doc = docs.getJSONObject(i);
26589 amit.gupta 1055
 
32339 tejbeer 1056
            for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
1057
                JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
1058
                int itemId = childItem.getInt("itemId_i");
1059
                TagListing tl = itemTagListingMap.get(itemId);
1060
                if (tl == null) {
1061
                    continue;
1062
                }
1063
                if (hotDeal) {
1064
                    if (!tl.isHotDeals()) {
1065
                        continue;
1066
                    }
1067
                }
1068
                float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
1069
                if (fofoAvailabilityInfoMap.containsKey(itemId)) {
1070
                    if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
1071
                        fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
1072
                        fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
1073
                    }
1074
                } else {
1075
                    FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
1076
                    fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
1077
                    fdi.setMop((float) childItem.getDouble("mop_f"));
1078
                    fdi.setMop((float) tl.getMrp());
1079
                    fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
1080
                    fdi.setTagId(childItem.getInt("tagId_i"));
1081
                    fdi.setItem_id(itemId);
1082
                    Item item = itemRepository.selectById(itemId);
1083
                    // In case its tampered glass moq should be 5
1084
                    if (item.getCategoryId() == 10020) {
1085
                        fdi.setMinBuyQuantity(10);
1086
                    } else {
1087
                        fdi.setMinBuyQuantity(1);
1088
                    }
1089
                    fdi.setAvailability(itemFilter.get(itemId));
1090
                    fdi.setQuantityStep(1);
1091
                    fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
1092
                    fofoAvailabilityInfoMap.put(itemId, fdi);
1093
                }
1094
            }
1095
            if (fofoAvailabilityInfoMap.values().size() > 0) {
1096
                for (FofoAvailabilityInfo fofoAvailabilityInfo : fofoAvailabilityInfoMap.values()) {
1097
                    FofoCatalogResponse ffdr = new FofoCatalogResponse();
1098
                    ffdr.setCatalogId(doc.getInt("catalogId_i"));
1099
                    ffdr.setImageUrl(doc.getString("imageUrl_s"));
1100
                    ffdr.setTitle(doc.getString("title_s"));
1101
                    try {
1102
                        ffdr.setFeature(doc.getString("feature_s"));
1103
                    } catch (Exception e) {
1104
                        ffdr.setFeature(null);
1105
                        logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
1106
                    }
1107
                    ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
1108
                    ffdr.setItems(Arrays.asList(fofoAvailabilityInfo));
1109
                    dealResponse.add(ffdr);
1110
                }
1111
            }
1112
        }
1113
        return dealResponse;
25880 amit.gupta 1114
 
32339 tejbeer 1115
    }
25880 amit.gupta 1116
 
32339 tejbeer 1117
    @RequestMapping(value = "/combo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
1118
    public ResponseEntity<?> getBanners(@RequestParam int catalogId, @RequestParam int warehouseId) {
1119
        List<ComboModel> comboModels = comboModelRepository.selectByCatalogIdAndWarehouseId(catalogId, warehouseId);
1120
        return responseSender.ok(comboModels);
1121
    }
32344 tejbeer 1122
 
1123
    @RequestMapping(value = "/checkCombo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
33575 amit.gupta 1124
    public ResponseEntity<?> checkCombo(HttpServletRequest request, @RequestParam int catalogId,
1125
                                        @RequestParam int warehouseId, @RequestParam int qty) throws Exception {
32344 tejbeer 1126
        boolean isCombo = false;
1127
        ComboModel comboModel = comboModelRepository.selectByCatalogIdWarehouseIdAndQty(catalogId, warehouseId, qty);
1128
        if (comboModel != null) {
1129
            isCombo = true;
1130
        }
1131
 
1132
        return responseSender.ok(isCombo);
1133
    }
1134
 
1135
 
25967 amit.gupta 1136
}