Subversion Repositories SmartDukaan

Rev

Rev 35394 | Rev 35482 | 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()
35481 amit 240
                    .filter(x -> x.getValue() != null && x.getValue().getPartnerType() != null && x.getValue().getPartnerType().equals(partnerType)).count();
29165 manish 241
 
33071 amit.gupta 242
            partnerTypeCount.put(partnerType.toString(), count);
29165 manish 243
 
33071 amit.gupta 244
        }
29165 manish 245
 
33071 amit.gupta 246
        ChartInvestmentModel cm = new ChartInvestmentModel();
29165 manish 247
 
33071 amit.gupta 248
        HashSet<String> labels = new HashSet<String>();
249
        labels.addAll(partnerTypes.stream().skip(1).map(x -> x.toString()).collect(Collectors.toList()));
250
        List<String> labelList = new ArrayList<>(labels);
29165 manish 251
 
33071 amit.gupta 252
        List<String> backgroundColor = new ArrayList<>();
29165 manish 253
 
33071 amit.gupta 254
        List<Float> values = new ArrayList<>();
29165 manish 255
 
33071 amit.gupta 256
        for (String label : labelList) {
257
            values.add(partnerTypeCount.get(label));
258
            if (label.equals("BRONZE")) {
259
                backgroundColor.add("#CD7F32");
260
            }
261
            if (label.equals("SILVER")) {
262
                backgroundColor.add("silver");
263
            }
264
            if (label.equals("GOLD")) {
265
                backgroundColor.add("#FFD700");
266
            }
267
            if (label.equals("DIAMOND")) {
268
                backgroundColor.add("#B9F2FF");
269
            }
29165 manish 270
 
33071 amit.gupta 271
            if (label.equals("PLATINUM")) {
272
                backgroundColor.add("#800080");
273
            }
274
            if (label.equals("NEW")) {
275
                backgroundColor.add("green");
276
            }
29165 manish 277
 
33071 amit.gupta 278
        }
29165 manish 279
 
33071 amit.gupta 280
        LOGGER.info("valuesPartnerType" + values);
281
        LOGGER.info("partnerTypeCount" + partnerTypeCount);
29165 manish 282
 
33071 amit.gupta 283
        Data data = new Data();
284
        data.setData(values);
285
        data.setBackgroundColor(backgroundColor);
286
        data.setLabel("DataSet 1");
29165 manish 287
 
33071 amit.gupta 288
        PieLables label = new PieLables();
289
        label.setFontColor("black");
290
        label.setFontSize(22);
29165 manish 291
 
33071 amit.gupta 292
        Legend legend = new Legend();
293
        legend.setLabels(label);
294
        legend.setPosition("left");
29165 manish 295
 
33071 amit.gupta 296
        List<Data> dataList = new ArrayList<>();
297
        dataList.add(data);
29165 manish 298
 
33071 amit.gupta 299
        DataInvestmentModel datasets = new DataInvestmentModel();
300
        datasets.setDatasets(dataList);
301
        datasets.setLabels(labels);
29165 manish 302
 
33071 amit.gupta 303
        OptionModel om = new OptionModel();
304
        om.setLegend(legend);
305
        cm.setType("pie");
306
        cm.setData(datasets);
307
        cm.setOptions(om);
29165 manish 308
 
33071 amit.gupta 309
        return cm;
310
    }
29165 manish 311
 
33071 amit.gupta 312
    public Map<String, Object> getFilter(int warehouseId, String email, LocalDateTime date, LocalDateTime endDate)
