Subversion Repositories SmartDukaan

Rev

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

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