Subversion Repositories SmartDukaan

Rev

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