Subversion Repositories SmartDukaan

Rev

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