Subversion Repositories SmartDukaan

Rev

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