Subversion Repositories SmartDukaan

Rev

Rev 35481 | Rev 35483 | 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;
9
import com.spice.profitmandi.dao.entity.cs.Position;
10
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
29165 manish 11
import com.spice.profitmandi.dao.entity.fofo.PartnerType;
28468 tejbeer 12
import com.spice.profitmandi.dao.entity.inventory.ReporticoCacheTable;
32172 jai.hind 13
import com.spice.profitmandi.dao.entity.transaction.LoanSummary;
35316 ranu 14
import com.spice.profitmandi.dao.entity.transaction.StateWiseLoanSummary;
28468 tejbeer 15
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
16
import com.spice.profitmandi.dao.model.BrandWiseModel;
17
import com.spice.profitmandi.dao.model.PartnerDetailModel;
18
import com.spice.profitmandi.dao.model.WarehouseWiseStockModel;
19
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
20
import com.spice.profitmandi.dao.repository.auth.MenuCategoryRepository;
21
import com.spice.profitmandi.dao.repository.auth.MenuRepository;
22
import com.spice.profitmandi.dao.repository.cs.CsService;
31662 amit.gupta 23
import com.spice.profitmandi.dao.repository.cs.CsService1;
28468 tejbeer 24
import com.spice.profitmandi.dao.repository.cs.PositionRepository;
25
import com.spice.profitmandi.dao.repository.cs.TicketRepository;
26
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
28825 tejbeer 27
import com.spice.profitmandi.dao.repository.fofo.ActivatedImeiRepository;
28468 tejbeer 28
import com.spice.profitmandi.dao.repository.inventory.ReporticoCacheTableRepository;
29
import com.spice.profitmandi.dao.repository.inventory.SaholicInventoryCISRepository;
30
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
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;
41
import java.time.LocalDate;
42
import java.time.LocalDateTime;
43
import java.time.Period;
44
import java.time.YearMonth;
45
import java.time.format.DateTimeFormatter;
46
import java.time.temporal.ChronoUnit;
47
import java.util.*;
48
import java.util.Map.Entry;
49
import java.util.stream.Collectors;
50
import java.util.stream.LongStream;
51
 
