Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
28468 tejbeer 1
package com.spice.profitmandi.service;
2
 
3
import com.google.gson.Gson;
4
import com.spice.profitmandi.common.enumuration.ReporticoProject;
5
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
30449 amit.gupta 6
import com.spice.profitmandi.common.model.*;
28468 tejbeer 7
import com.spice.profitmandi.dao.entity.auth.AuthUser;
8
import com.spice.profitmandi.dao.entity.auth.Menu;
35549 ranu 9
import com.spice.profitmandi.dao.entity.cs.Bulletin;
28468 tejbeer 10
import com.spice.profitmandi.dao.entity.cs.Position;
11
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
29165 manish 12
import com.spice.profitmandi.dao.entity.fofo.PartnerType;
28468 tejbeer 13
import com.spice.profitmandi.dao.entity.inventory.ReporticoCacheTable;
32172 jai.hind 14
import com.spice.profitmandi.dao.entity.transaction.LoanSummary;
35316 ranu 15
import com.spice.profitmandi.dao.entity.transaction.StateWiseLoanSummary;
28468 tejbeer 16
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
17
import com.spice.profitmandi.dao.model.BrandWiseModel;
35549 ranu 18
import com.spice.profitmandi.dao.model.BulletinOfferModal;
28468 tejbeer 19
import com.spice.profitmandi.dao.model.PartnerDetailModel;
20
import com.spice.profitmandi.dao.model.WarehouseWiseStockModel;
21
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
22
import com.spice.profitmandi.dao.repository.auth.MenuCategoryRepository;
23
import com.spice.profitmandi.dao.repository.auth.MenuRepository;
35549 ranu 24
import com.spice.profitmandi.dao.repository.cs.*;
28468 tejbeer 25
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
28825 tejbeer 26
import com.spice.profitmandi.dao.repository.fofo.ActivatedImeiRepository;
28468 tejbeer 27
import com.spice.profitmandi.dao.repository.inventory.ReporticoCacheTableRepository;
28
import com.spice.profitmandi.dao.repository.inventory.SaholicInventoryCISRepository;
29
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
35549 ranu 30
import com.spice.profitmandi.service.offers.TodayOfferService;
32172 jai.hind 31
import com.spice.profitmandi.service.transaction.SDCreditService;
28468 tejbeer 32
import com.spice.profitmandi.service.user.RetailerService;
30449 amit.gupta 33
import org.apache.logging.log4j.LogManager;
34
import org.apache.logging.log4j.Logger;
35
import org.springframework.beans.factory.annotation.Autowired;
36
import org.springframework.stereotype.Component;
37
import org.springframework.ui.Model;
28468 tejbeer 38
 
30449 amit.gupta 39
import java.io.FileInputStream;
40
import java.io.ObjectInputStream;
35549 ranu 41
import java.time.*;
30449 amit.gupta 42
import java.time.format.DateTimeFormatter;
43
import java.time.temporal.ChronoUnit;
44
import java.util.*;
45
import java.util.Map.Entry;
46
import java.util.stream.Collectors;
47
import java.util.stream.LongStream;
48
 
