Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
26460 amit.gupta 1
package com.spice.profitmandi.service;
2
 
32429 amit.gupta 3
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
32421 amit.gupta 4
import com.spice.profitmandi.common.model.ProfitMandiConstants;
27548 tejbeer 5
import com.spice.profitmandi.dao.entity.auth.AuthUser;
26479 amit.gupta 6
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
26460 amit.gupta 7
import com.spice.profitmandi.dao.entity.fofo.PartnerDailyInvestment;
27548 tejbeer 8
import com.spice.profitmandi.dao.entity.fofo.PartnerType;
27545 tejbeer 9
import com.spice.profitmandi.dao.entity.transaction.UserWallet;
27548 tejbeer 10
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
26460 amit.gupta 11
import com.spice.profitmandi.dao.model.PartnerDetailModel;
32429 amit.gupta 12
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
26460 amit.gupta 13
import com.spice.profitmandi.dao.repository.cs.CsService;
32430 amit.gupta 14
import com.spice.profitmandi.dao.repository.cs.PositionRepository;
26460 amit.gupta 15
import com.spice.profitmandi.dao.repository.cs.TicketRepository;
26479 amit.gupta 16
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
26460 amit.gupta 17
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
18
import com.spice.profitmandi.dao.repository.fofo.HygieneDataRepository;
27903 tejbeer 19
import com.spice.profitmandi.dao.repository.fofo.PartnerDailyInvestmentRepository;
27548 tejbeer 20
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeService;
27893 tejbeer 21
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
27545 tejbeer 22
import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;
26460 amit.gupta 23
import com.spice.profitmandi.service.user.RetailerService;
32429 amit.gupta 24
import org.apache.logging.log4j.LogManager;
25
import org.apache.logging.log4j.Logger;
26
import org.springframework.beans.factory.annotation.Autowired;
27
import org.springframework.stereotype.Component;
26460 amit.gupta 28
 
32429 amit.gupta 29
import java.time.LocalDate;
30
import java.time.LocalDateTime;
31
import java.time.LocalTime;
32
import java.util.*;
33
import java.util.stream.Collectors;
34
 
26461 amit.gupta 35
@Component
26460 amit.gupta 36
public class PartnerStatsServiceImpl implements PartnerStatsService {
37
 
32435 amit.gupta 38
    private static final Logger LOGGER = LogManager.getLogger(PartnerStatsServiceImpl.class);
27545 tejbeer 39
 
32435 amit.gupta 40
    @Autowired
41
    RetailerService retailerService;
26460 amit.gupta 42
 
32435 amit.gupta 43
    @Autowired
44
    FofoStoreRepository fofoStoreRepository;
26479 amit.gupta 45
 
32435 amit.gupta 46
    @Autowired
47
    FofoOrderItemRepository fofoOrderItemRepository;
26460 amit.gupta 48
 
32435 amit.gupta 49
    @Autowired
50
    CsService csService;
26460 amit.gupta 51
 
32435 amit.gupta 52
    @Autowired
53
    TicketRepository ticketRepository;
26460 amit.gupta 54
 
32435 amit.gupta 55
    @Autowired
56
    PartnerInvestmentService partnerInvestmentService;
26460 amit.gupta 57
 
32435 amit.gupta 58
    @Autowired
59
    HygieneDataRepository hygieneDataRepository;
26460 amit.gupta 60
 
32435 amit.gupta 61
    @Autowired
62
    UserWalletRepository userWalletRepository;
27545 tejbeer 63
 
32435 amit.gupta 64
    @Autowired
65
    PartnerTypeChangeService partnerTypeChangeService;
27548 tejbeer 66
 
32435 amit.gupta 67
    @Autowired
68
    OrderRepository orderRepository;
27893 tejbeer 69
 
32435 amit.gupta 70
    @Autowired
71
    AuthRepository authRepository;
32421 amit.gupta 72
 
32435 amit.gupta 73
    @Autowired
74
    PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
27903 tejbeer 75
 
32435 amit.gupta 76
    @Autowired
77
    PositionRepository positionRepository;
32430 amit.gupta 78
 
32435 amit.gupta 79
    @Override
80
    // @Cacheable(value = "partnerStats", cacheManager =
81
    // "thirtyMinsTimeOutCacheManager")
82
    public Map<Integer, PartnerDetailModel> getAllPartnerStats() throws ProfitMandiBusinessException {
83
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
84
        Map<Integer, Double> lmtdSale = fofoOrderItemRepository.selectSumMopGroupByRetailer(
85
                curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), 0, false);
28617 tejbeer 86
 
32435 amit.gupta 87
        Map<Integer, Double> mtdSale = fofoOrderItemRepository.selectSumMopGroupByRetailer(curDate.withDayOfMonth(1),
88
                curDate.with(LocalTime.MAX), 0, false);
26460 amit.gupta 89
 
32435 amit.gupta 90
        Map<Integer, Double> lmsSale = fofoOrderItemRepository.selectSumMopGroupByRetailer(
91
                curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), 0, false);
