Subversion Repositories SmartDukaan

Rev

Rev 33574 | Rev 33979 | 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;
33542 amit.gupta 12
import com.spice.profitmandi.dao.entity.similarModel.SimilarModel;
33973 tejus.loha 13
import com.spice.profitmandi.dao.repository.catalog.SuperCatalogMappingRepository;
33245 ranu 14
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
15
import com.spice.profitmandi.dao.repository.catalog.TagRankingRepository;
16
import com.spice.profitmandi.dao.repository.dtr.Mongo;
17
import com.spice.profitmandi.dao.repository.dtr.WebListingRepository;
18
import com.spice.profitmandi.dao.repository.dtr.WebProductListingRepository;
33542 amit.gupta 19
import com.spice.profitmandi.dao.repository.similarModel.SimilarModelRepository;
33973 tejus.loha 20
import com.spice.profitmandi.service.catalog.SuperCatalogModel;
33245 ranu 21
import com.spice.profitmandi.service.tag.ItemTagModel;
22
import in.shop2020.model.v1.catalog.status;
31604 tejbeer 23
import org.apache.logging.log4j.LogManager;
24
import org.apache.logging.log4j.Logger;
25
import org.apache.solr.client.solrj.SolrClient;
26
import org.apache.solr.client.solrj.impl.HttpSolrClient;
27
import org.apache.solr.common.SolrInputDocument;
33570 amit.gupta 28
import org.apache.solr.common.SolrInputField;
31604 tejbeer 29
import org.json.JSONArray;
30
import org.json.JSONException;
31
import org.json.JSONObject;
32
import org.springframework.beans.factory.annotation.Autowired;
31613 tejbeer 33
import org.springframework.beans.factory.annotation.Value;
31604 tejbeer 34
import org.springframework.stereotype.Component;
35
 
33245 ranu 36
import java.io.BufferedReader;
37
import java.io.IOException;
38
import java.io.InputStream;
39
import java.io.InputStreamReader;
40
import java.net.HttpURLConnection;
41
import java.net.URL;
42
import java.net.URLConnection;
43
import java.time.ZoneId;
44
import java.util.*;
45
import java.util.Map.Entry;
46
import java.util.stream.Collectors;
47
import java.util.zip.GZIPInputStream;
31604 tejbeer 48
 
