Subversion Repositories SmartDukaan

Rev

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