Subversion Repositories SmartDukaan

Rev

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