Subversion Repositories SmartDukaan

Rev

Rev 37845 | 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
 
37873 amit 59
    // These users see every sidebar menu regardless of auth.menu_category (as do L8/L9 position holders).
37779 amit 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) {
37873 amit 626
                if (positions.stream().anyMatch(x -> x.getEscalationType().equals(EscalationType.L8)
627
                        || x.getEscalationType().equals(EscalationType.L9))) {
33071 amit.gupta 628
                    menus = menuRepository.selectAllBySequence();
629
                } else {
630
                    List<Integer> menuIds = menuCategoryRepository.selectAllByPositions(positions).stream()
631
                            .map(x -> x.getMenuId()).collect(Collectors.toList());
632
                    if (menuIds.size() > 0) {
633
                        menus = menuRepository.selectAllByIds(menuIds);
634
                    }
635
                }
636
            }
28468 tejbeer 637
 
33071 amit.gupta 638
            model.addAttribute("authId", authUser.getId());
37336 amit 639
            // needed by views that gate a section on the exact logged-in email
640
            // rather than on role, which is all auth.menu can express
641
            model.addAttribute("loginEmail", authUser.getEmailId());
28468 tejbeer 642
 
33071 amit.gupta 643
            model.addAttribute("warehousePartnerDetailMap", warehousePartnerDetailMap);
644
            model.addAttribute("warehouseMap", wm);
645
            model.addAttribute("authUserTicketCount", authUserTicketCount);
646
            model.addAttribute("warehouseStockMap", warehouseStockSortedMap);
647
            LocalDateTime curDate = LocalDate.now().atStartOfDay();
28468 tejbeer 648
 
33071 amit.gupta 649
            model.addAttribute("date", curDate.withDayOfMonth(1).minusMonths(6).toLocalDate());
28468 tejbeer 650
 
33071 amit.gupta 651
        } catch (ProfitMandiBusinessException e) {
652
        }
35629 amit 653
        // Filter out "Manager Ticket" menu item for L1-only users (must be at least L2 in any position)
654
        if (menus != null && !isAboveL1) {
655
            menus = menus.stream()
656
                    .filter(m -> !"manager-ticket".equals(m.getActionClass()))
657
                    .collect(Collectors.toList());
658
        }
33071 amit.gupta 659
        List<Menu> menuList = (menus != null) ? this.prepareMenu(menus) : new ArrayList<>();
33072 amit.gupta 660
        //LOGGER.info("menu" + menuList);
33071 amit.gupta 661
        model.addAttribute("menu", menuList);
37374 ranu 662
        // Feeds the brand-filter dropdown on the "Warehouse Wise Report" widget.
663
        // Filter itself is applied via AJAX to /getWarehouseStockByBrand; loading is unaffected.
37394 ranu 664
        model.addAttribute("whrBrandList", brandsService.getBrandsToDisplay(3));
33071 amit.gupta 665
        return "admin";
666
    }
28468 tejbeer 667
 
35549 ranu 668
 
37374 ranu 669
    /**
670
     * Reproduces the Warehouse Wise Report data-fetch used by {@link #adminPanel} but
671
     * with an optional brand filter, so the main dashboard can swap the widget's rows
672
     * without a full page reload. Permission scope (fofoIds) is resolved with the
673
     * same rules as adminPanel so a user only ever sees their own warehouse territory.
674
     *
675
     * @param email  logged-in user's email — used for fofoId scope resolution
676
     * @param brands non-empty → filter to these brands; null/empty → all brands (identical to adminPanel behavior)
677
     */
