Subversion Repositories SmartDukaan

Rev

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