28468 tejbeer 52
@Component
53
public class AdminUser {
33071 amit.gupta 54
    @Autowired
55
    private Gson gson;
28468 tejbeer 56
 
33071 amit.gupta 57
    @Autowired
58
    private OrderRepository orderRepository;
28468 tejbeer 59
 
33071 amit.gupta 60
    @Autowired
61
    TicketRepository ticketRepository;
28468 tejbeer 62
 
33071 amit.gupta 63
    @Autowired
64
    private ChartService chartService;
28468 tejbeer 65
 
33071 amit.gupta 66
    @Autowired
67
    RetailerService retailerService;
28468 tejbeer 68
 
33071 amit.gupta 69
    @Autowired
70
    AuthRepository authRepository;
28468 tejbeer 71
 
33071 amit.gupta 72
    @Autowired
73
    FofoStoreRepository fofoStoreRepository;
28468 tejbeer 74
 
33071 amit.gupta 75
    @Autowired
76
    CsService1 csService1;
31662 amit.gupta 77
 
33071 amit.gupta 78
    @Autowired
79
    CsService csService;
28468 tejbeer 80
 
33071 amit.gupta 81
    @Autowired
82
    private MenuRepository menuRepository;
28468 tejbeer 83
 
33071 amit.gupta 84
    @Autowired
85
    private PositionRepository positionRepository;
28468 tejbeer 86
 
33071 amit.gupta 87
    @Autowired
88
    private MenuCategoryRepository menuCategoryRepository;
28468 tejbeer 89
 
33071 amit.gupta 90
    @Autowired
91
    private SaholicInventoryCISRepository saholicInventoryCISRepository;
28468 tejbeer 92
 
33071 amit.gupta 93
    @Autowired
94
    private ReporticoCacheTableRepository reporticoCacheTableRepository;
28468 tejbeer 95
 
33071 amit.gupta 96
    @Autowired
97
    private ActivatedImeiRepository activatedImeiRepository;
28825 tejbeer 98
 
33071 amit.gupta 99
    @Autowired
100
    private PartnerStatsService partnerStatsService;
101
    @Autowired
102
    private SDCreditService sdCreditService;
28468 tejbeer 103
 
33071 amit.gupta 104
    List<String> colorList = Arrays.asList("mediumseagreen", "dodgerblue", "darkblue", "gold", "#eb0029", "coral",
105
            "#63C5DA", "red", "deeppink", "midnightblue", "cornsilk");
28468 tejbeer 106
 
33071 amit.gupta 107
    List<String> borderList = Arrays.asList("lawngreen", "lightblue", "#0000cd", "#f7e98e", "#eb0029", "lightcoral",
108
            "#0000cd", "lightsalmon", "pink", "#0000cd", "cornsilk");
28468 tejbeer 109
 
33071 amit.gupta 110
    List<String> brands = Arrays.asList("Oppo", "Vivo", "Samsung", "Realme", "OnePlus", "Xiaomi", "Tecno", "Itel",
111
            "Lava", "Nokia");
28468 tejbeer 112
 
33071 amit.gupta 113
    private static final Logger LOGGER = LogManager.getLogger(AdminUser.class);
28468 tejbeer 114
 
33071 amit.gupta 115
    public ChartModel getBrandWiseLmp(List<Integer> warehouseIds, List<Integer> fofoIds, LocalDate startDate,
116
                                      LocalDate endDate, String filterType) {
33072 amit.gupta 117
        //LOGGER.info("params" + warehouseIds + fofoIds + startDate);
28468 tejbeer 118
 
33071 amit.gupta 119
        List<BrandWiseModel> brandWiseLms = orderRepository.selectGroupByBrandLmp(fofoIds, warehouseIds, startDate,
120
                endDate, filterType);
121
        LOGGER.info("brandWiseLms" + brandWiseLms);
122
        ChartModel cm = null;
28468 tejbeer 123
 
33071 amit.gupta 124
        if (filterType.equals("dateWise")) {
125
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-dd-yyyy");
28468 tejbeer 126
 
33071 amit.gupta 127
            Map<String, Map<LocalDate, Double>> brandDateValue = new HashMap<>();
128
            for (BrandWiseModel bwl : brandWiseLms) {
129
                if (!brandDateValue.containsKey(bwl.getBrand())) {
130
                    brandDateValue.put(bwl.getBrand(), new HashMap<>());
131
                }
132
                Map<LocalDate, Double> dateWiseSalesMap = brandDateValue.get(bwl.getBrand());
133
                dateWiseSalesMap.put(LocalDate.parse(bwl.getYearMonth(), dateTimeFormatter), (double) bwl.getAmount());
134
            }
28468 tejbeer 135
 
33071 amit.gupta 136
            long days = startDate.until(endDate, ChronoUnit.DAYS);
137
            List<LocalDate> allDatesBetween = LongStream.range(0, days).mapToObj(x -> startDate.plusDays(x))
138
                    .collect(Collectors.toList());
139
            LOGGER.info("All dates between {}", allDatesBetween);
28468 tejbeer 140
 
33071 amit.gupta 141
            Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
28468 tejbeer 142
 
33071 amit.gupta 143
            for (String brand : brands) {
144
                if (!brandDateValue.containsKey(brand)) {
145
                    brandDateValue.put(brand, new HashMap<>());
146
                }
147
                Map<LocalDate, Double> dateWiseBrand = brandDateValue.get(brand);
148
                for (LocalDate date : allDatesBetween) {
149
                    if (dateWiseBrand.get(date) == null) {
150
                        dateWiseBrand.put(date, 0.0);
151
                    }
152
                }
30279 tejbeer 153
 
33071 amit.gupta 154
                Map<LocalDate, Double> sortedMonthBrandValue = new TreeMap<>(dateWiseBrand);
155
                sortedBrandValue.put(brand, new ArrayList<>(sortedMonthBrandValue.values()));
156
                LOGGER.info("Sorted Brandwise values count {}", sortedMonthBrandValue.size());
157
            }
30279 tejbeer 158
 
33071 amit.gupta 159
            LOGGER.info("brandMonthValueCount {}", brandDateValue.size());
30279 tejbeer 160
 
33071 amit.gupta 161
            LOGGER.info("sortedBrandValueCount {}", sortedBrandValue.size());
162
            cm = chartService.createChartWithLabels(
163
                    allDatesBetween.stream().map(x -> x.format((DateTimeFormatter.ofPattern("dd MMM''uu"))))
164
                            .collect(Collectors.toCollection(LinkedHashSet::new)),
165
                    sortedBrandValue, colorList, borderList, "Brand Wise Date Wise Purchase");
30279 tejbeer 166
 
33071 amit.gupta 167
        } else {
30279 tejbeer 168
 
33071 amit.gupta 169
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
30279 tejbeer 170
 
33071 amit.gupta 171
            Map<String, Map<YearMonth, Double>> brandMonthValue = new HashMap<>();
172
            for (BrandWiseModel bwl : brandWiseLms) {
173
                Map<YearMonth, Double> yearMonthValue = new HashMap<>();
174
                if (brandMonthValue.containsKey(bwl.getBrand())) {
175
                    yearMonthValue = brandMonthValue.get(bwl.getBrand());
176
                    yearMonthValue.put(YearMonth.parse(bwl.getYearMonth(), dateTimeFormatter),
177
                            (double) bwl.getAmount());
178
                } else {
30279 tejbeer 179
 
33071 amit.gupta 180
                    yearMonthValue.put(YearMonth.parse(bwl.getYearMonth(), dateTimeFormatter),
181
                            (double) bwl.getAmount());
30279 tejbeer 182
 
33071 amit.gupta 183
                }
184
                brandMonthValue.put(bwl.getBrand(), yearMonthValue);
30279 tejbeer 185
 
33071 amit.gupta 186
            }
187
            LocalDateTime curDate = LocalDate.now().atStartOfDay();
28468 tejbeer 188
 
33071 amit.gupta 189
            Period age = Period.between(startDate, endDate);
190
            int months = age.getMonths();
191
            LOGGER.info("months" + months);
192
            LOGGER.info("brandWiseLms" + brandWiseLms);
193
            LOGGER.info("brandMonthValue" + brandMonthValue);
28468 tejbeer 194
 
33071 amit.gupta 195
            Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
28468 tejbeer 196
 
33071 amit.gupta 197
            for (String brand : brands) {
198
                Map<YearMonth, Double> yearMonthValue = brandMonthValue.get(brand);
199
                for (int i = months; i >= 0; i--) {
28468 tejbeer 200
 
33071 amit.gupta 201
                    LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
28468 tejbeer 202
 
33071 amit.gupta 203
                    if (yearMonthValue != null) {
204
                        if (yearMonthValue.get(YearMonth.from(startMonth)) == null) {
205
                            yearMonthValue.put(YearMonth.from(startMonth), 0.0);
206
                        }
30279 tejbeer 207
 
33071 amit.gupta 208
                    } else {
209
                        yearMonthValue = new HashMap<>();
210
                        yearMonthValue.put(YearMonth.from(startMonth), 0.0);
211
                    }
212
                }
30279 tejbeer 213
 
33071 amit.gupta 214
                Map<YearMonth, Double> sortedMonthBrandValue = new TreeMap<>(yearMonthValue);
30279 tejbeer 215
 
33071 amit.gupta 216
                brandMonthValue.put(brand, sortedMonthBrandValue);
30279 tejbeer 217
 
33071 amit.gupta 218
                sortedBrandValue.put(brand, sortedMonthBrandValue.values().stream().collect(Collectors.toList()));
30279 tejbeer 219
 
33071 amit.gupta 220
            }
30279 tejbeer 221
 
33071 amit.gupta 222
            cm = chartService.createChart(months, sortedBrandValue, colorList, borderList,
223
                    "Brand Wise Monthly Purchase");
30279 tejbeer 224
 
33071 amit.gupta 225
        }
30279 tejbeer 226
 
33071 amit.gupta 227
        return cm;
228
    }
28468 tejbeer 229
 
33071 amit.gupta 230
    public ChartInvestmentModel getAllStatePartnerType(Map<Integer, PartnerDetailModel> fofoIdAndallValues)
231
            throws ProfitMandiBusinessException {
29165 manish 232
 
33071 amit.gupta 233
        Map<String, Float> partnerTypeCount = new HashMap<>();
29165 manish 234
 
33071 amit.gupta 235
        List<PartnerType> partnerTypes = Arrays.asList(PartnerType.values());
29165 manish 236
 
33071 amit.gupta 237
        for (PartnerType partnerType : partnerTypes) {
29165 manish 238
 
33071 amit.gupta 239
            float count = fofoIdAndallValues.entrySet().stream()
35482 amit 240
                    .filter(x -> x.getValue() != null)
241
                    .filter(x -> {
242
                        PartnerType pt = x.getValue().getPartnerType();
243
                        if (pt == null) {
244
                            pt = PartnerType.NEW; // Default to Rising Star
245
                        }
246
                        return pt.equals(partnerType);
247
                    }).count();
29165 manish 248
 
33071 amit.gupta 249
            partnerTypeCount.put(partnerType.toString(), count);
29165 manish 250
 
33071 amit.gupta 251
        }
29165 manish 252
 
33071 amit.gupta 253
        ChartInvestmentModel cm = new ChartInvestmentModel();
29165 manish 254
 
33071 amit.gupta 255
        HashSet<String> labels = new HashSet<String>();
256
        labels.addAll(partnerTypes.stream().skip(1).map(x -> x.toString()).collect(Collectors.toList()));
257
        List<String> labelList = new ArrayList<>(labels);
29165 manish 258
 
33071 amit.gupta 259
        List<String> backgroundColor = new ArrayList<>();
29165 manish 260
 
33071 amit.gupta 261
        List<Float> values = new ArrayList<>();
29165 manish 262
 
33071 amit.gupta 263
        for (String label : labelList) {
264
            values.add(partnerTypeCount.get(label));
265
            if (label.equals("BRONZE")) {
266
                backgroundColor.add("#CD7F32");
267
            }
268
            if (label.equals("SILVER")) {
269
                backgroundColor.add("silver");
270
            }
271
            if (label.equals("GOLD")) {
272
                backgroundColor.add("#FFD700");
273
            }
274
            if (label.equals("DIAMOND")) {
275
                backgroundColor.add("#B9F2FF");
276
            }
29165 manish 277
 
33071 amit.gupta 278
            if (label.equals("PLATINUM")) {
279
                backgroundColor.add("#800080");
280
            }
281
            if (label.equals("NEW")) {
282
                backgroundColor.add("green");
283
            }
29165 manish 284
 
33071 amit.gupta 285
        }
29165 manish 286
 
33071 amit.gupta 287
        LOGGER.info("valuesPartnerType" + values);
288
        LOGGER.info("partnerTypeCount" + partnerTypeCount);
29165 manish 289
 
33071 amit.gupta 290
        Data data = new Data();
291
        data.setData(values);
292
        data.setBackgroundColor(backgroundColor);
293
        data.setLabel("DataSet 1");
29165 manish 294
 
33071 amit.gupta 295
        PieLables label = new PieLables();
296
        label.setFontColor("black");
297
        label.setFontSize(22);
29165 manish 298
 
33071 amit.gupta 299
        Legend legend = new Legend();
300
        legend.setLabels(label);
301
        legend.setPosition("left");
29165 manish 302
 
33071 amit.gupta 303
        List<Data> dataList = new ArrayList<>();
304
        dataList.add(data);
29165 manish 305
 
33071 amit.gupta 306
        DataInvestmentModel datasets = new DataInvestmentModel();
307
        datasets.setDatasets(dataList);
308
        datasets.setLabels(labels);
29165 manish 309
 
33071 amit.gupta 310
        OptionModel om = new OptionModel();
311
        om.setLegend(legend);
312
        cm.setType("pie");
313
        cm.setData(datasets);
314
        cm.setOptions(om);
29165 manish 315
 
33071 amit.gupta 316
        return cm;
317
    }
29165 manish 318
 
33071 amit.gupta 319
    public Map<String, Object> getFilter(int warehouseId, String email, LocalDateTime date, LocalDateTime endDate)
320
            throws ProfitMandiBusinessException {
321
        Map<String, Object> map = new HashMap<>();
322
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
323
        Map<Integer, CustomRetailer> crm = null;
324
        Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
28468 tejbeer 325
 
33071 amit.gupta 326
        Set<Integer> fofoIds = csService1.getAuthFofoIds(email, true);
28468 tejbeer 327
 
33071 amit.gupta 328
        if (warehouseId != 0) {
28468 tejbeer 329
 
33071 amit.gupta 330
            fofoIds = fofoStoreRepository.selectPartnerByfofoIdAndWarehouse(new ArrayList<>(fofoIds), warehouseId)
331
                    .stream().map(x -> x).collect(Collectors.toSet());
28468 tejbeer 332
 
33071 amit.gupta 333
        }
28468 tejbeer 334
 
33071 amit.gupta 335
        if (fofoIds != null) {
28468 tejbeer 336
 
33071 amit.gupta 337
            crm = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null)
338
                    .collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
30426 tejbeer 339
 
33071 amit.gupta 340
        }
28468 tejbeer 341
 
33071 amit.gupta 342
        map.put("date", date);
343
        map.put("endDate", endDate);
344
        map.put("customRetailersMap", crm);
345
        map.put("fofoIds", fofoIds);
346
        map.put("warehouseMap", warehouseMap);
28468 tejbeer 347
 
33071 amit.gupta 348
        return map;
28468 tejbeer 349
 
33071 amit.gupta 350
    }
