Subversion Repositories SmartDukaan

Rev

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