313
            throws ProfitMandiBusinessException {
314
        Map<String, Object> map = new HashMap<>();
315
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
316
        Map<Integer, CustomRetailer> crm = null;
317
        Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
28468 tejbeer 318
 
33071 amit.gupta 319
        Set<Integer> fofoIds = csService1.getAuthFofoIds(email, true);
28468 tejbeer 320
 
33071 amit.gupta 321
        if (warehouseId != 0) {
28468 tejbeer 322
 
33071 amit.gupta 323
            fofoIds = fofoStoreRepository.selectPartnerByfofoIdAndWarehouse(new ArrayList<>(fofoIds), warehouseId)
324
                    .stream().map(x -> x).collect(Collectors.toSet());
28468 tejbeer 325
 
33071 amit.gupta 326
        }
28468 tejbeer 327
 
33071 amit.gupta 328
        if (fofoIds != null) {
28468 tejbeer 329
 
33071 amit.gupta 330
            crm = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null)
331
                    .collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
30426 tejbeer 332
 
33071 amit.gupta 333
        }
28468 tejbeer 334
 
33071 amit.gupta 335
        map.put("date", date);
336
        map.put("endDate", endDate);
337
        map.put("customRetailersMap", crm);
338
        map.put("fofoIds", fofoIds);
339
        map.put("warehouseMap", warehouseMap);
28468 tejbeer 340
 
33071 amit.gupta 341
        return map;
28468 tejbeer 342
 
33071 amit.gupta 343
    }
28468 tejbeer 344
 
