Subversion Repositories SmartDukaan

Rev

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