28468 tejbeer 351
 
33071 amit.gupta 352
    public ChartModel getBrandWiseLms(List<Integer> warehouseIds, List<Integer> fofoIds, LocalDate startDate,
353
                                      LocalDate endDate, String filterType) {
354
        //LOGGER.info("params" + warehouseIds + fofoIds + startDate);
28468 tejbeer 355
 
33071 amit.gupta 356
        List<BrandWiseModel> brandWiseLms = fofoStoreRepository.selectGroupByBrandLms(fofoIds, warehouseIds, startDate,
357
                endDate, filterType);
358
        //LOGGER.info("brandWiseLms" + brandWiseLms);
28468 tejbeer 359
 
33071 amit.gupta 360
        ChartModel cm = null;
28468 tejbeer 361
 
33071 amit.gupta 362
        if (filterType.equals("dateWise")) {
363
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-dd-yyyy");
28468 tejbeer 364
 
33071 amit.gupta 365
            Map<String, Map<LocalDate, Double>> brandDateValue = new HashMap<>();
366
            for (BrandWiseModel bwl : brandWiseLms) {
367
                if (!brandDateValue.containsKey(bwl.getBrand())) {
368
                    brandDateValue.put(bwl.getBrand(), new HashMap<>());
369
                }
370
                Map<LocalDate, Double> dateWiseSalesMap = brandDateValue.get(bwl.getBrand());
371
                dateWiseSalesMap.put(LocalDate.parse(bwl.getYearMonth(), dateTimeFormatter), (double) bwl.getAmount());
372
            }
28468 tejbeer 373
 
33071 amit.gupta 374
            long days = startDate.until(endDate, ChronoUnit.DAYS);
375
            List<LocalDate> allDatesBetween = LongStream.range(0, days).mapToObj(x -> startDate.plusDays(x))
376
                    .collect(Collectors.toList());
377
            //LOGGER.info("All dates between {}", allDatesBetween);
30279 tejbeer 378
 
33071 amit.gupta 379
            Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
30279 tejbeer 380
 
33071 amit.gupta 381
            for (String brand : brands) {
382
                if (!brandDateValue.containsKey(brand)) {
383
                    brandDateValue.put(brand, new HashMap<>());
384
                }
385
                Map<LocalDate, Double> dateWiseBrand = brandDateValue.get(brand);
386
                for (LocalDate date : allDatesBetween) {
387
                    if (dateWiseBrand.get(date) == null) {
388
                        dateWiseBrand.put(date, 0.0);
389
                    }
390
                }
30279 tejbeer 391
 
33071 amit.gupta 392
                Map<LocalDate, Double> sortedMonthBrandValue = new TreeMap<>(dateWiseBrand);
393
                sortedBrandValue.put(brand, new ArrayList<>(sortedMonthBrandValue.values()));
394
                LOGGER.info("Sorted Brandwise values count {}", sortedMonthBrandValue.size());
395
            }
28468 tejbeer 396
 
33071 amit.gupta 397
            LOGGER.info("brandMonthValueCount {}", brandDateValue.size());
28468 tejbeer 398
 
33071 amit.gupta 399
            LOGGER.info("sortedBrandValueCount {}", sortedBrandValue.size());
400
            cm = chartService.createChartWithLabels(
401
                    allDatesBetween.stream().map(x -> x.format((DateTimeFormatter.ofPattern("dd MMM''uu"))))
402
                            .collect(Collectors.toCollection(LinkedHashSet::new)),
403
                    sortedBrandValue, colorList, borderList, "Brand Wise Date Wise Sale");
28468 tejbeer 404
 
33071 amit.gupta 405
        } else {
28468 tejbeer 406
 
33071 amit.gupta 407
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
28468 tejbeer 408
 
33071 amit.gupta 409
            Map<String, Map<YearMonth, Double>> brandMonthValue = new HashMap<>();
410
            for (BrandWiseModel bwl : brandWiseLms) {
411
                Map<YearMonth, Double> yearMonthValue = new HashMap<>();
412
                if (brandMonthValue.containsKey(bwl.getBrand())) {
413
                    yearMonthValue = brandMonthValue.get(bwl.getBrand());
414
                    yearMonthValue.put(YearMonth.parse(bwl.getYearMonth(), dateTimeFormatter),
415
                            (double) bwl.getAmount());
416
                } else {
28468 tejbeer 417
 
33071 amit.gupta 418
                    yearMonthValue.put(YearMonth.parse(bwl.getYearMonth(), dateTimeFormatter),
419
                            (double) bwl.getAmount());
28468 tejbeer 420
 
33071 amit.gupta 421
                }
422
                brandMonthValue.put(bwl.getBrand(), yearMonthValue);
30279 tejbeer 423
 
33071 amit.gupta 424
            }
425
            LocalDateTime curDate = LocalDate.now().atStartOfDay();
28468 tejbeer 426
 
33071 amit.gupta 427
            Period age = Period.between(startDate, endDate);
428
            int months = age.getMonths();
429
            //LOGGER.info("months" + months);
430
            //LOGGER.info("brandWiseLms" + brandWiseLms);
431
            //LOGGER.info("brandMonthValue" + brandMonthValue);
28468 tejbeer 432
 
33071 amit.gupta 433
            Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
28468 tejbeer 434
 
33071 amit.gupta 435
            for (String brand : brands) {
436
                Map<YearMonth, Double> yearMonthValue = brandMonthValue.get(brand);
437
                for (int i = months; i >= 0; i--) {
28468 tejbeer 438
 
33071 amit.gupta 439
                    LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
30279 tejbeer 440
 
33071 amit.gupta 441
                    if (yearMonthValue != null) {
442
                        if (yearMonthValue.get(YearMonth.from(startMonth)) == null) {
443
                            yearMonthValue.put(YearMonth.from(startMonth), 0.0);
444
                        }
30279 tejbeer 445
 
33071 amit.gupta 446
                    } else {
447
                        yearMonthValue = new HashMap<>();
448
                        yearMonthValue.put(YearMonth.from(startMonth), 0.0);
449
                    }
450
                }
30279 tejbeer 451
 
33071 amit.gupta 452
                Map<YearMonth, Double> sortedMonthBrandValue = new TreeMap<>(yearMonthValue);
30279 tejbeer 453
 
33071 amit.gupta 454
                brandMonthValue.put(brand, sortedMonthBrandValue);
30279 tejbeer 455
 
33071 amit.gupta 456
                sortedBrandValue.put(brand, sortedMonthBrandValue.values().stream().collect(Collectors.toList()));
30279 tejbeer 457
 
33071 amit.gupta 458
            }
30279 tejbeer 459
 
33071 amit.gupta 460
            cm = chartService.createChart(months, sortedBrandValue, colorList, borderList, "Brand Wise Monthly Sale");
461
        }
28468 tejbeer 462
 
33071 amit.gupta 463
        return cm;
464
    }