27660 tejbeer 92
 
32435 amit.gupta 93
        Map<Integer, Double> todaytertiary = fofoOrderItemRepository.selectSumMopGroupByRetailer(curDate,
94
                curDate.with(LocalTime.MAX), 0, false);
27545 tejbeer 95
 
32435 amit.gupta 96
        Map<Integer, Long> last3daystertiary = fofoOrderItemRepository.selectQtyGroupByRetailer(curDate.minusDays(4),
97
                curDate.minusDays(1).with(LocalTime.MAX), 0, false);
27545 tejbeer 98
 
32435 amit.gupta 99
        Map<Integer, Long> ticketMap = ticketRepository.selectAllOpenTicketsGroupByRetailer();
26460 amit.gupta 100
 
32435 amit.gupta 101
        Map<Integer, Double> secondaryMtd = orderRepository
102
                .selectBillingDatesBetweenSumGroupByRetailerId(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX));
103
        Map<Integer, Double> secondarylmtd = orderRepository.selectBillingDatesBetweenSumGroupByRetailerId(
104
                curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1));
105
        Map<Integer, Double> secondarylms = orderRepository.selectBillingDatesBetweenSumGroupByRetailerId(
106
                curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1));
27893 tejbeer 107
 
32435 amit.gupta 108
        LOGGER.info("secondarylmtd" + secondarylmtd);
109
        LOGGER.info("secondarylms" + secondarylms);
110
        List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores();
111
        Set<Integer> fofoIds = fofoStores.stream().filter(x -> !x.isInternal()).map(x -> x.getId()).collect(Collectors.toSet());
112
        Map<Integer, UserWallet> userWallet = userWalletRepository.selectByRetailerIds(fofoIds).stream()
113
                .collect(Collectors.toMap(x -> x.getUserId(), x -> x));
27545 tejbeer 114
 
32435 amit.gupta 115
        Map<Integer, PartnerDetailModel> allPartnerStats = new HashMap<>();
26460 amit.gupta 116
 
32435 amit.gupta 117
        List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository
118
                .selectAll(curDate.withDayOfMonth(1).toLocalDate(), curDate.toLocalDate());
119
        Map<Integer, Long> investmentMaintainedDaysMap = partnerDailyInvestments.stream()
120
                .filter(x -> x.getShortPercentage() <= 10)
121
                .collect(Collectors.groupingBy(x -> x.getFofoId(), Collectors.counting()));
27903 tejbeer 122
 
32435 amit.gupta 123
        LOGGER.info("investmentMaintainedDaysMap" + investmentMaintainedDaysMap);
27903 tejbeer 124
 
32435 amit.gupta 125
        Map<Integer, PartnerDailyInvestment> investmentMap = fofoStores.stream().map(x -> {
126
            try {
127
                return partnerInvestmentService.getInvestment(x.getId(), 0);
128
            } catch (Exception e) {
129
                LOGGER.info("Could not get invetment summary for {}", x);
130
                return new PartnerDailyInvestment();
131
            }
132
        }).collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
26460 amit.gupta 133
 
32435 amit.gupta 134
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMappingByCategoryIds(Arrays.asList(ProfitMandiConstants.TICKET_CATEGORY_RBM), true);
135
        Map<String, AuthUser> authUserMap = authRepository.selectAll().stream().filter(x -> storeGuyMap.keySet().contains(x.getEmailId())).collect(Collectors.toMap(x -> x.getEmailId(), x -> x));
136
        Map<Integer, Set<AuthUser>> partnerRbmsMap = new HashMap<>();
137
        for (Map.Entry<String, Set<Integer>> storeGuySetEntry : storeGuyMap.entrySet()) {
138
            //store
139
            for (Integer storeId : storeGuySetEntry.getValue()) {
140
                if (!partnerRbmsMap.containsKey(storeId)) {
141
                    partnerRbmsMap.put(storeId, new HashSet<>());
142
                }
143
                partnerRbmsMap.get(storeId).add(authUserMap.get(storeGuySetEntry.getKey()));
144
            }
145
        }
32421 amit.gupta 146
 
32435 amit.gupta 147
        Set<Integer> l1Rbms = positionRepository.selectPositionbyCategoryIdAndEscalationType(
148
                ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L1).stream().map(x -> x.getAuthUserId()).collect(Collectors.toSet());
