Subversion Repositories SmartDukaan

Rev

Rev 32591 | Rev 32978 | 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);
32717 ranu 497
        List<BrandCatalog> brandsDisplay = brandsService.getBrandsToDisplay(categoryId);
498
        //List<DBObject> brandsDisplay = mongoClient.getMongoBrands(userInfo.getRetailerId(), userInfo.getEmail(), categoryId);
32339 tejbeer 499
        return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
500
    }
25879 amit.gupta 501
 
32339 tejbeer 502
    @RequestMapping(value = "/fofo/brandCatalog", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
503
    public ResponseEntity<?> getBrands(HttpServletRequest request, @RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {
504
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
505
        logger.info("userInfo [{}]", userInfo);
31507 tejbeer 506
 
32339 tejbeer 507
        List<BrandCatalog> brandsDisplay = brandsService.getBrands(userInfo.getRetailerId(), userInfo.getEmail(), categoryId);
508
        return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
509
    }
31507 tejbeer 510
 
32339 tejbeer 511
    @RequestMapping(value = "/fofo/accessory/all-categories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
512
    public ResponseEntity<?> getSubCategoriesToDisplay(HttpServletRequest request) throws Exception {
513
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
514
        logger.info("userInfo [{}]", userInfo);
515
        List<DBObject> subCategoriesDisplay = this.getSubCategoriesToDisplay();
516
        return new ResponseEntity<>(subCategoriesDisplay, HttpStatus.OK);
517
    }
23816 amit.gupta 518
 
32339 tejbeer 519
    private List<DBObject> getSubCategoriesToDisplay() throws Exception {
520
        List<DBObject> subCategories = new ArrayList<>();
521
        RestClient rc = new RestClient();
522
        Map<String, String> params = new HashMap<>();
523
        params.put("q", "categoryId_i:6");
524
        params.put("group", "true");
525
        params.put("group.field", "subCategoryId_i");
526
        params.put("wt", "json");
527
        params.put("rows", "50");
528
        params.put("fl", "subCategoryId_i");
529
        String response = null;
530
        try {
531
            response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
532
        } catch (HttpHostConnectException e) {
533
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
534
        }
535
        JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("grouped");
536
        JSONArray groups = solrResponseJSONObj.getJSONObject("subCategoryId_i").getJSONArray("groups");
537
        List<Integer> categoryIds = new ArrayList<>();
538
        for (int i = 0; i < groups.length(); i++) {
539
            JSONObject groupObject = groups.getJSONObject(i);
540
            int subCategoryId = groupObject.getInt("groupValue");
541
            int quantity = groupObject.getJSONObject("doclist").getInt("numFound");
542
            categoryIds.add(subCategoryId);
543
        }
25015 amit.gupta 544
 
32339 tejbeer 545
        List<Category> categories = categoryRepository.selectByIds(categoryIds);
546
        AtomicInteger i = new AtomicInteger(0);
547
        categories.forEach(x -> {
548
            DBObject dbObject = new BasicDBObject();
549
            dbObject.put("name", x.getLabel());
550
            dbObject.put("subCategoryId", x.getId());
551
            dbObject.put("rank", i.incrementAndGet());
552
            dbObject.put("categoryId", 6);
553
            dbObject.put("url", "https://images.smartdukaan.com/uploads/campaigns/" + x.getId() + ".png");
554
            subCategories.add(dbObject);
555
        });
25015 amit.gupta 556
 
32339 tejbeer 557
        return subCategories;
25015 amit.gupta 558
 
32339 tejbeer 559
    }
25010 amit.gupta 560
 
32339 tejbeer 561
    @RequestMapping(value = "/banners/{bannerType}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
562
    public ResponseEntity<?> getBanners(@PathVariable String bannerType) {
563
        return new ResponseEntity<>(mongoClient.getBannersByType(bannerType), HttpStatus.OK);
564
    }
23816 amit.gupta 565
 
32339 tejbeer 566
    @RequestMapping(value = "/deals/subCategories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
567
    public ResponseEntity<?> getSubcategoriesToDisplay() {
568
        return new ResponseEntity<>(mongoClient.getSubcategoriesToDisplay(), HttpStatus.OK);
569
    }
23816 amit.gupta 570
 
32339 tejbeer 571
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
572
    @RequestMapping(value = "/deals/skus/{skus}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
573
    public ResponseEntity<?> getDealsBySkus(@PathVariable String skus) throws ProfitMandiBusinessException {
574
        StringBuffer sb = new StringBuffer("/getDealsForNotification/");
575
        String uri = sb.append(skus).toString();
576
        RestClient rc = new RestClient();
577
        String response;
578
        try {
579
            response = rc.get(SchemeType.HTTP, host, port, uri, new HashMap<>());
580
        } catch (HttpHostConnectException e) {
581
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
582
        }
583
        JsonArray result_json = Json.parse(response).asArray();
584
        List<Object> responseObject = new ArrayList<>();
585
        for (JsonValue j : result_json) {
586
            // logger.info("res " + j.asArray());
587
            List<Object> innerObject = new ArrayList<>();
588
            for (JsonValue jsonObject : j.asArray()) {
589
                innerObject.add(toDealObject(jsonObject.asObject()));
590
            }
591
            if (innerObject.size() > 0) {
592
                responseObject.add(innerObject);
593
            }
594
        }
595
        return responseSender.ok(responseObject);
596
    }
21339 kshitij.so 597
 
32339 tejbeer 598
    @RequestMapping(value = "/partner/listing", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
599
    public ResponseEntity<?> getPartnersListing(HttpServletRequest request) throws Exception {
600
        List<WebListing> webListings = webListingRepository.selectAllWebListingByType(Optional.of(true), WebListingSource.partner);
601
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
602
        for (WebListing webListing : webListings) {
31642 tejbeer 603
 
32339 tejbeer 604
            webListing.setFofoCatalogResponses(getDealResponses(userInfo, webListing, "0", "20"));
605
        }
606
        return responseSender.ok(webListings);
607
    }
31547 tejbeer 608
 
32339 tejbeer 609
    private List<FofoCatalogResponse> getDealResponses(UserInfo userInfo, WebListing webListing, String offset, String limit) throws Exception {
31572 tejbeer 610
 
32339 tejbeer 611
        RestClient rc = new RestClient();
612
        Map<String, String> params = new HashMap<>();
613
        List<String> mandatoryQ = new ArrayList<>();
31670 tejbeer 614
 
32339 tejbeer 615
        FofoStore fs = fofoStoreRepository.selectByRetailerId(userInfo.getRetailerId());
31670 tejbeer 616
 
32339 tejbeer 617
        params.put("sort", "w" + fs.getWarehouseId() + "_i desc");
31576 tejbeer 618
 
32339 tejbeer 619
        List<Integer> webProducts = null;
620
        if (webListing.getType().equals(WebListingType.solr)) {
621
            logger.info("solrtype {}", webListing.getSolrQuery());
622
            mandatoryQ.add(String.format("+{!parent which=\"" + webListing.getSolrQuery() + "\"} AND active_b:true AND show_default_b:true"));
623
        } else {
624
            logger.info("solrtype2 {}", webListing.getSolrQuery());
31675 tejbeer 625
 
32339 tejbeer 626
            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 627
 
32339 tejbeer 628
            if (webProducts.size() == 0) {
629
                return new ArrayList<>();
630
            }
31572 tejbeer 631
 
32339 tejbeer 632
            mandatoryQ.add(String.format(
633
                    "+{!parent which=\"catalogId_i:" + StringUtils.join(webProducts, " ") + "\"} AND active_b:true AND show_default_b:true"));
31642 tejbeer 634
 
32339 tejbeer 635
        }
636
        params.put("q", StringUtils.join(mandatoryQ, " "));
637
        params.put("fl", "*, [child parentFilter=id:catalog* childFilter=active_b:true ]");
31612 tejbeer 638
 
32339 tejbeer 639
        params.put("start", String.valueOf(offset));
640
        params.put("rows", String.valueOf(limit));
641
        params.put("wt", "json");
642
        String response = null;
643
        try {
644
            response = rc.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
645
        } catch (HttpHostConnectException e) {
646
            throw new ProfitMandiBusinessException("", "", "Could not connect to host");
647
        }
648
        JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
649
        JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
650
        List<FofoCatalogResponse> dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId());
31671 tejbeer 651
 
32339 tejbeer 652
        if (webProducts != null && webListing.getUrl().equals("new-launches")) {
653
            List<Integer> webProductsFinal = webProducts;
654
            dealResponse = dealResponse.stream().sorted(Comparator.comparing(x -> webProductsFinal.indexOf(x.getCatalogId()))).collect(Collectors.toList());
31671 tejbeer 655
 
32339 tejbeer 656
        }
31547 tejbeer 657
 
32339 tejbeer 658
        return dealResponse;
659
    }
30669 amit.gupta 660
 
32339 tejbeer 661
    @Autowired
662
    private SaholicCISTableRepository saholicCISTableRepository;
27053 amit.gupta 663
 
32339 tejbeer 664
    private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal, int fofoId) throws Exception {
665
        List<FofoCatalogResponse> dealResponse = new ArrayList<>();
666
        List<Integer> tagIds = Arrays.asList(4);
667
        List<Integer> itemIds = new ArrayList<>();
668
        if (docs.length() > 0) {
669
            for (int i = 0; i < docs.length(); i++) {
670
                JSONObject doc = docs.getJSONObject(i);
671
                if (doc.has("_childDocuments_")) {
672
                    for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
673
                        JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
674
                        int itemId = childItem.getInt("itemId_i");
675
                        itemIds.add(itemId);
676
                    }
677
                }
678
            }
679
            if (itemIds.size() == 0) {
680
                return dealResponse;
681
            }
682
        }
683
        // get warehouse Id
684
        int warehouseId = fofoStoreRepository.selectByRetailerId(fofoId).getWarehouseId();
685
        Map<Integer, List<SaholicPOItem>> poItemAvailabilityMap = saholicInventoryService.getSaholicPOItems().get(warehouseId);
686
        List<Integer> catalogIds = new ArrayList<>();
687
        for (int i = 0; i < docs.length(); i++) {
688
            Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
689
            JSONObject doc = docs.getJSONObject(i);
690
            catalogIds.add(doc.getInt("catalogId_i"));
691
        }
692
        List<CreateOfferRequest> allSchemOffers = null;
693
        Map<Integer, PriceCircularItemModelNew> priceCircularItemModelMap = new HashMap<>();
694
        if (catalogIds.size() > 0) {
695
            PriceCircularModel priceCircularModel = priceCircularService.getPriceCircularByOffer(fofoId, catalogIds, LocalDate.now());
696
            allSchemOffers = priceCircularModel.getOffers();
30188 amit.gupta 697
 
32339 tejbeer 698
            List<PriceCircularItemModelNew> priceCircularItemModelNews = priceCircularModel.getPriceCircularItemModelNews();
699
            if (priceCircularItemModelNews != null) {
700
                priceCircularItemModelMap = priceCircularItemModelNews.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));
701
            }
702
        }
31629 tejbeer 703
 
32339 tejbeer 704
        List<CatalogFavourite> catalogFavourites = catalogFavouriteRepository.selectBypartnerId(fofoId);
705
        List<Integer> catalogFavouriteIds = new ArrayList<>();
706
        if (!catalogFavourites.isEmpty()) {
707
            catalogFavouriteIds = catalogFavourites.stream().map(x -> x.getCatalogId()).collect(Collectors.toList());
708
        }
31629 tejbeer 709
 
32339 tejbeer 710
        if (!catalogFavourites.isEmpty()) {
711
            catalogFavourites.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));
712
        }
30595 tejbeer 713
 
32339 tejbeer 714
        for (int i = 0; i < docs.length(); i++) {
715
            Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
716
            JSONObject doc = docs.getJSONObject(i);
717
            FofoCatalogResponse fofoCatalogResponse = new FofoCatalogResponse();
718
            fofoCatalogResponse.setCatalogId(doc.getInt("catalogId_i"));
719
            fofoCatalogResponse.setImageUrl(doc.getString("imageUrl_s"));
720
            fofoCatalogResponse.setTitle(doc.getString("title_s"));
31629 tejbeer 721
 
32339 tejbeer 722
            if (catalogFavouriteIds.contains(fofoCatalogResponse.getCatalogId())) {
723
                fofoCatalogResponse.setFavourite(true);
724
            }
30683 tejbeer 725
 
32339 tejbeer 726
            List<WebOffer> webOffers = webOfferRepository.selectAllActiveOffers().get(fofoCatalogResponse.getCatalogId());
31612 tejbeer 727
 
32339 tejbeer 728
            logger.info("webOffers {}", webOffers);
729
            if (webOffers != null && webOffers.size() > 0) {
730
                fofoCatalogResponse.setWebOffers(webOffers);
731
                fofoCatalogResponse.setOffers(webOffers.stream().map(x -> x.getTitle()).collect(Collectors.toList()));
30683 tejbeer 732
 
32339 tejbeer 733
            }
30683 tejbeer 734
 
32339 tejbeer 735
            List<ComboModel> comboModels = comboModelRepository.selectByWarehouseId(warehouseId).stream().filter(x -> x.getCatalogId() == fofoCatalogResponse.getCatalogId()).collect(Collectors.toList());
30683 tejbeer 736
 
32339 tejbeer 737
            logger.info("comboModels {}", comboModels);
32344 tejbeer 738
 
32339 tejbeer 739
            if (comboModels != null && comboModels.size() > 0) {
740
                fofoCatalogResponse.setComboModels(comboModels);
741
            }
30683 tejbeer 742
 
32339 tejbeer 743
            try {
744
                fofoCatalogResponse.setFeature(doc.getString("feature_s"));
745
            } catch (Exception e) {
746
                fofoCatalogResponse.setFeature(null);
747
                logger.info("Could not find Feature_s for {}", fofoCatalogResponse.getCatalogId());
748
            }
30683 tejbeer 749
 
32339 tejbeer 750
            fofoCatalogResponse.setBrand(doc.getJSONArray("brand_ss").getString(0));
751
            logger.info("labelss {}", doc.has("label_ss"));
30683 tejbeer 752
 
32339 tejbeer 753
            if (doc.has("label_ss")) {
754
                logger.info("label {}", doc.getJSONArray("label_ss"));
30683 tejbeer 755
 
32339 tejbeer 756
                JSONArray arr = doc.getJSONArray("label_ss");
757
                Set<String> labels = new HashSet<String>();
758
                for (int j = 0; j < arr.length(); j++) {
759
                    labels.add(arr.getString(j));
760
                }
31612 tejbeer 761
 
32339 tejbeer 762
                fofoCatalogResponse.setLabels(new ArrayList<>(labels));
31612 tejbeer 763
 
32339 tejbeer 764
            }
31612 tejbeer 765
 
32339 tejbeer 766
            if (doc.has("_childDocuments_")) {
767
                String modelColorClass = "grey";
768
                FofoAvailabilityInfo fdiAnyColour = null;
769
                // Iterating itemIds
770
                for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
771
                    PriceCircularItemModelNew priceCircularItemModel = priceCircularItemModelMap.get(fofoCatalogResponse.getCatalogId());
772
                    JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
773
                    int itemId = childItem.getInt("itemId_i");
774
                    float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
775
                    if (!fofoAvailabilityInfoMap.containsKey(itemId)) {
776
                        FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
777
                        List<SaholicCISTable> currentAvailability = saholicCISTableRepository.selectByItemWarehouse(itemId, warehouseId);
778
                        List<SaholicPOItem> poItemAvailability = null;
779
                        if (poItemAvailabilityMap != null) {
780
                            poItemAvailability = poItemAvailabilityMap.get(itemId);
781
                        }
31612 tejbeer 782
 
32339 tejbeer 783
                        if (priceCircularItemModel != null) {
784
                            fdi.setNlc((float) priceCircularItemModel.getNetNlc());
785
                        }
31612 tejbeer 786
 
32339 tejbeer 787
                        for (SaholicCISTable saholicCISTable : currentAvailability) {
788
                            saholicCISTable.setWarehouseName(
789
                                    ProfitMandiConstants.WAREHOUSE_MAP.get(saholicCISTable.getWarehouseFrom()));
790
                        }
31612 tejbeer 791
 
32339 tejbeer 792
                        Map<Integer, SaholicCISTable> map = currentAvailability.stream().collect(Collectors.toMap(SaholicCISTable::getWarehouseFrom, x -> x));
793
                        if (poItemAvailability != null) {
794
                            for (SaholicPOItem saholicPOItem : poItemAvailability) {
795
                                if (map.containsKey(saholicPOItem.getWarehouseFrom())) {
796
                                    map.get(saholicPOItem.getWarehouseFrom()).setPopendingQty(saholicPOItem.getUnfulfilledQty());
797
                                } else {
798
                                    SaholicCISTable saholicCISTable = new SaholicCISTable();
799
                                    saholicCISTable.setAvailability(0);
800
                                    saholicCISTable.setReserved(0);
801
                                    saholicCISTable.setItemId(itemId);
802
                                    saholicCISTable.setWarehouseId(warehouseId);
803
                                    saholicCISTable.setPopendingQty(saholicPOItem.getUnfulfilledQty());
804
                                    saholicCISTable.setWarehouseFrom(saholicPOItem.getWarehouseFrom());
805
                                    saholicCISTable.setWarehouseName(
806
                                            ProfitMandiConstants.WAREHOUSE_MAP.get(saholicPOItem.getWarehouseFrom()));
807
                                    map.put(saholicPOItem.getWarehouseFrom(), saholicCISTable);
808
                                }
809
                            }
810
                        }
811
                        fdi.setSaholicCISTableList(new ArrayList<>(map.values()));
812
                        String poColor = "grey";
813
                        boolean active = false;
814
                        if (currentAvailability != null && currentAvailability.stream().collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)) > 0) {
815
                            poColor = "green";
816
                            modelColorClass = "green";
817
                        } else
818
                            if (poItemAvailability != null && poItemAvailability.stream().collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty)) > 0) {
819
                                if (currentAvailability != null && poItemAvailability.stream().collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty)) + currentAvailability.stream().collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)) <= 0) {
820
                                    poColor = "grey";
821
                                } else {
822
                                    poColor = "yellow";
823
                                    if (modelColorClass != "green") {
824
                                        modelColorClass = poColor;
825
                                    }
826
                                }