28468 tejbeer 465
 
33071 amit.gupta 466
    public String adminPanel(int fofoId, String email, Model model) throws Exception {
467
        List<Menu> menus = null;
468
        try {
469
            AuthUser authUser = authRepository.selectByEmailOrMobile(email);
35394 amit 470
            List<Position> positions = positionRepository.selectAllByAuthUserId(authUser.getId());
34779 ranu 471
            LOGGER.info("positionslist - {}", positions);
33071 amit.gupta 472
            Map<Integer, PartnerDetailModel> warehousePartnerDetailMap = null;
28468 tejbeer 473
 
35189 amit 474
            Map<Integer, WarehouseWiseStockModel> warehouseStockMap;
33071 amit.gupta 475
            LinkedHashMap<Integer, WarehouseWiseStockModel> warehouseStockSortedMap = new LinkedHashMap<>();
28468 tejbeer 476
 
33071 amit.gupta 477
            Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
478
            Map<Integer, String> wm = new LinkedHashMap<>();
28468 tejbeer 479
 
33071 amit.gupta 480
            Map<AuthUser, Long> authUserTicketCount = null;
481
            LoanSummary loanSummary = sdCreditService.getLoanSummary();
35316 ranu 482
 
483
            Map<String, StateWiseLoanSummary> stateWiseLoanSummaryMap = sdCreditService.getLoanSummaryStateWise();
33071 amit.gupta 484
            model.addAttribute("loanSummary", loanSummary);
35316 ranu 485
            model.addAttribute("stateWiseLoanSummaryMap", stateWiseLoanSummaryMap);
28468 tejbeer 486
 
32172 jai.hind 487
 
33071 amit.gupta 488
            for (Map.Entry<Integer, String> entry : warehouseMap.entrySet()) {
489
                wm.put(entry.getKey(), entry.getValue());
490
            }
28468 tejbeer 491
 
33071 amit.gupta 492
            wm.put(0, "Total Values");
493
            long stockValue = 0;
494
            long stockQty = 0;
495
            long pendingIndent = 0;
496
            long tertiary = 0;
28468 tejbeer 497
 
34779 ranu 498
            boolean isAboveL1 = positions.stream().anyMatch(pos -> pos.getEscalationType() != EscalationType.L1);
499
            boolean isRBM = positions.stream().anyMatch(pos -> pos.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_RBM);
28468 tejbeer 500
 
34779 ranu 501
            Set<Integer> fofoIds = new HashSet<>();
502
            if (isAboveL1 && isRBM) {
503
                fofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId()).collect(Collectors.toSet());
504
            } else {
505
                fofoIds = csService1.getAuthFofoIds(email, true);
506
            }
507
 
508
 
33071 amit.gupta 509
            if (fofoIds != null && fofoIds.size() > 0) {
35189 amit 510
                Map<Integer, List<Integer>> warehouseIdFofoIdMap = getWarehouseIdFofoIdMap(fofoIds);
33071 amit.gupta 511
                List<WarehouseWiseStockModel> warehouseStocks = saholicInventoryCISRepository
512
                        .selectGroupByWarehouse(new ArrayList<>(warehouseIdFofoIdMap.keySet()));
28468 tejbeer 513
 
33071 amit.gupta 514
                warehouseStockMap = warehouseStocks.stream().collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));
