Subversion Repositories SmartDukaan

Rev

Rev 37114 | Rev 37640 | 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;
36971 amit 14
import com.spice.profitmandi.dao.repository.catalog.*;
33245 ranu 15
import com.spice.profitmandi.dao.repository.dtr.Mongo;
16
import com.spice.profitmandi.dao.repository.dtr.WebListingRepository;
17
import com.spice.profitmandi.dao.repository.dtr.WebProductListingRepository;
33542 amit.gupta 18
import com.spice.profitmandi.dao.repository.similarModel.SimilarModelRepository;
33973 tejus.loha 19
import com.spice.profitmandi.service.catalog.SuperCatalogModel;
34021 ranu 20
import com.spice.profitmandi.service.inventory.SaholicInventoryService;
33245 ranu 21
import com.spice.profitmandi.service.tag.ItemTagModel;
22
import in.shop2020.model.v1.catalog.status;
31604 tejbeer 23
import org.apache.logging.log4j.LogManager;
24
import org.apache.logging.log4j.Logger;
25
import org.apache.solr.client.solrj.SolrClient;
26
import org.apache.solr.client.solrj.impl.HttpSolrClient;
27
import org.apache.solr.common.SolrInputDocument;
28
import org.json.JSONArray;
29
import org.json.JSONException;
30
import org.json.JSONObject;
31
import org.springframework.beans.factory.annotation.Autowired;
31613 tejbeer 32
import org.springframework.beans.factory.annotation.Value;
31604 tejbeer 33
import org.springframework.stereotype.Component;
34
 
33245 ranu 35
import java.io.BufferedReader;
36
import java.io.IOException;
37
import java.io.InputStream;
38
import java.io.InputStreamReader;
39
import java.net.HttpURLConnection;
40
import java.net.URL;
41
import java.net.URLConnection;
42
import java.time.ZoneId;
43
import java.util.*;
44
import java.util.Map.Entry;
45
import java.util.stream.Collectors;
46
import java.util.zip.GZIPInputStream;
31604 tejbeer 47
 