33071 amit.gupta 345
    public ChartModel getBrandWiseLms(List<Integer> warehouseIds, List<Integer> fofoIds, LocalDate startDate,
346
                                      LocalDate endDate, String filterType) {
347
        //LOGGER.info("params" + warehouseIds + fofoIds + startDate);
28468 tejbeer 348
 
33071 amit.gupta 349
        List<BrandWiseModel> brandWiseLms = fofoStoreRepository.selectGroupByBrandLms(fofoIds, warehouseIds, startDate,
350
                endDate, filterType);
351
        //LOGGER.info("brandWiseLms" + brandWiseLms);
28468 tejbeer 352
 
33071 amit.gupta 353
        ChartModel cm = null;
28468 tejbeer 354
 
33071 amit.gupta 355
        if (filterType.equals("dateWise")) {
356
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-dd-yyyy");
28468 tejbeer 357
 
33071 amit.gupta 358
            Map<String, Map<LocalDate, Double>> brandDateValue = new HashMap<>();
359
            for (BrandWiseModel bwl : brandWiseLms) {
360
                if (!brandDateValue.containsKey(bwl.getBrand())) {
361
                    brandDateValue.put(bwl.getBrand(), new HashMap<>());
362
                }
363
                Map<LocalDate, Double> dateWiseSalesMap = brandDateValue.get(bwl.getBrand());
364
                dateWiseSalesMap.put(LocalDate.parse(bwl.getYearMonth(), dateTimeFormatter), (double) bwl.getAmount());
365
            }
28468 tejbeer 366
 
33071 amit.gupta 367
            long days = startDate.until(endDate, ChronoUnit.DAYS);
368
            List<LocalDate> allDatesBetween = LongStream.range(0, days).mapToObj(x -> startDate.plusDays(x))
369
                    .collect(Collectors.toList());
370
            //LOGGER.info("All dates between {}", allDatesBetween);
30279 tejbeer 371
 
33071 amit.gupta 372
            Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
30279 tejbeer 373
 
33071 amit.gupta 374
            for (String brand : brands) {
375
                if (!brandDateValue.containsKey(brand)) {
376
                    brandDateValue.put(brand, new HashMap<>());
377
                }
378
                Map<LocalDate, Double> dateWiseBrand = brandDateValue.get(brand);
379
                for (LocalDate date : allDatesBetween) {
380
                    if (dateWiseBrand.get(date) == null) {
381
                        dateWiseBrand.put(date, 0.0);
382
                    }
383
                }
30279 tejbeer 384
 
33071 amit.gupta 385
                Map<LocalDate, Double> sortedMonthBrandValue = new TreeMap<>(dateWiseBrand);
386
                sortedBrandValue.put(brand, new ArrayList<>(sortedMonthBrandValue.values()));
387
                LOGGER.info("Sorted Brandwise values count {}", sortedMonthBrandValue.size());
388
            }
28468 tejbeer 389
 
33071 amit.gupta 390
            LOGGER.info("brandMonthValueCount {}", brandDateValue.size());
28468 tejbeer 391
 
33071 amit.gupta 392
            LOGGER.info("sortedBrandValueCount {}", sortedBrandValue.size());
393
            cm = chartService.createChartWithLabels(
394
                    allDatesBetween.stream().map(x -> x.format((DateTimeFormatter.ofPattern("dd MMM''uu"))))
395
                            .collect(Collectors.toCollection(LinkedHashSet::new)),
396
                    sortedBrandValue, colorList, borderList, "Brand Wise Date Wise Sale");
28468 tejbeer 397
 
33071 amit.gupta 398
        } else {
28468 tejbeer 399
 
33071 amit.gupta 400
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
28468 tejbeer 401
 
33071 amit.gupta 402
            Map<String, Map<YearMonth, Double>> brandMonthValue = new HashMap<>();
403
            for (BrandWiseModel bwl : brandWiseLms) {
404
                Map<YearMonth, Double> yearMonthValue = new HashMap<>();
405
                if (brandMonthValue.containsKey(bwl.getBrand())) {
406
                    yearMonthValue = brandMonthValue.get(bwl.getBrand());
407
                    yearMonthValue.put(YearMonth.parse(bwl.getYearMonth(), dateTimeFormatter),
408
                            (double) bwl.getAmount());
409
                } else {
28468 tejbeer 410
 
33071 amit.gupta 411
                    yearMonthValue.put(YearMonth.parse(bwl.getYearMonth(), dateTimeFormatter),
412
                            (double) bwl.getAmount());
28468 tejbeer 413
 
33071 amit.gupta 414
                }
415
                brandMonthValue.put(bwl.getBrand(), yearMonthValue);
30279 tejbeer 416
 
33071 amit.gupta 417
            }
418
            LocalDateTime curDate = LocalDate.now().atStartOfDay();
28468 tejbeer 419
 
33071 amit.gupta 420
            Period age = Period.between(startDate, endDate);
421
            int months = age.getMonths();
422
            //LOGGER.info("months" + months);
423
            //LOGGER.info("brandWiseLms" + brandWiseLms);
424
            //LOGGER.info("brandMonthValue" + brandMonthValue);
28468 tejbeer 425
 
33071 amit.gupta 426
            Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
28468 tejbeer 427
 
33071 amit.gupta 428
            for (String brand : brands) {
429
                Map<YearMonth, Double> yearMonthValue = brandMonthValue.get(brand);
430
                for (int i = months; i >= 0; i--) {
28468 tejbeer 431
 
33071 amit.gupta 432
                    LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
30279 tejbeer 433
 
33071 amit.gupta 434
                    if (yearMonthValue != null) {
435
                        if (yearMonthValue.get(YearMonth.from(startMonth)) == null) {
436
                            yearMonthValue.put(YearMonth.from(startMonth), 0.0);
437
                        }
30279 tejbeer 438
 
33071 amit.gupta 439
                    } else {
440
                        yearMonthValue = new HashMap<>();
441
                        yearMonthValue.put(YearMonth.from(startMonth), 0.0);
442
                    }
443
                }
30279 tejbeer 444
 
33071 amit.gupta 445
                Map<YearMonth, Double> sortedMonthBrandValue = new TreeMap<>(yearMonthValue);
30279 tejbeer 446
 
33071 amit.gupta 447
                brandMonthValue.put(brand, sortedMonthBrandValue);
30279 tejbeer 448
 
33071 amit.gupta 449
                sortedBrandValue.put(brand, sortedMonthBrandValue.values().stream().collect(Collectors.toList()));
30279 tejbeer 450
 
33071 amit.gupta 451
            }
30279 tejbeer 452
 
33071 amit.gupta 453
            cm = chartService.createChart(months, sortedBrandValue, colorList, borderList, "Brand Wise Monthly Sale");
454
        }
28468 tejbeer 455
 
33071 amit.gupta 456
        return cm;
457
    }