28468 tejbeer 49
@Component
50
public class AdminUser {
33071 amit.gupta 51
    @Autowired
52
    private Gson gson;
28468 tejbeer 53
 
33071 amit.gupta 54
    @Autowired
55
    private OrderRepository orderRepository;
28468 tejbeer 56
 
33071 amit.gupta 57
    @Autowired
58
    TicketRepository ticketRepository;
28468 tejbeer 59
 
33071 amit.gupta 60
    @Autowired
61
    private ChartService chartService;
28468 tejbeer 62
 
33071 amit.gupta 63
    @Autowired
64
    RetailerService retailerService;
28468 tejbeer 65
 
33071 amit.gupta 66
    @Autowired
67
    AuthRepository authRepository;
28468 tejbeer 68
 
33071 amit.gupta 69
    @Autowired
70
    FofoStoreRepository fofoStoreRepository;
28468 tejbeer 71
 
33071 amit.gupta 72
    @Autowired
73
    CsService1 csService1;
31662 amit.gupta 74
 
33071 amit.gupta 75
    @Autowired
76
    CsService csService;
28468 tejbeer 77
 
33071 amit.gupta 78
    @Autowired
79
    private MenuRepository menuRepository;
28468 tejbeer 80
 
33071 amit.gupta 81
    @Autowired
82
    private PositionRepository positionRepository;
28468 tejbeer 83
 
33071 amit.gupta 84
    @Autowired
85
    private MenuCategoryRepository menuCategoryRepository;
28468 tejbeer 86
 
33071 amit.gupta 87
    @Autowired
88
    private SaholicInventoryCISRepository saholicInventoryCISRepository;
28468 tejbeer 89
 
33071 amit.gupta 90
    @Autowired
91
    private ReporticoCacheTableRepository reporticoCacheTableRepository;
28468 tejbeer 92
 
33071 amit.gupta 93
    @Autowired
94
    private ActivatedImeiRepository activatedImeiRepository;
28825 tejbeer 95
 
33071 amit.gupta 96
    @Autowired
97
    private PartnerStatsService partnerStatsService;
98
    @Autowired
99
    private SDCreditService sdCreditService;
28468 tejbeer 100
 
35549 ranu 101
    @Autowired
102
    BulletinRepository bulletinRepository;
103
 
104
    @Autowired
105
    TodayOfferService todayOfferService;
106
 
33071 amit.gupta 107
    List<String> colorList = Arrays.asList("mediumseagreen", "dodgerblue", "darkblue", "gold", "#eb0029", "coral",
108
            "#63C5DA", "red", "deeppink", "midnightblue", "cornsilk");
28468 tejbeer 109
 
33071 amit.gupta 110
    List<String> borderList = Arrays.asList("lawngreen", "lightblue", "#0000cd", "#f7e98e", "#eb0029", "lightcoral",
111
            "#0000cd", "lightsalmon", "pink", "#0000cd", "cornsilk");
28468 tejbeer 112
 
33071 amit.gupta 113
    List<String> brands = Arrays.asList("Oppo", "Vivo", "Samsung", "Realme", "OnePlus", "Xiaomi", "Tecno", "Itel",
114
            "Lava", "Nokia");
28468 tejbeer 115
 
33071 amit.gupta 116
    private static final Logger LOGGER = LogManager.getLogger(AdminUser.class);
28468 tejbeer 117
 
33071 amit.gupta 118
    public ChartModel getBrandWiseLmp(List<Integer> warehouseIds, List<Integer> fofoIds, LocalDate startDate,
119
                                      LocalDate endDate, String filterType) {
33072 amit.gupta 120
        //LOGGER.info("params" + warehouseIds + fofoIds + startDate);
28468 tejbeer 121
 
33071 amit.gupta 122
        List<BrandWiseModel> brandWiseLms = orderRepository.selectGroupByBrandLmp(fofoIds, warehouseIds, startDate,
123
                endDate, filterType);
124
        LOGGER.info("brandWiseLms" + brandWiseLms);
125
        ChartModel cm = null;
28468 tejbeer 126
 
33071 amit.gupta 127
        if (filterType.equals("dateWise")) {
128
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-dd-yyyy");
28468 tejbeer 129
 
33071 amit.gupta 130
            Map<String, Map<LocalDate, Double>> brandDateValue = new HashMap<>();
131
            for (BrandWiseModel bwl : brandWiseLms) {
132
                if (!brandDateValue.containsKey(bwl.getBrand())) {
133
                    brandDateValue.put(bwl.getBrand(), new HashMap<>());
134
                }
135
                Map<LocalDate, Double> dateWiseSalesMap = brandDateValue.get(bwl.getBrand());
136
                dateWiseSalesMap.put(LocalDate.parse(bwl.getYearMonth(), dateTimeFormatter), (double) bwl.getAmount());
137
            }
28468 tejbeer 138
 
33071 amit.gupta 139
            long days = startDate.until(endDate, ChronoUnit.DAYS);
140
            List<LocalDate> allDatesBetween = LongStream.range(0, days).mapToObj(x -> startDate.plusDays(x))
141
                    .collect(Collectors.toList());
142
            LOGGER.info("All dates between {}", allDatesBetween);
28468 tejbeer 143
 
33071 amit.gupta 144
            Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
28468 tejbeer 145
 
33071 amit.gupta 146
            for (String brand : brands) {
147
                if (!brandDateValue.containsKey(brand)) {
148
                    brandDateValue.put(brand, new HashMap<>());
149
                }
150
                Map<LocalDate, Double> dateWiseBrand = brandDateValue.get(brand);
151
                for (LocalDate date : allDatesBetween) {
152
                    if (dateWiseBrand.get(date) == null) {
153
                        dateWiseBrand.put(date, 0.0);
154
                    }
155
                }
30279 tejbeer 156
 
33071 amit.gupta 157
                Map<LocalDate, Double> sortedMonthBrandValue = new TreeMap<>(dateWiseBrand);
158
                sortedBrandValue.put(brand, new ArrayList<>(sortedMonthBrandValue.values()));
159
                LOGGER.info("Sorted Brandwise values count {}", sortedMonthBrandValue.size());
160
            }
30279 tejbeer 161
 
33071 amit.gupta 162
            LOGGER.info("brandMonthValueCount {}", brandDateValue.size());
30279 tejbeer 163
 
33071 amit.gupta 164
            LOGGER.info("sortedBrandValueCount {}", sortedBrandValue.size());
165
            cm = chartService.createChartWithLabels(
166
                    allDatesBetween.stream().map(x -> x.format((DateTimeFormatter.ofPattern("dd MMM''uu"))))
167
                            .collect(Collectors.toCollection(LinkedHashSet::new)),
168
                    sortedBrandValue, colorList, borderList, "Brand Wise Date Wise Purchase");
30279 tejbeer 169
 
33071 amit.gupta 170
        } else {
30279 tejbeer 171
 
33071 amit.gupta 172
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
30279 tejbeer 173
 
33071 amit.gupta 174
            Map<String, Map<YearMonth, Double>> brandMonthValue = new HashMap<>();
175
            for (BrandWiseModel bwl : brandWiseLms) {
176
                Map<YearMonth, Double> yearMonthValue = new HashMap<>();
177
                if (brandMonthValue.containsKey(bwl.getBrand())) {
178
                    yearMonthValue = brandMonthValue.get(bwl.getBrand());
179
                    yearMonthValue.put(YearMonth.parse(bwl.getYearMonth(), dateTimeFormatter),
180
                            (double) bwl.getAmount());
181
                } else {
30279 tejbeer 182
 
33071 amit.gupta 183
                    yearMonthValue.put(YearMonth.parse(bwl.getYearMonth(), dateTimeFormatter),
184
                            (double) bwl.getAmount());
30279 tejbeer 185
 
33071 amit.gupta 186
                }
187
                brandMonthValue.put(bwl.getBrand(), yearMonthValue);
30279 tejbeer 188
 
33071 amit.gupta 189
            }
190
            LocalDateTime curDate = LocalDate.now().atStartOfDay();
28468 tejbeer 191
 
33071 amit.gupta 192
            Period age = Period.between(startDate, endDate);
193
            int months = age.getMonths();
194
            LOGGER.info("months" + months);
195
            LOGGER.info("brandWiseLms" + brandWiseLms);
196
            LOGGER.info("brandMonthValue" + brandMonthValue);
28468 tejbeer 197
 
33071 amit.gupta 198
            Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
28468 tejbeer 199
 
33071 amit.gupta 200
            for (String brand : brands) {
201
                Map<YearMonth, Double> yearMonthValue = brandMonthValue.get(brand);
202
                for (int i = months; i >= 0; i--) {
28468 tejbeer 203
 
33071 amit.gupta 204
                    LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
28468 tejbeer 205
 
33071 amit.gupta 206
                    if (yearMonthValue != null) {
207
                        if (yearMonthValue.get(YearMonth.from(startMonth)) == null) {
208
                            yearMonthValue.put(YearMonth.from(startMonth), 0.0);
209
                        }
30279 tejbeer 210
 
33071 amit.gupta 211
                    } else {
212
                        yearMonthValue = new HashMap<>();
213
                        yearMonthValue.put(YearMonth.from(startMonth), 0.0);
214
                    }
215
                }
30279 tejbeer 216
 
33071 amit.gupta 217
                Map<YearMonth, Double> sortedMonthBrandValue = new TreeMap<>(yearMonthValue);
30279 tejbeer 218
 
33071 amit.gupta 219
                brandMonthValue.put(brand, sortedMonthBrandValue);
30279 tejbeer 220
 
33071 amit.gupta 221
                sortedBrandValue.put(brand, sortedMonthBrandValue.values().stream().collect(Collectors.toList()));
30279 tejbeer 222
 
33071 amit.gupta 223
            }
30279 tejbeer 224
 
33071 amit.gupta 225
            cm = chartService.createChart(months, sortedBrandValue, colorList, borderList,
226
                    "Brand Wise Monthly Purchase");
30279 tejbeer 227
 
33071 amit.gupta 228
        }
30279 tejbeer 229
 
33071 amit.gupta 230
        return cm;
231
    }
28468 tejbeer 232
 
33071 amit.gupta 233
    public ChartInvestmentModel getAllStatePartnerType(Map<Integer, PartnerDetailModel> fofoIdAndallValues)
234
            throws ProfitMandiBusinessException {
29165 manish 235
 
33071 amit.gupta 236
        Map<String, Float> partnerTypeCount = new HashMap<>();
29165 manish 237
 
33071 amit.gupta 238
        List<PartnerType> partnerTypes = Arrays.asList(PartnerType.values());
29165 manish 239
 
33071 amit.gupta 240
        for (PartnerType partnerType : partnerTypes) {
29165 manish 241
 
33071 amit.gupta 242
            float count = fofoIdAndallValues.entrySet().stream()
35483 amit 243
                    .filter(x -> x.getValue() != null && x.getValue().getPartnerType().equals(partnerType)).count();
29165 manish 244
 
33071 amit.gupta 245
            partnerTypeCount.put(partnerType.toString(), count);
29165 manish 246
 
33071 amit.gupta 247
        }
29165 manish 248
 
33071 amit.gupta 249
        ChartInvestmentModel cm = new ChartInvestmentModel();
29165 manish 250
 
33071 amit.gupta 251
        HashSet<String> labels = new HashSet<String>();
252
        labels.addAll(partnerTypes.stream().skip(1).map(x -> x.toString()).collect(Collectors.toList()));
253
        List<String> labelList = new ArrayList<>(labels);
29165 manish 254
 
33071 amit.gupta 255
        List<String> backgroundColor = new ArrayList<>();
29165 manish 256
 
33071 amit.gupta 257
        List<Float> values = new ArrayList<>();
29165 manish 258
 
33071 amit.gupta 259
        for (String label : labelList) {
260
            values.add(partnerTypeCount.get(label));
261
            if (label.equals("BRONZE")) {
262
                backgroundColor.add("#CD7F32");
263
            }
264
            if (label.equals("SILVER")) {
265
                backgroundColor.add("silver");
266
            }
267
            if (label.equals("GOLD")) {
268
                backgroundColor.add("#FFD700");
269
            }
270
            if (label.equals("DIAMOND")) {
271
                backgroundColor.add("#B9F2FF");
272
            }
29165 manish 273
 
33071 amit.gupta 274
            if (label.equals("PLATINUM")) {
275
                backgroundColor.add("#800080");
276
            }
277
            if (label.equals("NEW")) {
278
                backgroundColor.add("green");
279
            }
29165 manish 280
 
33071 amit.gupta 281
        }
29165 manish 282
 
33071 amit.gupta 283
        LOGGER.info("valuesPartnerType" + values);
284
        LOGGER.info("partnerTypeCount" + partnerTypeCount);
29165 manish 285
 
33071 amit.gupta 286
        Data data = new Data();
287
        data.setData(values);
288
        data.setBackgroundColor(backgroundColor);
289
        data.setLabel("DataSet 1");
29165 manish 290
 
33071 amit.gupta 291
        PieLables label = new PieLables();
292
        label.setFontColor("black");
293
        label.setFontSize(22);
29165 manish 294
 
33071 amit.gupta 295
        Legend legend = new Legend();
296
        legend.setLabels(label);
297
        legend.setPosition("left");
29165 manish 298
 
33071 amit.gupta 299
        List<Data> dataList = new ArrayList<>();
300
        dataList.add(data);
29165 manish 301
 
33071 amit.gupta 302
        DataInvestmentModel datasets = new DataInvestmentModel();
303
        datasets.setDatasets(dataList);
304
        datasets.setLabels(labels);
29165 manish 305
 
33071 amit.gupta 306
        OptionModel om = new OptionModel();
307
        om.setLegend(legend);
308
        cm.setType("pie");
309
        cm.setData(datasets);
310
        cm.setOptions(om);
29165 manish 311
 
33071 amit.gupta 312
        return cm;
313
    }
29165 manish 314
 
33071 amit.gupta 315
    public Map<String, Object> getFilter(int warehouseId, String email, LocalDateTime date, LocalDateTime endDate)
316
            throws ProfitMandiBusinessException {
317
        Map<String, Object> map = new HashMap<>();
318
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
319
        Map<Integer, CustomRetailer> crm = null;
320
        Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
28468 tejbeer 321
 
33071 amit.gupta 322
        Set<Integer> fofoIds = csService1.getAuthFofoIds(email, true);
28468 tejbeer 323
 
33071 amit.gupta 324
        if (warehouseId != 0) {
28468 tejbeer 325
 
33071 amit.gupta 326
            fofoIds = fofoStoreRepository.selectPartnerByfofoIdAndWarehouse(new ArrayList<>(fofoIds), warehouseId)
327
                    .stream().map(x -> x).collect(Collectors.toSet());
28468 tejbeer 328
 
33071 amit.gupta 329
        }
28468 tejbeer 330
 
33071 amit.gupta 331
        if (fofoIds != null) {
28468 tejbeer 332
 
33071 amit.gupta 333
            crm = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null)
334
                    .collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
30426 tejbeer 335
 
33071 amit.gupta 336
        }
28468 tejbeer 337
 
33071 amit.gupta 338
        map.put("date", date);
339
        map.put("endDate", endDate);
340
        map.put("customRetailersMap", crm);
341
        map.put("fofoIds", fofoIds);
342
        map.put("warehouseMap", warehouseMap);
28468 tejbeer 343
 
33071 amit.gupta 344
        return map;
28468 tejbeer 345
 
33071 amit.gupta 346
    }
