Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
31604 tejbeer 1
package com.spice.profitmandi.dao.service.solr;
2
 
33973 tejus.loha 3
import com.fasterxml.jackson.core.JsonProcessingException;
4
import com.fasterxml.jackson.databind.ObjectMapper;
33245 ranu 5
import com.google.gson.Gson;
6
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
33562 amit.gupta 7
import com.spice.profitmandi.common.model.ProfitMandiConstants;
33973 tejus.loha 8
import com.spice.profitmandi.dao.entity.catalog.SuperCatalogMapping;
33245 ranu 9
import com.spice.profitmandi.dao.entity.catalog.TagListing;
10
import com.spice.profitmandi.dao.entity.catalog.TagRanking;
11
import com.spice.profitmandi.dao.entity.dtr.WebProductListing;
34021 ranu 12
import com.spice.profitmandi.dao.entity.inventory.SaholicCIS;
13
import com.spice.profitmandi.dao.entity.inventory.SaholicPOItem;
35357 ranu 14
import com.spice.profitmandi.dao.repository.catalog.CatalogRepository;
33973 tejus.loha 15
import com.spice.profitmandi.dao.repository.catalog.SuperCatalogMappingRepository;
33245 ranu 16
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
17
import com.spice.profitmandi.dao.repository.catalog.TagRankingRepository;
18
import com.spice.profitmandi.dao.repository.dtr.Mongo;
19
import com.spice.profitmandi.dao.repository.dtr.WebListingRepository;
20
import com.spice.profitmandi.dao.repository.dtr.WebProductListingRepository;
33542 amit.gupta 21
import com.spice.profitmandi.dao.repository.similarModel.SimilarModelRepository;
33973 tejus.loha 22
import com.spice.profitmandi.service.catalog.SuperCatalogModel;
34021 ranu 23
import com.spice.profitmandi.service.inventory.SaholicInventoryService;
33245 ranu 24
import com.spice.profitmandi.service.tag.ItemTagModel;
25
import in.shop2020.model.v1.catalog.status;
31604 tejbeer 26
import org.apache.logging.log4j.LogManager;
27
import org.apache.logging.log4j.Logger;
28
import org.apache.solr.client.solrj.SolrClient;
29
import org.apache.solr.client.solrj.impl.HttpSolrClient;
30
import org.apache.solr.common.SolrInputDocument;
31
import org.json.JSONArray;
32
import org.json.JSONException;
33
import org.json.JSONObject;
34
import org.springframework.beans.factory.annotation.Autowired;
31613 tejbeer 35
import org.springframework.beans.factory.annotation.Value;
31604 tejbeer 36
import org.springframework.stereotype.Component;
37
 
33245 ranu 38
import java.io.BufferedReader;
39
import java.io.IOException;
40
import java.io.InputStream;
41
import java.io.InputStreamReader;
42
import java.net.HttpURLConnection;
43
import java.net.URL;
44
import java.net.URLConnection;
45
import java.time.ZoneId;
46
import java.util.*;
47
import java.util.Map.Entry;
48
import java.util.stream.Collectors;
49
import java.util.zip.GZIPInputStream;
31604 tejbeer 50
 