149
        Set<Integer> l2Rbms = positionRepository.selectPositionbyCategoryIdAndEscalationType(
150
                ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L2).stream().map(x -> x.getAuthUserId()).collect(Collectors.toSet());
32430 amit.gupta 151
 
35394 amit 152
        // Batch fetch hygiene counts for all fofoIds at once (performance optimization)
153
        LocalDateTime hygieneStartDate = curDate.withDayOfMonth(1).minusMonths(1);
154
        LocalDateTime hygieneEndDate = curDate.plusMonths(1).withDayOfMonth(1);
155
        Map<Integer, Long> validHygieneCountMap = hygieneDataRepository.selectHygieneCountByFofoIds(fofoIds, true, hygieneStartDate, hygieneEndDate);
156
        Map<Integer, Long> invalidHygieneCountMap = hygieneDataRepository.selectHygieneCountByFofoIds(fofoIds, false, hygieneStartDate, hygieneEndDate);
157
 
32435 amit.gupta 158
        for (FofoStore store : fofoStores) {
159
            int fofoId = store.getId();
32421 amit.gupta 160
 
35394 amit 161
            // Use batch-fetched hygiene counts instead of N+1 queries
162
            int hygieneCount = validHygieneCountMap.getOrDefault(fofoId, 0L).intValue();
163
            int invalidHygieneCount = invalidHygieneCountMap.getOrDefault(fofoId, 0L).intValue();
32435 amit.gupta 164
            int totalHygieneCount = hygieneCount + invalidHygieneCount;
35394 amit 165
            // Note: getTypeOnDate is @Cacheable, so repeated calls are fast
32435 amit.gupta 166
            PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoId, LocalDate.now());
27548 tejbeer 167
 
32435 amit.gupta 168
            Map<EscalationType, AuthUser> authuserEsclationTypeMap = csService
169
                    .getAuthUserAndEsclationByPartnerId(fofoId);
170
            PartnerDetailModel pm = new PartnerDetailModel();
171
            pm.setFofoId(fofoId);
172
            pm.setLmtd(lmtdSale.get(fofoId) == null ? 0 : lmtdSale.get(fofoId).intValue());
173
            pm.setMtd(mtdSale.get(fofoId) == null ? 0 : mtdSale.get(fofoId).intValue());
174
            pm.setLms(lmsSale.get(fofoId) == null ? 0 : lmsSale.get(fofoId).intValue());
175
            pm.setSecondarymtd(secondaryMtd.get(fofoId) == null ? 0 : secondaryMtd.get(fofoId).intValue());
176
            pm.setSecondarylmtd(secondarylmtd.get(fofoId) == null ? 0 : secondarylmtd.get(fofoId).intValue());
177
            pm.setSecondarylms(secondarylms.get(fofoId) == null ? 0 : secondarylms.get(fofoId).intValue());
178
            pm.setTodayTertiary(todaytertiary.get(fofoId) == null ? 0 : todaytertiary.get(fofoId).intValue());
179
            pm.setLastThreeDaytertiary(last3daystertiary.get(fofoId) == null ? 0 : last3daystertiary.get(fofoId));
180
            pm.setWalletAmount(userWallet.get(fofoId) == null ? 0 : userWallet.get(fofoId).getAmount());
181
            pm.setInvestment(investmentMap.get(fofoId));
182
            pm.setTicket(ticketMap.get(fofoId) == null ? 0 : ticketMap.get(fofoId).intValue());
183
            pm.setHygiene(hygieneCount);
184
            pm.setInvestment_ok(
185
                    investmentMaintainedDaysMap.get(fofoId) == null ? 0 : investmentMaintainedDaysMap.get(fofoId));
186
            pm.setPartnerType(partnerType);
187
            if (authuserEsclationTypeMap.get(EscalationType.L1) != null) {
188
                pm.setAuthUser(authuserEsclationTypeMap.get(EscalationType.L1).getName());
189
            } else if (authuserEsclationTypeMap.get(EscalationType.L2) != null) {
190
                pm.setAuthUser(authuserEsclationTypeMap.get(EscalationType.L2).getName());
191
            } else if (authuserEsclationTypeMap.get(EscalationType.L3) != null) {
192
                pm.setAuthUser(authuserEsclationTypeMap.get(EscalationType.L3).getName());
193
            } else if (authuserEsclationTypeMap.get(EscalationType.L4) != null) {
194
                pm.setAuthUser(authuserEsclationTypeMap.get(EscalationType.L4).getName());
195
            } else {
196
                pm.setAuthUser(" - ");
197
            }
198
            pm.setTotalHygiene(totalHygieneCount);
26460 amit.gupta 199
 