28468 tejbeer 458
 
33071 amit.gupta 459
    public String adminPanel(int fofoId, String email, Model model) throws Exception {
460
        List<Menu> menus = null;
461
        try {
462
            AuthUser authUser = authRepository.selectByEmailOrMobile(email);
35394 amit 463
            List<Position> positions = positionRepository.selectAllByAuthUserId(authUser.getId());
34779 ranu 464
            LOGGER.info("positionslist - {}", positions);
33071 amit.gupta 465
            Map<Integer, PartnerDetailModel> warehousePartnerDetailMap = null;
28468 tejbeer 466
 
35189 amit 467
            Map<Integer, WarehouseWiseStockModel> warehouseStockMap;
33071 amit.gupta 468
            LinkedHashMap<Integer, WarehouseWiseStockModel> warehouseStockSortedMap = new LinkedHashMap<>();
28468 tejbeer 469
 
33071 amit.gupta 470
            Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
471
            Map<Integer, String> wm = new LinkedHashMap<>();
28468 tejbeer 472
 
33071 amit.gupta 473
            Map<AuthUser, Long> authUserTicketCount = null;
474
            LoanSummary loanSummary = sdCreditService.getLoanSummary();
35316 ranu 475
 
476
            Map<String, StateWiseLoanSummary> stateWiseLoanSummaryMap = sdCreditService.getLoanSummaryStateWise();
33071 amit.gupta 477
            model.addAttribute("loanSummary", loanSummary);
35316 ranu 478
            model.addAttribute("stateWiseLoanSummaryMap", stateWiseLoanSummaryMap);
28468 tejbeer 479
 
32172 jai.hind 480
 
33071 amit.gupta 481
            for (Map.Entry<Integer, String> entry : warehouseMap.entrySet()) {
482
                wm.put(entry.getKey(), entry.getValue());
483
            }
28468 tejbeer 484
 
33071 amit.gupta 485
            wm.put(0, "Total Values");
486
            long stockValue = 0;
487
            long stockQty = 0;
488
            long pendingIndent = 0;
489
            long tertiary = 0;
28468 tejbeer 490
 
34779 ranu 491
            boolean isAboveL1 = positions.stream().anyMatch(pos -> pos.getEscalationType() != EscalationType.L1);
492
            boolean isRBM = positions.stream().anyMatch(pos -> pos.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_RBM);
28468 tejbeer 493
 
34779 ranu 494
            Set<Integer> fofoIds = new HashSet<>();
495
            if (isAboveL1 && isRBM) {
496
                fofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId()).collect(Collectors.toSet());
497
            } else {
498
                fofoIds = csService1.getAuthFofoIds(email, true);
499
            }
500
 
501
 
33071 amit.gupta 502
            if (fofoIds != null && fofoIds.size() > 0) {
35189 amit 503
                Map<Integer, List<Integer>> warehouseIdFofoIdMap = getWarehouseIdFofoIdMap(fofoIds);
33071 amit.gupta 504
                List<WarehouseWiseStockModel> warehouseStocks = saholicInventoryCISRepository
505
                        .selectGroupByWarehouse(new ArrayList<>(warehouseIdFofoIdMap.keySet()));
28468 tejbeer 506
 
33071 amit.gupta 507
                warehouseStockMap = warehouseStocks.stream().collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));
28468 tejbeer 508
 
33071 amit.gupta 509
                if (!warehouseStockMap.isEmpty()) {
510
                    for (Entry<Integer, WarehouseWiseStockModel> warehouseStock : warehouseStockMap.entrySet()) {
511
                        stockValue += warehouseStock.getValue().getStockValue();
512
                        stockQty += warehouseStock.getValue().getStockQty();
513
                        pendingIndent += warehouseStock.getValue().getPendingIndent();
514
                        tertiary += warehouseStock.getValue().getTertiary();
515
                    }
516
                    WarehouseWiseStockModel ws = new WarehouseWiseStockModel();
517
                    ws.setStockQty(stockQty);
518
                    ws.setStockValue(stockValue);
519
                    ws.setPendingIndent(pendingIndent);
520
                    ws.setTertiary(tertiary);
521
                    ws.setWarehouseId(0);
522
                    warehouseStockMap.put(0, ws);
28468 tejbeer 523
 
33071 amit.gupta 524
                }
