Subversion Repositories SmartDukaan

Rev

Rev 35801 | 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
        }
648
        return responseSender.ok(dealResponse.get(0));
649
    }
24091 tejbeer 650
 
34436 ranu 651
 
652
    @RequestMapping(value = "/suggestedPoDeals", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
653
    public ResponseEntity<?> suggestedPoDeals(HttpServletRequest request,@RequestBody Set<Integer>catalogIds) throws Exception {
654
 
655
        int userId = (int) request.getAttribute("userId");
656
        UserCart uc = userAccountRepository.getUserCart(userId);
657
        int fofoId = uc.getUserId();
658
        List<FofoCatalogResponse> dealResponse = new ArrayList<>();
659
        if (!catalogIds.isEmpty()) {
660
            dealResponse = webSolrService.dealResponse(catalogIds, fofoId);
661
        }
662
        return responseSender.ok(dealResponse);
663
    }
664
 
32339 tejbeer 665
    @RequestMapping(value = "/fofo/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
33575 amit.gupta 666
    public ResponseEntity<?> getBrandsToDisplay(HttpServletRequest request,
667
                                                @RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {
32339 tejbeer 668
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
669
        logger.info("userInfo [{}]", userInfo);
32717 ranu 670
        List<BrandCatalog> brandsDisplay = brandsService.getBrandsToDisplay(categoryId);
671
        //List<DBObject> brandsDisplay = mongoClient.getMongoBrands(userInfo.getRetailerId(), userInfo.getEmail(), categoryId);
32339 tejbeer 672
        return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
673
    }
25879 amit.gupta 674
 
32339 tejbeer 675
    @RequestMapping(value = "/fofo/brandCatalog", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
33575 amit.gupta 676
    public ResponseEntity<?> getBrands(HttpServletRequest request,
677
                                       @RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {
32339 tejbeer 678
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
679
        logger.info("userInfo [{}]", userInfo);
31507 tejbeer 680
 
32339 tejbeer 681
        List<BrandCatalog> brandsDisplay = brandsService.getBrands(userInfo.getRetailerId(), userInfo.getEmail(), categoryId);
682
        return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
683
    }
31507 tejbeer 684
 
32339 tejbeer 685
    @RequestMapping(value = "/fofo/accessory/all-categories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
686
    public ResponseEntity<?> getSubCategoriesToDisplay(HttpServletRequest request) throws Exception {
687
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
688
        logger.info("userInfo [{}]", userInfo);
689
        List<DBObject> subCategoriesDisplay = this.getSubCategoriesToDisplay();
690
        return new ResponseEntity<>(subCategoriesDisplay, HttpStatus.OK);
691
    }
23816 amit.gupta 692
 
32339 tejbeer 693
    private List<DBObject> getSubCategoriesToDisplay() throws Exception {
694
        List<DBObject> subCategories = new ArrayList<>();
35410 amit 695
                Map<String, String> params = new HashMap<>();
32339 tejbeer 696
        params.put("q", "categoryId_i:6");
697
        params.put("group", "true");
698
        params.put("group.field", "subCategoryId_i");
699
        params.put("wt", "json");
700
        params.put("rows", "50");
701
        params.put("fl", "subCategoryId_i");
702
        String response = null;
703
        try {
35410 amit 704
            response = restClient.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
32339 tejbeer 705
        } catch (HttpHostConnectException e) {
706
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
707
        }
708
        JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("grouped");
709
        JSONArray groups = solrResponseJSONObj.getJSONObject("subCategoryId_i").getJSONArray("groups");
710
        List<Integer> categoryIds = new ArrayList<>();
711
        for (int i = 0; i < groups.length(); i++) {
712
            JSONObject groupObject = groups.getJSONObject(i);
713
            int subCategoryId = groupObject.getInt("groupValue");
714
            int quantity = groupObject.getJSONObject("doclist").getInt("numFound");
715
            categoryIds.add(subCategoryId);
716
        }
25015 amit.gupta 717
 
32339 tejbeer 718
        List<Category> categories = categoryRepository.selectByIds(categoryIds);
719
        AtomicInteger i = new AtomicInteger(0);
720
        categories.forEach(x -> {
721
            DBObject dbObject = new BasicDBObject();
722
            dbObject.put("name", x.getLabel());
723
            dbObject.put("subCategoryId", x.getId());
724
            dbObject.put("rank", i.incrementAndGet());
725
            dbObject.put("categoryId", 6);
726
            dbObject.put("url", "https://images.smartdukaan.com/uploads/campaigns/" + x.getId() + ".png");
727
            subCategories.add(dbObject);
728
        });
25015 amit.gupta 729
 
32339 tejbeer 730
        return subCategories;
25015 amit.gupta 731
 
32339 tejbeer 732
    }
25010 amit.gupta 733
 
35801 amit 734
    @RequestMapping(value = "/fofo/categories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
735
    public ResponseEntity<?> getFofoCategories() {
736
        Map<Integer, Category> categoryMap = categoryRepository.selectAll();
737
        List<Map<String, Object>> result = new ArrayList<>();
738
        for (Category category : categoryMap.values()) {
739
            if (category.isStatus()) {
740
                Map<String, Object> cat = new HashMap<>();
741
                cat.put("id", category.getId());
742
                cat.put("label", category.getLabel());
743
                cat.put("displayName", category.getDisplayName());
744
                cat.put("parentCategoryId", category.getParentCategoryId());
745
                cat.put("marginOnly", category.isMarginOnly());
746
                result.add(cat);
747
            }
748
        }
749
        return responseSender.ok(result);
750
    }
751
 
32339 tejbeer 752
    @RequestMapping(value = "/banners/{bannerType}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
753
    public ResponseEntity<?> getBanners(@PathVariable String bannerType) {
754
        return new ResponseEntity<>(mongoClient.getBannersByType(bannerType), HttpStatus.OK);
755
    }
23816 amit.gupta 756
 
32339 tejbeer 757
    @RequestMapping(value = "/deals/subCategories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
758
    public ResponseEntity<?> getSubcategoriesToDisplay() {
759
        return new ResponseEntity<>(mongoClient.getSubcategoriesToDisplay(), HttpStatus.OK);
760
    }
23816 amit.gupta 761
 
32339 tejbeer 762
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
763
    @RequestMapping(value = "/deals/skus/{skus}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
764
    public ResponseEntity<?> getDealsBySkus(@PathVariable String skus) throws ProfitMandiBusinessException {
765
        StringBuffer sb = new StringBuffer("/getDealsForNotification/");
766
        String uri = sb.append(skus).toString();
35410 amit 767
                String response;
32339 tejbeer 768
        try {
35410 amit 769
            response = restClient.get(SchemeType.HTTP, host, port, uri, new HashMap<>());
32339 tejbeer 770
        } catch (HttpHostConnectException e) {
771
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
772
        }
773
        JsonArray result_json = Json.parse(response).asArray();
774
        List<Object> responseObject = new ArrayList<>();
775
        for (JsonValue j : result_json) {
776
            // logger.info("res " + j.asArray());
777
            List<Object> innerObject = new ArrayList<>();
778
            for (JsonValue jsonObject : j.asArray()) {
779
                innerObject.add(toDealObject(jsonObject.asObject()));
780
            }
781
            if (innerObject.size() > 0) {
782
                responseObject.add(innerObject);
783
            }
784
        }
785
        return responseSender.ok(responseObject);
786
    }
21339 kshitij.so 787
 
32339 tejbeer 788
    @RequestMapping(value = "/partner/listing", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
789
    public ResponseEntity<?> getPartnersListing(HttpServletRequest request) throws Exception {
790
        List<WebListing> webListings = webListingRepository.selectAllWebListingByType(Optional.of(true), WebListingSource.partner);
791
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
34786 aman.kumar 792
 
35412 amit 793
        // Pre-fetch FofoStore once (instead of N times inside getDealResponses)
35411 amit 794
        FofoStore fs = fofoStoreRepository.selectByRetailerId(userInfo.getRetailerId());
795
 
35412 amit 796
        for (WebListing webListing : webListings) {
797
            webListing.setFofoCatalogResponses(getDealResponses(userInfo, fs, webListing, 0, 20));
798
        }
32339 tejbeer 799
        return responseSender.ok(webListings);
800
    }
31547 tejbeer 801
 
35652 vikas 802
    private List<FofoCatalogResponse> getDealResponses(UserInfo userInfo, FofoStore fs, WebListing webListing, int offset, int limit) throws Exception {
31572 tejbeer 803
 
35411 amit 804
        Map<String, String> params = new HashMap<>();
32339 tejbeer 805
        List<String> mandatoryQ = new ArrayList<>();
31670 tejbeer 806
 
32339 tejbeer 807
        params.put("sort", "w" + fs.getWarehouseId() + "_i desc");
31576 tejbeer 808
 
32339 tejbeer 809
        List<Integer> webProducts = null;
810
        if (webListing.getType().equals(WebListingType.solr)) {
811
            logger.info("solrtype {}", webListing.getSolrQuery());
812
            mandatoryQ.add(String.format("+{!parent which=\"" + webListing.getSolrQuery() + "\"} AND active_b:true AND show_default_b:true"));
813
        } else {
814
            logger.info("solrtype2 {}", webListing.getSolrQuery());
31675 tejbeer 815
 
33573 amit.gupta 816
            webProducts = webProductListingRepository.selectAllByWebListingId(webListing.getId(), offset, limit).stream().filter(x -> x.getRank() > 0).map(x -> x.getEntityId()).collect(Collectors.toList());
31572 tejbeer 817
 
32339 tejbeer 818
            if (webProducts.size() == 0) {
819
                return new ArrayList<>();
820
            }
31572 tejbeer 821
 
32339 tejbeer 822
            mandatoryQ.add(String.format(
33575 amit.gupta 823
                    "+{!parent which=\"catalogId_i:(" + StringUtils.join(webProducts, " ") + ")\"} AND active_b:true AND show_default_b:true"));
31642 tejbeer 824
 
32339 tejbeer 825
        }
826
        params.put("q", StringUtils.join(mandatoryQ, " "));
827
        params.put("fl", "*, [child parentFilter=id:catalog* childFilter=active_b:true ]");
31612 tejbeer 828
 
32339 tejbeer 829
        params.put("start", String.valueOf(offset));
830
        params.put("rows", String.valueOf(limit));
831
        params.put("wt", "json");
832
        String response = null;
833
        try {
35410 amit 834
            response = restClient.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
32339 tejbeer 835
        } catch (HttpHostConnectException e) {
836
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
837
        }
838
        JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
839
        JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
840
        List<FofoCatalogResponse> dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId());
31671 tejbeer 841
 
32339 tejbeer 842
        if (webProducts != null && webListing.getUrl().equals("new-launches")) {
843
            List<Integer> webProductsFinal = webProducts;
844
            dealResponse = dealResponse.stream().sorted(Comparator.comparing(x -> webProductsFinal.indexOf(x.getCatalogId()))).collect(Collectors.toList());
31671 tejbeer 845
 
32339 tejbeer 846
        }
31547 tejbeer 847
 
32339 tejbeer 848
        return dealResponse;
849
    }
30669 amit.gupta 850
 
32339 tejbeer 851
    @Autowired
852
    private SaholicCISTableRepository saholicCISTableRepository;
27053 amit.gupta 853
 
35652 vikas 854
    private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal, int fofoId) throws Exception {
32339 tejbeer 855
        List<FofoCatalogResponse> dealResponse = new ArrayList<>();
856
        List<Integer> tagIds = Arrays.asList(4);
857
        List<Integer> itemIds = new ArrayList<>();
34260 vikas.jang 858
        Map<Integer, Integer> partnerStockAvailabilityMap = null;
32339 tejbeer 859
        if (docs.length() > 0) {
860
            for (int i = 0; i < docs.length(); i++) {
861
                JSONObject doc = docs.getJSONObject(i);
862
                if (doc.has("_childDocuments_")) {
863
                    for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
864
                        JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
865
                        int itemId = childItem.getInt("itemId_i");
866
                        itemIds.add(itemId);
867
                    }
868
                }
869
            }
870
        }
35486 vikas 871
        if (itemIds.isEmpty()) {
872
            return dealResponse;
873
        }
32339 tejbeer 874
        // get warehouse Id
875
        int warehouseId = fofoStoreRepository.selectByRetailerId(fofoId).getWarehouseId();
876
        Map<Integer, List<SaholicPOItem>> poItemAvailabilityMap = saholicInventoryService.getSaholicPOItems().get(warehouseId);
877
        List<Integer> catalogIds = new ArrayList<>();
878
        for (int i = 0; i < docs.length(); i++) {
879
            JSONObject doc = docs.getJSONObject(i);
880
            catalogIds.add(doc.getInt("catalogId_i"));
881
        }
882
        List<CreateOfferRequest> allSchemOffers = null;
883
        Map<Integer, PriceCircularItemModelNew> priceCircularItemModelMap = new HashMap<>();
884
        if (catalogIds.size() > 0) {
885
            PriceCircularModel priceCircularModel = priceCircularService.getPriceCircularByOffer(fofoId, catalogIds, LocalDate.now());
886
            allSchemOffers = priceCircularModel.getOffers();
30188 amit.gupta 887
 
32339 tejbeer 888
            List<PriceCircularItemModelNew> priceCircularItemModelNews = priceCircularModel.getPriceCircularItemModelNews();
889
            if (priceCircularItemModelNews != null) {
890
                priceCircularItemModelMap = priceCircularItemModelNews.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));
891
            }
892
        }
31629 tejbeer 893
 
33575 amit.gupta 894
        /*List<CatalogFavourite> catalogFavourites = catalogFavouriteRepository.selectBypartnerId(fofoId);
32339 tejbeer 895
        List<Integer> catalogFavouriteIds = new ArrayList<>();
896
        if (!catalogFavourites.isEmpty()) {
897
            catalogFavouriteIds = catalogFavourites.stream().map(x -> x.getCatalogId()).collect(Collectors.toList());
898
        }
31629 tejbeer 899
 
32339 tejbeer 900
        if (!catalogFavourites.isEmpty()) {
901
            catalogFavourites.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));
33575 amit.gupta 902
        }*/
30595 tejbeer 903
 
34260 vikas.jang 904
        if (fofoId > 0) {
905
            partnerStockAvailabilityMap = currentInventorySnapshotRepository.selectItemsStock(fofoId).stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
906
            logger.info("partnerStockAvailabilityMap: {}",partnerStockAvailabilityMap);
907
        }
34786 aman.kumar 908
        List<CatalogFavourite> catalogFavouriteList = catalogFavouriteRepository.selectBypartnerId(fofoId);
909
        Set<Integer> favouriteCatalogIds = catalogFavouriteList.stream()
910
                .map(CatalogFavourite::getCatalogId)
911
                .collect(Collectors.toSet());
35410 amit 912
 
913
        // Pre-fetch CIS data for all items (batch query instead of N+1)
914
        Map<Integer, List<SaholicCISTable>> cisDataByItemId = saholicCISTableRepository
915
                .selectByItemWarehouse(itemIds, warehouseId).stream()
916
                .collect(Collectors.groupingBy(SaholicCISTable::getItemId));
917
 
918
        // Pre-fetch all Items (batch query instead of N+1)
919
        Map<Integer, Item> itemMap = itemRepository.selectByIds(new HashSet<>(itemIds)).stream()
920
                .collect(Collectors.toMap(Item::getId, x -> x));
921
 
922
        // Pre-fetch cashback data for all catalogs (batch query instead of N+1)
923
        Map<Integer, Float> cashbackMap = schemeService.getCatalogSchemeCashBack(fofoId, catalogIds);
924
 
925
        // Pre-fetch web offers (call once instead of inside loop)
926
        Map<Integer, List<WebOffer>> webOffersMap = webOfferRepository.selectAllActiveOffers();
927
 
928
        // Pre-fetch combo models (call once instead of inside loop)
929
        Map<Integer, List<ComboModel>> comboModelsByCatalogId = comboModelRepository.selectByWarehouseId(warehouseId)
930
                .stream().collect(Collectors.groupingBy(ComboModel::getCatalogId));
931
 
32339 tejbeer 932
        for (int i = 0; i < docs.length(); i++) {
933
            Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
934
            JSONObject doc = docs.getJSONObject(i);
935
            FofoCatalogResponse fofoCatalogResponse = new FofoCatalogResponse();
936
            fofoCatalogResponse.setCatalogId(doc.getInt("catalogId_i"));
937
            fofoCatalogResponse.setImageUrl(doc.getString("imageUrl_s"));
938
            fofoCatalogResponse.setTitle(doc.getString("title_s"));
33975 tejus.loha 939
            fofoCatalogResponse.setSuperCatalogTitle(doc.getString("superCatalog_s"));
940
            fofoCatalogResponse.setSuperCatalogId(doc.getInt("superCatalog_i"));
941
            fofoCatalogResponse.setSuperCatalogVariants(doc.getString("superCatalogVariants_s"));
31629 tejbeer 942
 
35652 vikas 943
            // optional, since default is false
944
            fofoCatalogResponse.setFavourite(favouriteCatalogIds.contains(fofoCatalogResponse.getCatalogId()));
35410 amit 945
            List<WebOffer> webOffers = webOffersMap.get(fofoCatalogResponse.getCatalogId());
31612 tejbeer 946
 
33573 amit.gupta 947
            //logger.info("webOffers {}", webOffers);
32339 tejbeer 948
            if (webOffers != null && webOffers.size() > 0) {
949
                fofoCatalogResponse.setWebOffers(webOffers);
950
                fofoCatalogResponse.setOffers(webOffers.stream().map(x -> x.getTitle()).collect(Collectors.toList()));
951
            }
30683 tejbeer 952
 
35663 vikas 953
            /*Map<Integer, OfferDiscoveryResponse> pineResponse = pinelabsOfferCacheService.getCachedOffersForItems(fofoCatalogResponse.getItems().stream().map(x -> (int) x.getItem_id()).collect(Collectors.toList()));
954
            if (pineResponse != null && pineResponse.size() > 0) {
955
                fofoCatalogResponse.setPineOffers(pineResponse);
956
            }*/
957
 
35410 amit 958
            List<ComboModel> comboModels = comboModelsByCatalogId.get(fofoCatalogResponse.getCatalogId());
30683 tejbeer 959
 
33573 amit.gupta 960
            //logger.info("comboModels {}", comboModels);
32344 tejbeer 961
 
32339 tejbeer 962
            if (comboModels != null && comboModels.size() > 0) {
963
                fofoCatalogResponse.setComboModels(comboModels);
964
            }
30683 tejbeer 965
 
32339 tejbeer 966
            try {
967
                fofoCatalogResponse.setFeature(doc.getString("feature_s"));
968
            } catch (Exception e) {
969
                fofoCatalogResponse.setFeature(null);
970
                logger.info("Could not find Feature_s for {}", fofoCatalogResponse.getCatalogId());
971
            }
30683 tejbeer 972
 
32339 tejbeer 973
            fofoCatalogResponse.setBrand(doc.getJSONArray("brand_ss").getString(0));
974
            logger.info("labelss {}", doc.has("label_ss"));
30683 tejbeer 975
 
32339 tejbeer 976
            if (doc.has("label_ss")) {
977
                logger.info("label {}", doc.getJSONArray("label_ss"));
30683 tejbeer 978
 
32339 tejbeer 979
                JSONArray arr = doc.getJSONArray("label_ss");
980
                Set<String> labels = new HashSet<String>();
981
                for (int j = 0; j < arr.length(); j++) {
982
                    labels.add(arr.getString(j));
983
                }
31612 tejbeer 984
 
32339 tejbeer 985
                fofoCatalogResponse.setLabels(new ArrayList<>(labels));
31612 tejbeer 986
 
32339 tejbeer 987
            }
33573 amit.gupta 988
            if (doc.has("similarModels_ii")) {
989
                JSONArray similarModelsArray = doc.getJSONArray("similarModels_ii");
990
                List<Integer> similarCatalogIds = new ArrayList<>();
991
                for (int j = 0; j < similarModelsArray.length(); j++) {
992
                    similarCatalogIds.add(similarModelsArray.getInt(j));
993
                }
994
                fofoCatalogResponse.setSimilarModelIds(similarCatalogIds);
995
            }
31612 tejbeer 996
 
32339 tejbeer 997
            if (doc.has("_childDocuments_")) {
998
                String modelColorClass = "grey";
999
                FofoAvailabilityInfo fdiAnyColour = null;
1000
                // Iterating itemIds
1001
                for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
1002
                    PriceCircularItemModelNew priceCircularItemModel = priceCircularItemModelMap.get(fofoCatalogResponse.getCatalogId());
1003
                    JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
1004
                    int itemId = childItem.getInt("itemId_i");
1005
                    float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
34260 vikas.jang 1006
                    int partnerAvailability = partnerStockAvailabilityMap.get(itemId) == null ? 0 : partnerStockAvailabilityMap.get(itemId);
32339 tejbeer 1007
                    if (!fofoAvailabilityInfoMap.containsKey(itemId)) {
35663 vikas 1008
                        OfferDiscoveryResponse offers = pinelabsOfferCacheService.getCachedOfferForItem(itemId);
32339 tejbeer 1009
                        FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
35663 vikas 1010
                        fdi.setOffers(offers);
35410 amit 1011
                        List<SaholicCISTable> currentAvailability = cisDataByItemId.getOrDefault(itemId, new ArrayList<>());
32339 tejbeer 1012
                        List<SaholicPOItem> poItemAvailability = null;
1013
                        if (poItemAvailabilityMap != null) {
1014
                            poItemAvailability = poItemAvailabilityMap.get(itemId);
1015
                        }
31612 tejbeer 1016
 
32339 tejbeer 1017
                        if (priceCircularItemModel != null) {
33410 ranu 1018
                            fdi.setNlc((float) priceCircularItemModel.getNetNlc());
32339 tejbeer 1019
                        }
31612 tejbeer 1020
 
32339 tejbeer 1021
                        for (SaholicCISTable saholicCISTable : currentAvailability) {
1022
                            saholicCISTable.setWarehouseName(
1023
                                    ProfitMandiConstants.WAREHOUSE_MAP.get(saholicCISTable.getWarehouseFrom()));
1024
                        }
31612 tejbeer 1025
 
32339 tejbeer 1026
                        Map<Integer, SaholicCISTable> map = currentAvailability.stream().collect(Collectors.toMap(SaholicCISTable::getWarehouseFrom, x -> x));
1027
                        if (poItemAvailability != null) {
1028
                            for (SaholicPOItem saholicPOItem : poItemAvailability) {
1029
                                if (map.containsKey(saholicPOItem.getWarehouseFrom())) {
1030
                                    map.get(saholicPOItem.getWarehouseFrom()).setPopendingQty(saholicPOItem.getUnfulfilledQty());
1031
                                } else {
1032
                                    SaholicCISTable saholicCISTable = new SaholicCISTable();
1033
                                    saholicCISTable.setAvailability(0);
1034
                                    saholicCISTable.setReserved(0);
1035
                                    saholicCISTable.setItemId(itemId);
1036
                                    saholicCISTable.setWarehouseId(warehouseId);
1037
                                    saholicCISTable.setPopendingQty(saholicPOItem.getUnfulfilledQty());
1038
                                    saholicCISTable.setWarehouseFrom(saholicPOItem.getWarehouseFrom());
1039
                                    saholicCISTable.setWarehouseName(
1040
                                            ProfitMandiConstants.WAREHOUSE_MAP.get(saholicPOItem.getWarehouseFrom()));
1041
                                    map.put(saholicPOItem.getWarehouseFrom(), saholicCISTable);
1042
                                }
1043
                            }
1044
                        }
1045
                        fdi.setSaholicCISTableList(new ArrayList<>(map.values()));
1046
                        String poColor = "grey";
1047
                        boolean active = false;
1048
                        if (currentAvailability != null && currentAvailability.stream().collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)) > 0) {
1049
                            poColor = "green";
1050
                            modelColorClass = "green";
32978 amit.gupta 1051
                        } else if (poItemAvailability != null && poItemAvailability.stream().collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty)) > 0) {
1052
                            if (currentAvailability != null && poItemAvailability.stream().collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty)) + currentAvailability.stream().collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)) <= 0) {
1053
                                poColor = "grey";
1054
                            } else {
1055
                                poColor = "yellow";
35410 amit 1056
                                if (!"green".equals(modelColorClass)) {
32978 amit.gupta 1057
                                    modelColorClass = poColor;
32339 tejbeer 1058
                                }
1059
                            }
32978 amit.gupta 1060
                        }
32339 tejbeer 1061
                        fdi.setColorClass(poColor);
1062
                        fdi.setSellingPrice(sellingPrice);
1063
                        fdi.setActive(active);
1064
                        fdi.setMrp(childItem.getDouble("mrp_f"));
1065
                        fdi.setMop((float) childItem.getDouble("mop_f"));
1066
                        fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
1067
                        if (fdi.getColor().equalsIgnoreCase("any colour")) {
1068
                            fdiAnyColour = fdi;
1069
                        }
33929 tejus.loha 1070
                        fdi.setBrand((String) doc.getJSONArray("brand_ss").get(0));
1071
                        fdi.setCategoryId(doc.getInt("subCategoryId_i"));
32339 tejbeer 1072
                        fdi.setTagId(childItem.getInt("tagId_i"));
1073
                        fdi.setItem_id(itemId);
34196 ranu 1074
                        fdi.setCatalog_id(doc.getInt("catalogId_i"));
35410 amit 1075
                        Float cashBack = cashbackMap.get(fofoCatalogResponse.getCatalogId());
32339 tejbeer 1076
                        cashBack = cashBack == null ? 0 : cashBack;
1077
                        fdi.setCashback(cashBack);
1078
                        fdi.setMinBuyQuantity(1);
1079
                        if (hotDeal) {
1080
                            if (currentAvailability != null) {
1081
                                fdi.setAvailability(currentAvailability.stream().collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)));
1082
                            } else {
1083
                                fdi.setAvailability(0);
1084
                            }
34260 vikas.jang 1085
                            fdi.setPartnerAvailability(partnerAvailability);
32339 tejbeer 1086
                        } else {
1087
                            // Lets consider that its out of stock
32591 amit.gupta 1088
                            fdi.setAvailability(400);
35410 amit 1089
                            Item item = itemMap.get(itemId);
32339 tejbeer 1090
                            // In case its tampered glass moq should be
35410 amit 1091
                            if (item != null && item.getCategoryId() == 10020) {
32339 tejbeer 1092
                                fdi.setMinBuyQuantity(5);
1093
                            }
1094
                        }