28468 tejbeer 515
 
33071 amit.gupta 516
                if (!warehouseStockMap.isEmpty()) {
517
                    for (Entry<Integer, WarehouseWiseStockModel> warehouseStock : warehouseStockMap.entrySet()) {
518
                        stockValue += warehouseStock.getValue().getStockValue();
519
                        stockQty += warehouseStock.getValue().getStockQty();
520
                        pendingIndent += warehouseStock.getValue().getPendingIndent();
521
                        tertiary += warehouseStock.getValue().getTertiary();
522
                    }
523
                    WarehouseWiseStockModel ws = new WarehouseWiseStockModel();
524
                    ws.setStockQty(stockQty);
525
                    ws.setStockValue(stockValue);
526
                    ws.setPendingIndent(pendingIndent);
527
                    ws.setTertiary(tertiary);
528
                    ws.setWarehouseId(0);
529
                    warehouseStockMap.put(0, ws);
28468 tejbeer 530
 
33071 amit.gupta 531
                }
28468 tejbeer 532
 
33071 amit.gupta 533
                warehouseStockMap.entrySet().stream().sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
534
                        .forEachOrdered(x -> warehouseStockSortedMap.put(x.getKey(), x.getValue()));
28468 tejbeer 535
 
33071 amit.gupta 536
                ReporticoCacheTable rctSaholic = reporticoCacheTableRepository.selectByTableName("SaholicInventoryCIS");