28468 tejbeer 347
 
33071 amit.gupta 348
    public ChartModel getBrandWiseLms(List<Integer> warehouseIds, List<Integer> fofoIds, LocalDate startDate,
349
                                      LocalDate endDate, String filterType) {
350
        //LOGGER.info("params" + warehouseIds + fofoIds + startDate);
28468 tejbeer 351
 
33071 amit.gupta 352
        List<BrandWiseModel> brandWiseLms = fofoStoreRepository.selectGroupByBrandLms(fofoIds, warehouseIds, startDate,
353
                endDate, filterType);
354
        //LOGGER.info("brandWiseLms" + brandWiseLms);
28468 tejbeer 355
 
33071 amit.gupta 356
        ChartModel cm = null;
28468 tejbeer 357
 
33071 amit.gupta 358
        if (filterType.equals("dateWise")) {
359
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-dd-yyyy");
28468 tejbeer 360
 
33071 amit.gupta 361
            Map<String, Map<LocalDate, Double>> brandDateValue = new HashMap<>();
362
            for (BrandWiseModel bwl : brandWiseLms) {
363
                if (!brandDateValue.containsKey(bwl.getBrand())) {
364
                    brandDateValue.put(bwl.getBrand(), new HashMap<>());
365
                }
366
                Map<LocalDate, Double> dateWiseSalesMap = brandDateValue.get(bwl.getBrand());
367
                dateWiseSalesMap.put(LocalDate.parse(bwl.getYearMonth(), dateTimeFormatter), (double) bwl.getAmount());
368
            }
28468 tejbeer 369
 
33071 amit.gupta 370
            long days = startDate.until(endDate, ChronoUnit.DAYS);
371
            List<LocalDate> allDatesBetween = LongStream.range(0, days).mapToObj(x -> startDate.plusDays(x))
372
                    .collect(Collectors.toList());
373
            //LOGGER.info("All dates between {}", allDatesBetween);
30279 tejbeer 374
 
33071 amit.gupta 375
            Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
30279 tejbeer 376
 
33071 amit.gupta 377
            for (String brand : brands) {
378
                if (!brandDateValue.containsKey(brand)) {
379
                    brandDateValue.put(brand, new HashMap<>());
380
                }
381
                Map<LocalDate, Double> dateWiseBrand = brandDateValue.get(brand);
382
                for (LocalDate date : allDatesBetween) {
383
                    if (dateWiseBrand.get(date) == null) {
384
                        dateWiseBrand.put(date, 0.0);
385
                    }
386
                }
30279 tejbeer 387
 
33071 amit.gupta 388
                Map<LocalDate, Double> sortedMonthBrandValue = new TreeMap<>(dateWiseBrand);
389
                sortedBrandValue.put(brand, new ArrayList<>(sortedMonthBrandValue.values()));
390
                LOGGER.info("Sorted Brandwise values count {}", sortedMonthBrandValue.size());
391
            }
28468 tejbeer 392
 
33071 amit.gupta 393
            LOGGER.info("brandMonthValueCount {}", brandDateValue.size());
28468 tejbeer 394
 
33071 amit.gupta 395
            LOGGER.info("sortedBrandValueCount {}", sortedBrandValue.size());
396
            cm = chartService.createChartWithLabels(
397
                    allDatesBetween.stream().map(x -> x.format((DateTimeFormatter.ofPattern("dd MMM''uu"))))
398
                            .collect(Collectors.toCollection(LinkedHashSet::new)),
399
                    sortedBrandValue, colorList, borderList, "Brand Wise Date Wise Sale");
28468 tejbeer 400
 
33071 amit.gupta 401
        } else {
28468 tejbeer 402
 
33071 amit.gupta 403
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
28468 tejbeer 404
 
33071 amit.gupta 405
            Map<String, Map<YearMonth, Double>> brandMonthValue = new HashMap<>();
406
            for (BrandWiseModel bwl : brandWiseLms) {
407
                Map<YearMonth, Double> yearMonthValue = new HashMap<>();
408
                if (brandMonthValue.containsKey(bwl.getBrand())) {
409
                    yearMonthValue = brandMonthValue.get(bwl.getBrand());
410
                    yearMonthValue.put(YearMonth.parse(bwl.getYearMonth(), dateTimeFormatter),
411
                            (double) bwl.getAmount());
412
                } else {
28468 tejbeer 413
 
33071 amit.gupta 414
                    yearMonthValue.put(YearMonth.parse(bwl.getYearMonth(), dateTimeFormatter),
415
                            (double) bwl.getAmount());
28468 tejbeer 416
 
33071 amit.gupta 417
                }
418
                brandMonthValue.put(bwl.getBrand(), yearMonthValue);
30279 tejbeer 419
 
33071 amit.gupta 420
            }
421
            LocalDateTime curDate = LocalDate.now().atStartOfDay();
28468 tejbeer 422
 
33071 amit.gupta 423
            Period age = Period.between(startDate, endDate);
424
            int months = age.getMonths();
425
            //LOGGER.info("months" + months);
426
            //LOGGER.info("brandWiseLms" + brandWiseLms);
427
            //LOGGER.info("brandMonthValue" + brandMonthValue);
28468 tejbeer 428
 
33071 amit.gupta 429
            Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
28468 tejbeer 430
 
33071 amit.gupta 431
            for (String brand : brands) {
432
                Map<YearMonth, Double> yearMonthValue = brandMonthValue.get(brand);
433
                for (int i = months; i >= 0; i--) {
28468 tejbeer 434
 
33071 amit.gupta 435
                    LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
30279 tejbeer 436
 
33071 amit.gupta 437
                    if (yearMonthValue != null) {
438
                        if (yearMonthValue.get(YearMonth.from(startMonth)) == null) {
439
                            yearMonthValue.put(YearMonth.from(startMonth), 0.0);
440
                        }
30279 tejbeer 441
 
33071 amit.gupta 442
                    } else {
443
                        yearMonthValue = new HashMap<>();
444
                        yearMonthValue.put(YearMonth.from(startMonth), 0.0);
445
                    }
446
                }
30279 tejbeer 447
 
33071 amit.gupta 448
                Map<YearMonth, Double> sortedMonthBrandValue = new TreeMap<>(yearMonthValue);
30279 tejbeer 449
 
33071 amit.gupta 450
                brandMonthValue.put(brand, sortedMonthBrandValue);
30279 tejbeer 451
 
33071 amit.gupta 452
                sortedBrandValue.put(brand, sortedMonthBrandValue.values().stream().collect(Collectors.toList()));
30279 tejbeer 453
 
33071 amit.gupta 454
            }
30279 tejbeer 455
 
33071 amit.gupta 456
            cm = chartService.createChart(months, sortedBrandValue, colorList, borderList, "Brand Wise Monthly Sale");
457
        }
28468 tejbeer 458
 
33071 amit.gupta 459
        return cm;
460
    }
