Subversion Repositories SmartDukaan

Rev

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