Subversion Repositories SmartDukaan

Rev

Rev 36222 | Rev 36971 | 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
            }
33542 amit.gupta 558
            catalogSolrObjs.add(catalogSolrObj);
559
        }
31604 tejbeer 560
 
33542 amit.gupta 561
        String solrPath = "http://" + solrUrl + ":8984/solr/demo";
562
        SolrClient solr = new HttpSolrClient.Builder(solrPath).build();
31604 tejbeer 563
 
33542 amit.gupta 564
        solr.deleteByQuery("*:*");
565
        solr.add(catalogSolrObjs);
566
 
567
        org.apache.solr.client.solrj.response.UpdateResponse updateResponse = solr.commit();
568
        logger.info("solr {}", updateResponse.getStatus());
569
 
570
    }
571
 
572
    public void pushData() throws Exception {
573
        this.populateTagItems();
574
    }
33973 tejus.loha 575
 
35547 amit 576
    /**
577
     * Updates a single catalog in Solr based on catalogId.
578
     * Used for real-time updates when TagListing changes.
579
     *
580
     * @param catalogId The catalog ID to update
581
     */
582
    public void updateSingleCatalog(int catalogId) throws Exception {
583
        logger.info("Updating single catalog in Solr: catalogId={}", catalogId);
584
 
585
        List<status> statuses = Arrays.asList(status.ACTIVE, status.PAUSED_BY_RISK, status.PARTIALLY_ACTIVE);
586
 
587
        // Get all TagListings for this catalog
588
        List<ItemTagModel> itemTagModels = tagListingRepository.getItemTagByCatalogIdAndStatus(catalogId, statuses);
589
 
590
        if (itemTagModels.isEmpty()) {
591
            logger.warn("No active TagListings found for catalogId={}, removing from Solr", catalogId);
592
            String solrPath = "http://" + solrUrl + ":8984/solr/demo";
593
            SolrClient solr = new HttpSolrClient.Builder(solrPath).build();
594
            solr.deleteById("catalog" + catalogId);
595
            solr.commit();
596
            return;
597
        }
598
 
599
        // Get availability for items in this catalog
600
        Map<String, Map<String, Map<String, Integer>>> availabilityItemMap = getItemMap();
601
 
602
        // Get ranking info
603
        List<TagRanking> tagRankingList = tagRankingRepository.getAllTagRanking();
604
        List<Integer> rankingList = new ArrayList<>();
605
        Map<Integer, String> featureMap = new HashMap<>();
606
        for (TagRanking tagRanking : tagRankingList) {
607
            rankingList.add(tagRanking.getCatalogItemId());
608
            featureMap.put(tagRanking.getCatalogItemId(), tagRanking.getFeature());
609
        }
610
 
611
        // Get labels
612
        Map<Integer, List<String>> catalogLabelMap = this.getLabels();
613
 
614
        // Get EOL info
615
        List<Integer> eolWithOutStock = catalogRepository.findAllWithEOLWithOutStock();
616
        List<Integer> eolWithBadQty = catalogRepository.findAllWithNoGoodStock();
617
        Set<Integer> eolSet = new HashSet<>(eolWithOutStock);
618
        eolSet.addAll(eolWithBadQty);
619
 
620
        // Build catalog document
621
        com.spice.profitmandi.dao.entity.catalog.Item firstItem = itemTagModels.get(0).getItem();
622
        TagListing firstTagListing = itemTagModels.get(0).getTagListing();
623
 
624
        Map<Integer, Integer> avColorMap = new HashMap<>();
625
        List<SolrInputDocument> itemObjs = new ArrayList<>();
626
        boolean active = false;
627
        float mop = 0;
628
        float dp = 0;
629
        int stockColor = 0;
630
 
631
        for (ItemTagModel itemTagModel : itemTagModels) {
632
            TagListing tagListing = itemTagModel.getTagListing();
633
            com.spice.profitmandi.dao.entity.catalog.Item item = itemTagModel.getItem();
634
 
635
            active = active || tagListing.isActive();
636
 
637
            // Build item document
638
            SolrInputDocument itemObj = new SolrInputDocument();
639
            itemObj.setField("id", "itemtag-" + item.getId() + "-" + tagListing.getTagId());
640
            itemObj.setField("color_s", item.getColor().replace("f_", ""));
641
            itemObj.setField("itemId_i", item.getId());
642
            itemObj.setField("tagId_i", tagListing.getTagId());
643
            itemObj.setField("mrp_f", tagListing.getMrp());
644
            itemObj.setField("mop_f", tagListing.getMop());
645
            itemObj.setField("sellingPrice_f", tagListing.getSellingPrice());
646
            itemObj.setField("active_b", tagListing.isActive());
647
            itemObj.setField("hot_deal_b", tagListing.isHotDeals());
648
            mop = tagListing.getMop();
649
            dp = tagListing.getSellingPrice();
650
            itemObjs.add(itemObj);
651
 
652
            // Calculate availability color
653
            if (availabilityItemMap.containsKey(String.valueOf(item.getId()))) {
654
                int itemStockColor = 0;
655
                for (Map.Entry<String, Map<String, Integer>> entry : availabilityItemMap
656
                        .get(String.valueOf(item.getId())).entrySet()) {
657
                    String warehouseId = entry.getKey();
658
                    Map<String, Integer> avMap = entry.getValue();
659
                    if (!avColorMap.containsKey(Integer.parseInt(warehouseId))) {
660
                        avColorMap.put(Integer.parseInt(warehouseId), 0);
661
                    }
662
                    int color = avColorMap.get(Integer.parseInt(warehouseId));
663
 
664
                    if (avMap.get("netAvailability") > 0) {
665
                        color = 2;
666
                    } else if (avMap.get("netPo") > 0) {
667
                        color = Math.max(color, 1);
668
                    } else {
669
                        color = Math.max(color, 0);
670
                    }
671
                    avColorMap.put(Integer.parseInt(warehouseId), color);
672
 
673
                    if (color > itemStockColor) {
674
                        itemStockColor = color;
675
                    }
676
                }
677
                if (itemStockColor > stockColor) {
678
                    stockColor = itemStockColor;
679
                }
680
            }
681
        }
682
 
683
        // Build catalog Solr document
684
        SolrInputDocument catalogSolrObj = new SolrInputDocument();
685
        catalogSolrObj.setField("id", "catalog" + catalogId);
686
        catalogSolrObj.setField("rank_i", rankingList.indexOf(catalogId));
687
        catalogSolrObj.setField("title_s", String.join(" ", Arrays.asList(
688
                firstItem.getBrand(), firstItem.getModelName(), firstItem.getModelNumber())
689
                .stream().filter(s -> s != null && !s.isEmpty()).collect(Collectors.toList())));
690
        catalogSolrObj.addChildDocuments(itemObjs);
691
        catalogSolrObj.setField("child_b", itemObjs.size() > 0);
692
        catalogSolrObj.setField("catalogId_i", catalogId);
693
 
694
        // Super catalog mapping
695
        List<SuperCatalogModel> superCatalogMappingList = superCatalogMappingRepository.selectJoinedData();
696
        List<SuperCatalogMapping> superCatalogs = superCatalogMappingRepository.selectAll();
697
        Optional<SuperCatalogModel> superCatalogMapping = findMappingByCatalogId(superCatalogMappingList, catalogId, itemTagModels);
698
 
699
        if (superCatalogMapping.isPresent()) {
700
            int superCatalogId = superCatalogMapping.get().getSuperCatalogId();
701
            String superCatalogMappingVariants = findMappingVariantsByCatalogId(superCatalogs, superCatalogId, itemTagModels);
702
            catalogSolrObj.setField("superCatalog_i", superCatalogId);
703
            catalogSolrObj.setField("superCatalog_s", superCatalogMapping.get().getSuperCatalogName());
704
            catalogSolrObj.setField("superCatalogVariants_s", superCatalogMappingVariants);
705
        } else {
706
            catalogSolrObj.setField("superCatalog_i", 0);
707
            catalogSolrObj.setField("superCatalog_s", catalogSolrObj.getFieldValue("title_s"));
708
            catalogSolrObj.setField("superCatalogVariants_s", "[]");
709
        }
710
 
711
        // Image URL
712
        try {
713
            String imageUrl = contentMongoClient.getEntityById(catalogId).getDefaultImageUrl();
714
            if (imageUrl != null) {
715
                catalogSolrObj.setField("imageUrl_s", imageUrl.replace("saholic", "smartdukaan"));
716
            } else {
717
                catalogSolrObj.setField("imageUrl_s",
718
                        "https://images.smartdukaan.com/uploads/campaigns/" + catalogId + ".jpg");
719
            }
720
        } catch (Exception e) {
721
            catalogSolrObj.setField("imageUrl_s",
722
                    "https://images.smartdukaan.com/uploads/campaigns/" + catalogId + ".jpg");
723
        }
724
 
725
        // Feature
726
        if (featureMap.containsKey(catalogId) && featureMap.get(catalogId) != null) {
727
            catalogSolrObj.setField("feature_s", featureMap.get(catalogId));
728
        } else {
729
            catalogSolrObj.setField("feature_s", "");
730
        }
731
 
732
        // Brand
733
        String[] brands = new String[]{firstItem.getBrand()};
734
        if (firstItem.getBrand().equals("Huawei") || firstItem.getBrand().equals("Honor")) {
735
            brands = new String[]{"Huawei", "Honor"};
736
        }
737
        if (firstItem.getBrand().equals("Mi") || firstItem.getBrand().equals("Xiaomi")
738
                || firstItem.getBrand().equals("Redmi")) {
739
            brands = new String[]{"Mi", "Xiaomi", "Redmi"};
740
        }
741
        catalogSolrObj.setField("brand_ss", brands);
742
 
743
        // Category
744
        catalogSolrObj.setField("categoryId_i", CATEGORY_MASTER.contains(firstItem.getCategoryId())
35797 amit 745
                ? ((firstItem.getCategoryId() == 10006) ? 3 : firstItem.getCategoryId()) : 6);
35547 amit 746
        catalogSolrObj.setField("subCategoryId_i", firstItem.getCategoryId());
747
 
748
        // Timestamps and labels
749
        catalogSolrObj.setField("create_s", firstTagListing.getCreatedTimestamp()
750
                .atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
751
        if (catalogLabelMap.containsKey(catalogId) && catalogLabelMap.get(catalogId) != null) {
752
            catalogSolrObj.setField("label_ss", catalogLabelMap.get(catalogId));
753
        }
754
 
755
        catalogSolrObj.setField("mop_f", mop);
756
        catalogSolrObj.setField("dp_f", dp);
757
        catalogSolrObj.setField("hsncode_s", firstItem.getHsnCode());
758
        catalogSolrObj.setField("show_default_b", true);
759
 
760
        for (String brand : brands) {
761
            if (brand.equals("FOC") || brand.equals("Live Demo")) {
762
                catalogSolrObj.setField("show_default_b", false);
763
            }
764
        }
765
 
766
        // Warehouse availability
767
        for (Integer warehouseId : ProfitMandiConstants.WAREHOUSE_MAP.keySet()) {
768
            catalogSolrObj.setField("w" + warehouseId + "_i", 0);
769
        }
770
        for (Entry<Integer, Integer> avColorEntry : avColorMap.entrySet()) {
771
            int whId = avColorEntry.getKey();
772
            int color = avColorEntry.getValue();
773
            catalogSolrObj.setField("w" + whId + "_i", color);
774
        }
775
 
776
        // Similar models - simplified for single update
777
        catalogSolrObj.setField("similarModels_ii", Collections.EMPTY_LIST);
778
 
779
        catalogSolrObj.setField("active_b", active);
780
        catalogSolrObj.setField("eol_no_stock_b", eolSet.contains(catalogId));
781
 
782
        // Push to Solr
783
        String solrPath = "http://" + solrUrl + ":8984/solr/demo";
784
        SolrClient solr = new HttpSolrClient.Builder(solrPath).build();
785
 
786
        // Delete existing and add updated document
787
        solr.deleteById("catalog" + catalogId);
788
        solr.add(catalogSolrObj);
789
        solr.commit();
790
 
791
        logger.info("Successfully updated catalogId={} in Solr", catalogId);
792
    }
793
 
34229 vikas.jang 794
    public Optional<SuperCatalogModel> findMappingByCatalogId(List<SuperCatalogModel> superCatalogMappingList, int id, List<ItemTagModel> itemTagModels) {
795
        if (itemTagModels.stream().anyMatch(tag -> tag.getItem().getCatalogItemId() == id && tag.getTagListing().isActive())) {
796
            return superCatalogMappingList.stream().filter(mapping -> mapping.getCatalogId() == id).findFirst();
797
        }
798
        return Optional.empty();
33973 tejus.loha 799
    }
800
 
34229 vikas.jang 801
    public String findMappingVariantsByCatalogId(List<SuperCatalogMapping> superCatalogMappingList, int id, List<ItemTagModel> itemTagModels) throws JsonProcessingException {
33973 tejus.loha 802
        List<Map<String, Object>> variantList = new ArrayList<>();
803
        List<SuperCatalogMapping> matchingVariantNames = superCatalogMappingList.parallelStream()
804
                .filter(mapping -> mapping.getSuperCatalogId() == id)
805
                .collect(Collectors.toList());
806
 
807
        if (!matchingVariantNames.isEmpty()) {
34229 vikas.jang 808
            for (SuperCatalogMapping matchingVariant : matchingVariantNames) {
809
                logger.info("matchingVariantName: "+matchingVariant);
35344 vikas 810
                ItemTagModel itemTagModel = itemTagModels.stream().filter(tag -> tag.getItem().getCatalogItemId() == matchingVariant.getCatalogId()).findFirst().orElse(null);
34229 vikas.jang 811
                   if (matchingVariant != null && matchingVariant.getVariantName() != null && itemTagModels.stream().anyMatch(tag -> tag.getItem().getCatalogItemId() == matchingVariant.getCatalogId() && tag.getTagListing().isActive())) {
33973 tejus.loha 812
                    Map<String, Object> variantObj = new HashMap<>();
34229 vikas.jang 813
                    variantObj.put("catalogId", matchingVariant.getCatalogId());
814
                    variantObj.put("variantName", matchingVariant.getVariantName());
35344 vikas 815
                    variantObj.put("mrp", itemTagModel != null ? itemTagModel.getTagListing().getMrp() : 0.0);
35345 vikas 816
                    variantObj.put("mop", itemTagModel != null ? itemTagModel.getTagListing().getMop() : 0.0);
35344 vikas 817
                    variantObj.put("sellingPrice", itemTagModel != null ? itemTagModel.getTagListing().getSellingPrice() : 0.0);
33973 tejus.loha 818
                    variantList.add(variantObj);
819
                }
820
            }
821
        }
822
 
823
        if (variantList.isEmpty()) {
824
            return "[]";
825
        }
826
 
827
        variantList.sort((v1, v2) -> {
828
            int[] n1 = extractNumbers((String) v1.get("variantName"));
829
            int[] n2 = extractNumbers((String) v2.get("variantName"));
830
            int cmp = Integer.compare(n1[0], n2[0]);
831
            return cmp != 0 ? cmp : Integer.compare(n1[1], n2[1]);
832
        });
833
 
834
        ObjectMapper mapper = new ObjectMapper();
835
        return mapper.writeValueAsString(variantList);
836
    }
33979 ranu 837
//(4GB 64GB)
33973 tejus.loha 838
    private int[] extractNumbers(String input) {
839
        String[] parts = input.split("\\s+");
840
        int[] result = new int[2];
841
 
842
        for (int i = 0; i < Math.min(parts.length, 2); i++) {
33979 ranu 843
            String part = (parts[i].toUpperCase()).replace("(", "").replace(")", "");
33973 tejus.loha 844
            if (part.endsWith("GB")) {
845
                result[i] = Integer.parseInt(part.replace("GB", "").trim());
846
            } else if (part.endsWith("TB")) {
847
                result[i] = Integer.parseInt(part.replace("TB", "").trim()) * 1024;
848
            }
849
        }
850
 
851
        return result;
852
    }
853
 
31604 tejbeer 854
}