Subversion Repositories SmartDukaan

Rev

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