28468 tejbeer 461
 
33071 amit.gupta 462
    public String adminPanel(int fofoId, String email, Model model) throws Exception {
463
        List<Menu> menus = null;
35629 amit 464
        boolean isAboveL1 = false;
33071 amit.gupta 465
        try {
466
            AuthUser authUser = authRepository.selectByEmailOrMobile(email);
35394 amit 467
            List<Position> positions = positionRepository.selectAllByAuthUserId(authUser.getId());
34779 ranu 468
            LOGGER.info("positionslist - {}", positions);
33071 amit.gupta 469
            Map<Integer, PartnerDetailModel> warehousePartnerDetailMap = null;
28468 tejbeer 470
 
35189 amit 471
            Map<Integer, WarehouseWiseStockModel> warehouseStockMap;
33071 amit.gupta 472
            LinkedHashMap<Integer, WarehouseWiseStockModel> warehouseStockSortedMap = new LinkedHashMap<>();
28468 tejbeer 473
 
33071 amit.gupta 474
            Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
475
            Map<Integer, String> wm = new LinkedHashMap<>();
28468 tejbeer 476
 
33071 amit.gupta 477
            Map<AuthUser, Long> authUserTicketCount = null;
478
            LoanSummary loanSummary = sdCreditService.getLoanSummary();
35316 ranu 479
 
480
            Map<String, StateWiseLoanSummary> stateWiseLoanSummaryMap = sdCreditService.getLoanSummaryStateWise();
33071 amit.gupta 481
            model.addAttribute("loanSummary", loanSummary);
35316 ranu 482
            model.addAttribute("stateWiseLoanSummaryMap", stateWiseLoanSummaryMap);
28468 tejbeer 483
 
32172 jai.hind 484
 
33071 amit.gupta 485
            for (Map.Entry<Integer, String> entry : warehouseMap.entrySet()) {
486
                wm.put(entry.getKey(), entry.getValue());
487
            }
28468 tejbeer 488
 
33071 amit.gupta 489
            wm.put(0, "Total Values");
490
            long stockValue = 0;
491
            long stockQty = 0;
492
            long pendingIndent = 0;
493
            long tertiary = 0;
28468 tejbeer 494
 
35629 amit 495
            isAboveL1 = positions.stream().anyMatch(pos -> pos.getEscalationType() != EscalationType.L1);
34779 ranu 496
            boolean isRBM = positions.stream().anyMatch(pos -> pos.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_RBM);
37286 ranu 497
            // See-all rule:
37287 ranu 498
            //   - RBM  category: L3 and above  (not L1, not L2)
499
            //   - Sales category: L5 and above (not L1, not L2, not L3, not L4)
37286 ranu 500
            // Everyone else stays territory-scoped via csService1.getAuthFofoIds.
501
            boolean isRbmL3OrAbove = positions.stream().anyMatch(pos ->
502
                    pos.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_RBM
503
                            && pos.getEscalationType() != null
36227 ranu 504
                            && pos.getEscalationType() != EscalationType.L1
37286 ranu 505
                            && pos.getEscalationType() != EscalationType.L2);
37287 ranu 506
            boolean isSalesL5OrAbove = positions.stream().anyMatch(pos ->
37286 ranu 507
                    pos.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES
508
                            && pos.getEscalationType() != null
509
                            && pos.getEscalationType() != EscalationType.L1
37278 ranu 510
                            && pos.getEscalationType() != EscalationType.L2
37287 ranu 511
                            && pos.getEscalationType() != EscalationType.L3
512
                            && pos.getEscalationType() != EscalationType.L4);
513
            boolean canSeeAllStores = isRbmL3OrAbove || isSalesL5OrAbove;
36194 vikas 514
            model.addAttribute("isRBM", isRBM);
36195 vikas 515
            model.addAttribute("authEmail", email);
34779 ranu 516
            Set<Integer> fofoIds = new HashSet<>();
37278 ranu 517
            if (canSeeAllStores) {
34779 ranu 518
                fofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId()).collect(Collectors.toSet());
519
            } else {
520
                fofoIds = csService1.getAuthFofoIds(email, true);
521
            }
522
 
523
 
33071 amit.gupta 524
            if (fofoIds != null && fofoIds.size() > 0) {
35189 amit 525
                Map<Integer, List<Integer>> warehouseIdFofoIdMap = getWarehouseIdFofoIdMap(fofoIds);
33071 amit.gupta 526
                List<WarehouseWiseStockModel> warehouseStocks = saholicInventoryCISRepository
527
                        .selectGroupByWarehouse(new ArrayList<>(warehouseIdFofoIdMap.keySet()));
28468 tejbeer 528
 
33071 amit.gupta 529
                warehouseStockMap = warehouseStocks.stream().collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));