28468 tejbeer 525
 
33071 amit.gupta 526
                warehouseStockMap.entrySet().stream().sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
527
                        .forEachOrdered(x -> warehouseStockSortedMap.put(x.getKey(), x.getValue()));
28468 tejbeer 528
 
33071 amit.gupta 529
                ReporticoCacheTable rctSaholic = reporticoCacheTableRepository.selectByTableName("SaholicInventoryCIS");
530
                model.addAttribute("reporticoDate", rctSaholic);
28468 tejbeer 531
 
33071 amit.gupta 532
                // warehouseStock
533
                warehousePartnerDetailMap = this.getWarehousePartnerDetail(warehouseIdFofoIdMap);
31259 tejbeer 534
 
33071 amit.gupta 535
                ReporticoCacheTable rctPartneStat = reporticoCacheTableRepository.selectByTableName("partnerStat");
28468 tejbeer 536
 
33071 amit.gupta 537
                Set<CustomRetailer> positionRetailers = fofoIds.stream()
33248 ranu 538
                        .map(x -> {
539
                            try {
540
                                return retailerService.getAllFofoRetailers().get(x);
541
                            } catch (ProfitMandiBusinessException e) {
542
                                throw new RuntimeException(e);
543
                            }
544
                        }).filter(x -> x != null)
33071 amit.gupta 545
                        .collect(Collectors.toSet());
546
                model.addAttribute("retailers", gson.toJson(positionRetailers));
547
                model.addAttribute("reporticoProjectMap", ReporticoProject.salesReporticoProjectMap);
548
                model.addAttribute("warehouses", getWarehouses(positionRetailers));
549
                model.addAttribute("rctPartneStat", rctPartneStat);
550
            } else {
551
                List<Position> warehousePositions = positions.stream()
552
                        .filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_WAREHOUSE)
553
                        .collect(Collectors.toList());
554
                if (warehousePositions.size() > 0) {
555
                    Set<CustomRetailer> positionRetailers = new HashSet<>();
556
                    csService.getPositionCustomRetailerMap(warehousePositions).values().forEach(customRetailers -> {
557
                        positionRetailers.addAll(customRetailers);
558
                    });
559
                    model.addAttribute("reporticoProjectMap", ReporticoProject.warehouseReporticoMap);
560
                    model.addAttribute("retailers", gson.toJson(positionRetailers));
561
                    model.addAttribute("warehouses", getWarehouses(positionRetailers));
562
                }
563
                List<Position> categoryPositions = positions.stream()
564
                        .filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_CATEGORY)
565
                        .collect(Collectors.toList());
566
                if (categoryPositions.size() > 0) {
567
                    Set<CustomRetailer> positionRetailers = new HashSet<>();
568
                    csService.getPositionCustomRetailerMap(warehousePositions).values().forEach(customRetailers -> {
569
                        positionRetailers.addAll(customRetailers);
570
                    });
571
                    model.addAttribute("reporticoProjectMap", ReporticoProject.warehouseReporticoMap);
572
                    model.addAttribute("retailers", gson.toJson(positionRetailers));
573
                    model.addAttribute("warehouses", getWarehouses(positionRetailers));
574
                }
575
            }
28468 tejbeer 576
 
33071 amit.gupta 577
            if (positions.size() > 0) {
578
                if (positions.stream()
579
                        .filter(x -> x.getEscalationType().equals(EscalationType.L3)
580
                                || x.getEscalationType().equals(EscalationType.L4)
581
                                || x.getEscalationType().equals(EscalationType.L5))
582
                        .count() > 0) {
583
                    authUserTicketCount = ticketRepository.selectAllAuthUserTicketCount(Optional.of(false));
584
                }
585
            }