48
@Component
49
public class FofoSolr {
50
 
33542 amit.gupta 51
    @Autowired
52
    private Gson gson;
31604 tejbeer 53
 
33542 amit.gupta 54
    @Autowired
55
    private TagListingRepository tagListingRepository;
31604 tejbeer 56
 
33542 amit.gupta 57
    @Autowired
35357 ranu 58
    private CatalogRepository catalogRepository;
59
 
60
    @Autowired
33542 amit.gupta 61
    TagRankingRepository tagRankingRepository;
31604 tejbeer 62
 
33542 amit.gupta 63
    @Autowired
64
    private Mongo contentMongoClient;
31604 tejbeer 65
 
33542 amit.gupta 66
    @Autowired
67
    private WebListingRepository webListingRepository;
31612 tejbeer 68
 
33542 amit.gupta 69
    @Autowired
70
    private WebProductListingRepository webProductListingRepository;
31612 tejbeer 71
 
33973 tejus.loha 72
    @Autowired
73
    private SuperCatalogMappingRepository superCatalogMappingRepository;
74
 
33542 amit.gupta 75
    @Value("${new.solr.url}")
76
    private String solrUrl;
31613 tejbeer 77
 
33542 amit.gupta 78
    @Value("${reportico.url}")
79
    private String reporticoUrl;
33486 amit.gupta 80
 
33542 amit.gupta 81
    private static final Logger logger = LogManager.getLogger(FofoSolr.class);
31604 tejbeer 82
 
35797 amit 83
    private static final List<Integer> CATEGORY_MASTER = Arrays.asList(10006, 10007, 10010, 14202, 14203);
31604 tejbeer 84
 
36971 amit 85
    @Autowired
86
    ModelFlagshipRepository modelFlagshipRepository;
87
 
37276 amit 88
    @Autowired
89
    ModelHotDealRepository modelHotDealRepository;
90
 
33542 amit.gupta 91
    private static String getUrlContent(String urlString) {
92
        BufferedReader reader = null;
93
        try {
94
            URL url = new URL(urlString);
95
            URLConnection conn = url.openConnection();
96
            conn.setConnectTimeout(5000);
97
            conn.setReadTimeout(5000);
98
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
99
            return reader.lines().collect(Collectors.joining(System.lineSeparator()));
100
        } catch (IOException e) {
101
            e.printStackTrace();
102
        } finally {
103
            if (reader != null) {
104
                try {
105
                    reader.close();
106
                } catch (IOException e) {
107
                    e.printStackTrace();
108
                }
109
            }
110
        }
111
        return null;
112
    }
31604 tejbeer 113
 
33542 amit.gupta 114
    public JSONArray getAvailability() throws IOException, JSONException {
115
        String url = reporticoUrl + "?execute_mode=EXECUTE&xmlin=warehousecisnew.xml&project=FOCOR&project_password=focor&target_format=JSON";
116
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
117
        connection.setRequestProperty("Accept-Encoding", "gzip");
118
        BufferedReader reader = null;
31604 tejbeer 119
 
33542 amit.gupta 120
        try {
121
            InputStream inputStream = connection.getInputStream();
31604 tejbeer 122
 
33542 amit.gupta 123
            if ("gzip".equals(connection.getContentEncoding())) {
124
                inputStream = new GZIPInputStream(inputStream);
125
            }
31604 tejbeer 126
 
33542 amit.gupta 127
            reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
128
            StringBuilder responseBuilder = new StringBuilder();
129
            String line;
31604 tejbeer 130
 
33542 amit.gupta 131
            while ((line = reader.readLine()) != null) {
132
                responseBuilder.append(line);
133
            }
31604 tejbeer 134
 
33542 amit.gupta 135
            JSONObject responseJson = new JSONObject(responseBuilder.toString());
136
            return responseJson.getJSONArray("data");
137
        } finally {
138
            if (reader != null) {
139
                try {
140
                    reader.close();
141
                } catch (IOException e) {
142
                    // Ignore
143
                }
144
            }
145
        }
146
    }
31604 tejbeer 147
 
33542 amit.gupta 148
    public JSONArray getPendingPO() throws IOException, JSONException {
149
        String url = reporticoUrl + "?execute_mode=EXECUTE&xmlin=UnfulfilledPOItemsNew.xml&project=FOCOR&project_password=focor&target_format=JSON";
150
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
151
        connection.setRequestProperty("Accept-Encoding", "gzip");
152
        BufferedReader reader = null;
31604 tejbeer 153
 
33542 amit.gupta 154
        try {
155
            InputStream inputStream = connection.getInputStream();
31604 tejbeer 156
 
33542 amit.gupta 157
            if ("gzip".equals(connection.getContentEncoding())) {
158
                inputStream = new GZIPInputStream(inputStream);
159
            }
31604 tejbeer 160
 
33542 amit.gupta 161
            reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
162
            StringBuilder responseBuilder = new StringBuilder();
163
            String line;
31604 tejbeer 164
 
33542 amit.gupta 165
            while ((line = reader.readLine()) != null) {
166
                responseBuilder.append(line);
167
            }
31604 tejbeer 168
 
33542 amit.gupta 169
            JSONObject responseJson = new JSONObject(responseBuilder.toString());
170
            return responseJson.getJSONArray("data");
171
        } finally {
172
            if (reader != null) {
173
                try {
174
                    reader.close();
175
                } catch (IOException e) {
176
                    // Ignore
177
                }
178
            }
179
        }
180
    }
31604 tejbeer 181
 
34021 ranu 182
    @Autowired
183
    SaholicInventoryService saholicInventoryService;
184
 
33542 amit.gupta 185
    public Map<String, Map<String, Map<String, Integer>>> getItemMap() throws Exception {
34021 ranu 186
 
187
//        JSONArray availabilityJSONArray = this.getAvailability();
35343 ranu 188
        List<SaholicCIS> saholicCISList = saholicInventoryService.getSaholicStockListWithoutCatalogMovingStatus();
34021 ranu 189
 
190
//        JSONArray pendingPOJSONArray = this.getPendingPO();
191
        List<SaholicPOItem> saholicPOItemList = saholicInventoryService.getSaholicPOItemList();
192
 
33542 amit.gupta 193
        Map<String, Map<String, Map<String, Integer>>> availabilityItemMap = new HashMap<>();
34021 ranu 194
        for (SaholicCIS rawAvailability : saholicCISList) {
31604 tejbeer 195
 
34021 ranu 196
            String itemId = String.valueOf(rawAvailability.getItemId());
197
            String warehouseId = String.valueOf(rawAvailability.getWarehouseId());
198
 
199
            if (!availabilityItemMap.containsKey(itemId)) {
200
                availabilityItemMap.put(itemId, new HashMap<>());
33542 amit.gupta 201
            }
34021 ranu 202
            if (!availabilityItemMap.get(itemId).containsKey(warehouseId)) {
203
                availabilityItemMap.get(itemId).put(warehouseId, new HashMap<String, Integer>());
204
                availabilityItemMap.get(itemId).get(warehouseId).put("netAvailability", 0);
205
                availabilityItemMap.get(itemId).get(warehouseId).put("netPo", 0);
33542 amit.gupta 206
            }
34021 ranu 207
            int netAvailability = availabilityItemMap.get(itemId).get(warehouseId).get("netAvailability") + rawAvailability.getNetavailability();
208
            availabilityItemMap.get(itemId).get(warehouseId).put("netAvailability", netAvailability);
33542 amit.gupta 209
        }
31604 tejbeer 210
 
34021 ranu 211
        for (SaholicPOItem rawPendingPo : saholicPOItemList) {
212
            String itemId = String.valueOf(rawPendingPo.getItemId());
213
            String warehouseId = String.valueOf(rawPendingPo.getWarehouseId());
33542 amit.gupta 214
            if (!availabilityItemMap.containsKey(itemId)) {
215
                availabilityItemMap.put(itemId, new HashMap<String, Map<String, Integer>>());
216
            }
217
            if (!availabilityItemMap.get(itemId).containsKey(warehouseId)) {
218
                availabilityItemMap.get(itemId).put(warehouseId, new HashMap<String, Integer>() {
219
                    {
220
                        put("netAvailability", 0);
221
                        put("netPo", 0);
222
                    }
223
                });
224
            }
225
            availabilityItemMap.get(itemId).get(warehouseId).put("netPo",
34021 ranu 226
                    availabilityItemMap.get(itemId).get(warehouseId).get("netPo") + rawPendingPo.getUnfulfilledQty());
31604 tejbeer 227
 
33542 amit.gupta 228
        }
229
        return availabilityItemMap;
31604 tejbeer 230
 
33542 amit.gupta 231
    }
31604 tejbeer 232
 
33245 ranu 233
    public Map<Integer, List<String>> getLabels() throws ProfitMandiBusinessException {
33542 amit.gupta 234
        List<String> labels = Arrays.asList("partner-best-sellers", "partner-price-drop", "new-launches",
235
                "upgrade-offer", "special-support");
31612 tejbeer 236
 
33542 amit.gupta 237
        Map<Integer, String> webListing = webListingRepository.selectByUrls(labels).stream()
238
                .collect(Collectors.toMap(x -> x.getId(), x -> x.getUrl()));
31612 tejbeer 239
 
33542 amit.gupta 240
        Map<Integer, List<WebProductListing>> webProductListingMap = webProductListingRepository
241
                .selectAllByWebListingIds(new ArrayList<>(webListing.keySet())).stream()
242
                .collect(Collectors.groupingBy(x -> x.getWebListingId()));
31612 tejbeer 243
 
33542 amit.gupta 244
        Map<Integer, List<String>> catalogLabelMap = new HashMap<>();
245
        for (Entry<Integer, List<WebProductListing>> webProductListingEntry : webProductListingMap.entrySet()) {
31612 tejbeer 246
 
33542 amit.gupta 247
            for (WebProductListing webProduct : webProductListingEntry.getValue()) {
31612 tejbeer 248
 
33542 amit.gupta 249
                if (!catalogLabelMap.containsKey(webProduct.getEntityId())) {
31612 tejbeer 250
 
33542 amit.gupta 251
                    catalogLabelMap.put(webProduct.getEntityId(), new ArrayList<>());
31612 tejbeer 252
 
33542 amit.gupta 253
                }
31612 tejbeer 254
 
33542 amit.gupta 255
                List<String> itemLabels = catalogLabelMap.get(webProduct.getEntityId());
256
                itemLabels.add(webListing.get(webProduct.getWebListingId()));
257
                catalogLabelMap.put(webProduct.getEntityId(), itemLabels);
31612 tejbeer 258
 
33542 amit.gupta 259
            }
31612 tejbeer 260
 
33542 amit.gupta 261
        }
31612 tejbeer 262
 
33542 amit.gupta 263
        return catalogLabelMap;
264
    }
31612 tejbeer 265
 
33542 amit.gupta 266
    @Autowired
267
    SimilarModelRepository similarModelRepository;
31604 tejbeer 268
 
33542 amit.gupta 269
    public void populateTagItems() throws Exception {
270
        Map<String, Map<String, Map<String, Integer>>> availabilityItemMap = getItemMap();
271
        List<TagRanking> tagRankingList = tagRankingRepository.getAllTagRanking();
272
        List<Integer> rankingList = new ArrayList<>();
273
        Map<Integer, String> featureMap = new HashMap<>();
274
        for (TagRanking tagRanking : tagRankingList) {
275
            rankingList.add(tagRanking.getCatalogItemId());
276
            featureMap.put(tagRanking.getCatalogItemId(), tagRanking.getFeature());
277
        }
278
        //Get Similar Models
33570 amit.gupta 279
        /*List<SimilarModel> similarModels = similarModelRepository.selectAll();
31612 tejbeer 280
 
33570 amit.gupta 281
        Map<Integer, List<Integer>> similarModelsMap = similarModels.stream().collect(Collectors.groupingBy(SimilarModel::getCatalogId, Collectors.mapping(x -> x.getSimilarCatalogId(), Collectors.toList())));*/
31612 tejbeer 282
 
33542 amit.gupta 283
        Map<Integer, Map<String, Object>> catalogMap = new HashMap<>();
31612 tejbeer 284
 
33542 amit.gupta 285
        List<status> statuses = Arrays.asList(status.ACTIVE, status.PAUSED_BY_RISK, status.PARTIALLY_ACTIVE);
31612 tejbeer 286
 
33542 amit.gupta 287
        Map<Integer, List<String>> catalogLabelMap = this.getLabels();
31604 tejbeer 288
 
33973 tejus.loha 289
        //logger.info("catalogLabelMap {}", catalogLabelMap);
31604 tejbeer 290
 
35364 ranu 291
        List<ItemTagModel> itemTagModels = tagListingRepository.getAllItemTagByStatus(statuses);
31604 tejbeer 292
 
35364 ranu 293
        logger.info("itemTagModels {}" , itemTagModels.size());
35358 ranu 294
 
35365 ranu 295
        List<Integer> eolWithOutStock = catalogRepository.findAllWithEOLWithOutStock();
35426 ranu 296
        List<Integer> eolWithBadQty = catalogRepository.findAllWithNoGoodStock();
35357 ranu 297
 
35365 ranu 298
        Set<Integer> eolSet = new HashSet<>(eolWithOutStock);
35426 ranu 299
        eolSet.addAll(eolWithBadQty);
35358 ranu 300
 
36971 amit 301
        // Flagship models active as of today (catalog.model_flagship start_date/end_date)
302
        Set<Integer> flagshipSet = modelFlagshipRepository.selectActiveFlagshipCatalogIds();
35426 ranu 303
 
37276 amit 304
        // Hot deal models active as of today (catalog.model_hot_deal start_date/end_date).
305
        // This table is the only source of hot_deal_b - tag_listing.hot_deals is not read.
306
        Set<Integer> hotDealSet = modelHotDealRepository.selectActiveCatalogIds(java.time.LocalDate.now());
307
 
36971 amit 308
        // Flagship is surfaced as a label (prepended so it shows first, ahead of all other flags)
309
        for (Integer flagshipCatalogId : flagshipSet) {
310
            catalogLabelMap.computeIfAbsent(flagshipCatalogId, k -> new ArrayList<>()).add(0, "flagship");
311
        }
312
 
313
 
35365 ranu 314
        logger.info("eolSetIds.size {}" , eolSet.size());
35357 ranu 315
 
33542 amit.gupta 316
        Map<String, Object> projection = new HashMap<>();
317
        projection.put("defaultImageUrl", 1);
31604 tejbeer 318
 
33542 amit.gupta 319
        List<String> excludeBrands = Arrays.asList("Dummy", "FOC HANDSET");
31604 tejbeer 320
 
33562 amit.gupta 321
        Map<Float, List<Integer>> priceModelMap = new TreeMap<>();
322
        for (ItemTagModel itemTagModel : itemTagModels) {
323
            TagListing tagListing = itemTagModel.getTagListing();
324
            com.spice.profitmandi.dao.entity.catalog.Item item = itemTagModel.getItem();
33542 amit.gupta 325
            if (excludeBrands.contains(item.getBrand())) {
326
                continue;
327
            }
31604 tejbeer 328
 
33542 amit.gupta 329
            if (!catalogMap.containsKey(item.getCatalogItemId())) {
33571 amit.gupta 330
                if (!priceModelMap.containsKey(tagListing.getMop()) && item.getCategoryId() == 10006) {
33572 amit.gupta 331
                    priceModelMap.put(tagListing.getMop(), new ArrayList<>());
33562 amit.gupta 332
                }
33570 amit.gupta 333
                if (item.getCategoryId() == 10006) {
33571 amit.gupta 334
                    List<Integer> priceModels = priceModelMap.get(tagListing.getMop());
33565 amit.gupta 335
                    priceModels.add(item.getCatalogItemId());
336
                }
33562 amit.gupta 337
 
33542 amit.gupta 338
                Map<String, Object> catalogObj = new HashMap<>();
33570 amit.gupta 339
                catalogObj.put("stockColor", 0);
33542 amit.gupta 340
                catalogObj.put("feature", "");
341
                catalogObj.put("hsnCode", item.getHsnCode());
342
                catalogObj.put("title",
343
                        String.join(" ", Arrays.asList(item.getBrand(), item.getModelName(), item.getModelNumber())
344
                                .stream().filter(s -> s != null && !s.isEmpty()).collect(Collectors.toList())));
345
                catalogObj.put("brand", new String[]{item.getBrand()});
346
                if (item.getBrand().equals("Huawei") || item.getBrand().equals("Honor")) {
347
                    catalogObj.put("brand", new String[]{"Huawei", "Honor"});
348
                }
349
                if (item.getBrand().equals("Mi") || item.getBrand().equals("Xiaomi")
350
                        || item.getBrand().equals("Redmi")) {
351
                    catalogObj.put("brand", new String[]{"Mi", "Xiaomi", "Redmi"});
352
                }
353
                catalogObj.put("identifier", item.getCatalogItemId());
354
                catalogObj.put("items", new HashMap<Integer, Map<String, Object>>());
355
                Map<String, Object> filterMap = new HashMap<>();
356
                filterMap.put("_id", item.getCatalogItemId());
357
                // Don't include if catalog not available
358
                try {
359
                    String imageUrl = contentMongoClient.getEntityById(item.getCatalogItemId()).getDefaultImageUrl();
31624 tejbeer 360
 
33542 amit.gupta 361
                    if (imageUrl != null) {
362
                        catalogObj.put("imageUrl", imageUrl);
363
                    } else {
364
                        catalogObj.put("imageUrl",
365
                                "https://images.smartdukaan.com/uploads/campaigns/" + item.getCatalogItemId() + ".jpg");
366
                    }
367
                } catch (Exception e) {
368
                    try {
369
                        catalogObj.put("imageUrl",
370
                                "https://images.smartdukaan.com/uploads/campaigns/" + item.getCatalogItemId() + ".jpg");
371
                    } catch (Exception e2) {
372
                        e2.printStackTrace();
373
                    }
374
                }
375
                try {
376
                    catalogObj.put("rank", rankingList.indexOf(item.getCatalogItemId()));
377
                } catch (Exception e) {
378
                    // A very big number
379
                    e.printStackTrace();
380
                    catalogObj.put("rank", 50000000);
381
                }
382
                if (featureMap.containsKey(item.getCatalogItemId())
383
                        && featureMap.get(item.getCatalogItemId()) != null) {
384
                    catalogObj.put("feature", featureMap.get(item.getCatalogItemId()));
31612 tejbeer 385
 
33542 amit.gupta 386
                }
31612 tejbeer 387
 
33542 amit.gupta 388
                catalogObj.put("categoryId", CATEGORY_MASTER.contains(item.getCategoryId()) ? item.getCategoryId() : 6);
31612 tejbeer 389
 
37114 amit 390
                if (item.getCategoryId() == 10006 || item.getCategoryId() == 10007) {
33542 amit.gupta 391
                    catalogObj.put("categoryId", 3);
392
                }
393
                catalogObj.put("subCategoryId", item.getCategoryId());
394
                catalogObj.put("create_timestamp",
33562 amit.gupta 395
                        tagListing.getCreatedTimestamp().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
31604 tejbeer 396
 
33542 amit.gupta 397
                if (catalogLabelMap.containsKey(item.getCatalogItemId())
398
                        && catalogLabelMap.get(item.getCatalogItemId()) != null) {
399
                    catalogObj.put("labels", catalogLabelMap.get(item.getCatalogItemId()));
31604 tejbeer 400
 
33542 amit.gupta 401
                }
402
                catalogMap.put(item.getCatalogItemId(), catalogObj);
403
                catalogObj.put("avColor", new HashMap<>());
31604 tejbeer 404
 
33542 amit.gupta 405
            }
31604 tejbeer 406
 
33542 amit.gupta 407
            Map<String, Object> catalogObj = catalogMap.get(item.getCatalogItemId());
408
            Map<Integer, Integer> avColorMap = (Map<Integer, Integer>) catalogObj.get("avColor");
31604 tejbeer 409
 
33542 amit.gupta 410
            if (availabilityItemMap.containsKey(String.valueOf(item.getId()))) {
33570 amit.gupta 411
                int itemStockColor = 0;
33542 amit.gupta 412
                for (Map.Entry<String, Map<String, Integer>> entry : availabilityItemMap
413
                        .get(String.valueOf(item.getId())).entrySet()) {
414
                    String warehouseId = entry.getKey();
415
                    Map<String, Integer> avMap = entry.getValue();
416
                    if (!avColorMap.containsKey(Integer.parseInt(warehouseId))) {
417
                        avColorMap.put(Integer.parseInt(warehouseId), 0);
418
                    }
419
                    int color = avColorMap.get(Integer.parseInt(warehouseId));
31604 tejbeer 420
 
33542 amit.gupta 421
                    if (avMap.get("netAvailability") > 0) {
422
                        color = 2;
33562 amit.gupta 423
                    } else if (avMap.get("netPo") > 0) {
33542 amit.gupta 424
                        color = Math.max(color, 1);
425
                    } else {
426
                        color = Math.max(color, 0);
427
                    }
428
                    avColorMap.put(Integer.parseInt(warehouseId), color);
31604 tejbeer 429
 
33542 amit.gupta 430
                    catalogObj.put("avColor", avColorMap);
33570 amit.gupta 431
                    if (color > itemStockColor) {
432
                        itemStockColor = color;
433
                    }
33542 amit.gupta 434
                }
33570 amit.gupta 435
                if (itemStockColor > 0 && itemStockColor > (Integer) catalogObj.get("stockColor")) {
436
                    catalogObj.put("stockColor", itemStockColor);
437
                }
33542 amit.gupta 438
            }
31604 tejbeer 439
 
33542 amit.gupta 440
            Map<Integer, Object> itemColorMap = (Map<Integer, Object>) catalogObj.get("items");
31604 tejbeer 441
 
33542 amit.gupta 442
            if (!itemColorMap.containsKey(item.getId())) {
443
                itemColorMap.put(item.getId(), new HashMap<String, Object>() {
444
                    {
445
                        put("color", item.getColor().replace("f_", ""));
446
                        put("tagPricing", new ArrayList<TagListing>());
447
                    }
448
                });
449
            }
450
            Map<String, Object> itemMap = (Map<String, Object>) itemColorMap.get(item.getId());
451
            List<TagListing> tagPricing = (List<TagListing>) itemMap.get("tagPricing");
33562 amit.gupta 452
            tagPricing.add(tagListing);
33542 amit.gupta 453
        }
33562 amit.gupta 454
        //logger.info("catalogObj {}", catalogMap);
31604 tejbeer 455
 
33973 tejus.loha 456
        List<SuperCatalogModel> superCatalogMappingList = superCatalogMappingRepository.selectJoinedData();
457
        List<SuperCatalogMapping> superCatalogs = superCatalogMappingRepository.selectAll();
33542 amit.gupta 458
        List<SolrInputDocument> catalogSolrObjs = new ArrayList<>();
459
        for (Entry<Integer, Map<String, Object>> entry : catalogMap.entrySet()) {
460
            int catalogId = entry.getKey();
34229 vikas.jang 461
            Optional<SuperCatalogModel> superCatalogMapping = findMappingByCatalogId(superCatalogMappingList, catalogId, itemTagModels);
33542 amit.gupta 462
            Map<String, Object> catalogValMap = entry.getValue();
463
            Map<Integer, Object> itemsMap = (Map<Integer, Object>) catalogValMap.get("items");
31604 tejbeer 464
 
33542 amit.gupta 465
            boolean active = false;
466
            // Map<Integer, Object> itemsMap = (Map<String, Object>)
467
            // catalogValMap.get("items");
468
            List<SolrInputDocument> itemObjs = new ArrayList<>();
469
            float mop = 0;
33574 amit.gupta 470
            float dp = 0;
31604 tejbeer 471
 
33542 amit.gupta 472
            for (Entry<Integer, Object> itemEntry : itemsMap.entrySet()) {
473
                int itemId = itemEntry.getKey();
474
                Map<String, Object> itemMap = (Map<String, Object>) itemEntry.getValue();
475
                List<TagListing> tags = (List<TagListing>) itemMap.get("tagPricing");
476
                SolrInputDocument itemObj = new SolrInputDocument();
31604 tejbeer 477
 
34136 amit.gupta 478
                for (TagListing tagListing : tags) {
479
                    active = active || tagListing.isActive();
480
                    itemObj.setField("id", "itemtag-" + itemId + "-" + tagListing.getTagId());
33542 amit.gupta 481
                    itemObj.setField("color_s", itemMap.get("color"));
482
                    itemObj.setField("itemId_i", itemId);
34136 amit.gupta 483
                    itemObj.setField("tagId_i", tagListing.getTagId());
484
                    itemObj.setField("mrp_f", tagListing.getMrp());
485
                    itemObj.setField("mop_f", tagListing.getMop());
486
                    itemObj.setField("sellingPrice_f", tagListing.getSellingPrice());
487
                    itemObj.setField("active_b", tagListing.isActive());
37276 amit 488
                    itemObj.setField("hot_deal_b", hotDealSet.contains(catalogId));
34136 amit.gupta 489
                    mop = tagListing.getMop();
490
                    dp = tagListing.getSellingPrice();
33542 amit.gupta 491
                }
492
                itemObjs.add(itemObj);
493
            }
31604 tejbeer 494
 
33542 amit.gupta 495
            SolrInputDocument catalogSolrObj = new SolrInputDocument();
496
            catalogSolrObj.setField("id", "catalog" + catalogId);
497
            catalogSolrObj.setField("rank_i", catalogValMap.get("rank"));
498
            catalogSolrObj.setField("title_s", catalogValMap.get("title"));
499
            catalogSolrObj.addChildDocuments(itemObjs);
500
            catalogSolrObj.setField("child_b", itemObjs.size() > 0);
501
            catalogSolrObj.setField("catalogId_i", catalogId);
33980 ranu 502
            logger.info("superCatalogMapping1- {}", superCatalogMapping);
33973 tejus.loha 503
            if (superCatalogMapping.isPresent()) {
504
                int superCatalogId = superCatalogMapping.get().getSuperCatalogId();
34229 vikas.jang 505
                String superCatalogMappingVariants = findMappingVariantsByCatalogId(superCatalogs, superCatalogId, itemTagModels);
33973 tejus.loha 506
                catalogSolrObj.setField("superCatalog_i", superCatalogId);
507
                catalogSolrObj.setField("superCatalog_s", superCatalogMapping.get().getSuperCatalogName());
508
                catalogSolrObj.setField("superCatalogVariants_s", superCatalogMappingVariants);
509
            } else {
510
                catalogSolrObj.setField("superCatalog_i", 0);
34023 vikas.jang 511
                catalogSolrObj.setField("superCatalog_s", catalogValMap.get("title"));
33973 tejus.loha 512
                catalogSolrObj.setField("superCatalogVariants_s", "[]");
513
            }
33542 amit.gupta 514
            catalogSolrObj.setField("imageUrl_s",
515
                    catalogValMap.get("imageUrl").toString().replace("saholic", "smartdukaan"));
516
            catalogSolrObj.setField("feature_s", catalogValMap.get("feature"));
517
            catalogSolrObj.setField("brand_ss", catalogValMap.get("brand"));
518
            catalogSolrObj.setField("create_s", catalogValMap.get("create_timestamp"));
519
            catalogSolrObj.setField("categoryId_i", catalogValMap.get("categoryId"));
520
            catalogSolrObj.setField("subCategoryId_i", catalogValMap.get("subCategoryId"));
521
            catalogSolrObj.setField("label_ss", catalogValMap.get("labels"));
522
            catalogSolrObj.setField("mop_f", mop);
33574 amit.gupta 523
            catalogSolrObj.setField("dp_f", dp);
33542 amit.gupta 524
            catalogSolrObj.setField("hsncode_s", catalogValMap.get("hsnCode"));
525
            catalogSolrObj.setField("show_default_b", true);
31710 tejbeer 526
 
33542 amit.gupta 527
            String[] brands = (String[]) catalogValMap.get("brand");
528
            for (String brand : brands) {
529
                if (brand.equals("FOC")) {
530
                    catalogSolrObj.setField("show_default_b", false);
531
                }
31604 tejbeer 532
 
33542 amit.gupta 533
                if (brand.equals("Live Demo")) {
534
                    catalogSolrObj.setField("show_default_b", false);
535
                }
536
            }
537
            Map<Integer, Integer> avColorMap = (Map<Integer, Integer>) catalogValMap.get("avColor");
33499 amit.gupta 538
 
33570 amit.gupta 539
            for (Integer warehouseId : ProfitMandiConstants.WAREHOUSE_MAP.keySet()) {
540
                catalogSolrObj.setField("w" + warehouseId + "_i", 0);
541
            }
33542 amit.gupta 542
            for (Entry<Integer, Integer> avColorEntry : avColorMap.entrySet()) {
543
                int whId = avColorEntry.getKey();
33562 amit.gupta 544
                int color = avColorEntry.getValue();
33542 amit.gupta 545
                catalogSolrObj.setField("w" + whId + "_i", color);
546
            }
33570 amit.gupta 547
 
548
            List<Integer> similalarModels = null;
549
            if ((Integer) catalogValMap.get("categoryId") == 3) {
33571 amit.gupta 550
                float starPrice = mop - 500f;
551
                float endPrice = mop + 1000f;
33570 amit.gupta 552
                similalarModels = new ArrayList<>();
553
                for (Entry<Float, List<Integer>> floatListEntry : priceModelMap.entrySet()) {
554
                    float modelPrice = floatListEntry.getKey();
555
                    if (modelPrice >= starPrice && modelPrice <= endPrice) {
556
                        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 557
                        //logger.info("Entry before - {}, after - {}", floatListEntry.getValue().size(), instock.size());
33570 amit.gupta 558
                        similalarModels.addAll(instock);
559
                    }
560
                    if (modelPrice > endPrice) break;
561
                }
562
                similalarModels.remove(Integer.valueOf(catalogId));
563
            }
34049 vikas.jang 564
            catalogSolrObj.setField("similarModels_ii", similalarModels == null ? Collections.EMPTY_LIST : similalarModels);
33570 amit.gupta 565
 
566
 
33542 amit.gupta 567
            catalogSolrObj.setField("active_b", active);
35365 ranu 568
            if(eolSet.contains(catalogId)){
35366 ranu 569
                catalogSolrObj.setField("eol_no_stock_b", true);
35365 ranu 570
            }else {
35366 ranu 571
                catalogSolrObj.setField("eol_no_stock_b", false);
35365 ranu 572
            }
36971 amit 573
            catalogSolrObj.setField("flagship_b", flagshipSet.contains(catalogId));
37276 amit 574
            catalogSolrObj.setField("hot_deal_b", hotDealSet.contains(catalogId));
33542 amit.gupta 575
            catalogSolrObjs.add(catalogSolrObj);
576
        }
31604 tejbeer 577
 
33542 amit.gupta 578
        String solrPath = "http://" + solrUrl + ":8984/solr/demo";
579
        SolrClient solr = new HttpSolrClient.Builder(solrPath).build();
31604 tejbeer 580
 
33542 amit.gupta 581
        solr.deleteByQuery("*:*");
582
        solr.add(catalogSolrObjs);
583
 
584
        org.apache.solr.client.solrj.response.UpdateResponse updateResponse = solr.commit();
585
        logger.info("solr {}", updateResponse.getStatus());
586
 
587
    }
588
 
589
    public void pushData() throws Exception {
590
        this.populateTagItems();
591
    }
33973 tejus.loha 592
 
35547 amit 593
    /**
594
     * Updates a single catalog in Solr based on catalogId.
595
     * Used for real-time updates when TagListing changes.
596
     *
597
     * @param catalogId The catalog ID to update
598
     */
599
    public void updateSingleCatalog(int catalogId) throws Exception {
600
        logger.info("Updating single catalog in Solr: catalogId={}", catalogId);
601
 
602
        List<status> statuses = Arrays.asList(status.ACTIVE, status.PAUSED_BY_RISK, status.PARTIALLY_ACTIVE);
36971 amit 603
        boolean flagship = !modelFlagshipRepository
604
                .selectActiveFlagshipCatalogIds(Collections.singletonList(catalogId)).isEmpty();
37276 amit 605
        boolean hotDeal = !modelHotDealRepository
606
                .selectActiveByCatalogItemIds(Collections.singletonList(catalogId), java.time.LocalDate.now())
607
                .isEmpty();
35547 amit 608
 
609
        // Get all TagListings for this catalog
610
        List<ItemTagModel> itemTagModels = tagListingRepository.getItemTagByCatalogIdAndStatus(catalogId, statuses);
611
 
612
        if (itemTagModels.isEmpty()) {
613
            logger.warn("No active TagListings found for catalogId={}, removing from Solr", catalogId);
614
            String solrPath = "http://" + solrUrl + ":8984/solr/demo";
615
            SolrClient solr = new HttpSolrClient.Builder(solrPath).build();
616
            solr.deleteById("catalog" + catalogId);
617
            solr.commit();
618
            return;
619
        }
620
 
621
        // Get availability for items in this catalog
622
        Map<String, Map<String, Map<String, Integer>>> availabilityItemMap = getItemMap();
623
 
624
        // Get ranking info
625
        List<TagRanking> tagRankingList = tagRankingRepository.getAllTagRanking();
626
        List<Integer> rankingList = new ArrayList<>();
627
        Map<Integer, String> featureMap = new HashMap<>();
628
        for (TagRanking tagRanking : tagRankingList) {
629
            rankingList.add(tagRanking.getCatalogItemId());
630
            featureMap.put(tagRanking.getCatalogItemId(), tagRanking.getFeature());
631
        }
632
 
633
        // Get labels
634
        Map<Integer, List<String>> catalogLabelMap = this.getLabels();
635
 
36971 amit 636
        // Flagship is surfaced as a label (prepended so it shows first, ahead of all other flags)
637
        if (flagship) {
638
            catalogLabelMap.computeIfAbsent(catalogId, k -> new ArrayList<>()).add(0, "flagship");
639
        }
640
 
35547 amit 641
        // Get EOL info
642
        List<Integer> eolWithOutStock = catalogRepository.findAllWithEOLWithOutStock();
643
        List<Integer> eolWithBadQty = catalogRepository.findAllWithNoGoodStock();
644
        Set<Integer> eolSet = new HashSet<>(eolWithOutStock);
645
        eolSet.addAll(eolWithBadQty);
646
 
647
        // Build catalog document
648
        com.spice.profitmandi.dao.entity.catalog.Item firstItem = itemTagModels.get(0).getItem();
649
        TagListing firstTagListing = itemTagModels.get(0).getTagListing();
650
 
651
        Map<Integer, Integer> avColorMap = new HashMap<>();
652
        List<SolrInputDocument> itemObjs = new ArrayList<>();
653
        boolean active = false;
654
        float mop = 0;
655
        float dp = 0;
656
        int stockColor = 0;
657
 
658
        for (ItemTagModel itemTagModel : itemTagModels) {
659
            TagListing tagListing = itemTagModel.getTagListing();
660
            com.spice.profitmandi.dao.entity.catalog.Item item = itemTagModel.getItem();
661
 
662
            active = active || tagListing.isActive();
663
 
664
            // Build item document
665
            SolrInputDocument itemObj = new SolrInputDocument();
666
            itemObj.setField("id", "itemtag-" + item.getId() + "-" + tagListing.getTagId());
667
            itemObj.setField("color_s", item.getColor().replace("f_", ""));
668
            itemObj.setField("itemId_i", item.getId());
669
            itemObj.setField("tagId_i", tagListing.getTagId());
670
            itemObj.setField("mrp_f", tagListing.getMrp());
671
            itemObj.setField("mop_f", tagListing.getMop());
672
            itemObj.setField("sellingPrice_f", tagListing.getSellingPrice());
673
            itemObj.setField("active_b", tagListing.isActive());
37276 amit 674
            itemObj.setField("hot_deal_b", hotDeal);
35547 amit 675
            mop = tagListing.getMop();
676
            dp = tagListing.getSellingPrice();
677
            itemObjs.add(itemObj);
678
 
679
            // Calculate availability color
680
            if (availabilityItemMap.containsKey(String.valueOf(item.getId()))) {
681
                int itemStockColor = 0;
682
                for (Map.Entry<String, Map<String, Integer>> entry : availabilityItemMap
683
                        .get(String.valueOf(item.getId())).entrySet()) {
684
                    String warehouseId = entry.getKey();
685
                    Map<String, Integer> avMap = entry.getValue();
686
                    if (!avColorMap.containsKey(Integer.parseInt(warehouseId))) {
687
                        avColorMap.put(Integer.parseInt(warehouseId), 0);
688
                    }
689
                    int color = avColorMap.get(Integer.parseInt(warehouseId));
690
 
691
                    if (avMap.get("netAvailability") > 0) {
692
                        color = 2;
693
                    } else if (avMap.get("netPo") > 0) {
694
                        color = Math.max(color, 1);
695
                    } else {
696
                        color = Math.max(color, 0);
697
                    }
698
                    avColorMap.put(Integer.parseInt(warehouseId), color);
699
 
700
                    if (color > itemStockColor) {
701
                        itemStockColor = color;
702
                    }
703
                }
704
                if (itemStockColor > stockColor) {
705
                    stockColor = itemStockColor;
706
                }
707
            }
708
        }
709
 
710
        // Build catalog Solr document
711
        SolrInputDocument catalogSolrObj = new SolrInputDocument();
712
        catalogSolrObj.setField("id", "catalog" + catalogId);
713
        catalogSolrObj.setField("rank_i", rankingList.indexOf(catalogId));
714
        catalogSolrObj.setField("title_s", String.join(" ", Arrays.asList(
715
                firstItem.getBrand(), firstItem.getModelName(), firstItem.getModelNumber())
716
                .stream().filter(s -> s != null && !s.isEmpty()).collect(Collectors.toList())));
717
        catalogSolrObj.addChildDocuments(itemObjs);
718
        catalogSolrObj.setField("child_b", itemObjs.size() > 0);
719
        catalogSolrObj.setField("catalogId_i", catalogId);
720
 
721
        // Super catalog mapping
722
        List<SuperCatalogModel> superCatalogMappingList = superCatalogMappingRepository.selectJoinedData();
723
        List<SuperCatalogMapping> superCatalogs = superCatalogMappingRepository.selectAll();
724
        Optional<SuperCatalogModel> superCatalogMapping = findMappingByCatalogId(superCatalogMappingList, catalogId, itemTagModels);
725
 
726
        if (superCatalogMapping.isPresent()) {
727
            int superCatalogId = superCatalogMapping.get().getSuperCatalogId();
728
            String superCatalogMappingVariants = findMappingVariantsByCatalogId(superCatalogs, superCatalogId, itemTagModels);
729
            catalogSolrObj.setField("superCatalog_i", superCatalogId);
730
            catalogSolrObj.setField("superCatalog_s", superCatalogMapping.get().getSuperCatalogName());
731
            catalogSolrObj.setField("superCatalogVariants_s", superCatalogMappingVariants);
732
        } else {
733
            catalogSolrObj.setField("superCatalog_i", 0);
734
            catalogSolrObj.setField("superCatalog_s", catalogSolrObj.getFieldValue("title_s"));
735
            catalogSolrObj.setField("superCatalogVariants_s", "[]");
736
        }
737
 
738
        // Image URL
739
        try {
740
            String imageUrl = contentMongoClient.getEntityById(catalogId).getDefaultImageUrl();
741
            if (imageUrl != null) {
742
                catalogSolrObj.setField("imageUrl_s", imageUrl.replace("saholic", "smartdukaan"));
743
            } else {
744
                catalogSolrObj.setField("imageUrl_s",
745
                        "https://images.smartdukaan.com/uploads/campaigns/" + catalogId + ".jpg");
746
            }
747
        } catch (Exception e) {
748
            catalogSolrObj.setField("imageUrl_s",
749
                    "https://images.smartdukaan.com/uploads/campaigns/" + catalogId + ".jpg");
750
        }
751
 
752
        // Feature
753
        if (featureMap.containsKey(catalogId) && featureMap.get(catalogId) != null) {
754
            catalogSolrObj.setField("feature_s", featureMap.get(catalogId));
755
        } else {
756
            catalogSolrObj.setField("feature_s", "");
757
        }
758
 
759
        // Brand
760
        String[] brands = new String[]{firstItem.getBrand()};
761
        if (firstItem.getBrand().equals("Huawei") || firstItem.getBrand().equals("Honor")) {
762
            brands = new String[]{"Huawei", "Honor"};
763
        }
764
        if (firstItem.getBrand().equals("Mi") || firstItem.getBrand().equals("Xiaomi")
765
                || firstItem.getBrand().equals("Redmi")) {
766
            brands = new String[]{"Mi", "Xiaomi", "Redmi"};
767
        }
768
        catalogSolrObj.setField("brand_ss", brands);
769
 
770
        // Category
771
        catalogSolrObj.setField("categoryId_i", CATEGORY_MASTER.contains(firstItem.getCategoryId())
37114 amit 772
                ? ((firstItem.getCategoryId() == 10006 || firstItem.getCategoryId() == 10007) ? 3 : firstItem.getCategoryId()) : 6);
35547 amit 773
        catalogSolrObj.setField("subCategoryId_i", firstItem.getCategoryId());
774
 
775
        // Timestamps and labels
776
        catalogSolrObj.setField("create_s", firstTagListing.getCreatedTimestamp()
777
                .atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
778
        if (catalogLabelMap.containsKey(catalogId) && catalogLabelMap.get(catalogId) != null) {
779
            catalogSolrObj.setField("label_ss", catalogLabelMap.get(catalogId));
780
        }
781
 
782
        catalogSolrObj.setField("mop_f", mop);
783
        catalogSolrObj.setField("dp_f", dp);
784
        catalogSolrObj.setField("hsncode_s", firstItem.getHsnCode());
785
        catalogSolrObj.setField("show_default_b", true);
786
 
787
        for (String brand : brands) {
788
            if (brand.equals("FOC") || brand.equals("Live Demo")) {
789
                catalogSolrObj.setField("show_default_b", false);
790
            }
791
        }
792
 
793
        // Warehouse availability
794
        for (Integer warehouseId : ProfitMandiConstants.WAREHOUSE_MAP.keySet()) {
795
            catalogSolrObj.setField("w" + warehouseId + "_i", 0);
796
        }
797
        for (Entry<Integer, Integer> avColorEntry : avColorMap.entrySet()) {
798
            int whId = avColorEntry.getKey();
799
            int color = avColorEntry.getValue();
800
            catalogSolrObj.setField("w" + whId + "_i", color);
801
        }
802
 
803
        // Similar models - simplified for single update
804
        catalogSolrObj.setField("similarModels_ii", Collections.EMPTY_LIST);
805
 
806
        catalogSolrObj.setField("active_b", active);
807
        catalogSolrObj.setField("eol_no_stock_b", eolSet.contains(catalogId));
36971 amit 808
        catalogSolrObj.setField("flagship_b", flagship);
37276 amit 809
        catalogSolrObj.setField("hot_deal_b", hotDeal);
35547 amit 810
 
811
        // Push to Solr
812
        String solrPath = "http://" + solrUrl + ":8984/solr/demo";
813
        SolrClient solr = new HttpSolrClient.Builder(solrPath).build();
814
 
815
        // Delete existing and add updated document
816
        solr.deleteById("catalog" + catalogId);
817
        solr.add(catalogSolrObj);
818
        solr.commit();
819
 
820
        logger.info("Successfully updated catalogId={} in Solr", catalogId);
821
    }
822
 
34229 vikas.jang 823
    public Optional<SuperCatalogModel> findMappingByCatalogId(List<SuperCatalogModel> superCatalogMappingList, int id, List<ItemTagModel> itemTagModels) {
824
        if (itemTagModels.stream().anyMatch(tag -> tag.getItem().getCatalogItemId() == id && tag.getTagListing().isActive())) {
825
            return superCatalogMappingList.stream().filter(mapping -> mapping.getCatalogId() == id).findFirst();
826
        }
827
        return Optional.empty();
33973 tejus.loha 828
    }
829
 
34229 vikas.jang 830
    public String findMappingVariantsByCatalogId(List<SuperCatalogMapping> superCatalogMappingList, int id, List<ItemTagModel> itemTagModels) throws JsonProcessingException {
33973 tejus.loha 831
        List<Map<String, Object>> variantList = new ArrayList<>();
832
        List<SuperCatalogMapping> matchingVariantNames = superCatalogMappingList.parallelStream()
833
                .filter(mapping -> mapping.getSuperCatalogId() == id)
834
                .collect(Collectors.toList());
835
 
836
        if (!matchingVariantNames.isEmpty()) {
34229 vikas.jang 837
            for (SuperCatalogMapping matchingVariant : matchingVariantNames) {
838
                logger.info("matchingVariantName: "+matchingVariant);
35344 vikas 839
                ItemTagModel itemTagModel = itemTagModels.stream().filter(tag -> tag.getItem().getCatalogItemId() == matchingVariant.getCatalogId()).findFirst().orElse(null);
34229 vikas.jang 840
                   if (matchingVariant != null && matchingVariant.getVariantName() != null && itemTagModels.stream().anyMatch(tag -> tag.getItem().getCatalogItemId() == matchingVariant.getCatalogId() && tag.getTagListing().isActive())) {
33973 tejus.loha 841
                    Map<String, Object> variantObj = new HashMap<>();
34229 vikas.jang 842
                    variantObj.put("catalogId", matchingVariant.getCatalogId());
843
                    variantObj.put("variantName", matchingVariant.getVariantName());
35344 vikas 844
                    variantObj.put("mrp", itemTagModel != null ? itemTagModel.getTagListing().getMrp() : 0.0);
35345 vikas 845
                    variantObj.put("mop", itemTagModel != null ? itemTagModel.getTagListing().getMop() : 0.0);
35344 vikas 846
                    variantObj.put("sellingPrice", itemTagModel != null ? itemTagModel.getTagListing().getSellingPrice() : 0.0);
33973 tejus.loha 847
                    variantList.add(variantObj);
848
                }
849
            }
850
        }
851
 
852
        if (variantList.isEmpty()) {
853
            return "[]";
854
        }
855
 
856
        variantList.sort((v1, v2) -> {
857
            int[] n1 = extractNumbers((String) v1.get("variantName"));
858
            int[] n2 = extractNumbers((String) v2.get("variantName"));
859
            int cmp = Integer.compare(n1[0], n2[0]);
860
            return cmp != 0 ? cmp : Integer.compare(n1[1], n2[1]);
861
        });
862
 
863
        ObjectMapper mapper = new ObjectMapper();
864
        return mapper.writeValueAsString(variantList);
865
    }
33979 ranu 866
//(4GB 64GB)
33973 tejus.loha 867
    private int[] extractNumbers(String input) {
868
        String[] parts = input.split("\\s+");
869
        int[] result = new int[2];
870
 
871
        for (int i = 0; i < Math.min(parts.length, 2); i++) {
33979 ranu 872
            String part = (parts[i].toUpperCase()).replace("(", "").replace(")", "");
33973 tejus.loha 873
            if (part.endsWith("GB")) {
874
                result[i] = Integer.parseInt(part.replace("GB", "").trim());
875
            } else if (part.endsWith("TB")) {
876
                result[i] = Integer.parseInt(part.replace("TB", "").trim()) * 1024;
877
            }
878
        }
879
 
880
        return result;
881
    }
882
 
31604 tejbeer 883
}