537
                model.addAttribute("reporticoDate", rctSaholic);
28468 tejbeer 538
 
33071 amit.gupta 539
                // warehouseStock
540
                warehousePartnerDetailMap = this.getWarehousePartnerDetail(warehouseIdFofoIdMap);
31259 tejbeer 541
 
33071 amit.gupta 542
                ReporticoCacheTable rctPartneStat = reporticoCacheTableRepository.selectByTableName("partnerStat");
28468 tejbeer 543
 
33071 amit.gupta 544
                Set<CustomRetailer> positionRetailers = fofoIds.stream()
33248 ranu 545
                        .map(x -> {
546
                            try {
547
                                return retailerService.getAllFofoRetailers().get(x);
548
                            } catch (ProfitMandiBusinessException e) {
549
                                throw new RuntimeException(e);
550
                            }
551
                        }).filter(x -> x != null)
33071 amit.gupta 552
                        .collect(Collectors.toSet());
553
                model.addAttribute("retailers", gson.toJson(positionRetailers));
554
                model.addAttribute("reporticoProjectMap", ReporticoProject.salesReporticoProjectMap);
555
                model.addAttribute("warehouses", getWarehouses(positionRetailers));
556
                model.addAttribute("rctPartneStat", rctPartneStat);
557
            } else {
558
                List<Position> warehousePositions = positions.stream()
559
                        .filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_WAREHOUSE)
