Subversion Repositories SmartDukaan

Rev

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