1095
                        fdi.setQuantityStep(1);
32590 amit.gupta 1096
                        fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 400));
32339 tejbeer 1097
                        fofoAvailabilityInfoMap.put(itemId, fdi);
1098
                    }
1099
                }
1100
                if (fdiAnyColour != null) {
1101
                    fdiAnyColour.setColorClass(modelColorClass);
1102
                }
33576 amit.gupta 1103
                fofoCatalogResponse.setInStock(!modelColorClass.equals("grey"));
32339 tejbeer 1104
            }
1105
            if (fofoAvailabilityInfoMap.values().size() > 0) {
1106
                List<FofoAvailabilityInfo> availabilityList = fofoAvailabilityInfoMap.values().stream().sorted(Comparator.comparing(FofoAvailabilityInfo::getAvailability).reversed()).collect(Collectors.toList());
1107
                fofoCatalogResponse.setItems(availabilityList);
1108
                if (priceCircularItemModelMap.containsKey(fofoCatalogResponse.getCatalogId())) {
1109
                    PriceCircularItemModelNew priceCircularItemModel = priceCircularItemModelMap.get(fofoCatalogResponse.getCatalogId());
1110
                    if (priceCircularItemModel.getSlabPayouts() != null) {
1111
                        List<CreateOfferRequest> schemeOffers = new ArrayList<>();
1112
                        List<Map<Integer, AmountModel>> slabPayouts = priceCircularItemModel.getSlabPayouts();
1113
                        Iterator<Map<Integer, AmountModel>> iterator = slabPayouts.iterator();
1114
                        int iteratorCount = 0;
1115
                        while (iterator.hasNext()) {
1116
                            Map<Integer, AmountModel> slabPayoutMap = iterator.next();
1117
                            if (slabPayoutMap != null) {
1118
                                schemeOffers.add(allSchemOffers.get(iteratorCount));
1119
                            } else {
1120
                                iterator.remove();
1121
                            }
1122
                            iteratorCount++;
1123
                        }
1124
                        fofoCatalogResponse.setSchemeOffers(schemeOffers);
1125
                    }
1126
                    fofoCatalogResponse.setPriceCircularItemModel(priceCircularItemModel);
1127
                }
1128
                dealResponse.add(fofoCatalogResponse);
1129
            }
