Subversion Repositories SmartDukaan

Rev

Rev 33487 | Rev 33573 | 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)
320
    public ResponseEntity<?> getFofo(HttpServletRequest request, @RequestParam(value = "categoryId", required = false, defaultValue = "3") String categoryId, @RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String 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 321
        List<FofoCatalogResponse> dealResponse;
32339 tejbeer 322
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
323
        FofoStore fs = fofoStoreRepository.selectByRetailerId(userInfo.getRetailerId());
324
        sort = "w" + fs.getWarehouseId() + "_i desc";
31548 tejbeer 325
 
32339 tejbeer 326
        logger.info("endPoint {}", endPoint);
31552 tejbeer 327
 
32339 tejbeer 328
        if (endPoint != null && !endPoint.trim().isEmpty()) {
329
            WebListing webListing = webListingRepository.selectByUrl(endPoint);
330
            dealResponse = this.getDealResponses(userInfo, webListing, offset, limit);
31552 tejbeer 331
 
32339 tejbeer 332
        } else {
31552 tejbeer 333
 
32339 tejbeer 334
            dealResponse = this.getCatalogResponse(
335
                    solrService.getSolrDocs(queryTerm, categoryId, offset, limit, sort, brand, subCategoryId, hotDeal), hotDeal, userInfo.getRetailerId());
336
        }
337
        logger.info("log me");
338
        return responseSender.ok(dealResponse);
339
    }
25015 amit.gupta 340
 