28468 tejbeer 530
 
33071 amit.gupta 531
                if (!warehouseStockMap.isEmpty()) {
532
                    for (Entry<Integer, WarehouseWiseStockModel> warehouseStock : warehouseStockMap.entrySet()) {
533
                        stockValue += warehouseStock.getValue().getStockValue();
534
                        stockQty += warehouseStock.getValue().getStockQty();
535
                        pendingIndent += warehouseStock.getValue().getPendingIndent();
536
                        tertiary += warehouseStock.getValue().getTertiary();
537
                    }
538
                    WarehouseWiseStockModel ws = new WarehouseWiseStockModel();
539
                    ws.setStockQty(stockQty);
540
                    ws.setStockValue(stockValue);
541
                    ws.setPendingIndent(pendingIndent);
542
                    ws.setTertiary(tertiary);
543
                    ws.setWarehouseId(0);
544
                    warehouseStockMap.put(0, ws);
28468 tejbeer 545
 
33071 amit.gupta 546
                }
28468 tejbeer 547
 
33071 amit.gupta 548
                warehouseStockMap.entrySet().stream().sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
549
                        .forEachOrdered(x -> warehouseStockSortedMap.put(x.getKey(), x.getValue()));
28468 tejbeer 550
 
33071 amit.gupta 551
                ReporticoCacheTable rctSaholic = reporticoCacheTableRepository.selectByTableName("SaholicInventoryCIS");
552
                model.addAttribute("reporticoDate", rctSaholic);
28468 tejbeer 553
 
33071 amit.gupta 554
                // warehouseStock
555
                warehousePartnerDetailMap = this.getWarehousePartnerDetail(warehouseIdFofoIdMap);
31259 tejbeer 556
 
33071 amit.gupta 557
                ReporticoCacheTable rctPartneStat = reporticoCacheTableRepository.selectByTableName("partnerStat");
28468 tejbeer 558
 
33071 amit.gupta 559
                Set<CustomRetailer> positionRetailers = fofoIds.stream()
33248 ranu 560
                        .map(x -> {
561
                            try {
562
                                return retailerService.getAllFofoRetailers().get(x);
563
                            } catch (ProfitMandiBusinessException e) {
564
                                throw new RuntimeException(e);
565
                            }
566
                        }).filter(x -> x != null)
33071 amit.gupta 567
                        .collect(Collectors.toSet());
568
                model.addAttribute("retailers", gson.toJson(positionRetailers));
569
                model.addAttribute("reporticoProjectMap", ReporticoProject.salesReporticoProjectMap);
570
                model.addAttribute("warehouses", getWarehouses(positionRetailers));
571
                model.addAttribute("rctPartneStat", rctPartneStat);
572
            } else {
573
                List<Position> warehousePositions = positions.stream()
574
                        .filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_WAREHOUSE)
575
                        .collect(Collectors.toList());
576
                if (warehousePositions.size() > 0) {
577
                    Set<CustomRetailer> positionRetailers = new HashSet<>();
578
                    csService.getPositionCustomRetailerMap(warehousePositions).values().forEach(customRetailers -> {
579
                        positionRetailers.addAll(customRetailers);
580
                    });
581
                    model.addAttribute("reporticoProjectMap", ReporticoProject.warehouseReporticoMap);
582
                    model.addAttribute("retailers", gson.toJson(positionRetailers));
583
                    model.addAttribute("warehouses", getWarehouses(positionRetailers));
584
                }
585
                List<Position> categoryPositions = positions.stream()
586
                        .filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_CATEGORY)
587
                        .collect(Collectors.toList());
