Subversion Repositories SmartDukaan

Rev

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