32339 tejbeer 341
    @RequestMapping(value = "/online-deals", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
342
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
343
    @ApiOperation(value = "Get online deals")
344
    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 {
345
        logger.info("Request " + request.getParameterMap());
346
        String response = null;
347
        int userId = (int) request.getAttribute("userId");
22289 amit.gupta 348
 
32339 tejbeer 349
        String uri = "/deals/" + userId;
350
        RestClient rc = new RestClient();
351
        Map<String, String> params = new HashMap<>();
352
        params.put("offset", offset);
353
        params.put("limit", limit);
354
        params.put("categoryId", categoryId);
355
        params.put("direction", direction);
356
        params.put("sort", sort);
357
        params.put("source", "online");
358
        params.put("filterData", filterData);
359
        /*
360
         * if (userInfo.getRoleNames().contains(RoleType.FOFO.toString())) {
361
         * params.put("tag_ids", getCommaSeparateTags(userId)); }
362
         */
363
        List<Object> responseObject = new ArrayList<>();
364
        try {
365
            response = rc.get(SchemeType.HTTP, host, port, uri, params);
366
        } catch (HttpHostConnectException e) {
367
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
368
        }
22931 ashik.ali 369
 
32339 tejbeer 370
        JsonArray result_json = Json.parse(response).asArray();
371
        for (JsonValue j : result_json) {
372
            // logger.info("res " + j.asArray());
373
            List<Object> innerObject = new ArrayList<>();
374
            for (JsonValue jsonObject : j.asArray()) {
375
                innerObject.add(toDealObject(jsonObject.asObject()));
376
            }
377
            if (innerObject.size() > 0) {
378
                responseObject.add(innerObject);
379
            }
380
        }
381
        return responseSender.ok(responseObject);
382
    }
22272 amit.gupta 383
 
32339 tejbeer 384
    private Object toDealObject(JsonObject jsonObject) {
385
        if (jsonObject.get("dealObject") != null && jsonObject.get("dealObject").asInt() == 1) {
386
            return new Gson().fromJson(jsonObject.toString(), DealObjectResponse.class);
387
        }
388
        return new Gson().fromJson(jsonObject.toString(), DealsResponse.class);
389
    }
22319 amit.gupta 390
 
32339 tejbeer 391
    @RequestMapping(value = ProfitMandiConstants.URL_BRANDS, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
392
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
393
    @ApiOperation(value = "Get brand list and count for category")
394
    public ResponseEntity<?> getBrands(HttpServletRequest request, @RequestParam(value = "category_id") String category_id) throws ProfitMandiBusinessException {
395
        logger.info("Request " + request.getParameterMap());
396
        String response = null;
397
        // TODO: move to properties
398
        String uri = ProfitMandiConstants.URL_BRANDS;
399
        RestClient rc = new RestClient();
400
        Map<String, String> params = new HashMap<>();
401
        params.put("category_id", category_id);
402
        List<DealBrands> dealBrandsResponse = null;
403
        try {
404
            response = rc.get(SchemeType.HTTP, host, port, uri, params);
405
        } catch (HttpHostConnectException e) {
406
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
407
        }
23816 amit.gupta 408
 
32339 tejbeer 409
        dealBrandsResponse = new Gson().fromJson(response, new TypeToken<List<DealBrands>>() {
410
        }.getType());
23022 ashik.ali 411
 
32339 tejbeer 412
        return responseSender.ok(dealBrandsResponse);
413
    }
22319 amit.gupta 414
 
32339 tejbeer 415
    @RequestMapping(value = ProfitMandiConstants.URL_UNIT_DEAL, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
416
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
417
    @ApiOperation(value = "Get unit deal object")
418
    public ResponseEntity<?> getUnitDeal(HttpServletRequest request, @PathVariable(value = "id") long id) throws ProfitMandiBusinessException {
419
        String response = null;
420
        // TODO: move to properties
421
        String uri = "getDealById/" + id;
422
        System.out.println("Unit deal " + uri);
423
        RestClient rc = new RestClient();
424
        Map<String, String> params = new HashMap<>();
425
        DealsResponse dealsResponse = null;
426
        try {
427
            response = rc.get(SchemeType.HTTP, host, port, uri, params);
428
        } catch (HttpHostConnectException e) {
429
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
430
        }
23816 amit.gupta 431
 
32339 tejbeer 432
        JsonObject result_json = Json.parse(response).asObject();
433
        if (!result_json.isEmpty()) {
434
            dealsResponse = new Gson().fromJson(response, DealsResponse.class);
435
            Iterator<AvailabilityInfo> iter = dealsResponse.getAvailabilityInfo().iterator();
436
            while (iter.hasNext()) {
437
                AvailabilityInfo ai = iter.next();
438
                if (ai.getAvailability() <= 0)
439
                    iter.remove();
440
            }
441
        }
442
        return responseSender.ok(dealsResponse);
443
    }
23816 amit.gupta 444
 
32339 tejbeer 445
    @RequestMapping(value = "/partnerdeals/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
446
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
447
    @ApiOperation(value = "Get unit deal object")
448
    public ResponseEntity<?> getUnitFocoDeal(HttpServletRequest request, @PathVariable(value = "id") long id) throws Exception {
449
        List<FofoCatalogResponse> dealResponse = new ArrayList<>();
450
        List<Integer> tagIds = Arrays.asList(4);
451
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
452
        if (roleManagerService.isPartner(userInfo.getRoleIds())) {
453
            String categoryId = "(3 OR 6)";
454
            UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
455
            RestClient rc = new RestClient();
456
            Map<String, String> params = new HashMap<>();
457
            List<String> mandatoryQ = new ArrayList<>();
458
            String catalogString = "catalog" + id;
24091 tejbeer 459
 
32339 tejbeer 460
            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 461
 
32339 tejbeer 462
            params.put("q", StringUtils.join(mandatoryQ, " "));
463
            params.put("fl", "*, [child parentFilter=id:catalog*]");
464
            params.put("sort", "rank_i asc, create_s desc");
465
            params.put("wt", "json");
466
            String response = null;
467
            try {
33487 amit.gupta 468
                response = rc.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
32339 tejbeer 469
            } catch (HttpHostConnectException e) {
470
                throw new ProfitMandiBusinessException("", "", "Could not connect to host");
471
            }
472
            JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
473
            JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
474
            dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId());
475
        } else {
476
            return responseSender.badRequest(
477
                    new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
478
        }
479
        return responseSender.ok(dealResponse.get(0));
480
    }
24091 tejbeer 481
 
32339 tejbeer 482
    @RequestMapping(value = "/fofo/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
483
    public ResponseEntity<?> getBrandsToDisplay(HttpServletRequest request, @RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {
484
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
485
        logger.info("userInfo [{}]", userInfo);
32717 ranu 486
        List<BrandCatalog> brandsDisplay = brandsService.getBrandsToDisplay(categoryId);
487
        //List<DBObject> brandsDisplay = mongoClient.getMongoBrands(userInfo.getRetailerId(), userInfo.getEmail(), categoryId);
32339 tejbeer 488
        return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
489
    }
25879 amit.gupta 490
 
32339 tejbeer 491
    @RequestMapping(value = "/fofo/brandCatalog", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
492
    public ResponseEntity<?> getBrands(HttpServletRequest request, @RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {
493
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
494
        logger.info("userInfo [{}]", userInfo);
31507 tejbeer 495
 
32339 tejbeer 496
        List<BrandCatalog> brandsDisplay = brandsService.getBrands(userInfo.getRetailerId(), userInfo.getEmail(), categoryId);
497
        return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
498
    }
31507 tejbeer 499
 
32339 tejbeer 500
    @RequestMapping(value = "/fofo/accessory/all-categories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
501
    public ResponseEntity<?> getSubCategoriesToDisplay(HttpServletRequest request) throws Exception {
502
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
503
        logger.info("userInfo [{}]", userInfo);
504
        List<DBObject> subCategoriesDisplay = this.getSubCategoriesToDisplay();
505
        return new ResponseEntity<>(subCategoriesDisplay, HttpStatus.OK);
506
    }
23816 amit.gupta 507
 
32339 tejbeer 508
    private List<DBObject> getSubCategoriesToDisplay() throws Exception {
509
        List<DBObject> subCategories = new ArrayList<>();
510
        RestClient rc = new RestClient();
511
        Map<String, String> params = new HashMap<>();
512
        params.put("q", "categoryId_i:6");
513
        params.put("group", "true");
514
        params.put("group.field", "subCategoryId_i");
515
        params.put("wt", "json");
516
        params.put("rows", "50");
517
        params.put("fl", "subCategoryId_i");
518
        String response = null;
519
        try {
33487 amit.gupta 520
            response = rc.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
32339 tejbeer 521
        } catch (HttpHostConnectException e) {
522
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
523
        }
524
        JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("grouped");
525
        JSONArray groups = solrResponseJSONObj.getJSONObject("subCategoryId_i").getJSONArray("groups");
526
        List<Integer> categoryIds = new ArrayList<>();
527
        for (int i = 0; i < groups.length(); i++) {
528
            JSONObject groupObject = groups.getJSONObject(i);
529
            int subCategoryId = groupObject.getInt("groupValue");
530
            int quantity = groupObject.getJSONObject("doclist").getInt("numFound");
531
            categoryIds.add(subCategoryId);
532
        }
25015 amit.gupta 533
 
32339 tejbeer 534
        List<Category> categories = categoryRepository.selectByIds(categoryIds);
535
        AtomicInteger i = new AtomicInteger(0);
536
        categories.forEach(x -> {
537
            DBObject dbObject = new BasicDBObject();
538
            dbObject.put("name", x.getLabel());
539
            dbObject.put("subCategoryId", x.getId());
540
            dbObject.put("rank", i.incrementAndGet());
541
            dbObject.put("categoryId", 6);
542
            dbObject.put("url", "https://images.smartdukaan.com/uploads/campaigns/" + x.getId() + ".png");
543
            subCategories.add(dbObject);
544
        });
25015 amit.gupta 545
 
32339 tejbeer 546
        return subCategories;
25015 amit.gupta 547
 
32339 tejbeer 548
    }
25010 amit.gupta 549
 
32339 tejbeer 550
    @RequestMapping(value = "/banners/{bannerType}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
551
    public ResponseEntity<?> getBanners(@PathVariable String bannerType) {
552
        return new ResponseEntity<>(mongoClient.getBannersByType(bannerType), HttpStatus.OK);
553
    }
23816 amit.gupta 554
 
32339 tejbeer 555
    @RequestMapping(value = "/deals/subCategories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
556
    public ResponseEntity<?> getSubcategoriesToDisplay() {
557
        return new ResponseEntity<>(mongoClient.getSubcategoriesToDisplay(), HttpStatus.OK);
558
    }
23816 amit.gupta 559
 
32339 tejbeer 560
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
561
    @RequestMapping(value = "/deals/skus/{skus}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
562
    public ResponseEntity<?> getDealsBySkus(@PathVariable String skus) throws ProfitMandiBusinessException {
563
        StringBuffer sb = new StringBuffer("/getDealsForNotification/");
564
        String uri = sb.append(skus).toString();
565
        RestClient rc = new RestClient();
566
        String response;
567
        try {
568
            response = rc.get(SchemeType.HTTP, host, port, uri, new HashMap<>());
569
        } catch (HttpHostConnectException e) {
570
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
571
        }
572
        JsonArray result_json = Json.parse(response).asArray();
573
        List<Object> responseObject = new ArrayList<>();
574
        for (JsonValue j : result_json) {
575
            // logger.info("res " + j.asArray());
576
            List<Object> innerObject = new ArrayList<>();
577
            for (JsonValue jsonObject : j.asArray()) {
578
                innerObject.add(toDealObject(jsonObject.asObject()));
579
            }
580
            if (innerObject.size() > 0) {
581
                responseObject.add(innerObject);
582
            }
583
        }
584
        return responseSender.ok(responseObject);
585
    }
21339 kshitij.so 586
 
32339 tejbeer 587
    @RequestMapping(value = "/partner/listing", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
588
    public ResponseEntity<?> getPartnersListing(HttpServletRequest request) throws Exception {
589
        List<WebListing> webListings = webListingRepository.selectAllWebListingByType(Optional.of(true), WebListingSource.partner);
590
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
591
        for (WebListing webListing : webListings) {
31642 tejbeer 592
 
32339 tejbeer 593
            webListing.setFofoCatalogResponses(getDealResponses(userInfo, webListing, "0", "20"));
594
        }
595
        return responseSender.ok(webListings);
596
    }
31547 tejbeer 597
 
32339 tejbeer 598
    private List<FofoCatalogResponse> getDealResponses(UserInfo userInfo, WebListing webListing, String offset, String limit) throws Exception {
31572 tejbeer 599
 
32339 tejbeer 600
        RestClient rc = new RestClient();
601
        Map<String, String> params = new HashMap<>();
602
        List<String> mandatoryQ = new ArrayList<>();
31670 tejbeer 603
 
32339 tejbeer 604
        FofoStore fs = fofoStoreRepository.selectByRetailerId(userInfo.getRetailerId());
31670 tejbeer 605
 
32339 tejbeer 606
        params.put("sort", "w" + fs.getWarehouseId() + "_i desc");
31576 tejbeer 607
 
32339 tejbeer 608
        List<Integer> webProducts = null;
609
        if (webListing.getType().equals(WebListingType.solr)) {
610
            logger.info("solrtype {}", webListing.getSolrQuery());
611
            mandatoryQ.add(String.format("+{!parent which=\"" + webListing.getSolrQuery() + "\"} AND active_b:true AND show_default_b:true"));
612
        } else {
613
            logger.info("solrtype2 {}", webListing.getSolrQuery());
31675 tejbeer 614
 
32339 tejbeer 615
            webProducts = webProductListingRepository.selectAllByWebListingId(webListing.getId(), Integer.parseInt(offset), Integer.parseInt(limit)).stream().filter(x -> x.getRank() > 0).map(x -> x.getEntityId()).collect(Collectors.toList());
31572 tejbeer 616
 
32339 tejbeer 617
            if (webProducts.size() == 0) {
618
                return new ArrayList<>();
619
            }
31572 tejbeer 620
 
32339 tejbeer 621
            mandatoryQ.add(String.format(
622
                    "+{!parent which=\"catalogId_i:" + StringUtils.join(webProducts, " ") + "\"} AND active_b:true AND show_default_b:true"));
31642 tejbeer 623
 
32339 tejbeer 624
        }
625
        params.put("q", StringUtils.join(mandatoryQ, " "));
626
        params.put("fl", "*, [child parentFilter=id:catalog* childFilter=active_b:true ]");
31612 tejbeer 627
 
32339 tejbeer 628
        params.put("start", String.valueOf(offset));
629
        params.put("rows", String.valueOf(limit));
630
        params.put("wt", "json");
631
        String response = null;
632
        try {
633
            response = rc.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
634
        } catch (HttpHostConnectException e) {
635
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
636
        }
637
        JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
638
        JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
639
        List<FofoCatalogResponse> dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId());
31671 tejbeer 640
 
32339 tejbeer 641
        if (webProducts != null && webListing.getUrl().equals("new-launches")) {
642
            List<Integer> webProductsFinal = webProducts;
643
            dealResponse = dealResponse.stream().sorted(Comparator.comparing(x -> webProductsFinal.indexOf(x.getCatalogId()))).collect(Collectors.toList());
31671 tejbeer 644
 
32339 tejbeer 645
        }
31547 tejbeer 646
 
32339 tejbeer 647
        return dealResponse;
648
    }
30669 amit.gupta 649
 
32339 tejbeer 650
    @Autowired
651
    private SaholicCISTableRepository saholicCISTableRepository;
27053 amit.gupta 652
 
32339 tejbeer 653
    private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal, int fofoId) throws Exception {
654
        List<FofoCatalogResponse> dealResponse = new ArrayList<>();
655
        List<Integer> tagIds = Arrays.asList(4);
656
        List<Integer> itemIds = new ArrayList<>();
657
        if (docs.length() > 0) {
658
            for (int i = 0; i < docs.length(); i++) {
659
                JSONObject doc = docs.getJSONObject(i);
660
                if (doc.has("_childDocuments_")) {
661
                    for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
662
                        JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
663
                        int itemId = childItem.getInt("itemId_i");
664
                        itemIds.add(itemId);
665
                    }
666
                }
667
            }
668
            if (itemIds.size() == 0) {
669
                return dealResponse;
670
            }
671
        }
672
        // get warehouse Id
673
        int warehouseId = fofoStoreRepository.selectByRetailerId(fofoId).getWarehouseId();
674
        Map<Integer, List<SaholicPOItem>> poItemAvailabilityMap = saholicInventoryService.getSaholicPOItems().get(warehouseId);
675
        List<Integer> catalogIds = new ArrayList<>();
676
        for (int i = 0; i < docs.length(); i++) {
677
            Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
678
            JSONObject doc = docs.getJSONObject(i);
679
            catalogIds.add(doc.getInt("catalogId_i"));
680
        }
681
        List<CreateOfferRequest> allSchemOffers = null;
682
        Map<Integer, PriceCircularItemModelNew> priceCircularItemModelMap = new HashMap<>();
683
        if (catalogIds.size() > 0) {
684
            PriceCircularModel priceCircularModel = priceCircularService.getPriceCircularByOffer(fofoId, catalogIds, LocalDate.now());
685
            allSchemOffers = priceCircularModel.getOffers();
30188 amit.gupta 686
 
32339 tejbeer 687
            List<PriceCircularItemModelNew> priceCircularItemModelNews = priceCircularModel.getPriceCircularItemModelNews();
688
            if (priceCircularItemModelNews != null) {
689
                priceCircularItemModelMap = priceCircularItemModelNews.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));
690
            }
691
        }
31629 tejbeer 692
 
32339 tejbeer 693
        List<CatalogFavourite> catalogFavourites = catalogFavouriteRepository.selectBypartnerId(fofoId);
694
        List<Integer> catalogFavouriteIds = new ArrayList<>();
695
        if (!catalogFavourites.isEmpty()) {
696
            catalogFavouriteIds = catalogFavourites.stream().map(x -> x.getCatalogId()).collect(Collectors.toList());
697
        }
31629 tejbeer 698
 
32339 tejbeer 699
        if (!catalogFavourites.isEmpty()) {
700
            catalogFavourites.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));
701
        }
30595 tejbeer 702
 
32339 tejbeer 703
        for (int i = 0; i < docs.length(); i++) {
704
            Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
705
            JSONObject doc = docs.getJSONObject(i);
706
            FofoCatalogResponse fofoCatalogResponse = new FofoCatalogResponse();
707
            fofoCatalogResponse.setCatalogId(doc.getInt("catalogId_i"));
708
            fofoCatalogResponse.setImageUrl(doc.getString("imageUrl_s"));
709
            fofoCatalogResponse.setTitle(doc.getString("title_s"));
31629 tejbeer 710
 
32339 tejbeer 711
            if (catalogFavouriteIds.contains(fofoCatalogResponse.getCatalogId())) {
712
                fofoCatalogResponse.setFavourite(true);
713
            }
30683 tejbeer 714
 
32339 tejbeer 715
            List<WebOffer> webOffers = webOfferRepository.selectAllActiveOffers().get(fofoCatalogResponse.getCatalogId());
31612 tejbeer 716
 
32339 tejbeer 717
            logger.info("webOffers {}", webOffers);
718
            if (webOffers != null && webOffers.size() > 0) {
719
                fofoCatalogResponse.setWebOffers(webOffers);
720
                fofoCatalogResponse.setOffers(webOffers.stream().map(x -> x.getTitle()).collect(Collectors.toList()));
30683 tejbeer 721
 
32339 tejbeer 722
            }
30683 tejbeer 723
 
32339 tejbeer 724
            List<ComboModel> comboModels = comboModelRepository.selectByWarehouseId(warehouseId).stream().filter(x -> x.getCatalogId() == fofoCatalogResponse.getCatalogId()).collect(Collectors.toList());
30683 tejbeer 725
 
32339 tejbeer 726
            logger.info("comboModels {}", comboModels);
32344 tejbeer 727
 
32339 tejbeer 728
            if (comboModels != null && comboModels.size() > 0) {
729
                fofoCatalogResponse.setComboModels(comboModels);
730
            }
30683 tejbeer 731
 
32339 tejbeer 732
            try {
733
                fofoCatalogResponse.setFeature(doc.getString("feature_s"));
734
            } catch (Exception e) {
735
                fofoCatalogResponse.setFeature(null);
736
                logger.info("Could not find Feature_s for {}", fofoCatalogResponse.getCatalogId());
737
            }
30683 tejbeer 738
 
32339 tejbeer 739
            fofoCatalogResponse.setBrand(doc.getJSONArray("brand_ss").getString(0));
740
            logger.info("labelss {}", doc.has("label_ss"));
30683 tejbeer 741
 
32339 tejbeer 742
            if (doc.has("label_ss")) {
743
                logger.info("label {}", doc.getJSONArray("label_ss"));
30683 tejbeer 744
 
32339 tejbeer 745
                JSONArray arr = doc.getJSONArray("label_ss");
746
                Set<String> labels = new HashSet<String>();
747
                for (int j = 0; j < arr.length(); j++) {
748
                    labels.add(arr.getString(j));
749
                }
31612 tejbeer 750
 
32339 tejbeer 751
                fofoCatalogResponse.setLabels(new ArrayList<>(labels));
31612 tejbeer 752
 
32339 tejbeer 753
            }
31612 tejbeer 754
 
32339 tejbeer 755
            if (doc.has("_childDocuments_")) {
756
                String modelColorClass = "grey";
757
                FofoAvailabilityInfo fdiAnyColour = null;
758
                // Iterating itemIds
759
                for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
760
                    PriceCircularItemModelNew priceCircularItemModel = priceCircularItemModelMap.get(fofoCatalogResponse.getCatalogId());
761
                    JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
762
                    int itemId = childItem.getInt("itemId_i");
763
                    float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
764
                    if (!fofoAvailabilityInfoMap.containsKey(itemId)) {
765
                        FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
766
                        List<SaholicCISTable> currentAvailability = saholicCISTableRepository.selectByItemWarehouse(itemId, warehouseId);
767
                        List<SaholicPOItem> poItemAvailability = null;
768
                        if (poItemAvailabilityMap != null) {
769
                            poItemAvailability = poItemAvailabilityMap.get(itemId);
770
                        }
31612 tejbeer 771
 
32339 tejbeer 772
                        if (priceCircularItemModel != null) {
33410 ranu 773
                            fdi.setNlc((float) priceCircularItemModel.getNetNlc());
32339 tejbeer 774
                        }
31612 tejbeer 775
 
32339 tejbeer 776
                        for (SaholicCISTable saholicCISTable : currentAvailability) {
777
                            saholicCISTable.setWarehouseName(
778
                                    ProfitMandiConstants.WAREHOUSE_MAP.get(saholicCISTable.getWarehouseFrom()));
779
                        }
31612 tejbeer 780
 
32339 tejbeer 781
                        Map<Integer, SaholicCISTable> map = currentAvailability.stream().collect(Collectors.toMap(SaholicCISTable::getWarehouseFrom, x -> x));
782
                        if (poItemAvailability != null) {
783
                            for (SaholicPOItem saholicPOItem : poItemAvailability) {
784
                                if (map.containsKey(saholicPOItem.getWarehouseFrom())) {
785
                                    map.get(saholicPOItem.getWarehouseFrom()).setPopendingQty(saholicPOItem.getUnfulfilledQty());
786
                                } else {
787
                                    SaholicCISTable saholicCISTable = new SaholicCISTable();
788
                                    saholicCISTable.setAvailability(0);
789
                                    saholicCISTable.setReserved(0);
790
                                    saholicCISTable.setItemId(itemId);
791
                                    saholicCISTable.setWarehouseId(warehouseId);
792
                                    saholicCISTable.setPopendingQty(saholicPOItem.getUnfulfilledQty());
793
                                    saholicCISTable.setWarehouseFrom(saholicPOItem.getWarehouseFrom());
794
                                    saholicCISTable.setWarehouseName(
795
                                            ProfitMandiConstants.WAREHOUSE_MAP.get(saholicPOItem.getWarehouseFrom()));
796
                                    map.put(saholicPOItem.getWarehouseFrom(), saholicCISTable);
797
                                }
798
                            }
799
                        }
800
                        fdi.setSaholicCISTableList(new ArrayList<>(map.values()));
801
                        String poColor = "grey";
802
                        boolean active = false;
803
                        if (currentAvailability != null && currentAvailability.stream().collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)) > 0) {
804
                            poColor = "green";
805
                            modelColorClass = "green";
32978 amit.gupta 806
                        } else if (poItemAvailability != null && poItemAvailability.stream().collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty)) > 0) {
807
                            if (currentAvailability != null && poItemAvailability.stream().collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty)) + currentAvailability.stream().collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)) <= 0) {
808
                                poColor = "grey";
809
                            } else {
810
                                poColor = "yellow";
811
                                if (modelColorClass != "green") {
812
                                    modelColorClass = poColor;
32339 tejbeer 813
                                }
814
                            }
32978 amit.gupta 815
                        }
32339 tejbeer 816
                        fdi.setColorClass(poColor);
817
                        fdi.setSellingPrice(sellingPrice);
818
                        fdi.setActive(active);
819
                        fdi.setMrp(childItem.getDouble("mrp_f"));
820
                        fdi.setMop((float) childItem.getDouble("mop_f"));
821
                        fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
822
                        if (fdi.getColor().equalsIgnoreCase("any colour")) {
823
                            fdiAnyColour = fdi;
824
                        }
825
                        fdi.setTagId(childItem.getInt("tagId_i"));
826
                        fdi.setItem_id(itemId);
32978 amit.gupta 827
                        Float cashBack = schemeService.getCatalogSchemeCashBack(fofoId, Arrays.asList(fofoCatalogResponse.getCatalogId())).get(fofoCatalogResponse.getCatalogId());
32339 tejbeer 828
                        cashBack = cashBack == null ? 0 : cashBack;
829
                        fdi.setCashback(cashBack);
830
                        fdi.setMinBuyQuantity(1);
831
                        if (hotDeal) {
832
                            if (currentAvailability != null) {
833
                                fdi.setAvailability(currentAvailability.stream().collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)));
834
                            } else {
835
                                fdi.setAvailability(0);
836
                            }
837
                        } else {
838
                            // Lets consider that its out of stock
32591 amit.gupta 839
                            fdi.setAvailability(400);
32339 tejbeer 840
                            Item item = null;
841
                            try {
842
                                item = itemRepository.selectById(itemId);
843
                            } catch (Exception e) {
844
                                e.printStackTrace();
845
                                continue;
846
                            }
847
                            // In case its tampered glass moq should be
848
                            if (item.getCategoryId() == 10020) {
849
                                fdi.setMinBuyQuantity(5);
850
                            }
851
                        }