678
    public LinkedHashMap<Integer, WarehouseWiseStockModel> getWarehouseStockMap(String email, List<String> brands) throws Exception {
679
        LinkedHashMap<Integer, WarehouseWiseStockModel> warehouseStockSortedMap = new LinkedHashMap<>();
680
 
681
        AuthUser authUser = authRepository.selectByEmailOrMobile(email);
682
        List<Position> positions = positionRepository.selectAllByAuthUserId(authUser.getId());
683
 
684
        boolean isRbmL3OrAbove = positions.stream().anyMatch(pos ->
685
                pos.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_RBM
686
                        && pos.getEscalationType() != null
687
                        && pos.getEscalationType() != EscalationType.L1
688
                        && pos.getEscalationType() != EscalationType.L2);
689
        boolean isSalesL5OrAbove = positions.stream().anyMatch(pos ->
690
                pos.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES
691
                        && pos.getEscalationType() != null
692
                        && pos.getEscalationType() != EscalationType.L1
693
                        && pos.getEscalationType() != EscalationType.L2
694
                        && pos.getEscalationType() != EscalationType.L3
695
                        && pos.getEscalationType() != EscalationType.L4);
696
        boolean canSeeAllStores = isRbmL3OrAbove || isSalesL5OrAbove;
697
 
698
        Set<Integer> fofoIds;
699
        if (canSeeAllStores) {
700
            fofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId()).collect(Collectors.toSet());
701
        } else {
702
            fofoIds = csService1.getAuthFofoIds(email, true);
703
        }
704
        if (fofoIds == null || fofoIds.isEmpty()) return warehouseStockSortedMap;
705
 
706
        Map<Integer, List<Integer>> warehouseIdFofoIdMap = getWarehouseIdFofoIdMap(fofoIds);
707
        List<Integer> warehouseIds = new ArrayList<>(warehouseIdFofoIdMap.keySet());
708
 
709
        List<WarehouseWiseStockModel> warehouseStocks;
710
        if (brands == null || brands.isEmpty()) {
711
            warehouseStocks = saholicInventoryCISRepository.selectGroupByWarehouse(warehouseIds);
712
        } else {
713
            warehouseStocks = saholicInventoryCISRepository.selectGroupByWarehouseFilteredByBrands(warehouseIds, brands);
714
        }
715
 
716
        Map<Integer, WarehouseWiseStockModel> warehouseStockMap =
717
                warehouseStocks.stream().collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));
718
 
719
        if (!warehouseStockMap.isEmpty()) {
720
            long stockValue = 0, stockQty = 0, pendingIndent = 0, tertiary = 0;
721
            for (Entry<Integer, WarehouseWiseStockModel> e : warehouseStockMap.entrySet()) {
722
                stockValue += e.getValue().getStockValue();
723
                stockQty += e.getValue().getStockQty();
724
                pendingIndent += e.getValue().getPendingIndent();
725
                tertiary += e.getValue().getTertiary();
726
            }
727
            WarehouseWiseStockModel totals = new WarehouseWiseStockModel();
728
            totals.setStockQty(stockQty);
729
            totals.setStockValue(stockValue);
730
            totals.setPendingIndent(pendingIndent);
731
            totals.setTertiary(tertiary);
732
            totals.setWarehouseId(0);
733
            warehouseStockMap.put(0, totals);
734
        }
735
 
736
        warehouseStockMap.entrySet().stream()
737
                .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
738
                .forEachOrdered(x -> warehouseStockSortedMap.put(x.getKey(), x.getValue()));
739
 
740
        return warehouseStockSortedMap;
741
    }
742
 
