Subversion Repositories SmartDukaan

Rev

Rev 37276 | 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
 
37640 amit 304
        // Hot deal membership IS brand membership (catalog.brand = 'Hot Deal'). There is no
305
        // date window any more; model_hot_deal supplies only the pill attributes and the
306
        // pre-move brand, which is pushed separately as oem_brand_s.
307
        Set<Integer> hotDealSet = catalogRepository
308
                .selectCatalogIdsByBrand(ProfitMandiConstants.HOT_DEAL_BRAND);
37276 amit 309
 
37640 amit 310
        // oem_brand_s drives the brand chips INSIDE the hot-deal listing. It is kept out of
311
        // brand_ss on purpose: brand_ss feeds SolrService.brandExclusionFq, so an OEM value
312
        // there would hide the SKU from a partner blocked on that OEM.
313
        Map<Integer, String> oemBrandByCatalog = new HashMap<>();
314
        for (com.spice.profitmandi.dao.entity.catalog.ModelHotDeal hotDealRow : modelHotDealRepository
315
                .selectByCatalogItemIds(new ArrayList<>(hotDealSet))) {
316
            if (hotDealRow.getOemBrand() != null) {
317
                oemBrandByCatalog.put(hotDealRow.getCatalogItemId(), hotDealRow.getOemBrand());
318
            }
319
        }
320
 
36971 amit 321
        // Flagship is surfaced as a label (prepended so it shows first, ahead of all other flags)
322
        for (Integer flagshipCatalogId : flagshipSet) {
323
            catalogLabelMap.computeIfAbsent(flagshipCatalogId, k -> new ArrayList<>()).add(0, "flagship");
324
        }
325
 
326
 
35365 ranu 327
        logger.info("eolSetIds.size {}" , eolSet.size());
35357 ranu 328
 
33542 amit.gupta 329
        Map<String, Object> projection = new HashMap<>();
330
        projection.put("defaultImageUrl", 1);
31604 tejbeer 331
 
33542 amit.gupta 332
        List<String> excludeBrands = Arrays.asList("Dummy", "FOC HANDSET");
31604 tejbeer 333
 
33562 amit.gupta 334
        Map<Float, List<Integer>> priceModelMap = new TreeMap<>();
