Subversion Repositories SmartDukaan

Rev

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