Subversion Repositories SmartDukaan

Rev

Rev 37260 | 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.*;
37250 amit 84
import java.util.concurrent.CompletableFuture;
85
import java.util.concurrent.CompletionException;
86
import java.util.concurrent.ExecutorService;
87
import java.util.concurrent.Executors;
30686 amit.gupta 88
import java.util.concurrent.atomic.AtomicInteger;
89
import java.util.stream.Collectors;
90
 
21339 kshitij.so 91
@Controller
22319 amit.gupta 92
@Transactional(rollbackFor = Throwable.class)
21339 kshitij.so 93
public class DealsController {
94
 
32339 tejbeer 95
    private static final Logger logger = LogManager.getLogger(DealsController.class);
96
    private static final List<Integer> TAG_IDS = Arrays.asList(4);
21339 kshitij.so 97
 
32339 tejbeer 98
    @Value("${python.api.host}")
99
    private String host;
23816 amit.gupta 100
 
32339 tejbeer 101
    @Value("${new.solr.url}")
102
    private String solrUrl;
26889 amit.gupta 103
 
32339 tejbeer 104
    @Value("${python.api.port}")
105
    private int port;
23816 amit.gupta 106
 
32339 tejbeer 107
    @Autowired
108
    RestClient restClient;
27051 amit.gupta 109
 
32339 tejbeer 110
    @Autowired
111
    SolrService solrService;
26889 amit.gupta 112
 
32339 tejbeer 113
    @Autowired
33873 ranu 114
    com.spice.profitmandi.web.services.SolrService webSolrService;
115
 
116
    @Autowired
37247 amit 117
    com.spice.profitmandi.web.services.HotDealEnrichmentService hotDealEnrichmentService;
118
 
119
 
120
    @Autowired
37144 amit 121
    private com.spice.profitmandi.web.services.PartnerSolrClient partnerSolrClient;
122
 
123
    @Autowired
35652 vikas 124
    PinelabsAffordabilityService pinelabsAffordabilityService;
26924 amit.gupta 125
 
36591 vikas 126
    @Autowired
127
    PinelabsDeviceService pinelabsDeviceService;
128
 
32339 tejbeer 129
    // This is now unused as we are not supporting multiple companies.
130
    @Value("${gadgetCops.invoice.cc}")
131
    private String[] ccGadgetCopInvoiceTo;
22319 amit.gupta 132
 
32339 tejbeer 133
    @Autowired
134
    private PricingService pricingService;
23816 amit.gupta 135
 
32339 tejbeer 136
    @Autowired
137
    private CategoryRepository categoryRepository;
25010 amit.gupta 138
 
32339 tejbeer 139
    @Autowired
140
    private SchemeService schemeService;
26695 amit.gupta 141
 
32339 tejbeer 142
    @Autowired
143
    private SaholicInventoryService saholicInventoryService;
26889 amit.gupta 144
 
32339 tejbeer 145
    @Autowired
146
    private Mongo mongoClient;
25879 amit.gupta 147
 
32339 tejbeer 148
    @Autowired
149
    private ItemBucketService itemBucketService;
23816 amit.gupta 150
 
32339 tejbeer 151
    @Autowired
152
    private UserAccountRepository userAccountRepository;
27051 amit.gupta 153
 
32339 tejbeer 154
    @Autowired
155
    private FofoStoreRepository fofoStoreRepository;
23816 amit.gupta 156
 
32339 tejbeer 157
    @Autowired
158
    private ResponseSender<?> responseSender;
23816 amit.gupta 159
 
32339 tejbeer 160
    @Autowired
161
    private TagListingRepository tagListingRepository;
23816 amit.gupta 162
 
32339 tejbeer 163
    @Autowired
164
    private ItemRepository itemRepository;
165
    @Autowired
166
    private PriceCircularService priceCircularService;
23816 amit.gupta 167
 
32339 tejbeer 168
    @Autowired
169
    private RoleManager roleManagerService;
23816 amit.gupta 170
 
32339 tejbeer 171
    @Autowired
32978 amit.gupta 172
    private SuggestedPoDetailRepository suggestedPoDetailRepository;
26846 tejbeer 173
 
32339 tejbeer 174
    @Autowired
175
    private SuggestedPoRepository suggestedPoRepository;
26847 tejbeer 176
 
32339 tejbeer 177
    @Autowired
178
    private WebOfferRepository webOfferRepository;
30595 tejbeer 179
 
32339 tejbeer 180
    @Autowired
181
    private ComboModelRepository comboModelRepository;
30683 tejbeer 182
 
32339 tejbeer 183
    @Autowired
35663 vikas 184
    private PinelabsOfferCacheService pinelabsOfferCacheService;
30683 tejbeer 185
 
32339 tejbeer 186
    @Autowired
187
    private BrandsService brandsService;
31547 tejbeer 188
 
32339 tejbeer 189
    @Autowired
37185 ranu 190
    private BrandsRepository brandsRepository;
191
 
192
    @Autowired
32339 tejbeer 193
    private WebListingRepository webListingRepository;
31547 tejbeer 194
 
32339 tejbeer 195
    @Autowired
196
    private WebProductListingRepository webProductListingRepository;
31547 tejbeer 197
 
32339 tejbeer 198
    @Autowired
199
    private CatalogFavouriteRepository catalogFavouriteRepository;
31625 tejbeer 200
 
33929 tejus.loha 201
    @Autowired
202
    PartnerOnBoardingPanelRepository partnerOnBoardingPanelRepository;
203
 
204
    @Autowired
205
    PartnerDealerRepository partnerDealerRepository;
206
 
207
    @Autowired
208
    BrandCommitRepository brandCommitRepository;
209
 
210
    @Autowired
211
    CatalogRepository catalogRepository;
212
 
34260 vikas.jang 213
    @Autowired
214
    private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
215
 
32339 tejbeer 216
    List<String> filterableParams = Arrays.asList("brand");
24949 amit.gupta 217
 
32339 tejbeer 218
    @RequestMapping(value = "/fofo/buckets", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
219
    public ResponseEntity<?> getBuckets(HttpServletRequest request) throws ProfitMandiBusinessException {
220
        logger.info("Request " + request.getParameterMap());
221
        return responseSender.ok(itemBucketService.getBuckets(Optional.of(true)));
222
    }
25879 amit.gupta 223
 
32339 tejbeer 224
    @RequestMapping(value = "/fofo/bucket", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
225
    public ResponseEntity<?> getBucketDetails(HttpServletRequest request, @RequestParam int id) throws ProfitMandiBusinessException {
226
        List<ItemQuantityPojo> iqPojo = itemBucketService.getBucketDetails(id);
227
        Map<Integer, Integer> itemIdsQtyMap = iqPojo.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x.getQuantity()));
228
        Set<Integer> catalogIds = itemRepository.selectByIds(itemIdsQtyMap.keySet()).stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet());
229
        Map<String, String> params = new HashMap<>();
230
        List<String> mandatoryQ = new ArrayList<>();
231
        mandatoryQ.add(
232
                String.format("+catalogId_i:(%s) +{!parent which=\"id:catalog*\"}", StringUtils.join(catalogIds, " ")));
233
        params.put("start", "0");
234
        params.put("rows", "100");
235
        params.put("q", StringUtils.join(mandatoryQ, " "));
236
        params.put("fl", "*, [child parentFilter=id:catalog*]");
25879 amit.gupta 237
 
32339 tejbeer 238
        params.put("wt", "json");
37144 amit 239
        int fofoId = userAccountRepository.getUserCart((int) request.getAttribute("userId")).getUserId();
240
        JSONArray docs = partnerSolrClient.selectDocs(params, fofoId);
37260 amit 241
        List<FofoCatalogResponse> dealResponse = getCatalogSingleSkuResponse(docs, itemIdsQtyMap);
26051 amit.gupta 242
 
32339 tejbeer 243
        Bucket bucket = itemBucketService.getBuckets(Optional.of(true)).stream().filter(x -> x.getId() == id).collect(Collectors.toList()).get(0);
244
        bucket.setFofoCatalogResponses(dealResponse);
245
        return responseSender.ok(bucket);
246
    }
25879 amit.gupta 247
 
32339 tejbeer 248
    @RequestMapping(value = "/fofo/suggestedPo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
249
    public ResponseEntity<?> getSuggestedPo(HttpServletRequest request, @RequestParam int id) throws ProfitMandiBusinessException {
34436 ranu 250
        int userId = (int) request.getAttribute("userId");
251
        UserCart uc = userAccountRepository.getUserCart(userId);
252
        int fofoId = uc.getUserId();
253
        SuggestedPo  suggestedPo = suggestedPoRepository.selectAllOpenPoByFofoId(fofoId).get(0);
254
        if(suggestedPo == null){
255
            throw new ProfitMandiBusinessException("", "", "Open po is not available in list");
256
        }
257
        List<SuggestedPoDetail> mpd = suggestedPoDetailRepository.selectByPoId(suggestedPo.getId());
32339 tejbeer 258
        Map<Integer, Integer> itemIdsQtyMap = mpd.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x.getQuantity()));
26846 tejbeer 259
 
32339 tejbeer 260
        Set<Integer> catalogIds = itemRepository.selectByIds(itemIdsQtyMap.keySet()).stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet());
35410 amit 261
                Map<String, String> params = new HashMap<>();
32339 tejbeer 262
        List<String> mandatoryQ = new ArrayList<>();
263
        mandatoryQ.add(
264
                String.format("+catalogId_i:(%s) +{!parent which=\"id:catalog*\"}", StringUtils.join(catalogIds, " ")));
265
        params.put("start", "0");
266
        params.put("rows", "100");
267
        params.put("q", StringUtils.join(mandatoryQ, " "));
268
        params.put("fl", "*, [child parentFilter=id:catalog*]");
26846 tejbeer 269
 
32339 tejbeer 270
        params.put("wt", "json");
37144 amit 271
        JSONArray docs = partnerSolrClient.selectDocs(params, fofoId);
37260 amit 272
        List<FofoCatalogResponse> dealResponse = getCatalogSingleSkuResponse(docs, itemIdsQtyMap);
26846 tejbeer 273
 
32339 tejbeer 274
        return responseSender.ok(dealResponse);
275
    }
26846 tejbeer 276
 