335
        for (ItemTagModel itemTagModel : itemTagModels) {
336
            TagListing tagListing = itemTagModel.getTagListing();
337
            com.spice.profitmandi.dao.entity.catalog.Item item = itemTagModel.getItem();
33542 amit.gupta 338
            if (excludeBrands.contains(item.getBrand())) {
339
                continue;
340
            }
31604 tejbeer 341
 
33542 amit.gupta 342
            if (!catalogMap.containsKey(item.getCatalogItemId())) {
33571 amit.gupta 343
                if (!priceModelMap.containsKey(tagListing.getMop()) && item.getCategoryId() == 10006) {
33572 amit.gupta 344
                    priceModelMap.put(tagListing.getMop(), new ArrayList<>());
33562 amit.gupta 345
                }
33570 amit.gupta 346
                if (item.getCategoryId() == 10006) {
33571 amit.gupta 347
                    List<Integer> priceModels = priceModelMap.get(tagListing.getMop());
33565 amit.gupta 348
                    priceModels.add(item.getCatalogItemId());
349
                }
33562 amit.gupta 350
 
33542 amit.gupta 351
                Map<String, Object> catalogObj = new HashMap<>();
33570 amit.gupta 352
                catalogObj.put("stockColor", 0);
33542 amit.gupta 353
                catalogObj.put("feature", "");
354
                catalogObj.put("hsnCode", item.getHsnCode());
355
                catalogObj.put("title",
356
                        String.join(" ", Arrays.asList(item.getBrand(), item.getModelName(), item.getModelNumber())
357
                                .stream().filter(s -> s != null && !s.isEmpty()).collect(Collectors.toList())));
358
                catalogObj.put("brand", new String[]{item.getBrand()});
359
                if (item.getBrand().equals("Huawei") || item.getBrand().equals("Honor")) {
360
                    catalogObj.put("brand", new String[]{"Huawei", "Honor"});
361
                }
362
                if (item.getBrand().equals("Mi") || item.getBrand().equals("Xiaomi")
363
                        || item.getBrand().equals("Redmi")) {
364
                    catalogObj.put("brand", new String[]{"Mi", "Xiaomi", "Redmi"});
365
                }
366
                catalogObj.put("identifier", item.getCatalogItemId());
367
                catalogObj.put("items", new HashMap<Integer, Map<String, Object>>());
368
                Map<String, Object> filterMap = new HashMap<>();
369
                filterMap.put("_id", item.getCatalogItemId());
370
                // Don't include if catalog not available
371
                try {
372
                    String imageUrl = contentMongoClient.getEntityById(item.getCatalogItemId()).getDefaultImageUrl();
31624 tejbeer 373
 
33542 amit.gupta 374
                    if (imageUrl != null) {
375
                        catalogObj.put("imageUrl", imageUrl);
376
                    } else {
377
                        catalogObj.put("imageUrl",
378
                                "https://images.smartdukaan.com/uploads/campaigns/" + item.getCatalogItemId() + ".jpg");
379
                    }
380
                } catch (Exception e) {
381
                    try {
382
                        catalogObj.put("imageUrl",
383
                                "https://images.smartdukaan.com/uploads/campaigns/" + item.getCatalogItemId() + ".jpg");
384
                    } catch (Exception e2) {
385
                        e2.printStackTrace();
386
                    }
387
                }
388
                try {
389
                    catalogObj.put("rank", rankingList.indexOf(item.getCatalogItemId()));
390
                } catch (Exception e) {
391
                    // A very big number
392
                    e.printStackTrace();
393
                    catalogObj.put("rank", 50000000);
394
                }
395
                if (featureMap.containsKey(item.getCatalogItemId())
396
                        && featureMap.get(item.getCatalogItemId()) != null) {
397
                    catalogObj.put("feature", featureMap.get(item.getCatalogItemId()));
31612 tejbeer 398
 
33542 amit.gupta 399
                }
31612 tejbeer 400
 
33542 amit.gupta 401
                catalogObj.put("categoryId", CATEGORY_MASTER.contains(item.getCategoryId()) ? item.getCategoryId() : 6);
31612 tejbeer 402
 
37114 amit 403
                if (item.getCategoryId() == 10006 || item.getCategoryId() == 10007) {
33542 amit.gupta 404
                    catalogObj.put("categoryId", 3);
405
                }
406
                catalogObj.put("subCategoryId", item.getCategoryId());
407
                catalogObj.put("create_timestamp",
33562 amit.gupta 408
                        tagListing.getCreatedTimestamp().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
31604 tejbeer 409
 
33542 amit.gupta 410
                if (catalogLabelMap.containsKey(item.getCatalogItemId())
411
                        && catalogLabelMap.get(item.getCatalogItemId()) != null) {
412
                    catalogObj.put("labels", catalogLabelMap.get(item.getCatalogItemId()));
31604 tejbeer 413
 
33542 amit.gupta 414
                }
415
                catalogMap.put(item.getCatalogItemId(), catalogObj);
416
                catalogObj.put("avColor", new HashMap<>());
31604 tejbeer 417
 
33542 amit.gupta 418
            }
31604 tejbeer 419
 
33542 amit.gupta 420
            Map<String, Object> catalogObj = catalogMap.get(item.getCatalogItemId());
421
            Map<Integer, Integer> avColorMap = (Map<Integer, Integer>) catalogObj.get("avColor");
31604 tejbeer 422
 
33542 amit.gupta 423
            if (availabilityItemMap.containsKey(String.valueOf(item.getId()))) {
33570 amit.gupta 424
                int itemStockColor = 0;
33542 amit.gupta 425
                for (Map.Entry<String, Map<String, Integer>> entry : availabilityItemMap
426
                        .get(String.valueOf(item.getId())).entrySet()) {
427
                    String warehouseId = entry.getKey();
428
                    Map<String, Integer> avMap = entry.getValue();
429
                    if (!avColorMap.containsKey(Integer.parseInt(warehouseId))) {
430
                        avColorMap.put(Integer.parseInt(warehouseId), 0);
431
                    }
432
                    int color = avColorMap.get(Integer.parseInt(warehouseId));
31604 tejbeer 433
 
33542 amit.gupta 434
                    if (avMap.get("netAvailability") > 0) {
435
                        color = 2;
33562 amit.gupta 436
                    } else if (avMap.get("netPo") > 0) {
33542 amit.gupta 437
                        color = Math.max(color, 1);
438
                    } else {
439
                        color = Math.max(color, 0);
440
                    }
441
                    avColorMap.put(Integer.parseInt(warehouseId), color);
31604 tejbeer 442
 
33542 amit.gupta 443
                    catalogObj.put("avColor", avColorMap);
33570 amit.gupta 444
                    if (color > itemStockColor) {
445
                        itemStockColor = color;
446
                    }
33542 amit.gupta 447
                }
33570 amit.gupta 448
                if (itemStockColor > 0 && itemStockColor > (Integer) catalogObj.get("stockColor")) {
449
                    catalogObj.put("stockColor", itemStockColor);
450
                }
33542 amit.gupta 451
            }
31604 tejbeer 452
 
33542 amit.gupta 453
            Map<Integer, Object> itemColorMap = (Map<Integer, Object>) catalogObj.get("items");
31604 tejbeer 454
 
33542 amit.gupta 455
            if (!itemColorMap.containsKey(item.getId())) {
456
                itemColorMap.put(item.getId(), new HashMap<String, Object>() {
457
                    {
458
                        put("color", item.getColor().replace("f_", ""));
459
                        put("tagPricing", new ArrayList<TagListing>());
460
                    }
461
                });
462
            }
463
            Map<String, Object> itemMap = (Map<String, Object>) itemColorMap.get(item.getId());
464
            List<TagListing> tagPricing = (List<TagListing>) itemMap.get("tagPricing");
33562 amit.gupta 465
            tagPricing.add(tagListing);
33542 amit.gupta 466
        }
33562 amit.gupta 467
        //logger.info("catalogObj {}", catalogMap);
31604 tejbeer 468
 
33973 tejus.loha 469
        List<SuperCatalogModel> superCatalogMappingList = superCatalogMappingRepository.selectJoinedData();
470
        List<SuperCatalogMapping> superCatalogs = superCatalogMappingRepository.selectAll();
33542 amit.gupta 471
        List<SolrInputDocument> catalogSolrObjs = new ArrayList<>();
472
        for (Entry<Integer, Map<String, Object>> entry : catalogMap.entrySet()) {
473
            int catalogId = entry.getKey();
34229 vikas.jang 474
            Optional<SuperCatalogModel> superCatalogMapping = findMappingByCatalogId(superCatalogMappingList, catalogId, itemTagModels);
33542 amit.gupta 475
            Map<String, Object> catalogValMap = entry.getValue();
476
            Map<Integer, Object> itemsMap = (Map<Integer, Object>) catalogValMap.get("items");
31604 tejbeer 477
 
33542 amit.gupta 478
            boolean active = false;
479
            // Map<Integer, Object> itemsMap = (Map<String, Object>)
480
            // catalogValMap.get("items");
481
            List<SolrInputDocument> itemObjs = new ArrayList<>();
482
            float mop = 0;
33574 amit.gupta 483
            float dp = 0;
31604 tejbeer 484
 
33542 amit.gupta 485
            for (Entry<Integer, Object> itemEntry : itemsMap.entrySet()) {
486
                int itemId = itemEntry.getKey();
487
                Map<String, Object> itemMap = (Map<String, Object>) itemEntry.getValue();
488
                List<TagListing> tags = (List<TagListing>) itemMap.get("tagPricing");
489
                SolrInputDocument itemObj = new SolrInputDocument();
31604 tejbeer 490
 
34136 amit.gupta 491
                for (TagListing tagListing : tags) {
492
                    active = active || tagListing.isActive();
493
                    itemObj.setField("id", "itemtag-" + itemId + "-" + tagListing.getTagId());
33542 amit.gupta 494
                    itemObj.setField("color_s", itemMap.get("color"));
495
                    itemObj.setField("itemId_i", itemId);
34136 amit.gupta 496
                    itemObj.setField("tagId_i", tagListing.getTagId());
497
                    itemObj.setField("mrp_f", tagListing.getMrp());
498
                    itemObj.setField("mop_f", tagListing.getMop());
499
                    itemObj.setField("sellingPrice_f", tagListing.getSellingPrice());
500
                    itemObj.setField("active_b", tagListing.isActive());
37276 amit 501
                    itemObj.setField("hot_deal_b", hotDealSet.contains(catalogId));
37640 amit 502
                    if (oemBrandByCatalog.containsKey(catalogId)) {
503
                        itemObj.setField("oem_brand_s", oemBrandByCatalog.get(catalogId));
504
                    }
34136 amit.gupta 505
                    mop = tagListing.getMop();
506
                    dp = tagListing.getSellingPrice();
33542 amit.gupta 507
                }
508
                itemObjs.add(itemObj);
509
            }
31604 tejbeer 510
 
33542 amit.gupta 511
            SolrInputDocument catalogSolrObj = new SolrInputDocument();
512
            catalogSolrObj.setField("id", "catalog" + catalogId);
513
            catalogSolrObj.setField("rank_i", catalogValMap.get("rank"));
514
            catalogSolrObj.setField("title_s", catalogValMap.get("title"));
515
            catalogSolrObj.addChildDocuments(itemObjs);
516
            catalogSolrObj.setField("child_b", itemObjs.size() > 0);
517
            catalogSolrObj.setField("catalogId_i", catalogId);
33980 ranu 518
            logger.info("superCatalogMapping1- {}", superCatalogMapping);
33973 tejus.loha 519
            if (superCatalogMapping.isPresent()) {
520
                int superCatalogId = superCatalogMapping.get().getSuperCatalogId();
34229 vikas.jang 521
                String superCatalogMappingVariants = findMappingVariantsByCatalogId(superCatalogs, superCatalogId, itemTagModels);
33973 tejus.loha 522
                catalogSolrObj.setField("superCatalog_i", superCatalogId);
523
                catalogSolrObj.setField("superCatalog_s", superCatalogMapping.get().getSuperCatalogName());
524
                catalogSolrObj.setField("superCatalogVariants_s", superCatalogMappingVariants);
525
            } else {
526
                catalogSolrObj.setField("superCatalog_i", 0);
34023 vikas.jang 527
                catalogSolrObj.setField("superCatalog_s", catalogValMap.get("title"));
33973 tejus.loha 528
                catalogSolrObj.setField("superCatalogVariants_s", "[]");
529
            }
33542 amit.gupta 530
            catalogSolrObj.setField("imageUrl_s",
531
                    catalogValMap.get("imageUrl").toString().replace("saholic", "smartdukaan"));
532
            catalogSolrObj.setField("feature_s", catalogValMap.get("feature"));
533
            catalogSolrObj.setField("brand_ss", catalogValMap.get("brand"));
534
            catalogSolrObj.setField("create_s", catalogValMap.get("create_timestamp"));
535
            catalogSolrObj.setField("categoryId_i", catalogValMap.get("categoryId"));
536
            catalogSolrObj.setField("subCategoryId_i", catalogValMap.get("subCategoryId"));
537
            catalogSolrObj.setField("label_ss", catalogValMap.get("labels"));
538
            catalogSolrObj.setField("mop_f", mop);
33574 amit.gupta 539
            catalogSolrObj.setField("dp_f", dp);
33542 amit.gupta 540
            catalogSolrObj.setField("hsncode_s", catalogValMap.get("hsnCode"));
541
            catalogSolrObj.setField("show_default_b", true);
31710 tejbeer 542
 
33542 amit.gupta 543
            String[] brands = (String[]) catalogValMap.get("brand");
544
            for (String brand : brands) {
545
                if (brand.equals("FOC")) {
546
                    catalogSolrObj.setField("show_default_b", false);
547
                }
31604 tejbeer 548
 
33542 amit.gupta 549
                if (brand.equals("Live Demo")) {
550
                    catalogSolrObj.setField("show_default_b", false);
551
                }
552
            }
553
            Map<Integer, Integer> avColorMap = (Map<Integer, Integer>) catalogValMap.get("avColor");
33499 amit.gupta 554
 
33570 amit.gupta 555
            for (Integer warehouseId : ProfitMandiConstants.WAREHOUSE_MAP.keySet()) {
556
                catalogSolrObj.setField("w" + warehouseId + "_i", 0);
557
            }
33542 amit.gupta 558
            for (Entry<Integer, Integer> avColorEntry : avColorMap.entrySet()) {
559
                int whId = avColorEntry.getKey();
33562 amit.gupta 560
                int color = avColorEntry.getValue();
33542 amit.gupta 561
                catalogSolrObj.setField("w" + whId + "_i", color);
562
            }
33570 amit.gupta 563
 
564
            List<Integer> similalarModels = null;
565
            if ((Integer) catalogValMap.get("categoryId") == 3) {
33571 amit.gupta 566
                float starPrice = mop - 500f;
567
                float endPrice = mop + 1000f;
33570 amit.gupta 568
                similalarModels = new ArrayList<>();
569
                for (Entry<Float, List<Integer>> floatListEntry : priceModelMap.entrySet()) {
570
                    float modelPrice = floatListEntry.getKey();
571
                    if (modelPrice >= starPrice && modelPrice <= endPrice) {
572
                        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 573
                        //logger.info("Entry before - {}, after - {}", floatListEntry.getValue().size(), instock.size());
33570 amit.gupta 574
                        similalarModels.addAll(instock);
575
                    }
576
                    if (modelPrice > endPrice) break;
577
                }
578
                similalarModels.remove(Integer.valueOf(catalogId));
579
            }
34049 vikas.jang 580
            catalogSolrObj.setField("similarModels_ii", similalarModels == null ? Collections.EMPTY_LIST : similalarModels);
33570 amit.gupta 581
 
582
 
33542 amit.gupta 583
            catalogSolrObj.setField("active_b", active);
35365 ranu 584
            if(eolSet.contains(catalogId)){
35366 ranu 585
                catalogSolrObj.setField("eol_no_stock_b", true);
35365 ranu 586
            }else {
35366 ranu 587
                catalogSolrObj.setField("eol_no_stock_b", false);
35365 ranu 588
            }
36971 amit 589
            catalogSolrObj.setField("flagship_b", flagshipSet.contains(catalogId));
37276 amit 590
            catalogSolrObj.setField("hot_deal_b", hotDealSet.contains(catalogId));
37640 amit 591
            if (oemBrandByCatalog.containsKey(catalogId)) {
592
                catalogSolrObj.setField("oem_brand_s", oemBrandByCatalog.get(catalogId));
593
            }
33542 amit.gupta 594
            catalogSolrObjs.add(catalogSolrObj);
595
        }
31604 tejbeer 596
 
33542 amit.gupta 597
        String solrPath = "http://" + solrUrl + ":8984/solr/demo";
598
        SolrClient solr = new HttpSolrClient.Builder(solrPath).build();
31604 tejbeer 599
 
33542 amit.gupta 600
        solr.deleteByQuery("*:*");
601
        solr.add(catalogSolrObjs);
602
 
603
        org.apache.solr.client.solrj.response.UpdateResponse updateResponse = solr.commit();
604
        logger.info("solr {}", updateResponse.getStatus());
605
 
606
    }