35583 ranu 743
    public Map<ProfitMandiConstants.BULLETIN_TYPE_ENUM, List<BulletinOfferModal>> getTodayBulletin(List<Position> positions, LocalDateTime date) throws Exception {
35549 ranu 744
        List<Long> regionIds = positions.stream().map(x -> Long.valueOf(x.getRegionId())).collect(Collectors.toList());
745
 
746
        regionIds.add(5L);
747
 
748
 
749
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("h:mm a");
750
 
35583 ranu 751
        LocalDateTime startDate = date.toLocalDate().minusDays(1).atTime(LocalTime.MAX);
752
        LocalDateTime endDate = date.toLocalDate().plusDays(1).atTime(LocalTime.MAX);
35549 ranu 753
        List<BulletinOfferModal> bulletinOfferModals = new ArrayList<>();
754
 
37097 ranu 755
        // Each sub-fetch is best-effort — one failing shouldn't wipe out the whole
756
        // bulletin response (especially the always-present Thought of the Day).
757
        try {
758
            List<Bulletin> bulletins = bulletinRepository.selectALlTodayBulletinByRegionIds(regionIds, startDate, endDate);
759
            for (Bulletin b : bulletins) {
35549 ranu 760
 
37097 ranu 761
                BulletinOfferModal modal = new BulletinOfferModal();
762
                modal.setOfferId(b.getId());
763
                modal.setDescription(b.getDescription());
764
                modal.setCreatedTime(formatter.format(b.getCreatedAt()));
765
                modal.setCatalogOffer(false);
766
                modal.setCreatedAt(b.getCreatedAt());
767
                modal.setCreatedBy(b.getCreatedBy());
768
                modal.setBulletinType(ProfitMandiConstants.BULLETIN_TYPE_ENUM.BULLETIN);
35549 ranu 769
 
37097 ranu 770
                if (b.getDocumentIds() != null && !b.getDocumentIds().isEmpty()) {
771
                    List<Integer> docIds = Arrays.stream(b.getDocumentIds().split(","))
772
                            .map(String::trim)
773
                            .map(Integer::parseInt)
774
                            .collect(Collectors.toList());
35549 ranu 775
 
37097 ranu 776
                    modal.setDocumentIds(docIds);
777
                }
778
 
779
                bulletinOfferModals.add(modal);
35549 ranu 780
            }
37097 ranu 781
        } catch (Exception e) {
782
            LOGGER.warn("selectALlTodayBulletinByRegionIds failed: {}", e.getMessage());
35549 ranu 783
        }
784
 
37097 ranu 785
        // 0️⃣ Thought of the Day (virtual bulletin) — always added, does not depend
786
        // on any DB/service call.
35585 ranu 787
        BulletinOfferModal thoughtModal = new BulletinOfferModal();
788
        thoughtModal.setOfferId(0L); // dummy
789
        thoughtModal.setDescription(SalesThoughtConstants.getTodayThought());
790
        thoughtModal.setCreatedAt(LocalDateTime.MAX); // IMPORTANT → always first
791
        thoughtModal.setCreatedTime("");
792
        thoughtModal.setCatalogOffer(false);
793
        thoughtModal.setCreatedBy("SYSTEM");
794
        thoughtModal.setBulletinType(ProfitMandiConstants.BULLETIN_TYPE_ENUM.BULLETIN);
35549 ranu 795
 
35585 ranu 796
        bulletinOfferModals.add(thoughtModal);
797
 
798
 
37097 ranu 799
        try {
800
            List<BulletinOfferModal> getTodayCreatedCatalogOffer = todayOfferService.findAllTodayCatalogOfferBulletin(regionIds.stream().map(x -> x.intValue()).collect(Collectors.toList()), startDate, endDate);
801
            bulletinOfferModals.addAll(getTodayCreatedCatalogOffer);
802
        } catch (Exception e) {
803
            LOGGER.warn("findAllTodayCatalogOfferBulletin failed: {}", e.getMessage());
804
        }
35549 ranu 805
 
37097 ranu 806
        try {
807
            List<BulletinOfferModal> getTodaySchemes = todayOfferService.findAllTodaySchemeBulletin(regionIds.stream().map(x -> x.intValue()).collect(Collectors.toList()), startDate, endDate);
808
            bulletinOfferModals.addAll(getTodaySchemes);
809
        } catch (Exception e) {
810
            LOGGER.warn("findAllTodaySchemeBulletin failed: {}", e.getMessage());
811
        }
35549 ranu 812
 
37097 ranu 813
        try {
814
            List<BulletinOfferModal> getTodayCardCashback = todayOfferService.findAllTodayWebOfferBulletin(startDate, endDate);
815
            bulletinOfferModals.addAll(getTodayCardCashback);
816
        } catch (Exception e) {
817
            LOGGER.warn("findAllTodayWebOfferBulletin failed: {}", e.getMessage());
818
        }
35549 ranu 819
 
37097 ranu 820
        try {
821
            List<BulletinOfferModal> getTodayPrebookingList = todayOfferService.getAllTodayCreatedPreBookingList(startDate, endDate);
822
            bulletinOfferModals.addAll(getTodayPrebookingList);
823
        } catch (Exception e) {
824
            LOGGER.warn("getAllTodayCreatedPreBookingList failed: {}", e.getMessage());
825
        }
35549 ranu 826
 
827
        bulletinOfferModals.sort(
828
                Comparator.comparing(BulletinOfferModal::getCreatedAt).reversed()
829
        );
830
 
831
        Map<ProfitMandiConstants.BULLETIN_TYPE_ENUM, List<BulletinOfferModal>> bulletinOffermap =
832
                bulletinOfferModals.stream()
833
                        .collect(Collectors.groupingBy(
834
                                BulletinOfferModal::getBulletinType,
835
                                () -> new EnumMap<>(ProfitMandiConstants.BULLETIN_TYPE_ENUM.class),
836
                                Collectors.toList()
837
                        ));
838
 
35585 ranu 839
        bulletinOfferModals.sort(
840
                Comparator.comparing(BulletinOfferModal::getCreatedAt).reversed()
841
        );
35549 ranu 842
 
35585 ranu 843
 
844
 
35549 ranu 845
        return bulletinOffermap;
846
    }
