Subversion Repositories SmartDukaan

Rev

Rev 37834 | Details | Compare with Previous | Last modification | View Log | RSS feed

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