852
                        fdi.setQuantityStep(1);
32590 amit.gupta 853
                        fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 400));
32339 tejbeer 854
                        fofoAvailabilityInfoMap.put(itemId, fdi);
855
                    }
856
                }
857
                if (fdiAnyColour != null) {
858
                    fdiAnyColour.setColorClass(modelColorClass);
859
                }
860
            }
861
            if (fofoAvailabilityInfoMap.values().size() > 0) {
862
                List<FofoAvailabilityInfo> availabilityList = fofoAvailabilityInfoMap.values().stream().sorted(Comparator.comparing(FofoAvailabilityInfo::getAvailability).reversed()).collect(Collectors.toList());
863
                fofoCatalogResponse.setItems(availabilityList);
864
                if (priceCircularItemModelMap.containsKey(fofoCatalogResponse.getCatalogId())) {
865
                    PriceCircularItemModelNew priceCircularItemModel = priceCircularItemModelMap.get(fofoCatalogResponse.getCatalogId());
866
                    if (priceCircularItemModel.getSlabPayouts() != null) {
867
                        List<CreateOfferRequest> schemeOffers = new ArrayList<>();
868
                        List<Map<Integer, AmountModel>> slabPayouts = priceCircularItemModel.getSlabPayouts();
869
                        Iterator<Map<Integer, AmountModel>> iterator = slabPayouts.iterator();
870
                        int iteratorCount = 0;
871
                        while (iterator.hasNext()) {
872
                            Map<Integer, AmountModel> slabPayoutMap = iterator.next();
873
                            if (slabPayoutMap != null) {
874
                                schemeOffers.add(allSchemOffers.get(iteratorCount));
875
                            } else {
876
                                iterator.remove();
877
                            }
878
                            iteratorCount++;
879
                        }
880
                        fofoCatalogResponse.setSchemeOffers(schemeOffers);
881
                    }
882
                    fofoCatalogResponse.setPriceCircularItemModel(priceCircularItemModel);
883
                }
884
                dealResponse.add(fofoCatalogResponse);
885
            }