827
                            }
828
                        fdi.setColorClass(poColor);
829
                        fdi.setSellingPrice(sellingPrice);
830
                        fdi.setActive(active);
831
                        fdi.setMrp(childItem.getDouble("mrp_f"));
832
                        fdi.setMop((float) childItem.getDouble("mop_f"));
833
                        fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
834
                        if (fdi.getColor().equalsIgnoreCase("any colour")) {
835
                            fdiAnyColour = fdi;
836
                        }
837
                        fdi.setTagId(childItem.getInt("tagId_i"));
838
                        fdi.setItem_id(itemId);
839
                        Float cashBack = schemeService.getCatalogSchemeCashBack().get(fofoCatalogResponse.getCatalogId());
840
                        cashBack = cashBack == null ? 0 : cashBack;
841
                        fdi.setCashback(cashBack);
842
                        fdi.setMinBuyQuantity(1);
843
                        if (hotDeal) {
844
                            if (currentAvailability != null) {
845
                                fdi.setAvailability(currentAvailability.stream().collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)));
846
                            } else {
847
                                fdi.setAvailability(0);
848
                            }
849
                        } else {
850
                            // Lets consider that its out of stock
32591 amit.gupta 851
                            fdi.setAvailability(400);
32339 tejbeer 852
                            Item item = null;
853
                            try {
854
                                item = itemRepository.selectById(itemId);
855
                            } catch (Exception e) {
856
                                e.printStackTrace();
857
                                continue;
858
                            }
859
                            // In case its tampered glass moq should be
860
                            if (item.getCategoryId() == 10020) {
861
                                fdi.setMinBuyQuantity(5);
862
                            }
863
                        }