51
@Component
52
public class FofoSolr {
53
 
33542 amit.gupta 54
    @Autowired
55
    private Gson gson;
31604 tejbeer 56
 
33542 amit.gupta 57
    @Autowired
58
    private TagListingRepository tagListingRepository;
31604 tejbeer 59
 
33542 amit.gupta 60
    @Autowired
35357 ranu 61
    private CatalogRepository catalogRepository;
62
 
63
    @Autowired
33542 amit.gupta 64
    TagRankingRepository tagRankingRepository;
31604 tejbeer 65
 
33542 amit.gupta 66
    @Autowired
67
    private Mongo contentMongoClient;
31604 tejbeer 68
 
33542 amit.gupta 69
    @Autowired
70
    private WebListingRepository webListingRepository;
31612 tejbeer 71
 
33542 amit.gupta 72
    @Autowired
73
    private WebProductListingRepository webProductListingRepository;
31612 tejbeer 74
 
33973 tejus.loha 75
    @Autowired
76
    private SuperCatalogMappingRepository superCatalogMappingRepository;
77
 
33542 amit.gupta 78
    @Value("${new.solr.url}")
79
    private String solrUrl;
31613 tejbeer 80
 
33542 amit.gupta 81
    @Value("${reportico.url}")
82
    private String reporticoUrl;
33486 amit.gupta 83
 
33542 amit.gupta 84
    private static final Logger logger = LogManager.getLogger(FofoSolr.class);
31604 tejbeer 85
 
33542 amit.gupta 86
    private static final List<Integer> CATEGORY_MASTER = Arrays.asList(10006, 10010, 14202, 14203);
31604 tejbeer 87
 
33542 amit.gupta 88
    private static String getUrlContent(String urlString) {
89
        BufferedReader reader = null;
90
        try {
91
            URL url = new URL(urlString);
92
            URLConnection conn = url.openConnection();
93
            conn.setConnectTimeout(5000);
94
            conn.setReadTimeout(5000);
95
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
96
            return reader.lines().collect(Collectors.joining(System.lineSeparator()));
97
        } catch (IOException e) {
98
            e.printStackTrace();
99
        } finally {
100
            if (reader != null) {
101
                try {
102
                    reader.close();
103
                } catch (IOException e) {
104
                    e.printStackTrace();
105
                }
106
            }
107
        }
108
        return null;
109
    }
31604 tejbeer 110
 
33542 amit.gupta 111
    public JSONArray getAvailability() throws IOException, JSONException {
112
        String url = reporticoUrl + "?execute_mode=EXECUTE&xmlin=warehousecisnew.xml&project=FOCOR&project_password=focor&target_format=JSON";
113
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
114
        connection.setRequestProperty("Accept-Encoding", "gzip");
115
        BufferedReader reader = null;
31604 tejbeer 116
 
33542 amit.gupta 117
        try {
118
            InputStream inputStream = connection.getInputStream();
31604 tejbeer 119
 
33542 amit.gupta 120
            if ("gzip".equals(connection.getContentEncoding())) {
121
                inputStream = new GZIPInputStream(inputStream);
122
            }
31604 tejbeer 123
 
33542 amit.gupta 124
            reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
125
            StringBuilder responseBuilder = new StringBuilder();
126
            String line;
31604 tejbeer 127
 
33542 amit.gupta 128
            while ((line = reader.readLine()) != null) {
129
                responseBuilder.append(line);
130
            }
31604 tejbeer 131
 
33542 amit.gupta 132
            JSONObject responseJson = new JSONObject(responseBuilder.toString());
133
            return responseJson.getJSONArray("data");
134
        } finally {
135
            if (reader != null) {
136
                try {
137
                    reader.close();
138
                } catch (IOException e) {
139
                    // Ignore
140
                }
141
            }
142
        }
143
    }
31604 tejbeer 144
 
33542 amit.gupta 145
    public JSONArray getPendingPO() throws IOException, JSONException {
146
        String url = reporticoUrl + "?execute_mode=EXECUTE&xmlin=UnfulfilledPOItemsNew.xml&project=FOCOR&project_password=focor&target_format=JSON";
147
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
148
        connection.setRequestProperty("Accept-Encoding", "gzip");
149
        BufferedReader reader = null;
31604 tejbeer 150
 
33542 amit.gupta 151
        try {
152
            InputStream inputStream = connection.getInputStream();
31604 tejbeer 153
 
33542 amit.gupta 154
            if ("gzip".equals(connection.getContentEncoding())) {
155
                inputStream = new GZIPInputStream(inputStream);
156
            }
31604 tejbeer 157
 
33542 amit.gupta 158
            reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
159
            StringBuilder responseBuilder = new StringBuilder();
160
            String line;
31604 tejbeer 161
 
33542 amit.gupta 162
            while ((line = reader.readLine()) != null) {
163
                responseBuilder.append(line);
164
            }
31604 tejbeer 165
 
33542 amit.gupta 166
            JSONObject responseJson = new JSONObject(responseBuilder.toString());
167
            return responseJson.getJSONArray("data");
168
        } finally {
169
            if (reader != null) {
170
                try {
171
                    reader.close();
172
                } catch (IOException e) {
173
                    // Ignore
174
                }
175
            }
176
        }
177
    }
31604 tejbeer 178
 
34021 ranu 179
    @Autowired
180
    SaholicInventoryService saholicInventoryService;
181
 
33542 amit.gupta 182
    public Map<String, Map<String, Map<String, Integer>>> getItemMap() throws Exception {
34021 ranu 183
 
184
//        JSONArray availabilityJSONArray = this.getAvailability();
35343 ranu 185
        List<SaholicCIS> saholicCISList = saholicInventoryService.getSaholicStockListWithoutCatalogMovingStatus();
34021 ranu 186
 
187
//        JSONArray pendingPOJSONArray = this.getPendingPO();
188
        List<SaholicPOItem> saholicPOItemList = saholicInventoryService.getSaholicPOItemList();
189
 
33542 amit.gupta 190
        Map<String, Map<String, Map<String, Integer>>> availabilityItemMap = new HashMap<>();
34021 ranu 191
        for (SaholicCIS rawAvailability : saholicCISList) {
31604 tejbeer 192
 
34021 ranu 193
            String itemId = String.valueOf(rawAvailability.getItemId());
194
            String warehouseId = String.valueOf(rawAvailability.getWarehouseId());
195
 
196
            if (!availabilityItemMap.containsKey(itemId)) {
197
                availabilityItemMap.put(itemId, new HashMap<>());
33542 amit.gupta 198
            }
34021 ranu 199
            if (!availabilityItemMap.get(itemId).containsKey(warehouseId)) {
200
                availabilityItemMap.get(itemId).put(warehouseId, new HashMap<String, Integer>());
201
                availabilityItemMap.get(itemId).get(warehouseId).put("netAvailability", 0);
202
                availabilityItemMap.get(itemId).get(warehouseId).put("netPo", 0);
33542 amit.gupta 203
            }
34021 ranu 204
            int netAvailability = availabilityItemMap.get(itemId).get(warehouseId).get("netAvailability") + rawAvailability.getNetavailability();
205
            availabilityItemMap.get(itemId).get(warehouseId).put("netAvailability", netAvailability);
33542 amit.gupta 206
        }
31604 tejbeer 207
 
34021 ranu 208
        for (SaholicPOItem rawPendingPo : saholicPOItemList) {
209
            String itemId = String.valueOf(rawPendingPo.getItemId());
210
            String warehouseId = String.valueOf(rawPendingPo.getWarehouseId());
33542 amit.gupta 211
            if (!availabilityItemMap.containsKey(itemId)) {
212
                availabilityItemMap.put(itemId, new HashMap<String, Map<String, Integer>>());
213
            }
214
            if (!availabilityItemMap.get(itemId).containsKey(warehouseId)) {
215
                availabilityItemMap.get(itemId).put(warehouseId, new HashMap<String, Integer>() {
216
                    {
217
                        put("netAvailability", 0);
218
                        put("netPo", 0);
219
                    }
220
                });
221
            }
222
            availabilityItemMap.get(itemId).get(warehouseId).put("netPo",
34021 ranu 223
                    availabilityItemMap.get(itemId).get(warehouseId).get("netPo") + rawPendingPo.getUnfulfilledQty());
31604 tejbeer 224
 
33542 amit.gupta 225
        }
226
        return availabilityItemMap;
31604 tejbeer 227
 
33542 amit.gupta 228
    }
31604 tejbeer 229
 
33245 ranu 230
    public Map<Integer, List<String>> getLabels() throws ProfitMandiBusinessException {
33542 amit.gupta 231
        List<String> labels = Arrays.asList("partner-best-sellers", "partner-price-drop", "new-launches",
232
                "upgrade-offer", "special-support");
31612 tejbeer 233
 
33542 amit.gupta 234
        Map<Integer, String> webListing = webListingRepository.selectByUrls(labels).stream()
235
                .collect(Collectors.toMap(x -> x.getId(), x -> x.getUrl()));
31612 tejbeer 236
 
33542 amit.gupta 237
        Map<Integer, List<WebProductListing>> webProductListingMap = webProductListingRepository
238
                .selectAllByWebListingIds(new ArrayList<>(webListing.keySet())).stream()
239
                .collect(Collectors.groupingBy(x -> x.getWebListingId()));
31612 tejbeer 240
 
33542 amit.gupta 241
        Map<Integer, List<String>> catalogLabelMap = new HashMap<>();
242
        for (Entry<Integer, List<WebProductListing>> webProductListingEntry : webProductListingMap.entrySet()) {
31612 tejbeer 243
 
33542 amit.gupta 244
            for (WebProductListing webProduct : webProductListingEntry.getValue()) {
31612 tejbeer 245
 
33542 amit.gupta 246
                if (!catalogLabelMap.containsKey(webProduct.getEntityId())) {
31612 tejbeer 247
 
33542 amit.gupta 248
                    catalogLabelMap.put(webProduct.getEntityId(), new ArrayList<>());
31612 tejbeer 249
 
33542 amit.gupta 250
                }
31612 tejbeer 251
 
33542 amit.gupta 252
                List<String> itemLabels = catalogLabelMap.get(webProduct.getEntityId());
253
                itemLabels.add(webListing.get(webProduct.getWebListingId()));
254
                catalogLabelMap.put(webProduct.getEntityId(), itemLabels);
31612 tejbeer 255
 
33542 amit.gupta 256
            }
31612 tejbeer 257
 
33542 amit.gupta 258
        }
31612 tejbeer 259
 
33542 amit.gupta 260
        return catalogLabelMap;
261
    }
31612 tejbeer 262
 
33542 amit.gupta 263
    @Autowired
264
    SimilarModelRepository similarModelRepository;
31604 tejbeer 265
 
33542 amit.gupta 266
    public void populateTagItems() throws Exception {
267
        Map<String, Map<String, Map<String, Integer>>> availabilityItemMap = getItemMap();
268
        List<TagRanking> tagRankingList = tagRankingRepository.getAllTagRanking();
269
        List<Integer> rankingList = new ArrayList<>();
270
        Map<Integer, String> featureMap = new HashMap<>();
271
        for (TagRanking tagRanking : tagRankingList) {
272
            rankingList.add(tagRanking.getCatalogItemId());
273
            featureMap.put(tagRanking.getCatalogItemId(), tagRanking.getFeature());
274
        }
275
        //Get Similar Models
33570 amit.gupta 276
        /*List<SimilarModel> similarModels = similarModelRepository.selectAll();
31612 tejbeer 277
 
33570 amit.gupta 278
        Map<Integer, List<Integer>> similarModelsMap = similarModels.stream().collect(Collectors.groupingBy(SimilarModel::getCatalogId, Collectors.mapping(x -> x.getSimilarCatalogId(), Collectors.toList())));*/
31612 tejbeer 279
 
33542 amit.gupta 280
        Map<Integer, Map<String, Object>> catalogMap = new HashMap<>();
31612 tejbeer 281
 
33542 amit.gupta 282
        List<status> statuses = Arrays.asList(status.ACTIVE, status.PAUSED_BY_RISK, status.PARTIALLY_ACTIVE);
31612 tejbeer 283
 
33542 amit.gupta 284
        Map<Integer, List<String>> catalogLabelMap = this.getLabels();
31604 tejbeer 285
 
33973 tejus.loha 286
        //logger.info("catalogLabelMap {}", catalogLabelMap);
31604 tejbeer 287
 
35357 ranu 288
        List<ItemTagModel> itemTagModelsByStatus = tagListingRepository.getAllItemTagByStatus(statuses);
31604 tejbeer 289
 
35358 ranu 290
        logger.info("itemTagModelsByStatus {}" , itemTagModelsByStatus.size());
291
 
35357 ranu 292
        List<Integer> eolItemIds = catalogRepository.findAllWithEOLWithOutStockItemId();
293
 
35358 ranu 294
        logger.info("eolItemIds.size {}" , eolItemIds.size());
295
 
35357 ranu 296
        Set<Integer> eolSet = new HashSet<>(eolItemIds);
297
 
35358 ranu 298
        logger.info("eolSetItemIds.size {}" , eolSet.size());
35357 ranu 299
 
300
//        remove eol itme id from listing
301
 
35358 ranu 302
        List<ItemTagModel> itemTagModels = new ArrayList<>();
35357 ranu 303
 
35358 ranu 304
        for (ItemTagModel itm : itemTagModelsByStatus) {
305
            // Check if the item's ID is NOT contained in the eolSet
306
            if (!eolSet.contains(itm.getItem().getId())) {
307
                // If it's NOT EOL, add it to the new list
308
                itemTagModels.add(itm);
309
            }
310
        }
311
 
312
        logger.info("itemTagModels {}" , itemTagModels.size());
313
 
33542 amit.gupta 314
        Map<String, Object> projection = new HashMap<>();
315
        projection.put("defaultImageUrl", 1);
31604 tejbeer 316
 
33542 amit.gupta 317
        List<String> excludeBrands = Arrays.asList("Dummy", "FOC HANDSET");
31604 tejbeer 318
 
33562 amit.gupta 319
        Map<Float, List<Integer>> priceModelMap = new TreeMap<>();
320
        for (ItemTagModel itemTagModel : itemTagModels) {
321
            TagListing tagListing = itemTagModel.getTagListing();
322
            com.spice.profitmandi.dao.entity.catalog.Item item = itemTagModel.getItem();
33542 amit.gupta 323
            if (excludeBrands.contains(item.getBrand())) {
324
                continue;
325
            }
31604 tejbeer 326
 
33542 amit.gupta 327
            if (!catalogMap.containsKey(item.getCatalogItemId())) {
33571 amit.gupta 328
                if (!priceModelMap.containsKey(tagListing.getMop()) && item.getCategoryId() == 10006) {
33572 amit.gupta 329
                    priceModelMap.put(tagListing.getMop(), new ArrayList<>());
33562 amit.gupta 330
                }
33570 amit.gupta 331
                if (item.getCategoryId() == 10006) {
33571 amit.gupta 332
                    List<Integer> priceModels = priceModelMap.get(tagListing.getMop());
33565 amit.gupta 333
                    priceModels.add(item.getCatalogItemId());
334
                }
33562 amit.gupta 335
 
33542 amit.gupta 336
                Map<String, Object> catalogObj = new HashMap<>();
33570 amit.gupta 337
                catalogObj.put("stockColor", 0);
33542 amit.gupta 338
                catalogObj.put("feature", "");
339
                catalogObj.put("hsnCode", item.getHsnCode());
340
                catalogObj.put("title",
341
                        String.join(" ", Arrays.asList(item.getBrand(), item.getModelName(), item.getModelNumber())
342
                                .stream().filter(s -> s != null && !s.isEmpty()).collect(Collectors.toList())));
343
                catalogObj.put("brand", new String[]{item.getBrand()});
344
                if (item.getBrand().equals("Huawei") || item.getBrand().equals("Honor")) {
345
                    catalogObj.put("brand", new String[]{"Huawei", "Honor"});
346
                }
347
                if (item.getBrand().equals("Mi") || item.getBrand().equals("Xiaomi")
348
                        || item.getBrand().equals("Redmi")) {
349
                    catalogObj.put("brand", new String[]{"Mi", "Xiaomi", "Redmi"});
350
                }
351
                catalogObj.put("identifier", item.getCatalogItemId());
352
                catalogObj.put("items", new HashMap<Integer, Map<String, Object>>());
353
                Map<String, Object> filterMap = new HashMap<>();
354
                filterMap.put("_id", item.getCatalogItemId());
355
                // Don't include if catalog not available
356
                try {
357
                    String imageUrl = contentMongoClient.getEntityById(item.getCatalogItemId()).getDefaultImageUrl();
31624 tejbeer 358
 
33542 amit.gupta 359
                    if (imageUrl != null) {
360
                        catalogObj.put("imageUrl", imageUrl);
361
                    } else {
362
                        catalogObj.put("imageUrl",
363
                                "https://images.smartdukaan.com/uploads/campaigns/" + item.getCatalogItemId() + ".jpg");
364
                    }
365
                } catch (Exception e) {
366
                    try {
367
                        catalogObj.put("imageUrl",
368
                                "https://images.smartdukaan.com/uploads/campaigns/" + item.getCatalogItemId() + ".jpg");
369
                    } catch (Exception e2) {
370
                        e2.printStackTrace();
371
                    }
372
                }
373
                try {
374
                    catalogObj.put("rank", rankingList.indexOf(item.getCatalogItemId()));
375
                } catch (Exception e) {
376
                    // A very big number
377
                    e.printStackTrace();
378
                    catalogObj.put("rank", 50000000);
379
                }
380
                if (featureMap.containsKey(item.getCatalogItemId())
381
                        && featureMap.get(item.getCatalogItemId()) != null) {
382
                    catalogObj.put("feature", featureMap.get(item.getCatalogItemId()));
31612 tejbeer 383
 
33542 amit.gupta 384
                }
31612 tejbeer 385
 
33542 amit.gupta 386
                catalogObj.put("categoryId", CATEGORY_MASTER.contains(item.getCategoryId()) ? item.getCategoryId() : 6);
31612 tejbeer 387
 
33542 amit.gupta 388
                if (item.getCategoryId() == 10006) {
389
                    catalogObj.put("categoryId", 3);
390
                }
391
                catalogObj.put("subCategoryId", item.getCategoryId());
392
                catalogObj.put("create_timestamp",
33562 amit.gupta 393
                        tagListing.getCreatedTimestamp().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
31604 tejbeer 394
 
33542 amit.gupta 395
                if (catalogLabelMap.containsKey(item.getCatalogItemId())
396
                        && catalogLabelMap.get(item.getCatalogItemId()) != null) {
397
                    catalogObj.put("labels", catalogLabelMap.get(item.getCatalogItemId()));
31604 tejbeer 398
 
33542 amit.gupta 399
                }
400
                catalogMap.put(item.getCatalogItemId(), catalogObj);
401
                catalogObj.put("avColor", new HashMap<>());
31604 tejbeer 402
 
33542 amit.gupta 403
            }
31604 tejbeer 404
 
33542 amit.gupta 405
            Map<String, Object> catalogObj = catalogMap.get(item.getCatalogItemId());
406
            Map<Integer, Integer> avColorMap = (Map<Integer, Integer>) catalogObj.get("avColor");
31604 tejbeer 407
 
33542 amit.gupta 408
            if (availabilityItemMap.containsKey(String.valueOf(item.getId()))) {
33570 amit.gupta 409
                int itemStockColor = 0;
33542 amit.gupta 410
                for (Map.Entry<String, Map<String, Integer>> entry : availabilityItemMap
411
                        .get(String.valueOf(item.getId())).entrySet()) {
412
                    String warehouseId = entry.getKey();
413
                    Map<String, Integer> avMap = entry.getValue();
414
                    if (!avColorMap.containsKey(Integer.parseInt(warehouseId))) {
415
                        avColorMap.put(Integer.parseInt(warehouseId), 0);
416
                    }
417
                    int color = avColorMap.get(Integer.parseInt(warehouseId));
31604 tejbeer 418
 
33542 amit.gupta 419
                    if (avMap.get("netAvailability") > 0) {
420
                        color = 2;
33562 amit.gupta 421
                    } else if (avMap.get("netPo") > 0) {
33542 amit.gupta 422
                        color = Math.max(color, 1);
423
                    } else {
424
                        color = Math.max(color, 0);
425
                    }
426
                    avColorMap.put(Integer.parseInt(warehouseId), color);
31604 tejbeer 427
 
33542 amit.gupta 428
                    catalogObj.put("avColor", avColorMap);
33570 amit.gupta 429
                    if (color > itemStockColor) {
430
                        itemStockColor = color;
431
                    }
33542 amit.gupta 432
                }
33570 amit.gupta 433
                if (itemStockColor > 0 && itemStockColor > (Integer) catalogObj.get("stockColor")) {
434
                    catalogObj.put("stockColor", itemStockColor);
435
                }
33542 amit.gupta 436
            }
31604 tejbeer 437
 
33542 amit.gupta 438
            Map<Integer, Object> itemColorMap = (Map<Integer, Object>) catalogObj.get("items");
31604 tejbeer 439
 
33542 amit.gupta 440
            if (!itemColorMap.containsKey(item.getId())) {
441
                itemColorMap.put(item.getId(), new HashMap<String, Object>() {
442
                    {
443
                        put("color", item.getColor().replace("f_", ""));
444
                        put("tagPricing", new ArrayList<TagListing>());
445
                    }
446
                });
447
            }
448
            Map<String, Object> itemMap = (Map<String, Object>) itemColorMap.get(item.getId());
449
            List<TagListing> tagPricing = (List<TagListing>) itemMap.get("tagPricing");
33562 amit.gupta 450
            tagPricing.add(tagListing);
33542 amit.gupta 451
        }
33562 amit.gupta 452
        //logger.info("catalogObj {}", catalogMap);
31604 tejbeer 453
 
33973 tejus.loha 454
        List<SuperCatalogModel> superCatalogMappingList = superCatalogMappingRepository.selectJoinedData();
455
        List<SuperCatalogMapping> superCatalogs = superCatalogMappingRepository.selectAll();
33542 amit.gupta 456
        List<SolrInputDocument> catalogSolrObjs = new ArrayList<>();
457
        for (Entry<Integer, Map<String, Object>> entry : catalogMap.entrySet()) {
458
            int catalogId = entry.getKey();
34229 vikas.jang 459
            Optional<SuperCatalogModel> superCatalogMapping = findMappingByCatalogId(superCatalogMappingList, catalogId, itemTagModels);
33542 amit.gupta 460
            Map<String, Object> catalogValMap = entry.getValue();
461
            Map<Integer, Object> itemsMap = (Map<Integer, Object>) catalogValMap.get("items");
31604 tejbeer 462
 
33542 amit.gupta 463
            boolean active = false;
464
            // Map<Integer, Object> itemsMap = (Map<String, Object>)
465
            // catalogValMap.get("items");
466
            List<SolrInputDocument> itemObjs = new ArrayList<>();
467
            float mop = 0;
33574 amit.gupta 468
            float dp = 0;
31604 tejbeer 469
 
33542 amit.gupta 470
            for (Entry<Integer, Object> itemEntry : itemsMap.entrySet()) {
471
                int itemId = itemEntry.getKey();
472
                Map<String, Object> itemMap = (Map<String, Object>) itemEntry.getValue();
473
                List<TagListing> tags = (List<TagListing>) itemMap.get("tagPricing");
474
                SolrInputDocument itemObj = new SolrInputDocument();
31604 tejbeer 475
 
34136 amit.gupta 476
                for (TagListing tagListing : tags) {
477
                    active = active || tagListing.isActive();
478
                    itemObj.setField("id", "itemtag-" + itemId + "-" + tagListing.getTagId());
33542 amit.gupta 479
                    itemObj.setField("color_s", itemMap.get("color"));
480
                    itemObj.setField("itemId_i", itemId);
34136 amit.gupta 481
                    itemObj.setField("tagId_i", tagListing.getTagId());
482
                    itemObj.setField("mrp_f", tagListing.getMrp());
483
                    itemObj.setField("mop_f", tagListing.getMop());
484
                    itemObj.setField("sellingPrice_f", tagListing.getSellingPrice());
485
                    itemObj.setField("active_b", tagListing.isActive());
486
                    itemObj.setField("hot_deal_b", tagListing.isHotDeals());
487
                    mop = tagListing.getMop();
488
                    dp = tagListing.getSellingPrice();
33542 amit.gupta 489
                }
490
                itemObjs.add(itemObj);
491
            }
31604 tejbeer 492
 
33542 amit.gupta 493
            SolrInputDocument catalogSolrObj = new SolrInputDocument();
494
            catalogSolrObj.setField("id", "catalog" + catalogId);
495
            catalogSolrObj.setField("rank_i", catalogValMap.get("rank"));
496
            catalogSolrObj.setField("title_s", catalogValMap.get("title"));
497
            catalogSolrObj.addChildDocuments(itemObjs);
498
            catalogSolrObj.setField("child_b", itemObjs.size() > 0);
499
            catalogSolrObj.setField("catalogId_i", catalogId);
33980 ranu 500
            logger.info("superCatalogMapping1- {}", superCatalogMapping);
33973 tejus.loha 501
            if (superCatalogMapping.isPresent()) {
502
                int superCatalogId = superCatalogMapping.get().getSuperCatalogId();
34229 vikas.jang 503
                String superCatalogMappingVariants = findMappingVariantsByCatalogId(superCatalogs, superCatalogId, itemTagModels);
33973 tejus.loha 504
                catalogSolrObj.setField("superCatalog_i", superCatalogId);
505
                catalogSolrObj.setField("superCatalog_s", superCatalogMapping.get().getSuperCatalogName());
506
                catalogSolrObj.setField("superCatalogVariants_s", superCatalogMappingVariants);
507
            } else {
508
                catalogSolrObj.setField("superCatalog_i", 0);
34023 vikas.jang 509
                catalogSolrObj.setField("superCatalog_s", catalogValMap.get("title"));
33973 tejus.loha 510
                catalogSolrObj.setField("superCatalogVariants_s", "[]");
511
            }
33542 amit.gupta 512
            catalogSolrObj.setField("imageUrl_s",
513
                    catalogValMap.get("imageUrl").toString().replace("saholic", "smartdukaan"));
514
            catalogSolrObj.setField("feature_s", catalogValMap.get("feature"));
515
            catalogSolrObj.setField("brand_ss", catalogValMap.get("brand"));
516
            catalogSolrObj.setField("create_s", catalogValMap.get("create_timestamp"));
517
            catalogSolrObj.setField("categoryId_i", catalogValMap.get("categoryId"));
518
            catalogSolrObj.setField("subCategoryId_i", catalogValMap.get("subCategoryId"));
519
            catalogSolrObj.setField("label_ss", catalogValMap.get("labels"));
520
            catalogSolrObj.setField("mop_f", mop);
33574 amit.gupta 521
            catalogSolrObj.setField("dp_f", dp);
33542 amit.gupta 522
            catalogSolrObj.setField("hsncode_s", catalogValMap.get("hsnCode"));
523
            catalogSolrObj.setField("show_default_b", true);
31710 tejbeer 524
 
33542 amit.gupta 525
            String[] brands = (String[]) catalogValMap.get("brand");
526
            for (String brand : brands) {
527
                if (brand.equals("FOC")) {
528
                    catalogSolrObj.setField("show_default_b", false);
529
                }
31604 tejbeer 530
 
33542 amit.gupta 531
                if (brand.equals("Live Demo")) {
532
                    catalogSolrObj.setField("show_default_b", false);
533
                }
534
            }
535
            Map<Integer, Integer> avColorMap = (Map<Integer, Integer>) catalogValMap.get("avColor");
33499 amit.gupta 536
 
33570 amit.gupta 537
            for (Integer warehouseId : ProfitMandiConstants.WAREHOUSE_MAP.keySet()) {
538
                catalogSolrObj.setField("w" + warehouseId + "_i", 0);
539
            }
33542 amit.gupta 540
            for (Entry<Integer, Integer> avColorEntry : avColorMap.entrySet()) {
541
                int whId = avColorEntry.getKey();
33562 amit.gupta 542
                int color = avColorEntry.getValue();
33542 amit.gupta 543
                catalogSolrObj.setField("w" + whId + "_i", color);
544
            }
33570 amit.gupta 545
 
546
            List<Integer> similalarModels = null;
547
            if ((Integer) catalogValMap.get("categoryId") == 3) {
33571 amit.gupta 548
                float starPrice = mop - 500f;
549
                float endPrice = mop + 1000f;
33570 amit.gupta 550
                similalarModels = new ArrayList<>();
551
                for (Entry<Float, List<Integer>> floatListEntry : priceModelMap.entrySet()) {
552
                    float modelPrice = floatListEntry.getKey();
553
                    if (modelPrice >= starPrice && modelPrice <= endPrice) {
554
                        List<Integer> instock = floatListEntry.getValue().stream().filter(x->catalogMap.get(x).get("stockColor") != null && (Integer) (catalogMap.get(x).get("stockColor"))>0).collect(Collectors.toList());
34229 vikas.jang 555
                        //logger.info("Entry before - {}, after - {}", floatListEntry.getValue().size(), instock.size());
33570 amit.gupta 556
                        similalarModels.addAll(instock);
557
                    }
558
                    if (modelPrice > endPrice) break;
559
                }
560
                similalarModels.remove(Integer.valueOf(catalogId));
561
            }
34049 vikas.jang 562
            catalogSolrObj.setField("similarModels_ii", similalarModels == null ? Collections.EMPTY_LIST : similalarModels);
33570 amit.gupta 563
 
564
 
33542 amit.gupta 565
            catalogSolrObj.setField("active_b", active);
566
            catalogSolrObjs.add(catalogSolrObj);
567
        }
31604 tejbeer 568
 
33542 amit.gupta 569
        String solrPath = "http://" + solrUrl + ":8984/solr/demo";
570
        SolrClient solr = new HttpSolrClient.Builder(solrPath).build();
31604 tejbeer 571
 
33542 amit.gupta 572
        solr.deleteByQuery("*:*");
573
        solr.add(catalogSolrObjs);
574
 
575
        org.apache.solr.client.solrj.response.UpdateResponse updateResponse = solr.commit();
576
        logger.info("solr {}", updateResponse.getStatus());
577
 
578
    }
579
 
580
    public void pushData() throws Exception {
581
        this.populateTagItems();
582
    }
33973 tejus.loha 583
 
34229 vikas.jang 584
    public Optional<SuperCatalogModel> findMappingByCatalogId(List<SuperCatalogModel> superCatalogMappingList, int id, List<ItemTagModel> itemTagModels) {
585
        if (itemTagModels.stream().anyMatch(tag -> tag.getItem().getCatalogItemId() == id && tag.getTagListing().isActive())) {
586
            return superCatalogMappingList.stream().filter(mapping -> mapping.getCatalogId() == id).findFirst();
587
        }
588
        return Optional.empty();
33973 tejus.loha 589
    }
590
 
34229 vikas.jang 591
    public String findMappingVariantsByCatalogId(List<SuperCatalogMapping> superCatalogMappingList, int id, List<ItemTagModel> itemTagModels) throws JsonProcessingException {
33973 tejus.loha 592
        List<Map<String, Object>> variantList = new ArrayList<>();
593
        List<SuperCatalogMapping> matchingVariantNames = superCatalogMappingList.parallelStream()
594
                .filter(mapping -> mapping.getSuperCatalogId() == id)
595
                .collect(Collectors.toList());
596
 
597
        if (!matchingVariantNames.isEmpty()) {
34229 vikas.jang 598
            for (SuperCatalogMapping matchingVariant : matchingVariantNames) {
599
                logger.info("matchingVariantName: "+matchingVariant);
35344 vikas 600
                ItemTagModel itemTagModel = itemTagModels.stream().filter(tag -> tag.getItem().getCatalogItemId() == matchingVariant.getCatalogId()).findFirst().orElse(null);
34229 vikas.jang 601
                   if (matchingVariant != null && matchingVariant.getVariantName() != null && itemTagModels.stream().anyMatch(tag -> tag.getItem().getCatalogItemId() == matchingVariant.getCatalogId() && tag.getTagListing().isActive())) {
33973 tejus.loha 602
                    Map<String, Object> variantObj = new HashMap<>();
34229 vikas.jang 603
                    variantObj.put("catalogId", matchingVariant.getCatalogId());
604
                    variantObj.put("variantName", matchingVariant.getVariantName());
35344 vikas 605
                    variantObj.put("mrp", itemTagModel != null ? itemTagModel.getTagListing().getMrp() : 0.0);
35345 vikas 606
                    variantObj.put("mop", itemTagModel != null ? itemTagModel.getTagListing().getMop() : 0.0);
35344 vikas 607
                    variantObj.put("sellingPrice", itemTagModel != null ? itemTagModel.getTagListing().getSellingPrice() : 0.0);
33973 tejus.loha 608
                    variantList.add(variantObj);
609
                }
610
            }
611
        }
612
 
613
        if (variantList.isEmpty()) {
614
            return "[]";
615
        }
616
 
617
        variantList.sort((v1, v2) -> {
618
            int[] n1 = extractNumbers((String) v1.get("variantName"));
619
            int[] n2 = extractNumbers((String) v2.get("variantName"));
620
            int cmp = Integer.compare(n1[0], n2[0]);
621
            return cmp != 0 ? cmp : Integer.compare(n1[1], n2[1]);
622
        });
623
 
624
        ObjectMapper mapper = new ObjectMapper();
625
        return mapper.writeValueAsString(variantList);
626
    }
33979 ranu 627
//(4GB 64GB)
33973 tejus.loha 628
    private int[] extractNumbers(String input) {
629
        String[] parts = input.split("\\s+");
630
        int[] result = new int[2];
631
 
632
        for (int i = 0; i < Math.min(parts.length, 2); i++) {
33979 ranu 633
            String part = (parts[i].toUpperCase()).replace("(", "").replace(")", "");
33973 tejus.loha 634
            if (part.endsWith("GB")) {
635
                result[i] = Integer.parseInt(part.replace("GB", "").trim());
636
            } else if (part.endsWith("TB")) {
637
                result[i] = Integer.parseInt(part.replace("TB", "").trim()) * 1024;
638
            }
639
        }
640
 
641
        return result;
642
    }
643
 
31604 tejbeer 644
}