Subversion Repositories SmartDukaan

Rev

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

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