560
                        .collect(Collectors.toList());
561
                if (warehousePositions.size() > 0) {
562
                    Set<CustomRetailer> positionRetailers = new HashSet<>();
563
                    csService.getPositionCustomRetailerMap(warehousePositions).values().forEach(customRetailers -> {
564
                        positionRetailers.addAll(customRetailers);
565
                    });
566
                    model.addAttribute("reporticoProjectMap", ReporticoProject.warehouseReporticoMap);
567
                    model.addAttribute("retailers", gson.toJson(positionRetailers));
568
                    model.addAttribute("warehouses", getWarehouses(positionRetailers));
569
                }
570
                List<Position> categoryPositions = positions.stream()
571
                        .filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_CATEGORY)
572
                        .collect(Collectors.toList());
573
                if (categoryPositions.size() > 0) {
574
                    Set<CustomRetailer> positionRetailers = new HashSet<>();
575
                    csService.getPositionCustomRetailerMap(warehousePositions).values().forEach(customRetailers -> {
576
                        positionRetailers.addAll(customRetailers);
577
                    });
578
                    model.addAttribute("reporticoProjectMap", ReporticoProject.warehouseReporticoMap);
579
                    model.addAttribute("retailers", gson.toJson(positionRetailers));
580
                    model.addAttribute("warehouses", getWarehouses(positionRetailers));
581
                }
582
            }
28468 tejbeer 583
 
33071 amit.gupta 584
            if (positions.size() > 0) {
585
                if (positions.stream()
586
                        .filter(x -> x.getEscalationType().equals(EscalationType.L3)
587
                                || x.getEscalationType().equals(EscalationType.L4)
588
                                || x.getEscalationType().equals(EscalationType.L5))
589
                        .count() > 0) {
590
                    authUserTicketCount = ticketRepository.selectAllAuthUserTicketCount(Optional.of(false));
591
                }
592
            }
28468 tejbeer 593
 
33071 amit.gupta 594
            if (Arrays.asList("amit.gupta@smartdukaan.com", "ranu.rajput@smartdukaan.com",
35337 aman 595
                    "vikas.jangra@smartdukaan.com","aman.gupta@smartdukaan.com").contains(email)) {
33071 amit.gupta 596
                menus = menuRepository.selectAllBySequence();
597
            } else if (positions.size() > 0) {
598
                if (positions.stream().filter(x -> x.getEscalationType().equals(EscalationType.L5)).count() > 0) {
599
                    menus = menuRepository.selectAllBySequence();
600
                } else {
601
                    List<Integer> menuIds = menuCategoryRepository.selectAllByPositions(positions).stream()
602
                            .map(x -> x.getMenuId()).collect(Collectors.toList());
603
                    if (menuIds.size() > 0) {
604
                        menus = menuRepository.selectAllByIds(menuIds);
605
                    }
606
                }
607
            }
28468 tejbeer 608
 
33071 amit.gupta 609
            model.addAttribute("authId", authUser.getId());
28468 tejbeer 610
 
33071 amit.gupta 611
            model.addAttribute("warehousePartnerDetailMap", warehousePartnerDetailMap);
612
            model.addAttribute("warehouseMap", wm);
613
            model.addAttribute("authUserTicketCount", authUserTicketCount);
614
            model.addAttribute("warehouseStockMap", warehouseStockSortedMap);
615
            LocalDateTime curDate = LocalDate.now().atStartOfDay();
28468 tejbeer 616
 
33071 amit.gupta 617
            model.addAttribute("date", curDate.withDayOfMonth(1).minusMonths(6).toLocalDate());
28468 tejbeer 618
 
33071 amit.gupta 619
        } catch (ProfitMandiBusinessException e) {
620
        }
621
        List<Menu> menuList = (menus != null) ? this.prepareMenu(menus) : new ArrayList<>();
33072 amit.gupta 622
        //LOGGER.info("menu" + menuList);
33071 amit.gupta 623
        model.addAttribute("menu", menuList);
624
        return "admin";
625
    }
28468 tejbeer 626
 
35189 amit 627
    private Map<Integer, List<Integer>> getWarehouseIdFofoIdMap(Set<Integer> fofoIds) throws ProfitMandiBusinessException {
628
        Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
629
                .selectActivePartnersByRetailerIds(new ArrayList<>(fofoIds)).stream()
630
                .collect(Collectors.groupingBy(FofoStore::getWarehouseId,
631
                        Collectors.mapping(FofoStore::getId, Collectors.toList())));
632
        // warehouseStock
633
        if (!warehouseIdFofoIdMap.containsKey(7573)) {
634
            warehouseIdFofoIdMap.put(7573, new ArrayList<>());
635
        }
636
        return warehouseIdFofoIdMap;
637
    }