32435 amit.gupta 200
            pm.setTicket(ticketMap.get(fofoId) == null ? 0 : ticketMap.get(fofoId).intValue());
201
            Set<AuthUser> rbmAuths = partnerRbmsMap.get(fofoId);
202
            if (rbmAuths == null) {
203
                pm.setRbms("-");
204
            } else {
205
                pm.setRbms(rbmAuths.stream().filter(x -> l1Rbms.contains(x.getId())).map(x -> x.getFullName()).collect(Collectors.joining(",")));
206
                if (pm.getRbms().equals("")) {
207
                    pm.setRbms(rbmAuths.stream().filter(x -> l2Rbms.contains(x.getId())).map(x -> x.getFullName()).collect(Collectors.joining(",")));
208
                }
209
                if (pm.getRbms().equals("")) {
210
                    pm.setRbms("-");
211
                }
212
            }
213
            allPartnerStats.put(fofoId, pm);
33505 amit.gupta 214
            //LOGGER.info("pm {}", pm);
27545 tejbeer 215
 
32435 amit.gupta 216
        }
217
        return allPartnerStats;
218
    }
26460 amit.gupta 219
 
32435 amit.gupta 220
    @Override
221
    // @Cacheable(value = "partnerAggregateStats", cacheManager =
222
    // "oneDayCacheManager")
223
    public PartnerDetailModel getAggregateStats(List<PartnerDetailModel> partnerDetailModels)
224
            throws ProfitMandiBusinessException {
225
        PartnerDetailModel pdm = new PartnerDetailModel();
226
        PartnerDailyInvestment aggregateInvestment = new PartnerDailyInvestment();
227
        pdm.setInvestment(aggregateInvestment);
228
        double totallmsAmount = 0;
229
        double totallmtdAmount = 0;
230
        double totalmtdAmount = 0;
231
        double totalTodayTertiary = 0;
232
        int totalTicketCount = 0;
26460 amit.gupta 233
 
32435 amit.gupta 234
        int currentHygieneCount = 0;
235
        int currentTotalHygieneCount = 0;
236
        if (partnerDetailModels != null && !partnerDetailModels.isEmpty()) {
237
            for (PartnerDetailModel partnerDetailModel : partnerDetailModels) {
238
                if (partnerDetailModel != null) {
239
                    PartnerDailyInvestment pdi = partnerDetailModel.getInvestment();
240
                    totallmsAmount += partnerDetailModel.getLms();
241
                    totallmtdAmount += partnerDetailModel.getLmtd();
242
                    totalmtdAmount += partnerDetailModel.getMtd();
243
                    totalTicketCount += partnerDetailModel.getTicket();
244
                    totalTodayTertiary += partnerDetailModel.getTodayTertiary();
245
                    currentHygieneCount += partnerDetailModel.getHygiene();
246
                    currentTotalHygieneCount += partnerDetailModel.getTotalHygiene();
247
                    if (pdi != null) {
248
                        aggregateInvestment.setActivatedStockAmount(
249
                                aggregateInvestment.getActivatedStockAmount() + pdi.getActivatedStockAmount());
250
                        aggregateInvestment.setGrnPendingAmount(
251
                                aggregateInvestment.getGrnPendingAmount() + pdi.getGrnPendingAmount());
252
                        aggregateInvestment
253
                                .setInStockAmount(aggregateInvestment.getInStockAmount() + pdi.getInStockAmount());
254
                        aggregateInvestment.setReturnInTransitAmount(
255
                                aggregateInvestment.getReturnInTransitAmount() + pdi.getReturnInTransitAmount());
256
                        aggregateInvestment.setSalesAmount(aggregateInvestment.getSalesAmount() + pdi.getSalesAmount());
257
                        aggregateInvestment
258
                                .setUnbilledAmount(aggregateInvestment.getUnbilledAmount() + pdi.getUnbilledAmount());
259
                        aggregateInvestment
260
                                .setWalletAmount(aggregateInvestment.getWalletAmount() + pdi.getWalletAmount());
261
                    }
262
                }
27635 tejbeer 263
 
32435 amit.gupta 264
                pdm.setHygiene(currentHygieneCount);
265
                pdm.setTotalHygiene(currentTotalHygieneCount);
266
                pdm.setLms((int) totallmsAmount);
267
                pdm.setLmtd((int) totallmtdAmount);
268
                pdm.setMtd((int) totalmtdAmount);
269
                pdm.setTicket((int) totalTicketCount);
270
                pdm.setTodayTertiary((int) totalTodayTertiary);
271
                pdm.setCount(partnerDetailModels.size());
272
            }
273
        }
274
        return pdm;
275
    }
26460 amit.gupta 276
 
277
}