886
        }
887
        return dealResponse;
30686 amit.gupta 888
 
32339 tejbeer 889
    }
30693 amit.gupta 890
 
32339 tejbeer 891
    private List<FofoCatalogResponse> getCatalogSingleSkuResponse(JSONArray docs, Map<Integer, Integer> itemFilter, boolean hotDeal) throws ProfitMandiBusinessException {
892
        Map<Integer, TagListing> itemTagListingMap = null;
893
        List<FofoCatalogResponse> dealResponse = new ArrayList<>();
894
        List<Integer> tagIds = Arrays.asList(4);
24091 tejbeer 895
 
32339 tejbeer 896
        itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemFilter.keySet(), new HashSet<>(tagIds)).stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x));
24091 tejbeer 897
 
32339 tejbeer 898
        for (int i = 0; i < docs.length(); i++) {
899
            Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
900
            JSONObject doc = docs.getJSONObject(i);
26589 amit.gupta 901
 
32339 tejbeer 902
            for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
903
                JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
904
                int itemId = childItem.getInt("itemId_i");
905
                TagListing tl = itemTagListingMap.get(itemId);
906
                if (tl == null) {
907
                    continue;
908
                }
909
                if (hotDeal) {
910
                    if (!tl.isHotDeals()) {
911
                        continue;
912
                    }
913
                }
914
                float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
915
                if (fofoAvailabilityInfoMap.containsKey(itemId)) {
916
                    if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
917
                        fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
918
                        fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
919
                    }
920
                } else {
921
                    FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
922
                    fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
923
                    fdi.setMop((float) childItem.getDouble("mop_f"));
924
                    fdi.setMop((float) tl.getMrp());
925
                    fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
926
                    fdi.setTagId(childItem.getInt("tagId_i"));
927
                    fdi.setItem_id(itemId);
928
                    Item item = itemRepository.selectById(itemId);
929
                    // In case its tampered glass moq should be 5
930
                    if (item.getCategoryId() == 10020) {
931
                        fdi.setMinBuyQuantity(10);
932
                    } else {
933
                        fdi.setMinBuyQuantity(1);
934
                    }
935
                    fdi.setAvailability(itemFilter.get(itemId));
936
                    fdi.setQuantityStep(1);
937
                    fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
938
                    fofoAvailabilityInfoMap.put(itemId, fdi);
939
                }