847
 
35189 amit 848
    private Map<Integer, List<Integer>> getWarehouseIdFofoIdMap(Set<Integer> fofoIds) throws ProfitMandiBusinessException {
849
        Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
850
                .selectActivePartnersByRetailerIds(new ArrayList<>(fofoIds)).stream()
851
                .collect(Collectors.groupingBy(FofoStore::getWarehouseId,
852
                        Collectors.mapping(FofoStore::getId, Collectors.toList())));
37845 amit 853
        // Dashboards list the ACTIVE warehouses: each gets a row even with no franchise store of its own (a hub such
854
        // as the HR warehouses carries only internal movement stores), and a suspended or closed one gets none even
855
        // while it still holds stock.
856
        Set<Integer> activeWarehouseIds = billingWarehouseService.getActiveWarehouses().keySet();
857
        for (Integer activeWarehouseId : activeWarehouseIds) {
858
            warehouseIdFofoIdMap.putIfAbsent(activeWarehouseId, new ArrayList<>());
35189 amit 859
        }
37845 amit 860
        warehouseIdFofoIdMap.keySet().retainAll(activeWarehouseIds);
35189 amit 861
        return warehouseIdFofoIdMap;
862
    }
863
 
33071 amit.gupta 864
    private List<Menu> prepareMenu(List<Menu> menus) {
865
        List<Menu> returnMenu = new ArrayList<>();
866
        Map<Menu, List<Menu>> subMenuMap = new HashMap<>();
867
        for (Menu menu : menus) {
868
            if (menu.get_parent() == null) {
869
                if (!subMenuMap.containsKey(menu)) {
870
                    subMenuMap.put(menu, new ArrayList<>());
871
                }
872
            } else {
873
                Menu parentMenu = menu.get_parent();
874
                if (!subMenuMap.containsKey(parentMenu)) {
875
                    subMenuMap.put(parentMenu, new ArrayList<>());
876
                }
877
                subMenuMap.get(parentMenu).add(menu);
878
            }
879
        }
36681 ranu 880
        // Sort submenus alphabetically by display text, then build the top-level list
881
        Comparator<Menu> byDisplayText = Comparator.comparing(
882
                m -> m.getDisplayText() == null ? "" : m.getDisplayText(),
883
                String.CASE_INSENSITIVE_ORDER);
33071 amit.gupta 884
        subMenuMap.entrySet().stream().forEach(entry -> {
36681 ranu 885
            List<Menu> subs = entry.getValue();
886
            subs.sort(byDisplayText);
887
            entry.getKey().setSubMenus(subs);
33071 amit.gupta 888
            returnMenu.add(entry.getKey());
889
        });
36681 ranu 890
        // Sort the top-level menus alphabetically
891
        returnMenu.sort(byDisplayText);
33071 amit.gupta 892
        return returnMenu;
893
    }
28468 tejbeer 894
 