864
                        fdi.setQuantityStep(1);
32590 amit.gupta 865
                        fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 400));
32339 tejbeer 866
                        fofoAvailabilityInfoMap.put(itemId, fdi);
867
                    }
868
                }
869
                if (fdiAnyColour != null) {
870
                    fdiAnyColour.setColorClass(modelColorClass);
871
                }
872
            }
873
            if (fofoAvailabilityInfoMap.values().size() > 0) {
874
                List<FofoAvailabilityInfo> availabilityList = fofoAvailabilityInfoMap.values().stream().sorted(Comparator.comparing(FofoAvailabilityInfo::getAvailability).reversed()).collect(Collectors.toList());
875
                fofoCatalogResponse.setItems(availabilityList);
876
                if (priceCircularItemModelMap.containsKey(fofoCatalogResponse.getCatalogId())) {
877
                    PriceCircularItemModelNew priceCircularItemModel = priceCircularItemModelMap.get(fofoCatalogResponse.getCatalogId());
878
                    if (priceCircularItemModel.getSlabPayouts() != null) {
879
                        List<CreateOfferRequest> schemeOffers = new ArrayList<>();
880
                        List<Map<Integer, AmountModel>> slabPayouts = priceCircularItemModel.getSlabPayouts();
881
                        Iterator<Map<Integer, AmountModel>> iterator = slabPayouts.iterator();
882
                        int iteratorCount = 0;
883
                        while (iterator.hasNext()) {
884
                            Map<Integer, AmountModel> slabPayoutMap = iterator.next();
885
                            if (slabPayoutMap != null) {
886
                                schemeOffers.add(allSchemOffers.get(iteratorCount));
887
                            } else {
888
                                iterator.remove();
889
                            }
890
                            iteratorCount++;
891
                        }
892
                        fofoCatalogResponse.setSchemeOffers(schemeOffers);
893
                    }
894
                    fofoCatalogResponse.setPriceCircularItemModel(priceCircularItemModel);
895
                }
896
                dealResponse.add(fofoCatalogResponse);
897
            }