1130
        }
1131
        return dealResponse;
30686 amit.gupta 1132
 
32339 tejbeer 1133
    }
30693 amit.gupta 1134
 
33575 amit.gupta 1135
    private List<FofoCatalogResponse> getCatalogSingleSkuResponse(JSONArray
1136
                                                                          docs, Map<Integer, Integer> itemFilter, boolean hotDeal) throws ProfitMandiBusinessException {
32339 tejbeer 1137
        List<FofoCatalogResponse> dealResponse = new ArrayList<>();
1138
        List<Integer> tagIds = Arrays.asList(4);
24091 tejbeer 1139
 
33873 ranu 1140
        Map<Integer, TagListing> itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemFilter.keySet(), new HashSet<>(tagIds)).stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x));
24091 tejbeer 1141
 
35410 amit 1142
        // Pre-fetch all items (batch query instead of N+1)
1143
        Map<Integer, Item> itemMap = itemRepository.selectByIds(itemFilter.keySet()).stream()
1144
                .collect(Collectors.toMap(Item::getId, x -> x));
1145
 
32339 tejbeer 1146
        for (int i = 0; i < docs.length(); i++) {
1147
            Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
1148
            JSONObject doc = docs.getJSONObject(i);
26589 amit.gupta 1149
 
32339 tejbeer 1150
            for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
1151
                JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
1152
                int itemId = childItem.getInt("itemId_i");
1153
                TagListing tl = itemTagListingMap.get(itemId);
1154
                if (tl == null) {
1155
                    continue;
1156
                }
1157
                if (hotDeal) {
1158
                    if (!tl.isHotDeals()) {
1159
                        continue;
1160
                    }
1161
                }
1162
                float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
1163
                if (fofoAvailabilityInfoMap.containsKey(itemId)) {
1164
                    if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
1165
                        fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
1166
                        fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
1167
                    }
1168
                } else {
1169
                    FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
1170
                    fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
1171
                    fdi.setMop((float) childItem.getDouble("mop_f"));
1172
                    fdi.setMop((float) tl.getMrp());
1173
                    fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
1174
                    fdi.setTagId(childItem.getInt("tagId_i"));
1175
                    fdi.setItem_id(itemId);
34196 ranu 1176
                    fdi.setCatalog_id(doc.getInt("catalogId_i"));
35410 amit 1177
                    Item item = itemMap.get(itemId);
32339 tejbeer 1178
                    // In case its tampered glass moq should be 5
35410 amit 1179
                    if (item != null && item.getCategoryId() == 10020) {
32339 tejbeer 1180
                        fdi.setMinBuyQuantity(10);
1181
                    } else {
1182
                        fdi.setMinBuyQuantity(1);
1183
                    }
1184
                    fdi.setAvailability(itemFilter.get(itemId));
1185
                    fdi.setQuantityStep(1);
1186
                    fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
1187
                    fofoAvailabilityInfoMap.put(itemId, fdi);
1188
                }
