Subversion Repositories SmartDukaan

Rev

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