Subversion Repositories SmartDukaan

Rev

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