638
 
33071 amit.gupta 639
    private List<Menu> prepareMenu(List<Menu> menus) {
640
        List<Menu> returnMenu = new ArrayList<>();
641
        Map<Menu, List<Menu>> subMenuMap = new HashMap<>();
642
        for (Menu menu : menus) {
643
            if (menu.get_parent() == null) {
644
                if (!subMenuMap.containsKey(menu)) {
645
                    subMenuMap.put(menu, new ArrayList<>());
646
                }
647
            } else {
648
                Menu parentMenu = menu.get_parent();
649
                if (!subMenuMap.containsKey(parentMenu)) {
650
                    subMenuMap.put(parentMenu, new ArrayList<>());
651
                }
652
                subMenuMap.get(parentMenu).add(menu);
653
            }
654
        }
655
        subMenuMap.entrySet().stream().forEach(entry -> {
656
            entry.getKey().setSubMenus(entry.getValue());
657
            returnMenu.add(entry.getKey());
658
        });
659
        return returnMenu;
660
    }
28468 tejbeer 661
 
33071 amit.gupta 662
    public Map<Integer, PartnerDetailModel> getWarehousePartnerDetail(Map<Integer, List<Integer>> warehousePartnerMap)
663
            throws Exception {
28468 tejbeer 664
 
33071 amit.gupta 665
        Map<Integer, PartnerDetailModel> warehouseIdAndallValues = new LinkedHashMap<>();
666
        // Map<Integer, List<FofoStore>> warehousePartnerMap =
667
        // fofoStoreRepository.getWarehousePartnerMap();
668
        Map<Integer, PartnerDetailModel> partnerStats = this.getPartnersStatDataFromFile();
669
        List<Integer> allfofoIds = new ArrayList<>();
670
        if (partnerStats != null) {
671
            for (Entry<Integer, List<Integer>> warehouse : warehousePartnerMap.entrySet()) {
672
                List<Integer> fofoIds = warehouse.getValue().stream().collect(Collectors.toList());
673
                allfofoIds.addAll(fofoIds);
674
                List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
675
                        .collect(Collectors.toList());
676
                if (partnerDetails != null && !partnerDetails.isEmpty()) {
677
                    PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
678
                    warehouseIdAndallValues.put(warehouse.getKey(), partnerDetailModel);
679
                }
28468 tejbeer 680
 
33071 amit.gupta 681
            }
682
            List<PartnerDetailModel> allPartnerDetails = allfofoIds.stream().map(x -> partnerStats.get(x))
683
                    .collect(Collectors.toList());
33072 amit.gupta 684
            //LOGGER.info("allPartnerDetails" + allPartnerDetails);
33071 amit.gupta 685
            PartnerDetailModel partnerDetailModel = partnerStatsService
686
                    .getAggregateStats(new ArrayList<>(allPartnerDetails));
687
            warehouseIdAndallValues.put(0, partnerDetailModel);
688
        }
689
        return warehouseIdAndallValues;
690
    }
28468 tejbeer 691
 
33071 amit.gupta 692
    public Map<Integer, PartnerDetailModel> getPartnersStatDataFromFile() throws Exception {
693
        ObjectInputStream objectinputstream = null;
694
        Map<Integer, PartnerDetailModel> partnerStat = null;
695
        try {
34665 ranu 696
//            FileInputStream streamIn = new FileInputStream("/tmp/partnerStat.tmp");
697
            FileInputStream streamIn = new FileInputStream("/var/www/partner_stats/partnerStat.tmp");
33071 amit.gupta 698
            objectinputstream = new ObjectInputStream(streamIn);
699
            partnerStat = (Map<Integer, PartnerDetailModel>) objectinputstream.readObject();
28468 tejbeer 700
 
33071 amit.gupta 701
            objectinputstream.close();
28468 tejbeer 702
 
33071 amit.gupta 703
        } catch (Exception e) {
704
            LOGGER.info("exceptionddd" + e);
28468 tejbeer 705
 
33071 amit.gupta 706
            e.printStackTrace();
28468 tejbeer 707
 
33071 amit.gupta 708
        } finally {
709
            if (objectinputstream != null) {
710
                objectinputstream.close();
711
            }
712
        }
713
        return partnerStat;
28468 tejbeer 714
 
33071 amit.gupta 715
    }
28468 tejbeer 716
 
33071 amit.gupta 717
    private String getWarehouses(Set<CustomRetailer> positionRetailers) {
718
        Map<Integer, String> warehouses = new HashMap<>();
719
        positionRetailers.stream().forEach(x -> {
720
            if (x.getWarehouseId() != 0) {
721
                warehouses.put(x.getWarehouseId(), ProfitMandiConstants.WAREHOUSE_MAP.get(x.getWarehouseId()));
722
            }
723
        });
724
        return gson.toJson(warehouses);
28468 tejbeer 725
 
33071 amit.gupta 726
    }
28468 tejbeer 727
 
728
 
729
}