49
@Component
50
public class FofoSolr {
51
 
33542 amit.gupta 52
    @Autowired
53
    private Gson gson;
31604 tejbeer 54
 
33542 amit.gupta 55
    @Autowired
56
    private TagListingRepository tagListingRepository;
31604 tejbeer 57
 
33542 amit.gupta 58
    @Autowired
59
    TagRankingRepository tagRankingRepository;
31604 tejbeer 60
 
33542 amit.gupta 61
    @Autowired
62
    private Mongo contentMongoClient;
31604 tejbeer 63
 
33542 amit.gupta 64
    @Autowired
65
    private WebListingRepository webListingRepository;
31612 tejbeer 66
 
33542 amit.gupta 67
    @Autowired
68
    private WebProductListingRepository webProductListingRepository;
31612 tejbeer 69
 
33973 tejus.loha 70
    @Autowired
71
    private SuperCatalogMappingRepository superCatalogMappingRepository;
72
 
33542 amit.gupta 73
    @Value("${new.solr.url}")
74
    private String solrUrl;
31613 tejbeer 75
 
33542 amit.gupta 76
    @Value("${reportico.url}")
77
    private String reporticoUrl;
33486 amit.gupta 78
 
33542 amit.gupta 79
    private static final Logger logger = LogManager.getLogger(FofoSolr.class);
31604 tejbeer 80
 
33542 amit.gupta 81
    private static final List<Integer> CATEGORY_MASTER = Arrays.asList(10006, 10010, 14202, 14203);
31604 tejbeer 82
 
33542 amit.gupta 83
    private static String getUrlContent(String urlString) {
84
        BufferedReader reader = null;
85
        try {
86
            URL url = new URL(urlString);
87
            URLConnection conn = url.openConnection();
88
            conn.setConnectTimeout(5000);
89
            conn.setReadTimeout(5000);
90
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
91
            return reader.lines().collect(Collectors.joining(System.lineSeparator()));
92
        } catch (IOException e) {
93
            e.printStackTrace();
94
        } finally {
95
            if (reader != null) {
96
                try {
97
                    reader.close();
98
                } catch (IOException e) {
99
                    e.printStackTrace();
100
                }
101
            }
102
        }
103
        return null;
104
    }
31604 tejbeer 105
 
33542 amit.gupta 106
    public JSONArray getAvailability() throws IOException, JSONException {
107
        String url = reporticoUrl + "?execute_mode=EXECUTE&xmlin=warehousecisnew.xml&project=FOCOR&project_password=focor&target_format=JSON";
108
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
109
        connection.setRequestProperty("Accept-Encoding", "gzip");
110
        BufferedReader reader = null;
31604 tejbeer 111
 
33542 amit.gupta 112
        try {
113
            InputStream inputStream = connection.getInputStream();
31604 tejbeer 114
 
33542 amit.gupta 115
            if ("gzip".equals(connection.getContentEncoding())) {
116
                inputStream = new GZIPInputStream(inputStream);
117
            }
31604 tejbeer 118
 
33542 amit.gupta 119
            reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
120
            StringBuilder responseBuilder = new StringBuilder();
121
            String line;
31604 tejbeer 122
 
33542 amit.gupta 123
            while ((line = reader.readLine()) != null) {
124
                responseBuilder.append(line);
125
            }
31604 tejbeer 126
 
33542 amit.gupta 127
            JSONObject responseJson = new JSONObject(responseBuilder.toString());
128
            return responseJson.getJSONArray("data");
129
        } finally {
130
            if (reader != null) {
131
                try {
132
                    reader.close();
133
                } catch (IOException e) {
134
                    // Ignore
135
                }
136
            }
137
        }
138
    }
31604 tejbeer 139
 
33542 amit.gupta 140
    public JSONArray getPendingPO() throws IOException, JSONException {
141
        String url = reporticoUrl + "?execute_mode=EXECUTE&xmlin=UnfulfilledPOItemsNew.xml&project=FOCOR&project_password=focor&target_format=JSON";
142
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
143
        connection.setRequestProperty("Accept-Encoding", "gzip");
144
        BufferedReader reader = null;
31604 tejbeer 145
 
33542 amit.gupta 146
        try {
147
            InputStream inputStream = connection.getInputStream();
31604 tejbeer 148
 
33542 amit.gupta 149
            if ("gzip".equals(connection.getContentEncoding())) {
150
                inputStream = new GZIPInputStream(inputStream);
151
            }
31604 tejbeer 152
 
33542 amit.gupta 153
            reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
154
            StringBuilder responseBuilder = new StringBuilder();
155
            String line;
31604 tejbeer 156
 
33542 amit.gupta 157
            while ((line = reader.readLine()) != null) {
158
                responseBuilder.append(line);
159
            }
31604 tejbeer 160
 
33542 amit.gupta 161
            JSONObject responseJson = new JSONObject(responseBuilder.toString());
162
            return responseJson.getJSONArray("data");
163
        } finally {
164
            if (reader != null) {
165
                try {
166
                    reader.close();
167
                } catch (IOException e) {
168
                    // Ignore
169
                }
170
            }
171
        }
172
    }
31604 tejbeer 173
 
33542 amit.gupta 174
    public Map<String, Map<String, Map<String, Integer>>> getItemMap() throws Exception {
175
        JSONArray availabilityJSONArray = this.getAvailability();
176
        JSONArray pendingPOJSONArray = this.getPendingPO();
177
        Map<String, Map<String, Map<String, Integer>>> availabilityItemMap = new HashMap<>();
31604 tejbeer 178
 
33542 amit.gupta 179
        for (int i = 0; i < availabilityJSONArray.length(); i++) {
180
            JSONObject rawAvailability = availabilityJSONArray.getJSONObject(i);
181
            if (!availabilityItemMap.containsKey(rawAvailability.getString("Itemid"))) {
182
                availabilityItemMap.put(rawAvailability.getString("Itemid"),
183
                        new HashMap<String, Map<String, Integer>>());
184
            }
185
            if (!availabilityItemMap.get(rawAvailability.getString("Itemid"))
186
                    .containsKey(rawAvailability.getString("Warehouseid"))) {
187
                availabilityItemMap.get(rawAvailability.getString("Itemid"))
188
                        .put(rawAvailability.getString("Warehouseid"), new HashMap<String, Integer>());
189
                availabilityItemMap.get(rawAvailability.getString("Itemid"))
190
                        .get(rawAvailability.getString("Warehouseid")).put("netAvailability", 0);
191
                availabilityItemMap.get(rawAvailability.getString("Itemid"))
192
                        .get(rawAvailability.getString("Warehouseid")).put("netPo", 0);
193
            }
194
            int netAvailability = availabilityItemMap.get(rawAvailability.getString("Itemid"))
195
                    .get(rawAvailability.getString("Warehouseid")).get("netAvailability")
196
                    + rawAvailability.getInt("Netavailability");
197
            availabilityItemMap.get(rawAvailability.getString("Itemid")).get(rawAvailability.getString("Warehouseid"))
198
                    .put("netAvailability", netAvailability);
199
        }
31604 tejbeer 200
 
33542 amit.gupta 201
        for (int i = 0; i < pendingPOJSONArray.length(); i++) {
202
            JSONObject rawPendingPo = pendingPOJSONArray.getJSONObject(i);
31604 tejbeer 203
 
33542 amit.gupta 204
            String itemId = rawPendingPo.getString("Itemid");
205
            String warehouseId = rawPendingPo.getString("Warehouseid");
206
            if (!availabilityItemMap.containsKey(itemId)) {
207
                availabilityItemMap.put(itemId, new HashMap<String, Map<String, Integer>>());
208
            }
209
            if (!availabilityItemMap.get(itemId).containsKey(warehouseId)) {
210
                availabilityItemMap.get(itemId).put(warehouseId, new HashMap<String, Integer>() {
211
                    {
212
                        put("netAvailability", 0);
213
                        put("netPo", 0);
214
                    }
215
                });
216
            }
217
            availabilityItemMap.get(itemId).get(warehouseId).put("netPo",
218
                    availabilityItemMap.get(itemId).get(warehouseId).get("netPo") + rawPendingPo.getInt("Unfulfilled"));
31604 tejbeer 219
 
33542 amit.gupta 220
        }
221
        return availabilityItemMap;
31604 tejbeer 222
 
33542 amit.gupta 223
    }
31604 tejbeer 224
 
33245 ranu 225
    public Map<Integer, List<String>> getLabels() throws ProfitMandiBusinessException {
33542 amit.gupta 226
        List<String> labels = Arrays.asList("partner-best-sellers", "partner-price-drop", "new-launches",
227
                "upgrade-offer", "special-support");
31612 tejbeer 228
 
33542 amit.gupta 229
        Map<Integer, String> webListing = webListingRepository.selectByUrls(labels).stream()
230
                .collect(Collectors.toMap(x -> x.getId(), x -> x.getUrl()));
31612 tejbeer 231
 
33542 amit.gupta 232
        Map<Integer, List<WebProductListing>> webProductListingMap = webProductListingRepository
233
                .selectAllByWebListingIds(new ArrayList<>(webListing.keySet())).stream()
234
                .collect(Collectors.groupingBy(x -> x.getWebListingId()));
31612 tejbeer 235
 
33542 amit.gupta 236
        Map<Integer, List<String>> catalogLabelMap = new HashMap<>();
237
        for (Entry<Integer, List<WebProductListing>> webProductListingEntry : webProductListingMap.entrySet()) {
31612 tejbeer 238
 
33542 amit.gupta 239
            for (WebProductListing webProduct : webProductListingEntry.getValue()) {
31612 tejbeer 240
 
33542 amit.gupta 241
                if (!catalogLabelMap.containsKey(webProduct.getEntityId())) {
31612 tejbeer 242
 
33542 amit.gupta 243
                    catalogLabelMap.put(webProduct.getEntityId(), new ArrayList<>());
31612 tejbeer 244
 
33542 amit.gupta 245
                }
31612 tejbeer 246
 
33542 amit.gupta 247
                List<String> itemLabels = catalogLabelMap.get(webProduct.getEntityId());
248
                itemLabels.add(webListing.get(webProduct.getWebListingId()));
249
                catalogLabelMap.put(webProduct.getEntityId(), itemLabels);
31612 tejbeer 250
 
33542 amit.gupta 251
            }
31612 tejbeer 252
 
33542 amit.gupta 253
        }
31612 tejbeer 254
 
33542 amit.gupta 255
        return catalogLabelMap;
256
    }
31612 tejbeer 257
 
33542 amit.gupta 258
    @Autowired
259
    SimilarModelRepository similarModelRepository;
31604 tejbeer 260
 
33542 amit.gupta 261
    public void populateTagItems() throws Exception {
262
        Map<String, Map<String, Map<String, Integer>>> availabilityItemMap = getItemMap();
263
        List<TagRanking> tagRankingList = tagRankingRepository.getAllTagRanking();
264
        List<Integer> rankingList = new ArrayList<>();
265
        Map<Integer, String> featureMap = new HashMap<>();
266
        for (TagRanking tagRanking : tagRankingList) {
267
            rankingList.add(tagRanking.getCatalogItemId());
268
            featureMap.put(tagRanking.getCatalogItemId(), tagRanking.getFeature());
269
        }
270
        //Get Similar Models
33570 amit.gupta 271
        /*List<SimilarModel> similarModels = similarModelRepository.selectAll();
31612 tejbeer 272
 
33570 amit.gupta 273
        Map<Integer, List<Integer>> similarModelsMap = similarModels.stream().collect(Collectors.groupingBy(SimilarModel::getCatalogId, Collectors.mapping(x -> x.getSimilarCatalogId(), Collectors.toList())));*/
31612 tejbeer 274
 
33542 amit.gupta 275
        Map<Integer, Map<String, Object>> catalogMap = new HashMap<>();
31612 tejbeer 276
 
33542 amit.gupta 277
        List<status> statuses = Arrays.asList(status.ACTIVE, status.PAUSED_BY_RISK, status.PARTIALLY_ACTIVE);
31612 tejbeer 278
 
33542 amit.gupta 279
        Map<Integer, List<String>> catalogLabelMap = this.getLabels();
31604 tejbeer 280
 
33973 tejus.loha 281
        //logger.info("catalogLabelMap {}", catalogLabelMap);
31604 tejbeer 282
 
33562 amit.gupta 283
        List<ItemTagModel> itemTagModels = tagListingRepository.getAllItemTagByStatus(statuses);
31604 tejbeer 284
 
33542 amit.gupta 285
        Map<String, Object> projection = new HashMap<>();
286
        projection.put("defaultImageUrl", 1);
31604 tejbeer 287
 
33542 amit.gupta 288
        List<String> excludeBrands = Arrays.asList("Dummy", "FOC HANDSET");
31604 tejbeer 289
 
33562 amit.gupta 290
        Map<Float, List<Integer>> priceModelMap = new TreeMap<>();
291
        for (ItemTagModel itemTagModel : itemTagModels) {
292
            TagListing tagListing = itemTagModel.getTagListing();
293
            com.spice.profitmandi.dao.entity.catalog.Item item = itemTagModel.getItem();
33542 amit.gupta 294
            if (excludeBrands.contains(item.getBrand())) {
295
                continue;
296
            }
31604 tejbeer 297
 
33542 amit.gupta 298
            if (!catalogMap.containsKey(item.getCatalogItemId())) {
33571 amit.gupta 299
                if (!priceModelMap.containsKey(tagListing.getMop()) && item.getCategoryId() == 10006) {
33572 amit.gupta 300
                    priceModelMap.put(tagListing.getMop(), new ArrayList<>());
33562 amit.gupta 301
                }
33570 amit.gupta 302
                if (item.getCategoryId() == 10006) {
33571 amit.gupta 303
                    List<Integer> priceModels = priceModelMap.get(tagListing.getMop());
33565 amit.gupta 304
                    priceModels.add(item.getCatalogItemId());
305
                }
33562 amit.gupta 306
 
33542 amit.gupta 307
                Map<String, Object> catalogObj = new HashMap<>();
33570 amit.gupta 308
                catalogObj.put("stockColor", 0);
33542 amit.gupta 309
                catalogObj.put("feature", "");
310
                catalogObj.put("hsnCode", item.getHsnCode());
311
                catalogObj.put("title",
312
                        String.join(" ", Arrays.asList(item.getBrand(), item.getModelName(), item.getModelNumber())
313
                                .stream().filter(s -> s != null && !s.isEmpty()).collect(Collectors.toList())));
314
                catalogObj.put("brand", new String[]{item.getBrand()});
315
                if (item.getBrand().equals("Huawei") || item.getBrand().equals("Honor")) {
316
                    catalogObj.put("brand", new String[]{"Huawei", "Honor"});
317
                }
318
                if (item.getBrand().equals("Mi") || item.getBrand().equals("Xiaomi")
319
                        || item.getBrand().equals("Redmi")) {
320
                    catalogObj.put("brand", new String[]{"Mi", "Xiaomi", "Redmi"});
321
                }
322
                catalogObj.put("identifier", item.getCatalogItemId());
323
                catalogObj.put("items", new HashMap<Integer, Map<String, Object>>());
324
                Map<String, Object> filterMap = new HashMap<>();
325
                filterMap.put("_id", item.getCatalogItemId());
326
                // Don't include if catalog not available
327
                try {
328
                    String imageUrl = contentMongoClient.getEntityById(item.getCatalogItemId()).getDefaultImageUrl();
31624 tejbeer 329
 
33542 amit.gupta 330
                    if (imageUrl != null) {
331
                        catalogObj.put("imageUrl", imageUrl);
332
                    } else {
333
                        catalogObj.put("imageUrl",
334
                                "https://images.smartdukaan.com/uploads/campaigns/" + item.getCatalogItemId() + ".jpg");
335
                    }
336
                } catch (Exception e) {
337
                    try {
338
                        catalogObj.put("imageUrl",
339
                                "https://images.smartdukaan.com/uploads/campaigns/" + item.getCatalogItemId() + ".jpg");
340
                    } catch (Exception e2) {
341
                        e2.printStackTrace();
342
                    }
343
                }
344
                try {
345
                    catalogObj.put("rank", rankingList.indexOf(item.getCatalogItemId()));
346
                } catch (Exception e) {
347
                    // A very big number
348
                    e.printStackTrace();
349
                    catalogObj.put("rank", 50000000);
350
                }
351
                if (featureMap.containsKey(item.getCatalogItemId())
352
                        && featureMap.get(item.getCatalogItemId()) != null) {
353
                    catalogObj.put("feature", featureMap.get(item.getCatalogItemId()));
31612 tejbeer 354
 
33542 amit.gupta 355
                }
31612 tejbeer 356
 
33542 amit.gupta 357
                catalogObj.put("categoryId", CATEGORY_MASTER.contains(item.getCategoryId()) ? item.getCategoryId() : 6);
31612 tejbeer 358
 
33542 amit.gupta 359
                if (item.getCategoryId() == 10006) {
360
                    catalogObj.put("categoryId", 3);
361
                }
362
                catalogObj.put("subCategoryId", item.getCategoryId());
363
                catalogObj.put("create_timestamp",
33562 amit.gupta 364
                        tagListing.getCreatedTimestamp().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
31604 tejbeer 365
 
33542 amit.gupta 366
                if (catalogLabelMap.containsKey(item.getCatalogItemId())
367
                        && catalogLabelMap.get(item.getCatalogItemId()) != null) {
368
                    catalogObj.put("labels", catalogLabelMap.get(item.getCatalogItemId()));
31604 tejbeer 369
 
33542 amit.gupta 370
                }
371
                catalogMap.put(item.getCatalogItemId(), catalogObj);
372
                catalogObj.put("avColor", new HashMap<>());
31604 tejbeer 373
 
33542 amit.gupta 374
            }
31604 tejbeer 375
 
33542 amit.gupta 376
            Map<String, Object> catalogObj = catalogMap.get(item.getCatalogItemId());
377
            Map<Integer, Integer> avColorMap = (Map<Integer, Integer>) catalogObj.get("avColor");
31604 tejbeer 378
 
33542 amit.gupta 379
            if (availabilityItemMap.containsKey(String.valueOf(item.getId()))) {
33570 amit.gupta 380
                int itemStockColor = 0;
33542 amit.gupta 381
                for (Map.Entry<String, Map<String, Integer>> entry : availabilityItemMap
382
                        .get(String.valueOf(item.getId())).entrySet()) {
383
                    String warehouseId = entry.getKey();
384
                    Map<String, Integer> avMap = entry.getValue();
385
                    if (!avColorMap.containsKey(Integer.parseInt(warehouseId))) {
386
                        avColorMap.put(Integer.parseInt(warehouseId), 0);
387
                    }
388
                    int color = avColorMap.get(Integer.parseInt(warehouseId));
31604 tejbeer 389
 
33542 amit.gupta 390
                    if (avMap.get("netAvailability") > 0) {
391
                        color = 2;
33562 amit.gupta 392
                    } else if (avMap.get("netPo") > 0) {
33542 amit.gupta 393
                        color = Math.max(color, 1);
394
                    } else {
395
                        color = Math.max(color, 0);
396
                    }
397
                    avColorMap.put(Integer.parseInt(warehouseId), color);
31604 tejbeer 398
 
33542 amit.gupta 399
                    catalogObj.put("avColor", avColorMap);
33570 amit.gupta 400
                    if (color > itemStockColor) {
401
                        itemStockColor = color;
402
                    }
33542 amit.gupta 403
                }
33570 amit.gupta 404
                if (itemStockColor > 0 && itemStockColor > (Integer) catalogObj.get("stockColor")) {
405
                    catalogObj.put("stockColor", itemStockColor);
406
                }
33542 amit.gupta 407
            }
31604 tejbeer 408
 
33542 amit.gupta 409
            Map<Integer, Object> itemColorMap = (Map<Integer, Object>) catalogObj.get("items");
31604 tejbeer 410
 
33542 amit.gupta 411
            if (!itemColorMap.containsKey(item.getId())) {
412
                itemColorMap.put(item.getId(), new HashMap<String, Object>() {
413
                    {
414
                        put("color", item.getColor().replace("f_", ""));
415
                        put("tagPricing", new ArrayList<TagListing>());
416
                    }
417
                });
418
            }
419
            Map<String, Object> itemMap = (Map<String, Object>) itemColorMap.get(item.getId());
420
            List<TagListing> tagPricing = (List<TagListing>) itemMap.get("tagPricing");
33562 amit.gupta 421
            tagPricing.add(tagListing);
33542 amit.gupta 422
        }
33562 amit.gupta 423
        //logger.info("catalogObj {}", catalogMap);
31604 tejbeer 424
 
33973 tejus.loha 425
        List<SuperCatalogModel> superCatalogMappingList = superCatalogMappingRepository.selectJoinedData();
426
        List<SuperCatalogMapping> superCatalogs = superCatalogMappingRepository.selectAll();
33542 amit.gupta 427
        List<SolrInputDocument> catalogSolrObjs = new ArrayList<>();
428
        for (Entry<Integer, Map<String, Object>> entry : catalogMap.entrySet()) {
429
            int catalogId = entry.getKey();
33973 tejus.loha 430
            Optional<SuperCatalogModel> superCatalogMapping = findMappingByCatalogId(superCatalogMappingList, catalogId);
33542 amit.gupta 431
            Map<String, Object> catalogValMap = entry.getValue();
432
            Map<Integer, Object> itemsMap = (Map<Integer, Object>) catalogValMap.get("items");
31604 tejbeer 433
 
33542 amit.gupta 434
            boolean active = false;
435
            // Map<Integer, Object> itemsMap = (Map<String, Object>)
436
            // catalogValMap.get("items");
437
            List<SolrInputDocument> itemObjs = new ArrayList<>();
438
            float mop = 0;
33574 amit.gupta 439
            float dp = 0;
31604 tejbeer 440
 
33542 amit.gupta 441
            for (Entry<Integer, Object> itemEntry : itemsMap.entrySet()) {
442
                int itemId = itemEntry.getKey();
443
                Map<String, Object> itemMap = (Map<String, Object>) itemEntry.getValue();
444
                List<TagListing> tags = (List<TagListing>) itemMap.get("tagPricing");
445
                SolrInputDocument itemObj = new SolrInputDocument();
31604 tejbeer 446
 
33542 amit.gupta 447
                for (TagListing taglist : tags) {
33562 amit.gupta 448
                    active = active || taglist.isActive();
33542 amit.gupta 449
                    itemObj.setField("id", "itemtag-" + itemId + "-" + taglist.getTagId());
450
                    itemObj.setField("color_s", itemMap.get("color"));
451
                    itemObj.setField("itemId_i", itemId);
452
                    itemObj.setField("tagId_i", taglist.getTagId());
453
                    itemObj.setField("mrp_f", taglist.getMrp());
454
                    itemObj.setField("mop_f", taglist.getMop());
455
                    itemObj.setField("sellingPrice_f", taglist.getSellingPrice());
456
                    itemObj.setField("active_b", taglist.isActive());
457
                    itemObj.setField("hot_deal_b", taglist.isHotDeals());
458
                    mop = taglist.getMop();
33574 amit.gupta 459
                    dp = taglist.getSellingPrice();
33542 amit.gupta 460
                }
461
                itemObjs.add(itemObj);
462
            }
31604 tejbeer 463
 
33542 amit.gupta 464
            SolrInputDocument catalogSolrObj = new SolrInputDocument();
465
            catalogSolrObj.setField("id", "catalog" + catalogId);
466
            catalogSolrObj.setField("rank_i", catalogValMap.get("rank"));
467
            catalogSolrObj.setField("title_s", catalogValMap.get("title"));
468
            catalogSolrObj.addChildDocuments(itemObjs);
469
            catalogSolrObj.setField("child_b", itemObjs.size() > 0);
470
            catalogSolrObj.setField("catalogId_i", catalogId);
33973 tejus.loha 471
            if (superCatalogMapping.isPresent()) {
472
                int superCatalogId = superCatalogMapping.get().getSuperCatalogId();
473
                String superCatalogMappingVariants = findMappingVariantsByCatalogId(superCatalogs, superCatalogId);
474
                catalogSolrObj.setField("superCatalog_i", superCatalogId);
475
                catalogSolrObj.setField("superCatalog_s", superCatalogMapping.get().getSuperCatalogName());
476
                catalogSolrObj.setField("superCatalogVariants_s", superCatalogMappingVariants);
477
            } else {
478
                catalogSolrObj.setField("superCatalog_i", 0);
479
                catalogSolrObj.setField("superCatalog_s", "_");
480
                catalogSolrObj.setField("superCatalogVariants_s", "[]");
481
            }
33542 amit.gupta 482
            catalogSolrObj.setField("imageUrl_s",
483
                    catalogValMap.get("imageUrl").toString().replace("saholic", "smartdukaan"));
484
            catalogSolrObj.setField("feature_s", catalogValMap.get("feature"));
485
            catalogSolrObj.setField("brand_ss", catalogValMap.get("brand"));
486
            catalogSolrObj.setField("create_s", catalogValMap.get("create_timestamp"));
487
            catalogSolrObj.setField("categoryId_i", catalogValMap.get("categoryId"));
488
            catalogSolrObj.setField("subCategoryId_i", catalogValMap.get("subCategoryId"));
489
            catalogSolrObj.setField("label_ss", catalogValMap.get("labels"));
490
            catalogSolrObj.setField("mop_f", mop);
33574 amit.gupta 491
            catalogSolrObj.setField("dp_f", dp);
33542 amit.gupta 492
            catalogSolrObj.setField("hsncode_s", catalogValMap.get("hsnCode"));
493
            catalogSolrObj.setField("show_default_b", true);
31710 tejbeer 494
 
33542 amit.gupta 495
            String[] brands = (String[]) catalogValMap.get("brand");
496
            for (String brand : brands) {
497
                if (brand.equals("FOC")) {
498
                    catalogSolrObj.setField("show_default_b", false);
499
                }
31604 tejbeer 500
 
33542 amit.gupta 501
                if (brand.equals("Live Demo")) {
502
                    catalogSolrObj.setField("show_default_b", false);
503
                }
504
            }
505
            Map<Integer, Integer> avColorMap = (Map<Integer, Integer>) catalogValMap.get("avColor");
33499 amit.gupta 506
 
33570 amit.gupta 507
            for (Integer warehouseId : ProfitMandiConstants.WAREHOUSE_MAP.keySet()) {
508
                catalogSolrObj.setField("w" + warehouseId + "_i", 0);
509
            }
33542 amit.gupta 510
            for (Entry<Integer, Integer> avColorEntry : avColorMap.entrySet()) {
511
                int whId = avColorEntry.getKey();
33562 amit.gupta 512
                int color = avColorEntry.getValue();
33542 amit.gupta 513
                catalogSolrObj.setField("w" + whId + "_i", color);
514
            }
33570 amit.gupta 515
 
516
            List<Integer> similalarModels = null;
517
            if ((Integer) catalogValMap.get("categoryId") == 3) {
33571 amit.gupta 518
                float starPrice = mop - 500f;
519
                float endPrice = mop + 1000f;
33570 amit.gupta 520
                similalarModels = new ArrayList<>();
521
                for (Entry<Float, List<Integer>> floatListEntry : priceModelMap.entrySet()) {
522
                    float modelPrice = floatListEntry.getKey();
523
                    if (modelPrice >= starPrice && modelPrice <= endPrice) {
524
                        List<Integer> instock = floatListEntry.getValue().stream().filter(x->catalogMap.get(x).get("stockColor") != null && (Integer) (catalogMap.get(x).get("stockColor"))>0).collect(Collectors.toList());
33571 amit.gupta 525
                        logger.info("Entry before - {}, after - {}", floatListEntry.getValue().size(), instock.size());
33570 amit.gupta 526
                        similalarModels.addAll(instock);
527
                    }
528
                    if (modelPrice > endPrice) break;
529
                }
530
                similalarModels.remove(Integer.valueOf(catalogId));
531
            }
33973 tejus.loha 532
            catalogSolrObj.setField("similarModels_is", similalarModels == null ? Collections.EMPTY_LIST : similalarModels);
33570 amit.gupta 533
 
534
 
33542 amit.gupta 535
            catalogSolrObj.setField("active_b", active);
536
            catalogSolrObjs.add(catalogSolrObj);
537
        }
31604 tejbeer 538
 
33542 amit.gupta 539
        String solrPath = "http://" + solrUrl + ":8984/solr/demo";
540
        SolrClient solr = new HttpSolrClient.Builder(solrPath).build();
31604 tejbeer 541
 
33542 amit.gupta 542
        solr.deleteByQuery("*:*");
543
        solr.add(catalogSolrObjs);
544
 
545
        org.apache.solr.client.solrj.response.UpdateResponse updateResponse = solr.commit();
546
        logger.info("solr {}", updateResponse.getStatus());
547
 
548
    }
549
 
550
    public void pushData() throws Exception {
551
        this.populateTagItems();
552
    }
33973 tejus.loha 553
 
554
    public Optional<SuperCatalogModel> findMappingByCatalogId(List<SuperCatalogModel> superCatalogMappingList, int id) {
555
 
556
        return superCatalogMappingList.parallelStream()
557
                .filter(mapping -> mapping.getCatalogId() == id)
558
                .findFirst();
559
    }
560
 
561
    public String findMappingVariantsByCatalogId(List<SuperCatalogMapping> superCatalogMappingList, int id) throws JsonProcessingException {
562
        List<Map<String, Object>> variantList = new ArrayList<>();
563
        List<SuperCatalogMapping> matchingVariantNames = superCatalogMappingList.parallelStream()
564
                .filter(mapping -> mapping.getSuperCatalogId() == id)
565
                .collect(Collectors.toList());
566
 
567
        if (!matchingVariantNames.isEmpty()) {
568
            for (SuperCatalogMapping matchingVariantName : matchingVariantNames) {
569
                logger.info("matchingVariantName: "+matchingVariantName);
570
                   if (matchingVariantName != null && matchingVariantName.getVariantName() != null) {
571
                    Map<String, Object> variantObj = new HashMap<>();
572
                    variantObj.put("catalogId", matchingVariantName.getCatalogId());
573
                    variantObj.put("variantName", matchingVariantName.getVariantName());
574
                    variantList.add(variantObj);
575
                }
576
            }
577
        }
578
 
579
        if (variantList.isEmpty()) {
580
            return "[]";
581
        }
582
 
583
        variantList.sort((v1, v2) -> {
584
            int[] n1 = extractNumbers((String) v1.get("variantName"));
585
            int[] n2 = extractNumbers((String) v2.get("variantName"));
586
            int cmp = Integer.compare(n1[0], n2[0]);
587
            return cmp != 0 ? cmp : Integer.compare(n1[1], n2[1]);
588
        });
589
 
590
        ObjectMapper mapper = new ObjectMapper();
591
        return mapper.writeValueAsString(variantList);
592
    }
593
 
594
    private int[] extractNumbers(String input) {
595
        String[] parts = input.split("\\s+");
596
        int[] result = new int[2];
597
 
598
        for (int i = 0; i < Math.min(parts.length, 2); i++) {
599
            String part = parts[i].toUpperCase();
600
            if (part.endsWith("GB")) {
601
                result[i] = Integer.parseInt(part.replace("GB", "").trim());
602
            } else if (part.endsWith("TB")) {
603
                result[i] = Integer.parseInt(part.replace("TB", "").trim()) * 1024;
604
            }
605
        }
606
 
607
        return result;
608
    }
609
 
31604 tejbeer 610
}