588
                if (categoryPositions.size() > 0) {
589
                    Set<CustomRetailer> positionRetailers = new HashSet<>();
590
                    csService.getPositionCustomRetailerMap(warehousePositions).values().forEach(customRetailers -> {
591
                        positionRetailers.addAll(customRetailers);
592
                    });
593
                    model.addAttribute("reporticoProjectMap", ReporticoProject.warehouseReporticoMap);
594
                    model.addAttribute("retailers", gson.toJson(positionRetailers));
595
                    model.addAttribute("warehouses", getWarehouses(positionRetailers));
596
                }
597
            }
28468 tejbeer 598
 
33071 amit.gupta 599
            if (positions.size() > 0) {
600
                if (positions.stream()
601
                        .filter(x -> x.getEscalationType().equals(EscalationType.L3)
602
                                || x.getEscalationType().equals(EscalationType.L4)
603
                                || x.getEscalationType().equals(EscalationType.L5))
604
                        .count() > 0) {
605
                    authUserTicketCount = ticketRepository.selectAllAuthUserTicketCount(Optional.of(false));
606
                }
607
            }
28468 tejbeer 608
 
36870 ranu 609
            if (Arrays.asList("amit.gupta@smartdukaan.com", "ranu.rajput@smartdukaan.com", "vikas.jangra@smartdukaan.com", "tanay.gupta@smartdukaan.com", "rudy.kanwar@smartdukaan.com").contains(email)) {
33071 amit.gupta 610
                menus = menuRepository.selectAllBySequence();
611
            } else if (positions.size() > 0) {
612
                if (positions.stream().filter(x -> x.getEscalationType().equals(EscalationType.L5)).count() > 0) {
613
                    menus = menuRepository.selectAllBySequence();
614
                } else {
615
                    List<Integer> menuIds = menuCategoryRepository.selectAllByPositions(positions).stream()
616
                            .map(x -> x.getMenuId()).collect(Collectors.toList());
617
                    if (menuIds.size() > 0) {
618
                        menus = menuRepository.selectAllByIds(menuIds);
619
                    }
620
                }
621
            }
28468 tejbeer 622
 
33071 amit.gupta 623
            model.addAttribute("authId", authUser.getId());
37336 amit 624
            // needed by views that gate a section on the exact logged-in email
625
            // rather than on role, which is all auth.menu can express
626
            model.addAttribute("loginEmail", authUser.getEmailId());
28468 tejbeer 627
 
33071 amit.gupta 628
            model.addAttribute("warehousePartnerDetailMap", warehousePartnerDetailMap);
629
            model.addAttribute("warehouseMap", wm);
630
            model.addAttribute("authUserTicketCount", authUserTicketCount);
631
            model.addAttribute("warehouseStockMap", warehouseStockSortedMap);
632
            LocalDateTime curDate = LocalDate.now().atStartOfDay();
28468 tejbeer 633
 
33071 amit.gupta 634
            model.addAttribute("date", curDate.withDayOfMonth(1).minusMonths(6).toLocalDate());
28468 tejbeer 635
 
33071 amit.gupta 636
        } catch (ProfitMandiBusinessException e) {
637
        }
35629 amit 638
        // Filter out "Manager Ticket" menu item for L1-only users (must be at least L2 in any position)
639
        if (menus != null && !isAboveL1) {
640
            menus = menus.stream()
641
                    .filter(m -> !"manager-ticket".equals(m.getActionClass()))
642
                    .collect(Collectors.toList());
643
        }
33071 amit.gupta 644
        List<Menu> menuList = (menus != null) ? this.prepareMenu(menus) : new ArrayList<>();
33072 amit.gupta 645
        //LOGGER.info("menu" + menuList);
33071 amit.gupta 646
        model.addAttribute("menu", menuList);
37374 ranu 647
        // Feeds the brand-filter dropdown on the "Warehouse Wise Report" widget.
648
        // Filter itself is applied via AJAX to /getWarehouseStockByBrand; loading is unaffected.
649
        model.addAttribute("whrBrandList", saholicInventoryCISRepository.selectAllBrand());
33071 amit.gupta 650
        return "admin";
651
    }
28468 tejbeer 652
 
35549 ranu 653
 
37374 ranu 654
    /**
655
     * Reproduces the Warehouse Wise Report data-fetch used by {@link #adminPanel} but
656
     * with an optional brand filter, so the main dashboard can swap the widget's rows
657
     * without a full page reload. Permission scope (fofoIds) is resolved with the
658
     * same rules as adminPanel so a user only ever sees their own warehouse territory.
659
     *
660
     * @param email  logged-in user's email — used for fofoId scope resolution
661
     * @param brands non-empty → filter to these brands; null/empty → all brands (identical to adminPanel behavior)
662
     */
663
    public LinkedHashMap<Integer, WarehouseWiseStockModel> getWarehouseStockMap(String email, List<String> brands) throws Exception {
664
        LinkedHashMap<Integer, WarehouseWiseStockModel> warehouseStockSortedMap = new LinkedHashMap<>();
665
 
666
        AuthUser authUser = authRepository.selectByEmailOrMobile(email);
667
        List<Position> positions = positionRepository.selectAllByAuthUserId(authUser.getId());
668
 
669
        boolean isRbmL3OrAbove = positions.stream().anyMatch(pos ->
670
                pos.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_RBM
671
                        && pos.getEscalationType() != null
672
                        && pos.getEscalationType() != EscalationType.L1
673
                        && pos.getEscalationType() != EscalationType.L2);
674
        boolean isSalesL5OrAbove = positions.stream().anyMatch(pos ->
675
                pos.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES
676
                        && pos.getEscalationType() != null
677
                        && pos.getEscalationType() != EscalationType.L1
678
                        && pos.getEscalationType() != EscalationType.L2
679
                        && pos.getEscalationType() != EscalationType.L3
680
                        && pos.getEscalationType() != EscalationType.L4);
681
        boolean canSeeAllStores = isRbmL3OrAbove || isSalesL5OrAbove;
682
 
683
        Set<Integer> fofoIds;
684
        if (canSeeAllStores) {
685
            fofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId()).collect(Collectors.toSet());
686
        } else {
687
            fofoIds = csService1.getAuthFofoIds(email, true);
688
        }
689
        if (fofoIds == null || fofoIds.isEmpty()) return warehouseStockSortedMap;
690
 
691
        Map<Integer, List<Integer>> warehouseIdFofoIdMap = getWarehouseIdFofoIdMap(fofoIds);
692
        List<Integer> warehouseIds = new ArrayList<>(warehouseIdFofoIdMap.keySet());
693
 
694
        List<WarehouseWiseStockModel> warehouseStocks;
695
        if (brands == null || brands.isEmpty()) {
696
            warehouseStocks = saholicInventoryCISRepository.selectGroupByWarehouse(warehouseIds);
697
        } else {
698
            warehouseStocks = saholicInventoryCISRepository.selectGroupByWarehouseFilteredByBrands(warehouseIds, brands);
699
        }
700
 
