Subversion Repositories SmartDukaan

Rev

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