1189
            }
1190
            if (fofoAvailabilityInfoMap.values().size() > 0) {
1191
                for (FofoAvailabilityInfo fofoAvailabilityInfo : fofoAvailabilityInfoMap.values()) {
1192
                    FofoCatalogResponse ffdr = new FofoCatalogResponse();
1193
                    ffdr.setCatalogId(doc.getInt("catalogId_i"));
1194
                    ffdr.setImageUrl(doc.getString("imageUrl_s"));
1195
                    ffdr.setTitle(doc.getString("title_s"));
1196
                    try {
1197
                        ffdr.setFeature(doc.getString("feature_s"));
1198
                    } catch (Exception e) {
1199
                        ffdr.setFeature(null);
1200
                        logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
1201
                    }
1202
                    ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
1203
                    ffdr.setItems(Arrays.asList(fofoAvailabilityInfo));
1204
                    dealResponse.add(ffdr);
1205
                }
1206
            }
1207
        }
1208
        return dealResponse;
25880 amit.gupta 1209
 
32339 tejbeer 1210
    }
25880 amit.gupta 1211
 
32339 tejbeer 1212
    @RequestMapping(value = "/combo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
1213
    public ResponseEntity<?> getBanners(@RequestParam int catalogId, @RequestParam int warehouseId) {
1214
        List<ComboModel> comboModels = comboModelRepository.selectByCatalogIdAndWarehouseId(catalogId, warehouseId);
1215
        return responseSender.ok(comboModels);
1216
    }
32344 tejbeer 1217
 
1218
    @RequestMapping(value = "/checkCombo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
33575 amit.gupta 1219
    public ResponseEntity<?> checkCombo(HttpServletRequest request, @RequestParam int catalogId,
1220
                                        @RequestParam int warehouseId, @RequestParam int qty) throws Exception {
32344 tejbeer 1221
        boolean isCombo = false;
1222
        ComboModel comboModel = comboModelRepository.selectByCatalogIdWarehouseIdAndQty(catalogId, warehouseId, qty);
1223
        if (comboModel != null) {
1224
            isCombo = true;
1225
        }
1226
 
1227
        return responseSender.ok(isCombo);
1228
    }
1229
 
33929 tejus.loha 1230
    @GetMapping(value = "/partner/wodCompleteBrands", produces = MediaType.APPLICATION_JSON_VALUE)
1231
    public ResponseEntity<?> getWodcompletBrands(HttpServletRequest request) throws Exception {
1232
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
34630 tejus.loha 1233
        BrandAndAddToCartEligibleModel brandAndAddToCartEligibleModel = brandsService.wodcompletBrands(userInfo.getRetailerId());
1234
        return responseSender.ok(brandAndAddToCartEligibleModel);
35652 vikas 1235
    }
33929 tejus.loha 1236
 
35652 vikas 1237
    @RequestMapping(value = "/pinelabs/offers", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
1238
    public ResponseEntity<?> getPineLabsOffers(@RequestBody OfferDiscoveryRequest offerDiscoveryRequest) {
1239
        logger.info("pinelabs offers {}", offerDiscoveryRequest);
1240
        OfferDiscoveryResponse pineLabsOffers = pinelabsAffordabilityService.discoverOffers(offerDiscoveryRequest);
1241
        logger.info("pinelabs offers response {}", pineLabsOffers);
1242
        return responseSender.ok(pineLabsOffers);
33929 tejus.loha 1243
    }
1244
 
35727 vikas 1245
    @RequestMapping(value = "/pinelabs/offers/cache", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
1246
    public ResponseEntity<?> cachePineLabsOffers() {
1247
        pinelabsOfferCacheService.cacheAllItemOffers();
1248
        return responseSender.ok("PineLabs offers cache initiated");
1249
    }
1250
 
1251
    @RequestMapping(value = "/pinelabs/offers/{itemId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
1252
    public ResponseEntity<?> pineLabsOfferById(@PathVariable int itemId) {
1253
        List<Integer> itemIds = new ArrayList<>();
1254
        itemIds.add(itemId);
1255
        Map<Integer, Map<String, List<Tenure>>> pineLabsOffers = pinelabsOfferCacheService.getGroupedCachedOffersForItems(itemIds);
1256
        return responseSender.ok(pineLabsOffers);
1257
    }
1258
 
36591 vikas 1259
    @RequestMapping(value = "/pinelabs/offers/downpayment", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
1260
    public ResponseEntity<?> getPineLabsDownpaymentDetails(@RequestBody DownpaymentDetailsRequest request) {
1261
        logger.info("pinelabs downpayment details request");
1262
        DownpaymentDetailsResponse response = pinelabsAffordabilityService.getDownpaymentDetails(request);
1263
        return responseSender.ok(response);
1264
    }
1265
 
1266
    @RequestMapping(value = "/pinelabs/offers/cardless", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
1267
    public ResponseEntity<?> getPineLabsCardlessOffers(@RequestBody OfferDiscoveryRequest offerDiscoveryRequest) {
1268
        logger.info("pinelabs cardless discovery request {}", offerDiscoveryRequest);
1269
        OfferDiscoveryResponse response = pinelabsAffordabilityService.discoverCardlessOffers(offerDiscoveryRequest);
1270
        return responseSender.ok(response);
1271
    }
1272
 
1273
    @RequestMapping(value = "/pinelabs/offers/validate", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
1274
    public ResponseEntity<?> validatePineLabsOffer(@RequestBody OfferValidateRequest request) {
1275
        logger.info("pinelabs offer validate request");
1276
        OfferValidateResponse response = pinelabsAffordabilityService.validateOffer(request);
1277
        return responseSender.ok(response);
1278
    }
1279
 
1280
    @RequestMapping(value = "/pinelabs/offers/create", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
1281
    public ResponseEntity<?> createPineLabsOffer(@RequestBody PineLablsCreateOfferRequest request) {
1282
        logger.info("pinelabs create offer request for orderId {}", request.getOrderId());
1283
        CreateOfferResponse response = pinelabsAffordabilityService.createOffer(request);
1284
        return responseSender.ok(response);
1285
    }
1286
 
1287
    @RequestMapping(value = "/pinelabs/imei/{orderId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
1288
    public ResponseEntity<?> validateImei(@PathVariable String orderId, @RequestBody Map<String, String> body) {
1289
        String imei = body.get("imei");
1290
        logger.info("pinelabs IMEI validation for orderId {} imei {}", orderId, imei);
1291
        ImeiValidationResponse response = pinelabsDeviceService.validateImei(orderId, imei);
1292
        return responseSender.ok(response);
1293
    }
1294
 
25967 amit.gupta 1295
}