701
        Map<Integer, WarehouseWiseStockModel> warehouseStockMap =
702
                warehouseStocks.stream().collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));
703
 
704
        if (!warehouseStockMap.isEmpty()) {
705
            long stockValue = 0, stockQty = 0, pendingIndent = 0, tertiary = 0;
706
            for (Entry<Integer, WarehouseWiseStockModel> e : warehouseStockMap.entrySet()) {
707
                stockValue += e.getValue().getStockValue();
708
                stockQty += e.getValue().getStockQty();
709
                pendingIndent += e.getValue().getPendingIndent();
710
                tertiary += e.getValue().getTertiary();
711
            }
712
            WarehouseWiseStockModel totals = new WarehouseWiseStockModel();
713
            totals.setStockQty(stockQty);
714
            totals.setStockValue(stockValue);
715
            totals.setPendingIndent(pendingIndent);
716
            totals.setTertiary(tertiary);
717
            totals.setWarehouseId(0);
718
            warehouseStockMap.put(0, totals);
719
        }
720
 
721
        warehouseStockMap.entrySet().stream()
722
                .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
723
                .forEachOrdered(x -> warehouseStockSortedMap.put(x.getKey(), x.getValue()));
724
 
725
        return warehouseStockSortedMap;
726
    }
727
 
35583 ranu 728
    public Map<ProfitMandiConstants.BULLETIN_TYPE_ENUM, List<BulletinOfferModal>> getTodayBulletin(List<Position> positions, LocalDateTime date) throws Exception {
35549 ranu 729
        List<Long> regionIds = positions.stream().map(x -> Long.valueOf(x.getRegionId())).collect(Collectors.toList());
730
 
731
        regionIds.add(5L);
732
 
733
 
734
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("h:mm a");
735
 
35583 ranu 736
        LocalDateTime startDate = date.toLocalDate().minusDays(1).atTime(LocalTime.MAX);
737
        LocalDateTime endDate = date.toLocalDate().plusDays(1).atTime(LocalTime.MAX);
35549 ranu 738
        List<BulletinOfferModal> bulletinOfferModals = new ArrayList<>();
739
 
37097 ranu 740
        // Each sub-fetch is best-effort — one failing shouldn't wipe out the whole
741
        // bulletin response (especially the always-present Thought of the Day).
742
        try {
743
            List<Bulletin> bulletins = bulletinRepository.selectALlTodayBulletinByRegionIds(regionIds, startDate, endDate);
744
            for (Bulletin b : bulletins) {
35549 ranu 745
 
37097 ranu 746
                BulletinOfferModal modal = new BulletinOfferModal();
747
                modal.setOfferId(b.getId());
748
                modal.setDescription(b.getDescription());
749
                modal.setCreatedTime(formatter.format(b.getCreatedAt()));
750
                modal.setCatalogOffer(false);
751
                modal.setCreatedAt(b.getCreatedAt());
752
                modal.setCreatedBy(b.getCreatedBy());
753
                modal.setBulletinType(ProfitMandiConstants.BULLETIN_TYPE_ENUM.BULLETIN);
35549 ranu 754
 
37097 ranu 755
                if (b.getDocumentIds() != null && !b.getDocumentIds().isEmpty()) {
756
                    List<Integer> docIds = Arrays.stream(b.getDocumentIds().split(","))
757
                            .map(String::trim)
758
                            .map(Integer::parseInt)
759
                            .collect(Collectors.toList());
35549 ranu 760
 
37097 ranu 761
                    modal.setDocumentIds(docIds);
762
                }
763
 
764
                bulletinOfferModals.add(modal);
35549 ranu 765
            }
37097 ranu 766
        } catch (Exception e) {
767
            LOGGER.warn("selectALlTodayBulletinByRegionIds failed: {}", e.getMessage());
35549 ranu 768
        }
769
 
37097 ranu 770
        // 0️⃣ Thought of the Day (virtual bulletin) — always added, does not depend
771
        // on any DB/service call.
35585 ranu 772
        BulletinOfferModal thoughtModal = new BulletinOfferModal();
773
        thoughtModal.setOfferId(0L); // dummy
774
        thoughtModal.setDescription(SalesThoughtConstants.getTodayThought());
775
        thoughtModal.setCreatedAt(LocalDateTime.MAX); // IMPORTANT → always first
776
        thoughtModal.setCreatedTime("");
777
        thoughtModal.setCatalogOffer(false);
778
        thoughtModal.setCreatedBy("SYSTEM");
779
        thoughtModal.setBulletinType(ProfitMandiConstants.BULLETIN_TYPE_ENUM.BULLETIN);
35549 ranu 780
 
35585 ranu 781
        bulletinOfferModals.add(thoughtModal);
782
 
783
 
37097 ranu 784
        try {
785
            List<BulletinOfferModal> getTodayCreatedCatalogOffer = todayOfferService.findAllTodayCatalogOfferBulletin(regionIds.stream().map(x -> x.intValue()).collect(Collectors.toList()), startDate, endDate);
786
            bulletinOfferModals.addAll(getTodayCreatedCatalogOffer);
787
        } catch (Exception e) {
788
            LOGGER.warn("findAllTodayCatalogOfferBulletin failed: {}", e.getMessage());
789
        }
35549 ranu 790
 
37097 ranu 791
        try {
792
            List<BulletinOfferModal> getTodaySchemes = todayOfferService.findAllTodaySchemeBulletin(regionIds.stream().map(x -> x.intValue()).collect(Collectors.toList()), startDate, endDate);
793
            bulletinOfferModals.addAll(getTodaySchemes);
794
        } catch (Exception e) {
795
            LOGGER.warn("findAllTodaySchemeBulletin failed: {}", e.getMessage());
796
        }
35549 ranu 797
 
37097 ranu 798
        try {
799
            List<BulletinOfferModal> getTodayCardCashback = todayOfferService.findAllTodayWebOfferBulletin(startDate, endDate);
800
            bulletinOfferModals.addAll(getTodayCardCashback);
801
        } catch (Exception e) {
802
            LOGGER.warn("findAllTodayWebOfferBulletin failed: {}", e.getMessage());
803
        }
35549 ranu 804
 
37097 ranu 805
        try {
806
            List<BulletinOfferModal> getTodayPrebookingList = todayOfferService.getAllTodayCreatedPreBookingList(startDate, endDate);
807
            bulletinOfferModals.addAll(getTodayPrebookingList);
808
        } catch (Exception e) {
809
            LOGGER.warn("getAllTodayCreatedPreBookingList failed: {}", e.getMessage());
810
        }
35549 ranu 811
 
812
        bulletinOfferModals.sort(
813
                Comparator.comparing(BulletinOfferModal::getCreatedAt).reversed()
814
        );
815
 
816
        Map<ProfitMandiConstants.BULLETIN_TYPE_ENUM, List<BulletinOfferModal>> bulletinOffermap =
817
                bulletinOfferModals.stream()
818
                        .collect(Collectors.groupingBy(
819
                                BulletinOfferModal::getBulletinType,
820
                                () -> new EnumMap<>(ProfitMandiConstants.BULLETIN_TYPE_ENUM.class),
821
                                Collectors.toList()
822
                        ));
823
 
35585 ranu 824
        bulletinOfferModals.sort(
825
                Comparator.comparing(BulletinOfferModal::getCreatedAt).reversed()
826
        );
35549 ranu 827
 
35585 ranu 828
 
829
 
35549 ranu 830
        return bulletinOffermap;
831
    }