898
        }
899
        return dealResponse;
30686 amit.gupta 900
 
32339 tejbeer 901
    }
30693 amit.gupta 902
 
32339 tejbeer 903
    private List<FofoCatalogResponse> getCatalogSingleSkuResponse(JSONArray docs, Map<Integer, Integer> itemFilter, boolean hotDeal) throws ProfitMandiBusinessException {
904
        Map<Integer, TagListing> itemTagListingMap = null;
905
        List<FofoCatalogResponse> dealResponse = new ArrayList<>();
906
        List<Integer> tagIds = Arrays.asList(4);
24091 tejbeer 907
 
32339 tejbeer 908
        itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemFilter.keySet(), new HashSet<>(tagIds)).stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x));
24091 tejbeer 909
 
32339 tejbeer 910
        for (int i = 0; i < docs.length(); i++) {
911
            Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
912
            JSONObject doc = docs.getJSONObject(i);
26589 amit.gupta 913
 
32339 tejbeer 914
            for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
915
                JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
916
                int itemId = childItem.getInt("itemId_i");
917
                TagListing tl = itemTagListingMap.get(itemId);
918
                if (tl == null) {
919
                    continue;
920
                }
921
                if (hotDeal) {
922
                    if (!tl.isHotDeals()) {
923
                        continue;
924
                    }
925
                }
926
                float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
927
                if (fofoAvailabilityInfoMap.containsKey(itemId)) {
928
                    if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
929
                        fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
930
                        fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
931
                    }
932
                } else {
933
                    FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
934
                    fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
935
                    fdi.setMop((float) childItem.getDouble("mop_f"));
936
                    fdi.setMop((float) tl.getMrp());
937
                    fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
938
                    fdi.setTagId(childItem.getInt("tagId_i"));
939
                    fdi.setItem_id(itemId);
940
                    Item item = itemRepository.selectById(itemId);
941
                    // In case its tampered glass moq should be 5
942
                    if (item.getCategoryId() == 10020) {
943
                        fdi.setMinBuyQuantity(10);
944
                    } else {
945
                        fdi.setMinBuyQuantity(1);
946
                    }
947
                    fdi.setAvailability(itemFilter.get(itemId));
948
                    fdi.setQuantityStep(1);
949
                    fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
950
                    fofoAvailabilityInfoMap.put(itemId, fdi);
951
                }