34436 ranu 277
    @RequestMapping(value = "/suggestedPo/status", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
32339 tejbeer 278
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
279
    @ApiOperation(value = "")
280
    public ResponseEntity<?> changeSuggestedPoStatus(HttpServletRequest request, @RequestParam int id) throws ProfitMandiBusinessException {
281
        SuggestedPo suggestedPo = suggestedPoRepository.selectById(id);
282
        suggestedPo.setStatus("closed");
33873 ranu 283
        //suggestedPo.setStatus(SuggestedPoStatus.valueOf("closed"));
26847 tejbeer 284
 
32339 tejbeer 285
        return responseSender.ok(true);
286
    }
26847 tejbeer 287
 
32339 tejbeer 288
    @RequestMapping(value = "/fofo/fovourites", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
289
    public ResponseEntity<?> getFavourites(HttpServletRequest request) throws Exception {
31625 tejbeer 290
 
32339 tejbeer 291
        int userId = (int) request.getAttribute("userId");
292
        UserCart uc = userAccountRepository.getUserCart(userId);
293
        int fofoId = uc.getUserId();
294
        List<FofoCatalogResponse> dealResponse = new ArrayList<>();
295
        Set<Integer> catalogIds = catalogFavouriteRepository.selectBypartnerId(fofoId).stream().map(x -> x.getCatalogId()).collect(Collectors.toSet());
296
        if (!catalogIds.isEmpty()) {
33929 tejus.loha 297
            dealResponse = webSolrService.dealResponse(catalogIds, fofoId);
37247 amit 298
            hotDealEnrichmentService.enrich(dealResponse);
32339 tejbeer 299
        }
300
        return responseSender.ok(dealResponse);
301
    }
31625 tejbeer 302
 
32339 tejbeer 303
    @RequestMapping(value = "/favourites/manage", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
304
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
305
    @ApiOperation(value = "")
306
    public ResponseEntity<?> mangeFavourites(HttpServletRequest request, @RequestParam int catalogId) throws ProfitMandiBusinessException {
31625 tejbeer 307
 
32339 tejbeer 308
        int userId = (int) request.getAttribute("userId");
309
        UserCart uc = userAccountRepository.getUserCart(userId);
310
        int fofoId = uc.getUserId();
31625 tejbeer 311
 
32339 tejbeer 312
        CatalogFavourite catalogFavourite = catalogFavouriteRepository.selectBypartnerAndCatalogId(fofoId, catalogId);
31625 tejbeer 313
 
32339 tejbeer 314
        if (catalogFavourite == null) {
315
            catalogFavourite = new CatalogFavourite();
316
            catalogFavourite.setCatalogId(catalogId);
317
            catalogFavourite.setFofoId(fofoId);
318
            catalogFavourite.setCreatedTimestamp(LocalDateTime.now());
319
            catalogFavouriteRepository.persist(catalogFavourite);
31625 tejbeer 320
 
32978 amit.gupta 321
        } else {
32339 tejbeer 322
            catalogFavouriteRepository.deleteByPartnerAndCatalogId(fofoId, catalogId);
323
        }
324
        return responseSender.ok(true);
325
    }
31625 tejbeer 326
 
33249 ranu 327
    private String getCommaSeparateTags(int userId) throws ProfitMandiBusinessException {
32339 tejbeer 328
        UserCart uc = userAccountRepository.getUserCart(userId);
329
        List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(uc.getUserId());
330
        List<String> strTagIds = new ArrayList<>();
331
        for (Integer tagId : tagIds) {
332
            strTagIds.add(String.valueOf(tagId));
333
        }
334
        return String.join(",", strTagIds);
335
    }
22273 amit.gupta 336
 
33575 amit.gupta 337
    @RequestMapping(value = "/fofo/similar-models/{modelId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
338
    public ResponseEntity<?> similarModels(HttpServletRequest httpServletRequest, @PathVariable int modelId) throws Throwable {
339
        UserInfo userInfo = (UserInfo) httpServletRequest.getAttribute("userInfo");
340
        //FofoStore fs = fofoStoreRepository.selectByRetailerId(userInfo.getRetailerId());
341
 
342
        JSONObject jsonObject = solrService.getContentByCatalogIds(Arrays.asList(modelId)).get(modelId);
343
 
344
        JSONArray similarModelsArray = jsonObject.getJSONArray("similarModels_ii");
345
        List<Integer> similarCatalogIds = new ArrayList<>();
346
        for (int j = 0; j < similarModelsArray.length(); j++) {
347
            similarCatalogIds.add(similarModelsArray.getInt(j));
348
        }
349
 
350
        Map<String, String> params = new HashMap<>();
351
        List<String> mandatoryQ = new ArrayList<>();
352
 
353
        mandatoryQ.add(String.format(
354
                "+{!parent which=\"catalogId_i:(" + StringUtils.join(similarCatalogIds, " ") + ")\"} AND active_b:true AND show_default_b:true"));
355
 
356
        params.put("q", StringUtils.join(mandatoryQ, " "));
357
        params.put("fl", "*, [child parentFilter=id:catalog* childFilter=active_b:true ]");
358
        params.put("wt", "json");
359
        params.put("rows", similarCatalogIds.size() + "");
37144 amit 360
        JSONArray docs = partnerSolrClient.selectDocs(params, userInfo.getRetailerId());
37641 amit 361
        return responseSender.ok(this.getCatalogResponse(docs, userInfo.getRetailerId()).stream().filter(x -> x.isInStock()).collect(Collectors.toList()));
33575 amit.gupta 362
    }
363
 
32339 tejbeer 364
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
37260 amit 365
    /**
366
     * Categories present among today's active hot deals (Solr facet over the curated
367
     * models), for the hot-deals page filter chips: [{"id": 3, "count": 4}, ...].
368
     */
369
    @RequestMapping(value = "/fofo/hotDeals/categories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
370
    public ResponseEntity<?> getHotDealCategories(HttpServletRequest request) throws Exception {
371
        List<Map<String, Object>> categories = new ArrayList<>();
37641 amit 372
        for (Map.Entry<Integer, Integer> entry
373
                : solrService.getHotDealCategoryFacet(hotDealCatalogIds()).entrySet()) {
37260 amit 374
            Map<String, Object> category = new HashMap<>();
375
            category.put("id", entry.getKey());
376
            category.put("count", entry.getValue());
377
            categories.add(category);
378
        }
379
        return responseSender.ok(categories);
380
    }
381
 
37641 amit 382
    /**
383
     * Brands present among the hot-deal models, for the hot-deals page brand chips:
384
     * [{"brand": "Samsung", "count": 4}, ...].
385
     *
386
     * <p>These are the ORIGINAL brands, held in Solr's oem_brand_s. Every hot-deal doc
387
     * reads "Hot Deal" in brand_ss, so that field would facet into one useless bucket.
388
     * The chip row is labelled simply "Brand" in both apps.
389
     */
390
    @RequestMapping(value = "/fofo/hotDeals/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
391
    public ResponseEntity<?> getHotDealBrands(HttpServletRequest request) throws Exception {
392
        List<Map<String, Object>> brands = new ArrayList<>();
393
        for (Map.Entry<String, Integer> entry
394
                : solrService.getHotDealBrandFacet(hotDealCatalogIds()).entrySet()) {
395
            Map<String, Object> brand = new HashMap<>();
396
            brand.put("brand", entry.getKey());
397
            brand.put("count", entry.getValue());
398
            brands.add(brand);
399
        }
400
        return responseSender.ok(brands);
401
    }
402
 
403
    /**
404
     * The hot-deal catalog set: membership is brand membership, with no date window.
405
     * Shared by the two facet endpoints and the hotDeal listing branch.
406
     */
407
    private List<Integer> hotDealCatalogIds() {
408
        return new ArrayList<>(
409
                catalogRepository.selectCatalogIdsByBrand(ProfitMandiConstants.HOT_DEAL_BRAND));
410
    }
411
 
32339 tejbeer 412
    @RequestMapping(value = "/fofo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
33573 amit.gupta 413
    public ResponseEntity<?> getFofo(HttpServletRequest request, @RequestParam(value = "categoryId", required = false, defaultValue = "3") String categoryId, @RequestParam(value = "offset") int offset,
37260 amit 414
         @RequestParam(value = "limit") int limit, @RequestParam(value = "sort", required = false) String sort, @RequestParam(value = "brand", required = false) String brand, @RequestParam(value = "subCategoryId", required = false, defaultValue = "0") 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 {
37185 ranu 415
        // Band-aid for URL '+' decode issue on brand names.
416
        // Front-end sends `brand=Ai+`. Depending on where along the request path the
417
        // '+' is decoded, the servlet may receive "Ai " (trailing space) or just "Ai"
418
        // (plus dropped entirely by the SPA before the request goes out).
419
        // Strategy: if the received value doesn't exist as a real brand in catalog.brand,
420
        // try appending '+' and see if THAT exists — if so, use it. Zero regression risk
421
        // for real brand names because the fallback only fires on unknown values.
422
        logger.info("getFofo received brand='{}' (len={})",
423
                brand, brand == null ? -1 : brand.length());
424
        if (brand != null && !brand.trim().isEmpty()) {
425
            String probe = brand.replaceAll("\\s+$", "");
426
            try {
427
                if (brandsRepository.selectByBrand(brand) == null
428
                        && (probe.equals(brand) || brandsRepository.selectByBrand(probe) == null)) {
429
                    String withPlus = probe + "+";
430
                    if (brandsRepository.selectByBrand(withPlus) != null) {
431
                        logger.info("getFofo brand fallback: '{}' -> '{}'", brand, withPlus);
432
                        brand = withPlus;
433
                    }
434
                }
435
            } catch (Exception e) {
436
                logger.warn("getFofo brand fallback lookup failed for '{}': {}", brand, e.getMessage());
437
            }
438
        }
33543 amit.gupta 439
        List<FofoCatalogResponse> dealResponse;
32339 tejbeer 440
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
441
        FofoStore fs = fofoStoreRepository.selectByRetailerId(userInfo.getRetailerId());
442
        sort = "w" + fs.getWarehouseId() + "_i desc";
31548 tejbeer 443
 
32339 tejbeer 444
        logger.info("endPoint {}", endPoint);
34024 vikas.jang 445
        logger.info("group Column {}", group);
31552 tejbeer 446
 
32339 tejbeer 447
        if (endPoint != null && !endPoint.trim().isEmpty()) {
448
            WebListing webListing = webListingRepository.selectByUrl(endPoint);
35411 amit 449
            dealResponse = this.getDealResponses(userInfo, fs, webListing, offset, limit);
31552 tejbeer 450
 
37247 amit 451
        } else if (hotDeal) {
37641 amit 452
            // Hot deals are the SKUs carrying the Hot Deal brand. Solr's hot_deal_b derives
453
            // from the same brand, but the set is resolved here so the listing does not
454
            // depend on the last re-index.
455
            List<Integer> hotDealCatalogIds = hotDealCatalogIds();
37247 amit 456
            if (hotDealCatalogIds.isEmpty()) {
457
                dealResponse = new ArrayList<>();
458
            } else {
37260 amit 459
                // Cross-category by default; a category chip on the page sends categoryId
460
                // explicitly, and only then does it narrow the hot-deal listing
461
                String explicitCategory = request.getParameter("categoryId") != null ? categoryId : null;
37247 amit 462
                dealResponse = this.getCatalogResponse(
37260 amit 463
                        solrService.getSolrDocs(queryTerm, explicitCategory, offset, limit, sort, brand, subCategoryId, false, group, true,
37641 amit 464
                                brandsService.restrictedBrands(userInfo.getRetailerId()), hotDealCatalogIds), userInfo.getRetailerId());
37247 amit 465
            }
32339 tejbeer 466
        } else {
31552 tejbeer 467
 
32339 tejbeer 468
            dealResponse = this.getCatalogResponse(
37144 amit 469
                    solrService.getSolrDocs(queryTerm, categoryId, offset, limit, sort, brand, subCategoryId, hotDeal, group, true,
37641 amit 470
                            brandsService.restrictedBrands(userInfo.getRetailerId())), userInfo.getRetailerId());
32339 tejbeer 471
        }
37247 amit 472
        hotDealEnrichmentService.enrich(dealResponse);
33573 amit.gupta 473
 
474
        Map<Integer, List<Integer>> similarModelMap = dealResponse.stream().filter(x -> x.getSimilarModelIds() != null && x.getSimilarModelIds().size() > 0)
475
                .collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getSimilarModelIds()));
476
        Set<Integer> similarModelIds = similarModelMap.values().stream().flatMap(x -> x.stream()).collect(Collectors.toSet());
477
        logger.info("similarModelIds - {}", similarModelIds);
33575 amit.gupta 478
        if (similarModelIds.size() > 0) {
33573 amit.gupta 479
 
33576 amit.gupta 480
            Map<Integer, FofoCatalogResponse> similarCatalogResponsesMap = this.getSimpleDocs(fs, similarModelIds).stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));
33573 amit.gupta 481
            logger.info("Similar Catalog ResponseMap - {}", similarCatalogResponsesMap.keySet());
482
 
483
            for (FofoCatalogResponse deal : dealResponse) {
484
                if (similarModelMap.containsKey(deal.getCatalogId())) {
485
                    List<Integer> similarCatalogIds = similarModelMap.get(deal.getCatalogId());
486
                    logger.info("Similar Catalog Ids - {}", similarCatalogIds);
33575 amit.gupta 487
                    List<FofoCatalogResponse> similarModels = similarCatalogIds.stream().filter(x -> similarCatalogResponsesMap.containsKey(x)).map(x -> similarCatalogResponsesMap.get(x)).collect(Collectors.toList());
33573 amit.gupta 488
                    deal.setSimilarModels(similarModels);
489
                }
490
            }
491
        }
32339 tejbeer 492
        return responseSender.ok(dealResponse);
493
    }
25015 amit.gupta 494
 
33576 amit.gupta 495
    private List<FofoCatalogResponse> getSimpleDocs(FofoStore fofoStore, Set<Integer> catalogIds) throws Exception {
33575 amit.gupta 496
        List<FofoCatalogResponse> fofoCatalogResponses = new ArrayList<>();
497
 
498
 
499
        Map<String, String> params = new HashMap<>();
500
        List<String> mandatoryQ = new ArrayList<>();
501
 
502
        mandatoryQ.add(String.format(
503
                "+{!parent which=\"catalogId_i:(" + StringUtils.join(catalogIds, " ") + ")\"} AND active_b:true AND show_default_b:true"));
504
 
505
        params.put("q", StringUtils.join(mandatoryQ, " "));
506
        params.put("fl", "*, [child parentFilter=id:catalog* childFilter=active_b:true ]");
507
        params.put("wt", "json");
508
        params.put("rows", catalogIds.size() + "");
509
 
37144 amit 510
        JSONArray docs = partnerSolrClient.selectDocs(params, fofoStore.getId());
35410 amit 511
        int warehouseId = fofoStore.getWarehouseId();
33576 amit.gupta 512
        Map<Integer, List<SaholicPOItem>> poItemAvailabilityMap = saholicInventoryService.getSaholicPOItems().get(warehouseId);
35410 amit 513
 
514
        // Pre-fetch all itemIds for batch CIS query
515
        List<Integer> allItemIds = new ArrayList<>();
33576 amit.gupta 516
        for (int i = 0; i < docs.length(); i++) {
517
            JSONObject doc = docs.getJSONObject(i);
35410 amit 518
            if (doc.has("_childDocuments_")) {
519
                for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
520
                    allItemIds.add(doc.getJSONArray("_childDocuments_").getJSONObject(j).getInt("itemId_i"));
521
                }
522
            }
523
        }
524
        // Batch fetch CIS data
525
        Map<Integer, List<SaholicCISTable>> cisDataByItemId = saholicCISTableRepository
526
                .selectByItemWarehouse(allItemIds, warehouseId).stream()
527
                .collect(Collectors.groupingBy(SaholicCISTable::getItemId));
528
 
529
        for (int i = 0; i < docs.length(); i++) {
530
            JSONObject doc = docs.getJSONObject(i);
33576 amit.gupta 531
            FofoCatalogResponse fofoCatalogResponse = this.toFofoCatalogResponse(doc);
532
            if (doc.has("_childDocuments_")) {
533
                String modelColorClass = "grey";
534
                FofoAvailabilityInfo fdiAnyColour = null;
535
                // Iterating itemIds
536
                for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
537
                    JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
538
                    int itemId = childItem.getInt("itemId_i");
539
 
35410 amit 540
                    List<SaholicCISTable> currentAvailability = cisDataByItemId.getOrDefault(itemId, new ArrayList<>());
33576 amit.gupta 541
                    List<SaholicPOItem> poItemAvailability = null;
542
                    if (poItemAvailabilityMap != null) {
543
                        poItemAvailability = poItemAvailabilityMap.get(itemId);
544
                    }
545
 
546
                    for (SaholicCISTable saholicCISTable : currentAvailability) {
547
                        saholicCISTable.setWarehouseName(
548
                                ProfitMandiConstants.WAREHOUSE_MAP.get(saholicCISTable.getWarehouseFrom()));
549
                    }
550
 
551
 
552
                    String poColor = "grey";
553
                    boolean active = false;
554
                    if (currentAvailability != null && currentAvailability.stream().collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)) > 0) {
555
                        poColor = "green";
556
                        modelColorClass = "green";
557
                    } else if (poItemAvailability != null && poItemAvailability.stream().collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty)) > 0) {
558
                        if (currentAvailability != null && poItemAvailability.stream().collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty)) + currentAvailability.stream().collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)) <= 0) {
559
                            poColor = "grey";
560
                        } else {
561
                            poColor = "yellow";
562
                            if (!modelColorClass.equals("green")) {
563
                                modelColorClass = poColor;
564
                            }
565
                        }