607
 
608
    public void pushData() throws Exception {
609
        this.populateTagItems();
610
    }
33973 tejus.loha 611
 
35547 amit 612
    /**
613
     * Updates a single catalog in Solr based on catalogId.
614
     * Used for real-time updates when TagListing changes.
615
     *
616
     * @param catalogId The catalog ID to update
617
     */
618
    public void updateSingleCatalog(int catalogId) throws Exception {
619
        logger.info("Updating single catalog in Solr: catalogId={}", catalogId);
620
 
621
        List<status> statuses = Arrays.asList(status.ACTIVE, status.PAUSED_BY_RISK, status.PARTIALLY_ACTIVE);
36971 amit 622
        boolean flagship = !modelFlagshipRepository
623
                .selectActiveFlagshipCatalogIds(Collections.singletonList(catalogId)).isEmpty();
37640 amit 624
        // Membership from the brand; oem_brand_s from the attributes row, which may be
625
        // absent on a freshly migrated SKU whose pills ops has not filled in yet.
626
        // Fully qualified: this package has its own Catalog class, which shadows the entity.
627
        com.spice.profitmandi.dao.entity.catalog.Catalog hotDealCatalog =
628
                catalogRepository.selectCatalogById(catalogId);
629
        boolean hotDeal = hotDealCatalog != null
630
                && ProfitMandiConstants.HOT_DEAL_BRAND.equals(hotDealCatalog.getBrand());
631
        com.spice.profitmandi.dao.entity.catalog.ModelHotDeal hotDealRow =
632
                hotDeal ? modelHotDealRepository.selectByCatalogItemId(catalogId) : null;
633
        String oemBrand = hotDealRow == null ? null : hotDealRow.getOemBrand();
35547 amit 634
 
635
        // Get all TagListings for this catalog
636
        List<ItemTagModel> itemTagModels = tagListingRepository.getItemTagByCatalogIdAndStatus(catalogId, statuses);
637
 
638
        if (itemTagModels.isEmpty()) {
639
            logger.warn("No active TagListings found for catalogId={}, removing from Solr", catalogId);
640
            String solrPath = "http://" + solrUrl + ":8984/solr/demo";
641
            SolrClient solr = new HttpSolrClient.Builder(solrPath).build();
642
            solr.deleteById("catalog" + catalogId);
643
            solr.commit();
644
            return;
645
        }
646
 
647
        // Get availability for items in this catalog
648
        Map<String, Map<String, Map<String, Integer>>> availabilityItemMap = getItemMap();
649
 
650
        // Get ranking info
651
        List<TagRanking> tagRankingList = tagRankingRepository.getAllTagRanking();
652
        List<Integer> rankingList = new ArrayList<>();
653
        Map<Integer, String> featureMap = new HashMap<>();
654
        for (TagRanking tagRanking : tagRankingList) {
655
            rankingList.add(tagRanking.getCatalogItemId());
656
            featureMap.put(tagRanking.getCatalogItemId(), tagRanking.getFeature());
657
        }
658
 
659
        // Get labels
660
        Map<Integer, List<String>> catalogLabelMap = this.getLabels();
661
 
36971 amit 662
        // Flagship is surfaced as a label (prepended so it shows first, ahead of all other flags)
663
        if (flagship) {
664
            catalogLabelMap.computeIfAbsent(catalogId, k -> new ArrayList<>()).add(0, "flagship");
665
        }
666
 
35547 amit 667
        // Get EOL info
668
        List<Integer> eolWithOutStock = catalogRepository.findAllWithEOLWithOutStock();
669
        List<Integer> eolWithBadQty = catalogRepository.findAllWithNoGoodStock();
670
        Set<Integer> eolSet = new HashSet<>(eolWithOutStock);
671
        eolSet.addAll(eolWithBadQty);
672
 
673
        // Build catalog document
674
        com.spice.profitmandi.dao.entity.catalog.Item firstItem = itemTagModels.get(0).getItem();
675
        TagListing firstTagListing = itemTagModels.get(0).getTagListing();
676
 
677
        Map<Integer, Integer> avColorMap = new HashMap<>();
678
        List<SolrInputDocument> itemObjs = new ArrayList<>();
679
        boolean active = false;
680
        float mop = 0;
681
        float dp = 0;
682
        int stockColor = 0;
683
 
684
        for (ItemTagModel itemTagModel : itemTagModels) {
685
            TagListing tagListing = itemTagModel.getTagListing();
686
            com.spice.profitmandi.dao.entity.catalog.Item item = itemTagModel.getItem();
687
 
688
            active = active || tagListing.isActive();
689
 
690
            // Build item document
691
            SolrInputDocument itemObj = new SolrInputDocument();
692
            itemObj.setField("id", "itemtag-" + item.getId() + "-" + tagListing.getTagId());
693
            itemObj.setField("color_s", item.getColor().replace("f_", ""));
694
            itemObj.setField("itemId_i", item.getId());
695
            itemObj.setField("tagId_i", tagListing.getTagId());
696
            itemObj.setField("mrp_f", tagListing.getMrp());
697
            itemObj.setField("mop_f", tagListing.getMop());
698
            itemObj.setField("sellingPrice_f", tagListing.getSellingPrice());
699
            itemObj.setField("active_b", tagListing.isActive());
37276 amit 700
            itemObj.setField("hot_deal_b", hotDeal);
37640 amit 701
            if (oemBrand != null) {
702
                itemObj.setField("oem_brand_s", oemBrand);
703
            }
35547 amit 704
            mop = tagListing.getMop();
705
            dp = tagListing.getSellingPrice();
706
            itemObjs.add(itemObj);
707
 
708
            // Calculate availability color
709
            if (availabilityItemMap.containsKey(String.valueOf(item.getId()))) {
710
                int itemStockColor = 0;
711
                for (Map.Entry<String, Map<String, Integer>> entry : availabilityItemMap
712
                        .get(String.valueOf(item.getId())).entrySet()) {
713
                    String warehouseId = entry.getKey();
714
                    Map<String, Integer> avMap = entry.getValue();
715
                    if (!avColorMap.containsKey(Integer.parseInt(warehouseId))) {
716
                        avColorMap.put(Integer.parseInt(warehouseId), 0);
717
                    }
718
                    int color = avColorMap.get(Integer.parseInt(warehouseId));
719
 
720
                    if (avMap.get("netAvailability") > 0) {
721
                        color = 2;
722
                    } else if (avMap.get("netPo") > 0) {
723
                        color = Math.max(color, 1);
724
                    } else {
725
                        color = Math.max(color, 0);
726
                    }
727
                    avColorMap.put(Integer.parseInt(warehouseId), color);
728
 
729
                    if (color > itemStockColor) {
730
                        itemStockColor = color;
731
                    }
732
                }
733
                if (itemStockColor > stockColor) {
734
                    stockColor = itemStockColor;
735
                }
736
            }
737
        }
738
 
739
        // Build catalog Solr document
740
        SolrInputDocument catalogSolrObj = new SolrInputDocument();
741
        catalogSolrObj.setField("id", "catalog" + catalogId);
742
        catalogSolrObj.setField("rank_i", rankingList.indexOf(catalogId));
743
        catalogSolrObj.setField("title_s", String.join(" ", Arrays.asList(
744
                firstItem.getBrand(), firstItem.getModelName(), firstItem.getModelNumber())
745
                .stream().filter(s -> s != null && !s.isEmpty()).collect(Collectors.toList())));
746
        catalogSolrObj.addChildDocuments(itemObjs);
747
        catalogSolrObj.setField("child_b", itemObjs.size() > 0);
748
        catalogSolrObj.setField("catalogId_i", catalogId);
749
 
750
        // Super catalog mapping
751
        List<SuperCatalogModel> superCatalogMappingList = superCatalogMappingRepository.selectJoinedData();
752
        List<SuperCatalogMapping> superCatalogs = superCatalogMappingRepository.selectAll();
753
        Optional<SuperCatalogModel> superCatalogMapping = findMappingByCatalogId(superCatalogMappingList, catalogId, itemTagModels);
754
 
755
        if (superCatalogMapping.isPresent()) {
756
            int superCatalogId = superCatalogMapping.get().getSuperCatalogId();
757
            String superCatalogMappingVariants = findMappingVariantsByCatalogId(superCatalogs, superCatalogId, itemTagModels);
758
            catalogSolrObj.setField("superCatalog_i", superCatalogId);
759
            catalogSolrObj.setField("superCatalog_s", superCatalogMapping.get().getSuperCatalogName());
760
            catalogSolrObj.setField("superCatalogVariants_s", superCatalogMappingVariants);
761
        } else {
762
            catalogSolrObj.setField("superCatalog_i", 0);
763
            catalogSolrObj.setField("superCatalog_s", catalogSolrObj.getFieldValue("title_s"));
764
            catalogSolrObj.setField("superCatalogVariants_s", "[]");
765
        }
766
 
767
        // Image URL
768
        try {
769
            String imageUrl = contentMongoClient.getEntityById(catalogId).getDefaultImageUrl();
770
            if (imageUrl != null) {
771
                catalogSolrObj.setField("imageUrl_s", imageUrl.replace("saholic", "smartdukaan"));
772
            } else {
773
                catalogSolrObj.setField("imageUrl_s",
774
                        "https://images.smartdukaan.com/uploads/campaigns/" + catalogId + ".jpg");
775
            }
776
        } catch (Exception e) {
777
            catalogSolrObj.setField("imageUrl_s",
778
                    "https://images.smartdukaan.com/uploads/campaigns/" + catalogId + ".jpg");
779
        }
780
 
781
        // Feature
782
        if (featureMap.containsKey(catalogId) && featureMap.get(catalogId) != null) {
783
            catalogSolrObj.setField("feature_s", featureMap.get(catalogId));
784
        } else {
785
            catalogSolrObj.setField("feature_s", "");
786
        }
787
 
788
        // Brand
789
        String[] brands = new String[]{firstItem.getBrand()};
790
        if (firstItem.getBrand().equals("Huawei") || firstItem.getBrand().equals("Honor")) {
791
            brands = new String[]{"Huawei", "Honor"};
792
        }
793
        if (firstItem.getBrand().equals("Mi") || firstItem.getBrand().equals("Xiaomi")
794
                || firstItem.getBrand().equals("Redmi")) {
795
            brands = new String[]{"Mi", "Xiaomi", "Redmi"};
796
        }
797
        catalogSolrObj.setField("brand_ss", brands);
798
 
799
        // Category
800
        catalogSolrObj.setField("categoryId_i", CATEGORY_MASTER.contains(firstItem.getCategoryId())
37114 amit 801
                ? ((firstItem.getCategoryId() == 10006 || firstItem.getCategoryId() == 10007) ? 3 : firstItem.getCategoryId()) : 6);
35547 amit 802
        catalogSolrObj.setField("subCategoryId_i", firstItem.getCategoryId());
803
 
804
        // Timestamps and labels
805
        catalogSolrObj.setField("create_s", firstTagListing.getCreatedTimestamp()
806
                .atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
807
        if (catalogLabelMap.containsKey(catalogId) && catalogLabelMap.get(catalogId) != null) {
808
            catalogSolrObj.setField("label_ss", catalogLabelMap.get(catalogId));
809
        }
810
 
811
        catalogSolrObj.setField("mop_f", mop);
812
        catalogSolrObj.setField("dp_f", dp);
813
        catalogSolrObj.setField("hsncode_s", firstItem.getHsnCode());
814
        catalogSolrObj.setField("show_default_b", true);
815
 
816
        for (String brand : brands) {
817
            if (brand.equals("FOC") || brand.equals("Live Demo")) {
818
                catalogSolrObj.setField("show_default_b", false);
819
            }
820
        }
821
 
822
        // Warehouse availability
823
        for (Integer warehouseId : ProfitMandiConstants.WAREHOUSE_MAP.keySet()) {
824
            catalogSolrObj.setField("w" + warehouseId + "_i", 0);
825
        }
826
        for (Entry<Integer, Integer> avColorEntry : avColorMap.entrySet()) {
827
            int whId = avColorEntry.getKey();
828
            int color = avColorEntry.getValue();
829
            catalogSolrObj.setField("w" + whId + "_i", color);
830
        }
831
 
832
        // Similar models - simplified for single update
833
        catalogSolrObj.setField("similarModels_ii", Collections.EMPTY_LIST);
834
 
835
        catalogSolrObj.setField("active_b", active);
836
        catalogSolrObj.setField("eol_no_stock_b", eolSet.contains(catalogId));
36971 amit 837
        catalogSolrObj.setField("flagship_b", flagship);
37276 amit 838
        catalogSolrObj.setField("hot_deal_b", hotDeal);
37640 amit 839
        if (oemBrand != null) {
840
            catalogSolrObj.setField("oem_brand_s", oemBrand);
841
        }
35547 amit 842
 
843
        // Push to Solr
844
        String solrPath = "http://" + solrUrl + ":8984/solr/demo";
845
        SolrClient solr = new HttpSolrClient.Builder(solrPath).build();
846
 
847
        // Delete existing and add updated document
848
        solr.deleteById("catalog" + catalogId);
849
        solr.add(catalogSolrObj);
850
        solr.commit();
851
 
852
        logger.info("Successfully updated catalogId={} in Solr", catalogId);
853
    }
854
 
34229 vikas.jang 855
    public Optional<SuperCatalogModel> findMappingByCatalogId(List<SuperCatalogModel> superCatalogMappingList, int id, List<ItemTagModel> itemTagModels) {
856
        if (itemTagModels.stream().anyMatch(tag -> tag.getItem().getCatalogItemId() == id && tag.getTagListing().isActive())) {
857
            return superCatalogMappingList.stream().filter(mapping -> mapping.getCatalogId() == id).findFirst();
858
        }
859
        return Optional.empty();
33973 tejus.loha 860
    }
861
 
34229 vikas.jang 862
    public String findMappingVariantsByCatalogId(List<SuperCatalogMapping> superCatalogMappingList, int id, List<ItemTagModel> itemTagModels) throws JsonProcessingException {
33973 tejus.loha 863
        List<Map<String, Object>> variantList = new ArrayList<>();
864
        List<SuperCatalogMapping> matchingVariantNames = superCatalogMappingList.parallelStream()
865
                .filter(mapping -> mapping.getSuperCatalogId() == id)
866
                .collect(Collectors.toList());
867
 
868
        if (!matchingVariantNames.isEmpty()) {
34229 vikas.jang 869
            for (SuperCatalogMapping matchingVariant : matchingVariantNames) {
870
                logger.info("matchingVariantName: "+matchingVariant);
35344 vikas 871
                ItemTagModel itemTagModel = itemTagModels.stream().filter(tag -> tag.getItem().getCatalogItemId() == matchingVariant.getCatalogId()).findFirst().orElse(null);
34229 vikas.jang 872
                   if (matchingVariant != null && matchingVariant.getVariantName() != null && itemTagModels.stream().anyMatch(tag -> tag.getItem().getCatalogItemId() == matchingVariant.getCatalogId() && tag.getTagListing().isActive())) {
33973 tejus.loha 873
                    Map<String, Object> variantObj = new HashMap<>();
34229 vikas.jang 874
                    variantObj.put("catalogId", matchingVariant.getCatalogId());
875
                    variantObj.put("variantName", matchingVariant.getVariantName());
35344 vikas 876
                    variantObj.put("mrp", itemTagModel != null ? itemTagModel.getTagListing().getMrp() : 0.0);
35345 vikas 877
                    variantObj.put("mop", itemTagModel != null ? itemTagModel.getTagListing().getMop() : 0.0);
35344 vikas 878
                    variantObj.put("sellingPrice", itemTagModel != null ? itemTagModel.getTagListing().getSellingPrice() : 0.0);
33973 tejus.loha 879
                    variantList.add(variantObj);
880
                }
881
            }
882
        }
883
 
884
        if (variantList.isEmpty()) {
885
            return "[]";
886
        }
887
 
888
        variantList.sort((v1, v2) -> {
889
            int[] n1 = extractNumbers((String) v1.get("variantName"));
890
            int[] n2 = extractNumbers((String) v2.get("variantName"));
891
            int cmp = Integer.compare(n1[0], n2[0]);
892
            return cmp != 0 ? cmp : Integer.compare(n1[1], n2[1]);
893
        });
894
 
895
        ObjectMapper mapper = new ObjectMapper();
896
        return mapper.writeValueAsString(variantList);
897
    }
33979 ranu 898
//(4GB 64GB)
33973 tejus.loha 899
    private int[] extractNumbers(String input) {
900
        String[] parts = input.split("\\s+");
901
        int[] result = new int[2];
902
 
903
        for (int i = 0; i < Math.min(parts.length, 2); i++) {
33979 ranu 904
            String part = (parts[i].toUpperCase()).replace("(", "").replace(")", "");
33973 tejus.loha 905
            if (part.endsWith("GB")) {
906
                result[i] = Integer.parseInt(part.replace("GB", "").trim());
907
            } else if (part.endsWith("TB")) {
908
                result[i] = Integer.parseInt(part.replace("TB", "").trim()) * 1024;
909
            }
910
        }
911
 
912
        return result;
913
    }
914
 
31604 tejbeer 915
}