28468 tejbeer 586
 
33071 amit.gupta 587
            if (Arrays.asList("amit.gupta@smartdukaan.com", "ranu.rajput@smartdukaan.com",
35337 aman 588
                    "vikas.jangra@smartdukaan.com","aman.gupta@smartdukaan.com").contains(email)) {
33071 amit.gupta 589
                menus = menuRepository.selectAllBySequence();
590
            } else if (positions.size() > 0) {
591
                if (positions.stream().filter(x -> x.getEscalationType().equals(EscalationType.L5)).count() > 0) {
592
                    menus = menuRepository.selectAllBySequence();
593
                } else {
594
                    List<Integer> menuIds = menuCategoryRepository.selectAllByPositions(positions).stream()
595
                            .map(x -> x.getMenuId()).collect(Collectors.toList());
596
                    if (menuIds.size() > 0) {
597
                        menus = menuRepository.selectAllByIds(menuIds);
598
                    }
599
                }
600
            }
28468 tejbeer 601
 
33071 amit.gupta 602
            model.addAttribute("authId", authUser.getId());
28468 tejbeer 603
 
33071 amit.gupta 604
            model.addAttribute("warehousePartnerDetailMap", warehousePartnerDetailMap);
605
            model.addAttribute("warehouseMap", wm);
606
            model.addAttribute("authUserTicketCount", authUserTicketCount);
607
            model.addAttribute("warehouseStockMap", warehouseStockSortedMap);
608
            LocalDateTime curDate = LocalDate.now().atStartOfDay();
28468 tejbeer 609
 
33071 amit.gupta 610
            model.addAttribute("date", curDate.withDayOfMonth(1).minusMonths(6).toLocalDate());
28468 tejbeer 611
 
33071 amit.gupta 612
        } catch (ProfitMandiBusinessException e) {
613
        }
614
        List<Menu> menuList = (menus != null) ? this.prepareMenu(menus) : new ArrayList<>();
33072 amit.gupta 615
        //LOGGER.info("menu" + menuList);
33071 amit.gupta 616
        model.addAttribute("menu", menuList);
617
        return "admin";
618
    }
28468 tejbeer 619
 
35189 amit 620
    private Map<Integer, List<Integer>> getWarehouseIdFofoIdMap(Set<Integer> fofoIds) throws ProfitMandiBusinessException {
621
        Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
622
                .selectActivePartnersByRetailerIds(new ArrayList<>(fofoIds)).stream()
623
                .collect(Collectors.groupingBy(FofoStore::getWarehouseId,
624
                        Collectors.mapping(FofoStore::getId, Collectors.toList())));
625
        // warehouseStock
626
        if (!warehouseIdFofoIdMap.containsKey(7573)) {
627
            warehouseIdFofoIdMap.put(7573, new ArrayList<>());
628
        }
629
        return warehouseIdFofoIdMap;
630
    }
631
 
33071 amit.gupta 632
    private List<Menu> prepareMenu(List<Menu> menus) {
633
        List<Menu> returnMenu = new ArrayList<>();
634
        Map<Menu, List<Menu>> subMenuMap = new HashMap<>();
635
        for (Menu menu : menus) {
636
            if (menu.get_parent() == null) {
637
                if (!subMenuMap.containsKey(menu)) {
638
                    subMenuMap.put(menu, new ArrayList<>());
639
                }
640
            } else {
641
                Menu parentMenu = menu.get_parent();
642
                if (!subMenuMap.containsKey(parentMenu)) {
643
                    subMenuMap.put(parentMenu, new ArrayList<>());
644
                }
645
                subMenuMap.get(parentMenu).add(menu);
646
            }
647
        }
648
        subMenuMap.entrySet().stream().forEach(entry -> {
649
            entry.getKey().setSubMenus(entry.getValue());
650
            returnMenu.add(entry.getKey());
651
        });
652
        return returnMenu;
653
    }