566
                    }
567
 
568
                }
569
                fofoCatalogResponse.setInStock(!modelColorClass.equals("grey"));
33575 amit.gupta 570
            }
33576 amit.gupta 571
 
572
            fofoCatalogResponses.add(fofoCatalogResponse);
33575 amit.gupta 573
        }
33576 amit.gupta 574
 
33575 amit.gupta 575
        return fofoCatalogResponses;
576
    }
577
 
578
    private FofoCatalogResponse toFofoCatalogResponse(JSONObject doc) {
579
        FofoCatalogResponse fofoCatalogResponse = new FofoCatalogResponse();
580
        fofoCatalogResponse.setCatalogId(doc.getInt("catalogId_i"));
581
        fofoCatalogResponse.setImageUrl(doc.getString("imageUrl_s"));
582
        fofoCatalogResponse.setTitle(doc.getString("title_s"));
583
        fofoCatalogResponse.setMop(doc.getFloat("mop_f"));
584
        fofoCatalogResponse.setDp(doc.getFloat("dp_f"));
585
        fofoCatalogResponse.setBrand(doc.getJSONArray("brand_ss").getString(0));
586
        return fofoCatalogResponse;
587
    }
588
 
32339 tejbeer 589
    @RequestMapping(value = "/online-deals", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
590
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
591
    @ApiOperation(value = "Get online deals")
33575 amit.gupta 592
    public ResponseEntity<?> getOnlineDeals(HttpServletRequest request, @RequestParam(value = "categoryId") String
593
            categoryId, @RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String
594
                                                    limit, @RequestParam(value = "sort", required = false) String
595
                                                    sort, @RequestParam(value = "direction", required = false) String
596
                                                    direction, @RequestParam(value = "filterData", required = false) String filterData) throws Throwable {
32339 tejbeer 597
        logger.info("Request " + request.getParameterMap());
598
        String response = null;
599
        int userId = (int) request.getAttribute("userId");
22289 amit.gupta 600
 
32339 tejbeer 601
        String uri = "/deals/" + userId;
35410 amit 602
                Map<String, String> params = new HashMap<>();
32339 tejbeer 603
        params.put("offset", offset);
604
        params.put("limit", limit);
605
        params.put("categoryId", categoryId);
606
        params.put("direction", direction);
607
        params.put("sort", sort);
608
        params.put("source", "online");
609
        params.put("filterData", filterData);
610
        /*
611
         * if (userInfo.getRoleNames().contains(RoleType.FOFO.toString())) {
612
         * params.put("tag_ids", getCommaSeparateTags(userId)); }
613
         */
614
        List<Object> responseObject = new ArrayList<>();
615
        try {
35410 amit 616
            response = restClient.get(SchemeType.HTTP, host, port, uri, params);
32339 tejbeer 617
        } catch (HttpHostConnectException e) {
618
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
619
        }
22931 ashik.ali 620
 
32339 tejbeer 621
        JsonArray result_json = Json.parse(response).asArray();
622
        for (JsonValue j : result_json) {
623
            // logger.info("res " + j.asArray());
624
            List<Object> innerObject = new ArrayList<>();
625
            for (JsonValue jsonObject : j.asArray()) {
626
                innerObject.add(toDealObject(jsonObject.asObject()));
627
            }
628
            if (innerObject.size() > 0) {
629
                responseObject.add(innerObject);
630
            }
631
        }
632
        return responseSender.ok(responseObject);
633
    }
22272 amit.gupta 634
 
32339 tejbeer 635
    private Object toDealObject(JsonObject jsonObject) {
636
        if (jsonObject.get("dealObject") != null && jsonObject.get("dealObject").asInt() == 1) {
637
            return new Gson().fromJson(jsonObject.toString(), DealObjectResponse.class);
638
        }
639
        return new Gson().fromJson(jsonObject.toString(), DealsResponse.class);
640
    }
22319 amit.gupta 641
 
32339 tejbeer 642
    @RequestMapping(value = ProfitMandiConstants.URL_BRANDS, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
643
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
644
    @ApiOperation(value = "Get brand list and count for category")
33575 amit.gupta 645
    public ResponseEntity<?> getBrands(HttpServletRequest request, @RequestParam(value = "category_id") String
646
            category_id) throws ProfitMandiBusinessException {
32339 tejbeer 647
        logger.info("Request " + request.getParameterMap());
648
        String response = null;
649
        // TODO: move to properties
650
        String uri = ProfitMandiConstants.URL_BRANDS;
35410 amit 651
                Map<String, String> params = new HashMap<>();
32339 tejbeer 652
        params.put("category_id", category_id);
653
        List<DealBrands> dealBrandsResponse = null;
654
        try {
35410 amit 655
            response = restClient.get(SchemeType.HTTP, host, port, uri, params);
32339 tejbeer 656
        } catch (HttpHostConnectException e) {
657
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
658
        }
23816 amit.gupta 659
 
32339 tejbeer 660
        dealBrandsResponse = new Gson().fromJson(response, new TypeToken<List<DealBrands>>() {
661
        }.getType());
23022 ashik.ali 662
 
37144 amit 663
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
664
        List<String> restrictedBrands = brandsService.restrictedBrands(userInfo.getRetailerId());
665
        dealBrandsResponse = dealBrandsResponse.stream().filter(x -> !restrictedBrands.contains(x.getBrand()))
666
                .collect(Collectors.toList());
667
 
32339 tejbeer 668
        return responseSender.ok(dealBrandsResponse);
669
    }
22319 amit.gupta 670
 
32339 tejbeer 671
    @RequestMapping(value = ProfitMandiConstants.URL_UNIT_DEAL, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
672
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
673
    @ApiOperation(value = "Get unit deal object")
33575 amit.gupta 674
    public ResponseEntity<?> getUnitDeal(HttpServletRequest request, @PathVariable(value = "id") long id) throws
675
            ProfitMandiBusinessException {
32339 tejbeer 676
        String response = null;
677
        // TODO: move to properties
678
        String uri = "getDealById/" + id;
679
        System.out.println("Unit deal " + uri);
35410 amit 680
                Map<String, String> params = new HashMap<>();
32339 tejbeer 681
        DealsResponse dealsResponse = null;
682
        try {
35410 amit 683
            response = restClient.get(SchemeType.HTTP, host, port, uri, params);
32339 tejbeer 684
        } catch (HttpHostConnectException e) {
685
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
686
        }
23816 amit.gupta 687
 
32339 tejbeer 688
        JsonObject result_json = Json.parse(response).asObject();
689
        if (!result_json.isEmpty()) {
690
            dealsResponse = new Gson().fromJson(response, DealsResponse.class);
691
            Iterator<AvailabilityInfo> iter = dealsResponse.getAvailabilityInfo().iterator();
692
            while (iter.hasNext()) {
693
                AvailabilityInfo ai = iter.next();
694
                if (ai.getAvailability() <= 0)
695
                    iter.remove();
696
            }
697
        }
698
        return responseSender.ok(dealsResponse);
699
    }
23816 amit.gupta 700
 
32339 tejbeer 701
    @RequestMapping(value = "/partnerdeals/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
702
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
703
    @ApiOperation(value = "Get unit deal object")
33575 amit.gupta 704
    public ResponseEntity<?> getUnitFocoDeal(HttpServletRequest request, @PathVariable(value = "id") long id) throws
705
            Exception {
32339 tejbeer 706
        List<FofoCatalogResponse> dealResponse = new ArrayList<>();
707
        List<Integer> tagIds = Arrays.asList(4);
708
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
709
        if (roleManagerService.isPartner(userInfo.getRoleIds())) {
710
            String categoryId = "(3 OR 6)";
711
            UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
35410 amit 712
                        Map<String, String> params = new HashMap<>();
32339 tejbeer 713
            List<String> mandatoryQ = new ArrayList<>();
714
            String catalogString = "catalog" + id;
24091 tejbeer 715
 
32339 tejbeer 716
            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 717
 
32339 tejbeer 718
            params.put("q", StringUtils.join(mandatoryQ, " "));
719
            params.put("fl", "*, [child parentFilter=id:catalog*]");
720
            params.put("sort", "rank_i asc, create_s desc");
721
            params.put("wt", "json");
37144 amit 722
            JSONArray docs = partnerSolrClient.selectDocs(params, userInfo.getRetailerId());
37641 amit 723
            dealResponse = getCatalogResponse(docs, userInfo.getRetailerId());
32339 tejbeer 724
        } else {
725
            return responseSender.badRequest(
726
                    new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
727
        }
37115 amit 728
        if (dealResponse.isEmpty()) {
729
            return responseSender.badRequest(
730
                    new ProfitMandiBusinessException("catalogId", id, "DEAL_NOT_FOUND"));
731
        }
37247 amit 732
        hotDealEnrichmentService.enrich(dealResponse);
32339 tejbeer 733
        return responseSender.ok(dealResponse.get(0));
734
    }
24091 tejbeer 735
 
34436 ranu 736
 
737
    @RequestMapping(value = "/suggestedPoDeals", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
738
    public ResponseEntity<?> suggestedPoDeals(HttpServletRequest request,@RequestBody Set<Integer>catalogIds) throws Exception {
739
 
740
        int userId = (int) request.getAttribute("userId");
741
        UserCart uc = userAccountRepository.getUserCart(userId);
742
        int fofoId = uc.getUserId();
743
        List<FofoCatalogResponse> dealResponse = new ArrayList<>();
744
        if (!catalogIds.isEmpty()) {
745
            dealResponse = webSolrService.dealResponse(catalogIds, fofoId);
746
        }
747
        return responseSender.ok(dealResponse);
748
    }
749
 
32339 tejbeer 750
    @RequestMapping(value = "/fofo/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
33575 amit.gupta 751
    public ResponseEntity<?> getBrandsToDisplay(HttpServletRequest request,
752
                                                @RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {
32339 tejbeer 753
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
754
        logger.info("userInfo [{}]", userInfo);
32717 ranu 755
        List<BrandCatalog> brandsDisplay = brandsService.getBrandsToDisplay(categoryId);
756
        //List<DBObject> brandsDisplay = mongoClient.getMongoBrands(userInfo.getRetailerId(), userInfo.getEmail(), categoryId);
32339 tejbeer 757
        return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
758
    }
25879 amit.gupta 759
 
32339 tejbeer 760
    @RequestMapping(value = "/fofo/brandCatalog", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
33575 amit.gupta 761
    public ResponseEntity<?> getBrands(HttpServletRequest request,
762
                                       @RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {
32339 tejbeer 763
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
764
        logger.info("userInfo [{}]", userInfo);
31507 tejbeer 765
 
32339 tejbeer 766
        List<BrandCatalog> brandsDisplay = brandsService.getBrands(userInfo.getRetailerId(), userInfo.getEmail(), categoryId);
37144 amit 767
        List<String> restrictedBrands = brandsService.restrictedBrands(userInfo.getRetailerId());
768
        brandsDisplay = brandsDisplay.stream().filter(x -> !restrictedBrands.contains(x.getName()))
769
                .collect(Collectors.toList());
32339 tejbeer 770
        return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
771
    }
31507 tejbeer 772
 
32339 tejbeer 773
    @RequestMapping(value = "/fofo/accessory/all-categories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
774
    public ResponseEntity<?> getSubCategoriesToDisplay(HttpServletRequest request) throws Exception {
775
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
776
        logger.info("userInfo [{}]", userInfo);
777
        List<DBObject> subCategoriesDisplay = this.getSubCategoriesToDisplay();
778
        return new ResponseEntity<>(subCategoriesDisplay, HttpStatus.OK);
779
    }
23816 amit.gupta 780
 
32339 tejbeer 781
    private List<DBObject> getSubCategoriesToDisplay() throws Exception {
782
        List<DBObject> subCategories = new ArrayList<>();
35410 amit 783
                Map<String, String> params = new HashMap<>();
32339 tejbeer 784
        params.put("q", "categoryId_i:6");
785
        params.put("group", "true");
786
        params.put("group.field", "subCategoryId_i");
787
        params.put("wt", "json");
788
        params.put("rows", "50");
789
        params.put("fl", "subCategoryId_i");
790
        String response = null;
791
        try {
35410 amit 792
            response = restClient.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
32339 tejbeer 793
        } catch (HttpHostConnectException e) {
794
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
795
        }
796
        JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("grouped");
797
        JSONArray groups = solrResponseJSONObj.getJSONObject("subCategoryId_i").getJSONArray("groups");
798
        List<Integer> categoryIds = new ArrayList<>();
799
        for (int i = 0; i < groups.length(); i++) {
800
            JSONObject groupObject = groups.getJSONObject(i);
801
            int subCategoryId = groupObject.getInt("groupValue");
802
            int quantity = groupObject.getJSONObject("doclist").getInt("numFound");
803
            categoryIds.add(subCategoryId);
804
        }
25015 amit.gupta 805
 
32339 tejbeer 806
        List<Category> categories = categoryRepository.selectByIds(categoryIds);
807
        AtomicInteger i = new AtomicInteger(0);
808
        categories.forEach(x -> {
809
            DBObject dbObject = new BasicDBObject();
810
            dbObject.put("name", x.getLabel());
811
            dbObject.put("subCategoryId", x.getId());
812
            dbObject.put("rank", i.incrementAndGet());
813
            dbObject.put("categoryId", 6);
814
            dbObject.put("url", "https://images.smartdukaan.com/uploads/campaigns/" + x.getId() + ".png");
815
            subCategories.add(dbObject);
816
        });
25015 amit.gupta 817
 
32339 tejbeer 818
        return subCategories;
25015 amit.gupta 819
 
32339 tejbeer 820
    }
25010 amit.gupta 821
 
35801 amit 822
    @RequestMapping(value = "/fofo/categories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
823
    public ResponseEntity<?> getFofoCategories() {
824
        Map<Integer, Category> categoryMap = categoryRepository.selectAll();
825
        List<Map<String, Object>> result = new ArrayList<>();
826
        for (Category category : categoryMap.values()) {
827
            if (category.isStatus()) {
828
                Map<String, Object> cat = new HashMap<>();
829
                cat.put("id", category.getId());
830
                cat.put("label", category.getLabel());
831
                cat.put("displayName", category.getDisplayName());
832
                cat.put("parentCategoryId", category.getParentCategoryId());
833
                cat.put("marginOnly", category.isMarginOnly());
834
                result.add(cat);
835
            }
836
        }
837
        return responseSender.ok(result);
838
    }
839
 
32339 tejbeer 840
    @RequestMapping(value = "/banners/{bannerType}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
841
    public ResponseEntity<?> getBanners(@PathVariable String bannerType) {
842
        return new ResponseEntity<>(mongoClient.getBannersByType(bannerType), HttpStatus.OK);
843
    }
23816 amit.gupta 844
 
32339 tejbeer 845
    @RequestMapping(value = "/deals/subCategories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
846
    public ResponseEntity<?> getSubcategoriesToDisplay() {
847
        return new ResponseEntity<>(mongoClient.getSubcategoriesToDisplay(), HttpStatus.OK);
848
    }
23816 amit.gupta 849
 
32339 tejbeer 850
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
851
    @RequestMapping(value = "/deals/skus/{skus}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
852
    public ResponseEntity<?> getDealsBySkus(@PathVariable String skus) throws ProfitMandiBusinessException {
853
        StringBuffer sb = new StringBuffer("/getDealsForNotification/");
854
        String uri = sb.append(skus).toString();
35410 amit 855
                String response;
32339 tejbeer 856
        try {
35410 amit 857
            response = restClient.get(SchemeType.HTTP, host, port, uri, new HashMap<>());
32339 tejbeer 858
        } catch (HttpHostConnectException e) {
859
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
860
        }
861
        JsonArray result_json = Json.parse(response).asArray();
862
        List<Object> responseObject = new ArrayList<>();
863
        for (JsonValue j : result_json) {
864
            // logger.info("res " + j.asArray());
865
            List<Object> innerObject = new ArrayList<>();
866
            for (JsonValue jsonObject : j.asArray()) {
867
                innerObject.add(toDealObject(jsonObject.asObject()));
868
            }
869
            if (innerObject.size() > 0) {
870
                responseObject.add(innerObject);
871
            }
872
        }
873
        return responseSender.ok(responseObject);
874
    }
21339 kshitij.so 875
 
37250 amit 876
    // Fans out the per-listing Solr HTTP calls only; every DB access stays on the request
877
    // thread because the Hibernate session is thread-bound. Pool size matches the
878
    // RestClient per-route connection limit.
879
    private static final ExecutorService SOLR_EXECUTOR = Executors.newFixedThreadPool(8, r -> {
880
        Thread t = new Thread(r, "partner-listing-solr");
881
        t.setDaemon(true);
882
        return t;
883
    });
884
 
32339 tejbeer 885
    @RequestMapping(value = "/partner/listing", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
886
    public ResponseEntity<?> getPartnersListing(HttpServletRequest request) throws Exception {
887
        List<WebListing> webListings = webListingRepository.selectAllWebListingByType(Optional.of(true), WebListingSource.partner);
888
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
37250 amit 889
        int fofoId = userInfo.getRetailerId();
890
        FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
34786 aman.kumar 891
 
37250 amit 892
        // Build every listing's Solr query on the request thread; the brand exclusion is
893
        // partner-scoped, so resolve it once instead of per listing.
894
        String exclusionFq = SolrService.brandExclusionFq(brandsService.restrictedBrands(fofoId));
895
        List<ListingQuery> queries = new ArrayList<>();
35412 amit 896
        for (WebListing webListing : webListings) {
37250 amit 897
            ListingQuery query = buildListingQuery(webListing, fs.getWarehouseId(), 0, 20);
898
            if (query.params != null && exclusionFq != null) {
899
                query.params.put("fq", exclusionFq);
900
            }
901
            queries.add(query);
35412 amit 902
        }
37250 amit 903
 
904
        Map<Integer, CompletableFuture<JSONArray>> futures = new HashMap<>();
905
        for (int i = 0; i < queries.size(); i++) {
906
            Map<String, String> params = queries.get(i).params;
907
            if (params != null) {
908
                futures.put(i, CompletableFuture.supplyAsync(() -> {
909
                    try {
910
                        return partnerSolrClient.selectDocsRaw(params);
911
                    } catch (ProfitMandiBusinessException e) {
912
                        throw new CompletionException(e);
913
                    }
914
                }, SOLR_EXECUTOR));
915
            }
916
        }
917
 
918
        Map<Integer, JSONArray> docsByListing = new HashMap<>();
919
        Set<Integer> allCatalogIds = new LinkedHashSet<>();
920
        Set<Integer> allItemIds = new LinkedHashSet<>();
921
        for (Map.Entry<Integer, CompletableFuture<JSONArray>> entry : futures.entrySet()) {
922
            JSONArray docs;
923
            try {
924
                docs = entry.getValue().join();
925
            } catch (CompletionException e) {
926
                throw e.getCause() instanceof Exception ? (Exception) e.getCause() : e;
927
            }
928
            docsByListing.put(entry.getKey(), docs);
929
            allCatalogIds.addAll(extractCatalogIds(docs));
930
            allItemIds.addAll(extractItemIds(docs));
931
        }
932
 
933
        CatalogBatchData batch = allItemIds.isEmpty() ? null
934
                : buildCatalogBatchData(fofoId, fs.getWarehouseId(), new ArrayList<>(allCatalogIds), new ArrayList<>(allItemIds));
935
 
936
        for (int i = 0; i < queries.size(); i++) {
937
            ListingQuery query = queries.get(i);
938
            JSONArray docs = docsByListing.get(i);
939
            List<FofoCatalogResponse> dealResponse;
940
            if (docs == null || batch == null) {
941
                dealResponse = new ArrayList<>();
942
            } else {
37641 amit 943
                dealResponse = buildCatalogResponses(docs, fofoId, batch);
37250 amit 944
                if (query.webProducts != null && query.webListing.getUrl().equals("new-launches")) {
945
                    List<Integer> webProductsFinal = query.webProducts;
946
                    dealResponse = dealResponse.stream().sorted(Comparator.comparing(x -> webProductsFinal.indexOf(x.getCatalogId()))).collect(Collectors.toList());
947
                }
948
            }
949
            query.webListing.setFofoCatalogResponses(dealResponse);
950
        }
32339 tejbeer 951
        return responseSender.ok(webListings);
952
    }
31547 tejbeer 953
 
35652 vikas 954
    private List<FofoCatalogResponse> getDealResponses(UserInfo userInfo, FofoStore fs, WebListing webListing, int offset, int limit) throws Exception {
37250 amit 955
        ListingQuery query = buildListingQuery(webListing, fs.getWarehouseId(), offset, limit);
956
        if (query.params == null) {
957
            return new ArrayList<>();
958
        }
959
        JSONArray docs = partnerSolrClient.selectDocs(query.params, userInfo.getRetailerId());
37641 amit 960
        List<FofoCatalogResponse> dealResponse = getCatalogResponse(docs, userInfo.getRetailerId());
31572 tejbeer 961
 
37250 amit 962
        if (query.webProducts != null && webListing.getUrl().equals("new-launches")) {
963
            List<Integer> webProductsFinal = query.webProducts;
964
            dealResponse = dealResponse.stream().sorted(Comparator.comparing(x -> webProductsFinal.indexOf(x.getCatalogId()))).collect(Collectors.toList());
965
        }
966
 
967
        return dealResponse;
968
    }
969
 
970
    /** Solr query for one web listing; params is null when a curated listing has no ranked products. */
971
    private static class ListingQuery {
972
        WebListing webListing;
973
        Map<String, String> params;
974
        List<Integer> webProducts;
975
    }
976
 
977
    private ListingQuery buildListingQuery(WebListing webListing, int warehouseId, int offset, int limit) {
978
        ListingQuery query = new ListingQuery();
979
        query.webListing = webListing;
980
 
35411 amit 981
        Map<String, String> params = new HashMap<>();
32339 tejbeer 982
        List<String> mandatoryQ = new ArrayList<>();
37250 amit 983
        params.put("sort", "w" + warehouseId + "_i desc");
31670 tejbeer 984
 
32339 tejbeer 985
        if (webListing.getType().equals(WebListingType.solr)) {
986
            mandatoryQ.add(String.format("+{!parent which=\"" + webListing.getSolrQuery() + "\"} AND active_b:true AND show_default_b:true"));
987
        } else {
37250 amit 988
            query.webProducts = webProductListingRepository.selectAllByWebListingId(webListing.getId(), offset, limit).stream().filter(x -> x.getRank() > 0).map(x -> x.getEntityId()).collect(Collectors.toList());
31675 tejbeer 989
 
37250 amit 990
            if (query.webProducts.size() == 0) {
991
                return query;
32339 tejbeer 992
            }
31572 tejbeer 993
 
32339 tejbeer 994
            mandatoryQ.add(String.format(
37250 amit 995
                    "+{!parent which=\"catalogId_i:(" + StringUtils.join(query.webProducts, " ") + ")\"} AND active_b:true AND show_default_b:true"));
32339 tejbeer 996
        }
997
        params.put("q", StringUtils.join(mandatoryQ, " "));
998
        params.put("fl", "*, [child parentFilter=id:catalog* childFilter=active_b:true ]");
31612 tejbeer 999
 
32339 tejbeer 1000
        params.put("start", String.valueOf(offset));
1001
        params.put("rows", String.valueOf(limit));
1002
        params.put("wt", "json");
37250 amit 1003
        query.params = params;
1004
        return query;
32339 tejbeer 1005
    }
30669 amit.gupta 1006
 
32339 tejbeer 1007
    @Autowired
1008
    private SaholicCISTableRepository saholicCISTableRepository;
27053 amit.gupta 1009
 
37641 amit 1010
    private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, int fofoId) throws Exception {
37250 amit 1011
        List<Integer> itemIds = extractItemIds(docs);
1012
        if (itemIds.isEmpty()) {
1013
            return new ArrayList<>();
1014
        }
1015
        int warehouseId = fofoStoreRepository.selectByRetailerId(fofoId).getWarehouseId();
1016
        CatalogBatchData batch = buildCatalogBatchData(fofoId, warehouseId, extractCatalogIds(docs), itemIds);
37641 amit 1017
        return buildCatalogResponses(docs, fofoId, batch);
37250 amit 1018
    }
1019
 
1020
    private List<Integer> extractItemIds(JSONArray docs) {
32339 tejbeer 1021
        List<Integer> itemIds = new ArrayList<>();
37250 amit 1022
        for (int i = 0; i < docs.length(); i++) {
1023
            JSONObject doc = docs.getJSONObject(i);
1024
            if (doc.has("_childDocuments_")) {
1025
                for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
1026
                    itemIds.add(doc.getJSONArray("_childDocuments_").getJSONObject(j).getInt("itemId_i"));
32339 tejbeer 1027
                }
1028
            }
1029
        }
37250 amit 1030
        return itemIds;
1031
    }
1032
 
1033
    private List<Integer> extractCatalogIds(JSONArray docs) {
32339 tejbeer 1034
        List<Integer> catalogIds = new ArrayList<>();
1035
        for (int i = 0; i < docs.length(); i++) {
37250 amit 1036
            catalogIds.add(docs.getJSONObject(i).getInt("catalogId_i"));
32339 tejbeer 1037
        }
37250 amit 1038
        return catalogIds;
1039
    }
1040
 
1041
    /** Partner-level data shared by every catalog response built in one request. */
1042
    private static class CatalogBatchData {
1043
        int warehouseId;
1044
        Map<Integer, List<SaholicPOItem>> poItemAvailabilityMap;
1045
        Map<Integer, Integer> partnerStockAvailabilityMap;
1046
        Set<Integer> favouriteCatalogIds;
1047
        Map<Integer, List<WebOffer>> webOffersMap;
1048
        Map<Integer, List<ComboModel>> comboModelsByCatalogId;
1049
        Map<Integer, PriceCircularItemModelNew> priceCircularItemModelMap;
1050
        Map<Integer, List<CreateOfferRequest>> schemeOffersByCatalogId;
1051
        Map<Integer, List<SaholicCISTable>> cisDataByItemId;
1052
        Map<Integer, Item> itemMap;
1053
        Map<Integer, Float> cashbackMap;
1054
    }
1055
 
1056
    private CatalogBatchData buildCatalogBatchData(int fofoId, int warehouseId, List<Integer> catalogIds, List<Integer> itemIds) throws Exception {
1057
        CatalogBatchData batch = new CatalogBatchData();
1058
        batch.warehouseId = warehouseId;
1059
        batch.poItemAvailabilityMap = saholicInventoryService.getSaholicPOItems().get(warehouseId);
1060
 
1061
        batch.priceCircularItemModelMap = new HashMap<>();
1062
        batch.schemeOffersByCatalogId = new HashMap<>();
32339 tejbeer 1063
        if (catalogIds.size() > 0) {
1064
            PriceCircularModel priceCircularModel = priceCircularService.getPriceCircularByOffer(fofoId, catalogIds, LocalDate.now());
37250 amit 1065
            List<CreateOfferRequest> allSchemOffers = priceCircularModel.getOffers();
30188 amit.gupta 1066
 
32339 tejbeer 1067
            List<PriceCircularItemModelNew> priceCircularItemModelNews = priceCircularModel.getPriceCircularItemModelNews();
1068
            if (priceCircularItemModelNews != null) {
37250 amit 1069
                batch.priceCircularItemModelMap = priceCircularItemModelNews.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));
32339 tejbeer 1070
            }
37250 amit 1071
            // Filter null slab payouts and align the surviving ones with the offer list exactly
1072
            // once per catalog. The models are shared when a catalog appears in more than one
1073
            // listing, and the iterator.remove() below breaks the index alignment on a second pass.
1074
            for (PriceCircularItemModelNew model : batch.priceCircularItemModelMap.values()) {
1075
                if (model.getSlabPayouts() == null) {
1076
                    continue;
1077
                }
1078
                List<CreateOfferRequest> schemeOffers = new ArrayList<>();
1079
                Iterator<Map<Integer, AmountModel>> iterator = model.getSlabPayouts().iterator();
1080
                int iteratorCount = 0;
1081
                while (iterator.hasNext()) {
1082
                    Map<Integer, AmountModel> slabPayoutMap = iterator.next();
1083
                    if (slabPayoutMap != null) {
1084
                        schemeOffers.add(allSchemOffers.get(iteratorCount));
1085
                    } else {
1086
                        iterator.remove();
1087
                    }
1088
                    iteratorCount++;
1089
                }
1090
                batch.schemeOffersByCatalogId.put(model.getCatalogId(), schemeOffers);
1091
            }
32339 tejbeer 1092
        }
31629 tejbeer 1093
 
34260 vikas.jang 1094
        if (fofoId > 0) {
37250 amit 1095
            batch.partnerStockAvailabilityMap = currentInventorySnapshotRepository.selectItemsStock(fofoId).stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
34260 vikas.jang 1096
        }
37250 amit 1097
        batch.favouriteCatalogIds = catalogFavouriteRepository.selectBypartnerId(fofoId).stream()
34786 aman.kumar 1098
                .map(CatalogFavourite::getCatalogId)
1099
                .collect(Collectors.toSet());
35410 amit 1100
 
37250 amit 1101
        batch.cisDataByItemId = saholicCISTableRepository
35410 amit 1102
                .selectByItemWarehouse(itemIds, warehouseId).stream()
1103
                .collect(Collectors.groupingBy(SaholicCISTable::getItemId));
1104
 
37250 amit 1105
        batch.itemMap = itemRepository.selectByIds(new HashSet<>(itemIds)).stream()
35410 amit 1106
                .collect(Collectors.toMap(Item::getId, x -> x));
1107
 
37250 amit 1108
        batch.cashbackMap = schemeService.getCatalogSchemeCashBack(fofoId, catalogIds);
35410 amit 1109
 
37250 amit 1110
        batch.webOffersMap = webOfferRepository.selectAllActiveOffers();
35410 amit 1111
 
37250 amit 1112
        batch.comboModelsByCatalogId = comboModelRepository.selectByWarehouseId(warehouseId)
35410 amit 1113
                .stream().collect(Collectors.groupingBy(ComboModel::getCatalogId));
37250 amit 1114
        return batch;
1115
    }
35410 amit 1116
 
37641 amit 1117
    private List<FofoCatalogResponse> buildCatalogResponses(JSONArray docs, int fofoId, CatalogBatchData batch) throws Exception {
37250 amit 1118
        List<FofoCatalogResponse> dealResponse = new ArrayList<>();
1119
        int warehouseId = batch.warehouseId;
1120
        Map<Integer, List<SaholicPOItem>> poItemAvailabilityMap = batch.poItemAvailabilityMap;
1121
        Map<Integer, Integer> partnerStockAvailabilityMap = batch.partnerStockAvailabilityMap;
1122
        Set<Integer> favouriteCatalogIds = batch.favouriteCatalogIds;
1123
        Map<Integer, List<WebOffer>> webOffersMap = batch.webOffersMap;
1124
        Map<Integer, List<ComboModel>> comboModelsByCatalogId = batch.comboModelsByCatalogId;
1125
        Map<Integer, PriceCircularItemModelNew> priceCircularItemModelMap = batch.priceCircularItemModelMap;
1126
        Map<Integer, List<SaholicCISTable>> cisDataByItemId = batch.cisDataByItemId;
1127
        Map<Integer, Item> itemMap = batch.itemMap;
1128
        Map<Integer, Float> cashbackMap = batch.cashbackMap;
1129
 
32339 tejbeer 1130
        for (int i = 0; i < docs.length(); i++) {
1131
            Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
1132
            JSONObject doc = docs.getJSONObject(i);
1133
            FofoCatalogResponse fofoCatalogResponse = new FofoCatalogResponse();
1134
            fofoCatalogResponse.setCatalogId(doc.getInt("catalogId_i"));
1135
            fofoCatalogResponse.setImageUrl(doc.getString("imageUrl_s"));
1136
            fofoCatalogResponse.setTitle(doc.getString("title_s"));
33975 tejus.loha 1137
            fofoCatalogResponse.setSuperCatalogTitle(doc.getString("superCatalog_s"));
1138
            fofoCatalogResponse.setSuperCatalogId(doc.getInt("superCatalog_i"));
1139
            fofoCatalogResponse.setSuperCatalogVariants(doc.getString("superCatalogVariants_s"));
31629 tejbeer 1140
 
35652 vikas 1141
            // optional, since default is false
1142
            fofoCatalogResponse.setFavourite(favouriteCatalogIds.contains(fofoCatalogResponse.getCatalogId()));
35410 amit 1143
            List<WebOffer> webOffers = webOffersMap.get(fofoCatalogResponse.getCatalogId());
31612 tejbeer 1144
 
33573 amit.gupta 1145
            //logger.info("webOffers {}", webOffers);
32339 tejbeer 1146
            if (webOffers != null && webOffers.size() > 0) {
1147
                fofoCatalogResponse.setWebOffers(webOffers);
1148
                fofoCatalogResponse.setOffers(webOffers.stream().map(x -> x.getTitle()).collect(Collectors.toList()));
1149
            }
30683 tejbeer 1150
 
35663 vikas 1151
            /*Map<Integer, OfferDiscoveryResponse> pineResponse = pinelabsOfferCacheService.getCachedOffersForItems(fofoCatalogResponse.getItems().stream().map(x -> (int) x.getItem_id()).collect(Collectors.toList()));
1152
            if (pineResponse != null && pineResponse.size() > 0) {
1153
                fofoCatalogResponse.setPineOffers(pineResponse);
1154
            }*/
1155
 
35410 amit 1156
            List<ComboModel> comboModels = comboModelsByCatalogId.get(fofoCatalogResponse.getCatalogId());
30683 tejbeer 1157
 
33573 amit.gupta 1158
            //logger.info("comboModels {}", comboModels);
32344 tejbeer 1159
 
32339 tejbeer 1160
            if (comboModels != null && comboModels.size() > 0) {
1161
                fofoCatalogResponse.setComboModels(comboModels);
1162
            }
30683 tejbeer 1163
 
32339 tejbeer 1164
            try {
1165
                fofoCatalogResponse.setFeature(doc.getString("feature_s"));
1166
            } catch (Exception e) {
1167
                fofoCatalogResponse.setFeature(null);
1168
                logger.info("Could not find Feature_s for {}", fofoCatalogResponse.getCatalogId());
1169
            }
30683 tejbeer 1170
 
32339 tejbeer 1171
            fofoCatalogResponse.setBrand(doc.getJSONArray("brand_ss").getString(0));
30683 tejbeer 1172
 
32339 tejbeer 1173
            if (doc.has("label_ss")) {
1174
                JSONArray arr = doc.getJSONArray("label_ss");
1175
                Set<String> labels = new HashSet<String>();
1176
                for (int j = 0; j < arr.length(); j++) {
1177
                    labels.add(arr.getString(j));
1178
                }
31612 tejbeer 1179
 
32339 tejbeer 1180
                fofoCatalogResponse.setLabels(new ArrayList<>(labels));
31612 tejbeer 1181
 
32339 tejbeer 1182
            }
33573 amit.gupta 1183
            if (doc.has("similarModels_ii")) {
1184
                JSONArray similarModelsArray = doc.getJSONArray("similarModels_ii");
1185
                List<Integer> similarCatalogIds = new ArrayList<>();
1186
                for (int j = 0; j < similarModelsArray.length(); j++) {
1187
                    similarCatalogIds.add(similarModelsArray.getInt(j));
1188
                }
1189
                fofoCatalogResponse.setSimilarModelIds(similarCatalogIds);
1190
            }
31612 tejbeer 1191
 
32339 tejbeer 1192
            if (doc.has("_childDocuments_")) {
1193
                String modelColorClass = "grey";
1194
                FofoAvailabilityInfo fdiAnyColour = null;
1195
                // Iterating itemIds
1196
                for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
1197
                    PriceCircularItemModelNew priceCircularItemModel = priceCircularItemModelMap.get(fofoCatalogResponse.getCatalogId());
1198
                    JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
1199
                    int itemId = childItem.getInt("itemId_i");
1200
                    float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
34260 vikas.jang 1201
                    int partnerAvailability = partnerStockAvailabilityMap.get(itemId) == null ? 0 : partnerStockAvailabilityMap.get(itemId);
32339 tejbeer 1202
                    if (!fofoAvailabilityInfoMap.containsKey(itemId)) {
35663 vikas 1203
                        OfferDiscoveryResponse offers = pinelabsOfferCacheService.getCachedOfferForItem(itemId);
32339 tejbeer 1204
                        FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
35663 vikas 1205
                        fdi.setOffers(offers);
35410 amit 1206
                        List<SaholicCISTable> currentAvailability = cisDataByItemId.getOrDefault(itemId, new ArrayList<>());
32339 tejbeer 1207
                        List<SaholicPOItem> poItemAvailability = null;
1208
                        if (poItemAvailabilityMap != null) {
1209
                            poItemAvailability = poItemAvailabilityMap.get(itemId);
1210
                        }
31612 tejbeer 1211
 
32339 tejbeer 1212
                        if (priceCircularItemModel != null) {
33410 ranu 1213
                            fdi.setNlc((float) priceCircularItemModel.getNetNlc());
32339 tejbeer 1214
                        }
31612 tejbeer 1215
 
32339 tejbeer 1216
                        for (SaholicCISTable saholicCISTable : currentAvailability) {
1217
                            saholicCISTable.setWarehouseName(
1218
                                    ProfitMandiConstants.WAREHOUSE_MAP.get(saholicCISTable.getWarehouseFrom()));
1219
                        }
31612 tejbeer 1220
 
32339 tejbeer 1221
                        Map<Integer, SaholicCISTable> map = currentAvailability.stream().collect(Collectors.toMap(SaholicCISTable::getWarehouseFrom, x -> x));
1222
                        if (poItemAvailability != null) {
1223
                            for (SaholicPOItem saholicPOItem : poItemAvailability) {
1224
                                if (map.containsKey(saholicPOItem.getWarehouseFrom())) {
1225
                                    map.get(saholicPOItem.getWarehouseFrom()).setPopendingQty(saholicPOItem.getUnfulfilledQty());
1226
                                } else {
1227
                                    SaholicCISTable saholicCISTable = new SaholicCISTable();
1228
                                    saholicCISTable.setAvailability(0);
1229
                                    saholicCISTable.setReserved(0);
1230
                                    saholicCISTable.setItemId(itemId);
1231
                                    saholicCISTable.setWarehouseId(warehouseId);
1232
                                    saholicCISTable.setPopendingQty(saholicPOItem.getUnfulfilledQty());
1233
                                    saholicCISTable.setWarehouseFrom(saholicPOItem.getWarehouseFrom());
1234
                                    saholicCISTable.setWarehouseName(
1235
                                            ProfitMandiConstants.WAREHOUSE_MAP.get(saholicPOItem.getWarehouseFrom()));
1236
                                    map.put(saholicPOItem.getWarehouseFrom(), saholicCISTable);
1237
                                }
1238
                            }
1239
                        }
1240
                        fdi.setSaholicCISTableList(new ArrayList<>(map.values()));
1241
                        String poColor = "grey";
1242
                        boolean active = false;
1243
                        if (currentAvailability != null && currentAvailability.stream().collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)) > 0) {
1244
                            poColor = "green";
1245
                            modelColorClass = "green";
32978 amit.gupta 1246
                        } else if (poItemAvailability != null && poItemAvailability.stream().collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty)) > 0) {
1247
                            if (currentAvailability != null && poItemAvailability.stream().collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty)) + currentAvailability.stream().collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)) <= 0) {
1248
                                poColor = "grey";
1249
                            } else {
1250
                                poColor = "yellow";
35410 amit 1251
                                if (!"green".equals(modelColorClass)) {
32978 amit.gupta 1252
                                    modelColorClass = poColor;
32339 tejbeer 1253
                                }
1254
                            }
32978 amit.gupta 1255
                        }
32339 tejbeer 1256
                        fdi.setColorClass(poColor);
1257
                        fdi.setSellingPrice(sellingPrice);
1258
                        fdi.setActive(active);
1259
                        fdi.setMrp(childItem.getDouble("mrp_f"));
1260
                        fdi.setMop((float) childItem.getDouble("mop_f"));
1261
                        fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
1262
                        if (fdi.getColor().equalsIgnoreCase("any colour")) {
1263
                            fdiAnyColour = fdi;
1264
                        }
33929 tejus.loha 1265
                        fdi.setBrand((String) doc.getJSONArray("brand_ss").get(0));
1266
                        fdi.setCategoryId(doc.getInt("subCategoryId_i"));
32339 tejbeer 1267
                        fdi.setTagId(childItem.getInt("tagId_i"));
1268
                        fdi.setItem_id(itemId);
34196 ranu 1269
                        fdi.setCatalog_id(doc.getInt("catalogId_i"));
35410 amit 1270
                        Float cashBack = cashbackMap.get(fofoCatalogResponse.getCatalogId());
32339 tejbeer 1271
                        cashBack = cashBack == null ? 0 : cashBack;
1272
                        fdi.setCashback(cashBack);
1273
                        fdi.setMinBuyQuantity(1);
37641 amit 1274
                        // Real availability on every listing.
1275
                        //
1276
                        // This used to branch on the hotDeal flag (r32339, 2023): hot deals
1277
                        // got real stock, everything else a hardcoded 400. Since 400 is the
1278
                        // max-quantity cap rather than zero, the effect was the opposite of
1279
                        // the old "out of stock" comment - a partner could order 400 of a SKU
1280
                        // with none in stock, and the app's out-of-stock and over-order
1281
                        // warnings (which test availability == 0 and quantity > availability)
1282
                        // could never fire outside hot deals.
1283
                        //
1284
                        // The data was always there: cisDataByItemId is built on every call.
1285
                        fdi.setAvailability(currentAvailability.stream()
1286
                                .collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)));
1287
                        fdi.setPartnerAvailability(partnerAvailability);
32339 tejbeer 1288
                        fdi.setQuantityStep(1);
37641 amit 1289
                        // Partners can always order up to 10, so a zero-stock model can
1290
                        // still be indented ahead of supply; beyond that the cap follows
1291
                        // real stock, up to 400.
1292
                        fdi.setMaxQuantity(Math.min(Math.max(fdi.getAvailability(), 10), 400));
32339 tejbeer 1293
                        fofoAvailabilityInfoMap.put(itemId, fdi);
1294
                    }
1295
                }
1296
                if (fdiAnyColour != null) {
1297
                    fdiAnyColour.setColorClass(modelColorClass);
1298
                }
33576 amit.gupta 1299
                fofoCatalogResponse.setInStock(!modelColorClass.equals("grey"));
32339 tejbeer 1300
            }
1301
            if (fofoAvailabilityInfoMap.values().size() > 0) {
1302
                List<FofoAvailabilityInfo> availabilityList = fofoAvailabilityInfoMap.values().stream().sorted(Comparator.comparing(FofoAvailabilityInfo::getAvailability).reversed()).collect(Collectors.toList());
1303
                fofoCatalogResponse.setItems(availabilityList);
1304
                if (priceCircularItemModelMap.containsKey(fofoCatalogResponse.getCatalogId())) {
1305
                    PriceCircularItemModelNew priceCircularItemModel = priceCircularItemModelMap.get(fofoCatalogResponse.getCatalogId());
37250 amit 1306
                    List<CreateOfferRequest> schemeOffers = batch.schemeOffersByCatalogId.get(fofoCatalogResponse.getCatalogId());
1307
                    if (schemeOffers != null) {
32339 tejbeer 1308
                        fofoCatalogResponse.setSchemeOffers(schemeOffers);
1309
                    }
1310
                    fofoCatalogResponse.setPriceCircularItemModel(priceCircularItemModel);
1311
                }
1312
                dealResponse.add(fofoCatalogResponse);
1313
            }
1314
        }
1315
        return dealResponse;
30686 amit.gupta 1316
 
32339 tejbeer 1317
    }
30693 amit.gupta 1318
 
33575 amit.gupta 1319
    private List<FofoCatalogResponse> getCatalogSingleSkuResponse(JSONArray
37260 amit 1320
                                                                          docs, Map<Integer, Integer> itemFilter) throws ProfitMandiBusinessException {
32339 tejbeer 1321
        List<FofoCatalogResponse> dealResponse = new ArrayList<>();
1322
        List<Integer> tagIds = Arrays.asList(4);
24091 tejbeer 1323
 
33873 ranu 1324
        Map<Integer, TagListing> itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemFilter.keySet(), new HashSet<>(tagIds)).stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x));