33071 amit.gupta 895
    public Map<Integer, PartnerDetailModel> getWarehousePartnerDetail(Map<Integer, List<Integer>> warehousePartnerMap)
896
            throws Exception {
28468 tejbeer 897
 
33071 amit.gupta 898
        Map<Integer, PartnerDetailModel> warehouseIdAndallValues = new LinkedHashMap<>();
899
        // Map<Integer, List<FofoStore>> warehousePartnerMap =
900
        // fofoStoreRepository.getWarehousePartnerMap();
901
        Map<Integer, PartnerDetailModel> partnerStats = this.getPartnersStatDataFromFile();
902
        List<Integer> allfofoIds = new ArrayList<>();
903
        if (partnerStats != null) {
904
            for (Entry<Integer, List<Integer>> warehouse : warehousePartnerMap.entrySet()) {
905
                List<Integer> fofoIds = warehouse.getValue().stream().collect(Collectors.toList());
906
                allfofoIds.addAll(fofoIds);
907
                List<PartnerDetailModel> partnerDetails = fofoIds.stream().map(x -> partnerStats.get(x))
908
                        .collect(Collectors.toList());
909
                if (partnerDetails != null && !partnerDetails.isEmpty()) {
910
                    PartnerDetailModel partnerDetailModel = partnerStatsService.getAggregateStats(partnerDetails);
911
                    warehouseIdAndallValues.put(warehouse.getKey(), partnerDetailModel);
912
                }
28468 tejbeer 913
 
33071 amit.gupta 914
            }
915
            List<PartnerDetailModel> allPartnerDetails = allfofoIds.stream().map(x -> partnerStats.get(x))
916
                    .collect(Collectors.toList());
33072 amit.gupta 917
            //LOGGER.info("allPartnerDetails" + allPartnerDetails);
33071 amit.gupta 918
            PartnerDetailModel partnerDetailModel = partnerStatsService
919
                    .getAggregateStats(new ArrayList<>(allPartnerDetails));
920
            warehouseIdAndallValues.put(0, partnerDetailModel);
921
        }
922
        return warehouseIdAndallValues;
923
    }
28468 tejbeer 924
 
33071 amit.gupta 925
    public Map<Integer, PartnerDetailModel> getPartnersStatDataFromFile() throws Exception {
926
        ObjectInputStream objectinputstream = null;
927
        Map<Integer, PartnerDetailModel> partnerStat = null;
928
        try {
34665 ranu 929
//            FileInputStream streamIn = new FileInputStream("/tmp/partnerStat.tmp");
930
            FileInputStream streamIn = new FileInputStream("/var/www/partner_stats/partnerStat.tmp");
33071 amit.gupta 931
            objectinputstream = new ObjectInputStream(streamIn);
932
            partnerStat = (Map<Integer, PartnerDetailModel>) objectinputstream.readObject();
28468 tejbeer 933
 
33071 amit.gupta 934
            objectinputstream.close();
28468 tejbeer 935
 
33071 amit.gupta 936
        } catch (Exception e) {
937
            LOGGER.info("exceptionddd" + e);
28468 tejbeer 938
 
33071 amit.gupta 939
            e.printStackTrace();
28468 tejbeer 940
 
33071 amit.gupta 941
        } finally {
942
            if (objectinputstream != null) {
943
                objectinputstream.close();
944
            }
945
        }
946
        return partnerStat;
28468 tejbeer 947
 
33071 amit.gupta 948
    }
28468 tejbeer 949
 
33071 amit.gupta 950
    private String getWarehouses(Set<CustomRetailer> positionRetailers) {
951
        Map<Integer, String> warehouses = new HashMap<>();
952
        positionRetailers.stream().forEach(x -> {
953
            if (x.getWarehouseId() != 0) {
37845 amit 954
                warehouses.put(x.getWarehouseId(), billingWarehouseService.getName(x.getWarehouseId()));
33071 amit.gupta 955
            }
956
        });
957
        return gson.toJson(warehouses);
28468 tejbeer 958
 
33071 amit.gupta 959
    }
28468 tejbeer 960
 
961
 
962
}