28468 tejbeer 654
 
33071 amit.gupta 655
    public Map<Integer, PartnerDetailModel> getWarehousePartnerDetail(Map<Integer, List<Integer>> warehousePartnerMap)
656
            throws Exception {
28468 tejbeer 657
 
33071 amit.gupta 658
        Map<Integer, PartnerDetailModel> warehouseIdAndallValues = new LinkedHashMap<>();
659
        // Map<Integer, List<FofoStore>> warehousePartnerMap =
660
        // fofoStoreRepository.getWarehousePartnerMap();
661
        Map<Integer, PartnerDetailModel> partnerStats = this.getPartnersStatDataFromFile();
662
        List<Integer> allfofoIds = new ArrayList<>();
663
        if (partnerStats != null) {
664
            for (Entry<Integer, List<Integer>> warehouse : warehousePartnerMap.entrySet()) {
665
                List<Integer> fofoIds = warehouse.getValue().stream().collect(Collectors.toList());
666
                allfofoIds.addAll(fofoIds);
667
                List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
668
                        .collect(Collectors.toList());
669
                if (partnerDetails != null && !partnerDetails.isEmpty()) {
670
                    PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
671
                    warehouseIdAndallValues.put(warehouse.getKey(), partnerDetailModel);
672
                }
28468 tejbeer 673
 
33071 amit.gupta 674
            }
675
            List<PartnerDetailModel> allPartnerDetails = allfofoIds.stream().map(x -> partnerStats.get(x))
676
                    .collect(Collectors.toList());
33072 amit.gupta 677
            //LOGGER.info("allPartnerDetails" + allPartnerDetails);
33071 amit.gupta 678
            PartnerDetailModel partnerDetailModel = partnerStatsService
679
                    .getAggregateStats(new ArrayList<>(allPartnerDetails));
680
            warehouseIdAndallValues.put(0, partnerDetailModel);
681
        }
682
        return warehouseIdAndallValues;
683
    }
28468 tejbeer 684
 
33071 amit.gupta 685
    public Map<Integer, PartnerDetailModel> getPartnersStatDataFromFile() throws Exception {
686
        ObjectInputStream objectinputstream = null;
687
        Map<Integer, PartnerDetailModel> partnerStat = null;
688
        try {
34665 ranu 689
//            FileInputStream streamIn = new FileInputStream("/tmp/partnerStat.tmp");
690
            FileInputStream streamIn = new FileInputStream("/var/www/partner_stats/partnerStat.tmp");
33071 amit.gupta 691
            objectinputstream = new ObjectInputStream(streamIn);
692
            partnerStat = (Map<Integer, PartnerDetailModel>) objectinputstream.readObject();
28468 tejbeer 693
 
33071 amit.gupta 694
            objectinputstream.close();
28468 tejbeer 695
 
33071 amit.gupta 696
        } catch (Exception e) {
697
            LOGGER.info("exceptionddd" + e);
28468 tejbeer 698
 
33071 amit.gupta 699
            e.printStackTrace();
28468 tejbeer 700
 
33071 amit.gupta 701
        } finally {
702
            if (objectinputstream != null) {
703
                objectinputstream.close();
704
            }
705
        }
706
        return partnerStat;
28468 tejbeer 707
 
33071 amit.gupta 708
    }
28468 tejbeer 709
 
33071 amit.gupta 710
    private String getWarehouses(Set<CustomRetailer> positionRetailers) {
711
        Map<Integer, String> warehouses = new HashMap<>();
712
        positionRetailers.stream().forEach(x -> {
713
            if (x.getWarehouseId() != 0) {
714
                warehouses.put(x.getWarehouseId(), ProfitMandiConstants.WAREHOUSE_MAP.get(x.getWarehouseId()));
715
            }
716
        });
717
        return gson.toJson(warehouses);
28468 tejbeer 718
 
33071 amit.gupta 719
    }
28468 tejbeer 720
 
721
 
722
}