24091 tejbeer 1325
 
35410 amit 1326
        // Pre-fetch all items (batch query instead of N+1)
1327
        Map<Integer, Item> itemMap = itemRepository.selectByIds(itemFilter.keySet()).stream()
1328
                .collect(Collectors.toMap(Item::getId, x -> x));
1329
 
32339 tejbeer 1330
        for (int i = 0; i < docs.length(); i++) {
1331
            Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
1332
            JSONObject doc = docs.getJSONObject(i);
26589 amit.gupta 1333
 
32339 tejbeer 1334
            for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
1335
                JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
1336
                int itemId = childItem.getInt("itemId_i");
1337
                TagListing tl = itemTagListingMap.get(itemId);
1338
                if (tl == null) {
1339
                    continue;
1340
                }
1341
                float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
1342
                if (fofoAvailabilityInfoMap.containsKey(itemId)) {
1343
                    if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
1344
                        fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
1345
                        fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
1346
                    }
1347
                } else {
1348
                    FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
1349
                    fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
1350
                    fdi.setMop((float) childItem.getDouble("mop_f"));
1351
                    fdi.setMop((float) tl.getMrp());
1352
                    fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
1353
                    fdi.setTagId(childItem.getInt("tagId_i"));
1354
                    fdi.setItem_id(itemId);
34196 ranu 1355
                    fdi.setCatalog_id(doc.getInt("catalogId_i"));
35410 amit 1356
                    Item item = itemMap.get(itemId);
32339 tejbeer 1357
                    // In case its tampered glass moq should be 5
35410 amit 1358
                    if (item != null && item.getCategoryId() == 10020) {
32339 tejbeer 1359
                        fdi.setMinBuyQuantity(10);
1360
                    } else {
1361
                        fdi.setMinBuyQuantity(1);
1362
                    }
1363
                    fdi.setAvailability(itemFilter.get(itemId));
1364
                    fdi.setQuantityStep(1);
1365
                    fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
1366
                    fofoAvailabilityInfoMap.put(itemId, fdi);
1367
                }