832
 
35189 amit 833
    private Map<Integer, List<Integer>> getWarehouseIdFofoIdMap(Set<Integer> fofoIds) throws ProfitMandiBusinessException {
834
        Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
835
                .selectActivePartnersByRetailerIds(new ArrayList<>(fofoIds)).stream()
836
                .collect(Collectors.groupingBy(FofoStore::getWarehouseId,
837
                        Collectors.mapping(FofoStore::getId, Collectors.toList())));
838
        // warehouseStock
839
        if (!warehouseIdFofoIdMap.containsKey(7573)) {
840
            warehouseIdFofoIdMap.put(7573, new ArrayList<>());
841
        }
842
        return warehouseIdFofoIdMap;
843
    }
844
 
33071 amit.gupta 845
    private List<Menu> prepareMenu(List<Menu> menus) {
846
        List<Menu> returnMenu = new ArrayList<>();
847
        Map<Menu, List<Menu>> subMenuMap = new HashMap<>();
848
        for (Menu menu : menus) {
849
            if (menu.get_parent() == null) {
850
                if (!subMenuMap.containsKey(menu)) {
851
                    subMenuMap.put(menu, new ArrayList<>());
852
                }
853
            } else {
854
                Menu parentMenu = menu.get_parent();
855
                if (!subMenuMap.containsKey(parentMenu)) {
856
                    subMenuMap.put(parentMenu, new ArrayList<>());
857
                }
858
                subMenuMap.get(parentMenu).add(menu);
859
            }
860
        }
36681 ranu 861
        // Sort submenus alphabetically by display text, then build the top-level list
862
        Comparator<Menu> byDisplayText = Comparator.comparing(
863
                m -> m.getDisplayText() == null ? "" : m.getDisplayText(),
864
                String.CASE_INSENSITIVE_ORDER);
33071 amit.gupta 865
        subMenuMap.entrySet().stream().forEach(entry -> {
36681 ranu 866
            List<Menu> subs = entry.getValue();
867
            subs.sort(byDisplayText);
868
            entry.getKey().setSubMenus(subs);
33071 amit.gupta 869
            returnMenu.add(entry.getKey());
870
        });
36681 ranu 871
        // Sort the top-level menus alphabetically
872
        returnMenu.sort(byDisplayText);
33071 amit.gupta 873
        return returnMenu;
874
    }
28468 tejbeer 875
 
33071 amit.gupta 876
    public Map<Integer, PartnerDetailModel> getWarehousePartnerDetail(Map<Integer, List<Integer>> warehousePartnerMap)
877
            throws Exception {
28468 tejbeer 878
 
33071 amit.gupta 879
        Map<Integer, PartnerDetailModel> warehouseIdAndallValues = new LinkedHashMap<>();
880
        // Map<Integer, List<FofoStore>> warehousePartnerMap =
881
        // fofoStoreRepository.getWarehousePartnerMap();
882
        Map<Integer, PartnerDetailModel> partnerStats = this.getPartnersStatDataFromFile();
883
        List<Integer> allfofoIds = new ArrayList<>();
884
        if (partnerStats != null) {
885
            for (Entry<Integer, List<Integer>> warehouse : warehousePartnerMap.entrySet()) {
886
                List<Integer> fofoIds = warehouse.getValue().stream().collect(Collectors.toList());
887
                allfofoIds.addAll(fofoIds);
888
                List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
889
                        .collect(Collectors.toList());
890
                if (partnerDetails != null && !partnerDetails.isEmpty()) {
891
                    PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
892
                    warehouseIdAndallValues.put(warehouse.getKey(), partnerDetailModel);
893
                }
28468 tejbeer 894
 
33071 amit.gupta 895
            }
896
            List<PartnerDetailModel> allPartnerDetails = allfofoIds.stream().map(x -> partnerStats.get(x))
897
                    .collect(Collectors.toList());
33072 amit.gupta 898
            //LOGGER.info("allPartnerDetails" + allPartnerDetails);
33071 amit.gupta 899
            PartnerDetailModel partnerDetailModel = partnerStatsService
900
                    .getAggregateStats(new ArrayList<>(allPartnerDetails));
901
            warehouseIdAndallValues.put(0, partnerDetailModel);
902
        }
903
        return warehouseIdAndallValues;
904
    }
28468 tejbeer 905
 
33071 amit.gupta 906
    public Map<Integer, PartnerDetailModel> getPartnersStatDataFromFile() throws Exception {
907
        ObjectInputStream objectinputstream = null;
908
        Map<Integer, PartnerDetailModel> partnerStat = null;
909
        try {
34665 ranu 910
//            FileInputStream streamIn = new FileInputStream("/tmp/partnerStat.tmp");
911
            FileInputStream streamIn = new FileInputStream("/var/www/partner_stats/partnerStat.tmp");
33071 amit.gupta 912
            objectinputstream = new ObjectInputStream(streamIn);
913
            partnerStat = (Map<Integer, PartnerDetailModel>) objectinputstream.readObject();
28468 tejbeer 914
 
33071 amit.gupta 915
            objectinputstream.close();
28468 tejbeer 916
 
33071 amit.gupta 917
        } catch (Exception e) {
918
            LOGGER.info("exceptionddd" + e);
28468 tejbeer 919
 
33071 amit.gupta 920
            e.printStackTrace();
28468 tejbeer 921
 
33071 amit.gupta 922
        } finally {
923
            if (objectinputstream != null) {
924
                objectinputstream.close();
925
            }
926
        }
927
        return partnerStat;
28468 tejbeer 928
 
33071 amit.gupta 929
    }
28468 tejbeer 930
 
33071 amit.gupta 931
    private String getWarehouses(Set<CustomRetailer> positionRetailers) {
932
        Map<Integer, String> warehouses = new HashMap<>();
933
        positionRetailers.stream().forEach(x -> {
934
            if (x.getWarehouseId() != 0) {
935
                warehouses.put(x.getWarehouseId(), ProfitMandiConstants.WAREHOUSE_MAP.get(x.getWarehouseId()));
936
            }
937
        });
938
        return gson.toJson(warehouses);
28468 tejbeer 939
 
33071 amit.gupta 940
    }
28468 tejbeer 941
 
942
 
943
}