Subversion Repositories SmartDukaan

Rev

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

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