940
            }
941
            if (fofoAvailabilityInfoMap.values().size() > 0) {
942
                for (FofoAvailabilityInfo fofoAvailabilityInfo : fofoAvailabilityInfoMap.values()) {
943
                    FofoCatalogResponse ffdr = new FofoCatalogResponse();
944
                    ffdr.setCatalogId(doc.getInt("catalogId_i"));
945
                    ffdr.setImageUrl(doc.getString("imageUrl_s"));
946
                    ffdr.setTitle(doc.getString("title_s"));
947
                    try {
948
                        ffdr.setFeature(doc.getString("feature_s"));
949
                    } catch (Exception e) {
950
                        ffdr.setFeature(null);
951
                        logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
952
                    }
953
                    ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
954
                    ffdr.setItems(Arrays.asList(fofoAvailabilityInfo));
955
                    dealResponse.add(ffdr);
956
                }
957
            }
958
        }
959
        return dealResponse;
25880 amit.gupta 960
 
32339 tejbeer 961
    }
25880 amit.gupta 962
 
32339 tejbeer 963
    @RequestMapping(value = "/combo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
964
    public ResponseEntity<?> getBanners(@RequestParam int catalogId, @RequestParam int warehouseId) {
965
        List<ComboModel> comboModels = comboModelRepository.selectByCatalogIdAndWarehouseId(catalogId, warehouseId);
966
        return responseSender.ok(comboModels);
967
    }
32344 tejbeer 968
 
969
    @RequestMapping(value = "/checkCombo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
970
    public ResponseEntity<?> checkCombo(HttpServletRequest request, @RequestParam int catalogId, @RequestParam int warehouseId, @RequestParam int qty) throws Exception {
971
        boolean isCombo = false;
972
        ComboModel comboModel = comboModelRepository.selectByCatalogIdWarehouseIdAndQty(catalogId, warehouseId, qty);
973
        if (comboModel != null) {
974
            isCombo = true;
975
        }
976
 
977
        return responseSender.ok(isCombo);
978
    }
979
 
980
 
25967 amit.gupta 981
}