Subversion Repositories SmartDukaan

Rev

Rev 35412 | Rev 35458 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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