1368
            }
1369
            if (fofoAvailabilityInfoMap.values().size() > 0) {
1370
                for (FofoAvailabilityInfo fofoAvailabilityInfo : fofoAvailabilityInfoMap.values()) {
1371
                    FofoCatalogResponse ffdr = new FofoCatalogResponse();
1372
                    ffdr.setCatalogId(doc.getInt("catalogId_i"));
1373
                    ffdr.setImageUrl(doc.getString("imageUrl_s"));
1374
                    ffdr.setTitle(doc.getString("title_s"));
1375
                    try {
1376
                        ffdr.setFeature(doc.getString("feature_s"));
1377
                    } catch (Exception e) {
1378
                        ffdr.setFeature(null);
1379
                        logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
1380
                    }
1381
                    ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
1382
                    ffdr.setItems(Arrays.asList(fofoAvailabilityInfo));
1383
                    dealResponse.add(ffdr);
1384
                }
1385
            }
1386
        }
1387
        return dealResponse;
25880 amit.gupta 1388
 
32339 tejbeer 1389
    }
25880 amit.gupta 1390
 
32339 tejbeer 1391
    @RequestMapping(value = "/combo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
1392
    public ResponseEntity<?> getBanners(@RequestParam int catalogId, @RequestParam int warehouseId) {
1393
        List<ComboModel> comboModels = comboModelRepository.selectByCatalogIdAndWarehouseId(catalogId, warehouseId);
1394
        return responseSender.ok(comboModels);
1395
    }
32344 tejbeer 1396
 
1397
    @RequestMapping(value = "/checkCombo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
33575 amit.gupta 1398
    public ResponseEntity<?> checkCombo(HttpServletRequest request, @RequestParam int catalogId,
1399
                                        @RequestParam int warehouseId, @RequestParam int qty) throws Exception {
32344 tejbeer 1400
        boolean isCombo = false;
1401
        ComboModel comboModel = comboModelRepository.selectByCatalogIdWarehouseIdAndQty(catalogId, warehouseId, qty);
1402
        if (comboModel != null) {
1403
            isCombo = true;
1404
        }
1405
 
1406
        return responseSender.ok(isCombo);
1407
    }
1408
 
33929 tejus.loha 1409
    @GetMapping(value = "/partner/wodCompleteBrands", produces = MediaType.APPLICATION_JSON_VALUE)
1410
    public ResponseEntity<?> getWodcompletBrands(HttpServletRequest request) throws Exception {
1411
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
34630 tejus.loha 1412
        BrandAndAddToCartEligibleModel brandAndAddToCartEligibleModel = brandsService.wodcompletBrands(userInfo.getRetailerId());
1413
        return responseSender.ok(brandAndAddToCartEligibleModel);
35652 vikas 1414
    }
33929 tejus.loha 1415
 
35652 vikas 1416
    @RequestMapping(value = "/pinelabs/offers", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
1417
    public ResponseEntity<?> getPineLabsOffers(@RequestBody OfferDiscoveryRequest offerDiscoveryRequest) {
1418
        logger.info("pinelabs offers {}", offerDiscoveryRequest);
1419
        OfferDiscoveryResponse pineLabsOffers = pinelabsAffordabilityService.discoverOffers(offerDiscoveryRequest);
1420
        logger.info("pinelabs offers response {}", pineLabsOffers);
1421
        return responseSender.ok(pineLabsOffers);
33929 tejus.loha 1422
    }
1423
 
35727 vikas 1424
    @RequestMapping(value = "/pinelabs/offers/cache", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
1425
    public ResponseEntity<?> cachePineLabsOffers() {
1426
        pinelabsOfferCacheService.cacheAllItemOffers();
1427
        return responseSender.ok("PineLabs offers cache initiated");
1428
    }
1429
 
1430
    @RequestMapping(value = "/pinelabs/offers/{itemId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
1431
    public ResponseEntity<?> pineLabsOfferById(@PathVariable int itemId) {
1432
        List<Integer> itemIds = new ArrayList<>();
1433
        itemIds.add(itemId);
1434
        Map<Integer, Map<String, List<Tenure>>> pineLabsOffers = pinelabsOfferCacheService.getGroupedCachedOffersForItems(itemIds);
1435
        return responseSender.ok(pineLabsOffers);
1436
    }
1437
 
36591 vikas 1438
    @RequestMapping(value = "/pinelabs/offers/downpayment", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
1439
    public ResponseEntity<?> getPineLabsDownpaymentDetails(@RequestBody DownpaymentDetailsRequest request) {
1440
        logger.info("pinelabs downpayment details request");
1441
        DownpaymentDetailsResponse response = pinelabsAffordabilityService.getDownpaymentDetails(request);
1442
        return responseSender.ok(response);
1443
    }
1444
 
1445
    @RequestMapping(value = "/pinelabs/offers/cardless", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
1446
    public ResponseEntity<?> getPineLabsCardlessOffers(@RequestBody OfferDiscoveryRequest offerDiscoveryRequest) {
1447
        logger.info("pinelabs cardless discovery request {}", offerDiscoveryRequest);
1448
        OfferDiscoveryResponse response = pinelabsAffordabilityService.discoverCardlessOffers(offerDiscoveryRequest);
1449
        return responseSender.ok(response);
1450
    }
1451
 
1452
    @RequestMapping(value = "/pinelabs/offers/validate", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
1453
    public ResponseEntity<?> validatePineLabsOffer(@RequestBody OfferValidateRequest request) {
1454
        logger.info("pinelabs offer validate request");
1455
        OfferValidateResponse response = pinelabsAffordabilityService.validateOffer(request);
1456
        return responseSender.ok(response);
1457
    }
1458
 
1459
    @RequestMapping(value = "/pinelabs/offers/create", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
1460
    public ResponseEntity<?> createPineLabsOffer(@RequestBody PineLablsCreateOfferRequest request) {
1461
        logger.info("pinelabs create offer request for orderId {}", request.getOrderId());
1462
        CreateOfferResponse response = pinelabsAffordabilityService.createOffer(request);
1463
        return responseSender.ok(response);
1464
    }
1465
 
1466
    @RequestMapping(value = "/pinelabs/imei/{orderId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
1467
    public ResponseEntity<?> validateImei(@PathVariable String orderId, @RequestBody Map<String, String> body) {
1468
        String imei = body.get("imei");
1469
        logger.info("pinelabs IMEI validation for orderId {} imei {}", orderId, imei);
1470
        ImeiValidationResponse response = pinelabsDeviceService.validateImei(orderId, imei);
1471
        return responseSender.ok(response);
1472
    }
1473
 
25967 amit.gupta 1474
}