952
            }
953
            if (fofoAvailabilityInfoMap.values().size() > 0) {
954
                for (FofoAvailabilityInfo fofoAvailabilityInfo : fofoAvailabilityInfoMap.values()) {
955
                    FofoCatalogResponse ffdr = new FofoCatalogResponse();
956
                    ffdr.setCatalogId(doc.getInt("catalogId_i"));
957
                    ffdr.setImageUrl(doc.getString("imageUrl_s"));
958
                    ffdr.setTitle(doc.getString("title_s"));
959
                    try {
960
                        ffdr.setFeature(doc.getString("feature_s"));
961
                    } catch (Exception e) {
962
                        ffdr.setFeature(null);
963
                        logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
964
                    }
965
                    ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
966
                    ffdr.setItems(Arrays.asList(fofoAvailabilityInfo));
967
                    dealResponse.add(ffdr);
968
                }
969
            }
970
        }
971
        return dealResponse;
25880 amit.gupta 972
 
32339 tejbeer 973
    }
25880 amit.gupta 974
 
32339 tejbeer 975
    @RequestMapping(value = "/combo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
976
    public ResponseEntity<?> getBanners(@RequestParam int catalogId, @RequestParam int warehouseId) {
977
        List<ComboModel> comboModels = comboModelRepository.selectByCatalogIdAndWarehouseId(catalogId, warehouseId);
978
        return responseSender.ok(comboModels);
979
    }
32344 tejbeer 980
 
981
    @RequestMapping(value = "/checkCombo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
982
    public ResponseEntity<?> checkCombo(HttpServletRequest request, @RequestParam int catalogId, @RequestParam int warehouseId, @RequestParam int qty) throws Exception {
983
        boolean isCombo = false;
984
        ComboModel comboModel = comboModelRepository.selectByCatalogIdWarehouseIdAndQty(catalogId, warehouseId, qty);
985
        if (comboModel != null) {
986
            isCombo = true;
987
        }
988
 
989
        return responseSender.ok(isCombo);
990
    }
991
 
992
 
25967 amit.gupta 993
}