Subversion Repositories SmartDukaan

Rev

Rev 35460 | Rev 35537 | 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
 
35536 amit 125
        // Batch fetch investments for all fofoStores at once (performance optimization)
126
        Map<Integer, PartnerDailyInvestment> investmentMap;
127
        try {
128
            investmentMap = partnerInvestmentService.getInvestmentsForFofoStores(fofoStores);
129
        } catch (Exception e) {
130
            LOGGER.error("Error fetching investments in batch, falling back to individual calls", e);
131
            investmentMap = fofoStores.stream().map(x -> {
132
                try {
133
                    return partnerInvestmentService.getInvestment(x.getId(), 0);
134
                } catch (Exception ex) {
135
                    LOGGER.info("Could not get investment summary for {}", x);
136
                    return new PartnerDailyInvestment();
137
                }
138
            }).collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
139
        }
26460 amit.gupta 140
 
32435 amit.gupta 141
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMappingByCategoryIds(Arrays.asList(ProfitMandiConstants.TICKET_CATEGORY_RBM), true);
142
        Map<String, AuthUser> authUserMap = authRepository.selectAll().stream().filter(x -> storeGuyMap.keySet().contains(x.getEmailId())).collect(Collectors.toMap(x -> x.getEmailId(), x -> x));
143
        Map<Integer, Set<AuthUser>> partnerRbmsMap = new HashMap<>();
144
        for (Map.Entry<String, Set<Integer>> storeGuySetEntry : storeGuyMap.entrySet()) {
145
            //store
146
            for (Integer storeId : storeGuySetEntry.getValue()) {
147
                if (!partnerRbmsMap.containsKey(storeId)) {
148
                    partnerRbmsMap.put(storeId, new HashSet<>());
149
                }
150
                partnerRbmsMap.get(storeId).add(authUserMap.get(storeGuySetEntry.getKey()));
151
            }
152
        }
32421 amit.gupta 153
 
32435 amit.gupta 154
        Set<Integer> l1Rbms = positionRepository.selectPositionbyCategoryIdAndEscalationType(
155
                ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L1).stream().map(x -> x.getAuthUserId()).collect(Collectors.toSet());
156
        Set<Integer> l2Rbms = positionRepository.selectPositionbyCategoryIdAndEscalationType(
157
                ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L2).stream().map(x -> x.getAuthUserId()).collect(Collectors.toSet());
32430 amit.gupta 158
 
35394 amit 159
        // Batch fetch hygiene counts for all fofoIds at once (performance optimization)
160
        LocalDateTime hygieneStartDate = curDate.withDayOfMonth(1).minusMonths(1);
161
        LocalDateTime hygieneEndDate = curDate.plusMonths(1).withDayOfMonth(1);
162
        Map<Integer, Long> validHygieneCountMap = hygieneDataRepository.selectHygieneCountByFofoIds(fofoIds, true, hygieneStartDate, hygieneEndDate);
163
        Map<Integer, Long> invalidHygieneCountMap = hygieneDataRepository.selectHygieneCountByFofoIds(fofoIds, false, hygieneStartDate, hygieneEndDate);
164
 
35460 amit 165
        // Bulk fetch partner types to avoid N+1 queries
166
        Map<Integer, PartnerType> partnerTypeMap = partnerTypeChangeService.getTypesForFofoIds(new ArrayList<>(fofoIds), LocalDate.now());
167
 
35536 amit 168
        // Batch fetch auth user escalations for all fofoIds at once (performance optimization)
169
        Map<Integer, Map<EscalationType, AuthUser>> authUserEscalationMap = csService.getAuthUserAndEsclationByPartnerIds(fofoIds);
170
 
32435 amit.gupta 171
        for (FofoStore store : fofoStores) {
172
            int fofoId = store.getId();
32421 amit.gupta 173
 
35394 amit 174
            // Use batch-fetched hygiene counts instead of N+1 queries
175
            int hygieneCount = validHygieneCountMap.getOrDefault(fofoId, 0L).intValue();
176
            int invalidHygieneCount = invalidHygieneCountMap.getOrDefault(fofoId, 0L).intValue();
32435 amit.gupta 177
            int totalHygieneCount = hygieneCount + invalidHygieneCount;
35460 amit 178
            PartnerType partnerType = partnerTypeMap.get(fofoId);
27548 tejbeer 179
 
35536 amit 180
            // Use batch-fetched auth user escalations instead of N+1 queries
181
            Map<EscalationType, AuthUser> authuserEsclationTypeMap = authUserEscalationMap.getOrDefault(fofoId, new HashMap<>());
32435 amit.gupta 182
            PartnerDetailModel pm = new PartnerDetailModel();
183
            pm.setFofoId(fofoId);
184
            pm.setLmtd(lmtdSale.get(fofoId) == null ? 0 : lmtdSale.get(fofoId).intValue());
185
            pm.setMtd(mtdSale.get(fofoId) == null ? 0 : mtdSale.get(fofoId).intValue());
186
            pm.setLms(lmsSale.get(fofoId) == null ? 0 : lmsSale.get(fofoId).intValue());
187
            pm.setSecondarymtd(secondaryMtd.get(fofoId) == null ? 0 : secondaryMtd.get(fofoId).intValue());
188
            pm.setSecondarylmtd(secondarylmtd.get(fofoId) == null ? 0 : secondarylmtd.get(fofoId).intValue());
189
            pm.setSecondarylms(secondarylms.get(fofoId) == null ? 0 : secondarylms.get(fofoId).intValue());
190
            pm.setTodayTertiary(todaytertiary.get(fofoId) == null ? 0 : todaytertiary.get(fofoId).intValue());
191
            pm.setLastThreeDaytertiary(last3daystertiary.get(fofoId) == null ? 0 : last3daystertiary.get(fofoId));
192
            pm.setWalletAmount(userWallet.get(fofoId) == null ? 0 : userWallet.get(fofoId).getAmount());
193
            pm.setInvestment(investmentMap.get(fofoId));
194
            pm.setTicket(ticketMap.get(fofoId) == null ? 0 : ticketMap.get(fofoId).intValue());
195
            pm.setHygiene(hygieneCount);
196
            pm.setInvestment_ok(
197
                    investmentMaintainedDaysMap.get(fofoId) == null ? 0 : investmentMaintainedDaysMap.get(fofoId));
198
            pm.setPartnerType(partnerType);
199
            if (authuserEsclationTypeMap.get(EscalationType.L1) != null) {
200
                pm.setAuthUser(authuserEsclationTypeMap.get(EscalationType.L1).getName());
201
            } else if (authuserEsclationTypeMap.get(EscalationType.L2) != null) {
202
                pm.setAuthUser(authuserEsclationTypeMap.get(EscalationType.L2).getName());
203
            } else if (authuserEsclationTypeMap.get(EscalationType.L3) != null) {
204
                pm.setAuthUser(authuserEsclationTypeMap.get(EscalationType.L3).getName());
205
            } else if (authuserEsclationTypeMap.get(EscalationType.L4) != null) {
206
                pm.setAuthUser(authuserEsclationTypeMap.get(EscalationType.L4).getName());
207
            } else {
208
                pm.setAuthUser(" - ");
209
            }
210
            pm.setTotalHygiene(totalHygieneCount);
26460 amit.gupta 211
 
32435 amit.gupta 212
            pm.setTicket(ticketMap.get(fofoId) == null ? 0 : ticketMap.get(fofoId).intValue());
213
            Set<AuthUser> rbmAuths = partnerRbmsMap.get(fofoId);
214
            if (rbmAuths == null) {
215
                pm.setRbms("-");
216
            } else {
217
                pm.setRbms(rbmAuths.stream().filter(x -> l1Rbms.contains(x.getId())).map(x -> x.getFullName()).collect(Collectors.joining(",")));
218
                if (pm.getRbms().equals("")) {
219
                    pm.setRbms(rbmAuths.stream().filter(x -> l2Rbms.contains(x.getId())).map(x -> x.getFullName()).collect(Collectors.joining(",")));
220
                }
221
                if (pm.getRbms().equals("")) {
222
                    pm.setRbms("-");
223
                }
224
            }
225
            allPartnerStats.put(fofoId, pm);
33505 amit.gupta 226
            //LOGGER.info("pm {}", pm);
27545 tejbeer 227
 
32435 amit.gupta 228
        }
229
        return allPartnerStats;
230
    }
26460 amit.gupta 231
 
32435 amit.gupta 232
    @Override
233
    // @Cacheable(value = "partnerAggregateStats", cacheManager =
234
    // "oneDayCacheManager")
235
    public PartnerDetailModel getAggregateStats(List<PartnerDetailModel> partnerDetailModels)
236
            throws ProfitMandiBusinessException {
237
        PartnerDetailModel pdm = new PartnerDetailModel();
238
        PartnerDailyInvestment aggregateInvestment = new PartnerDailyInvestment();
239
        pdm.setInvestment(aggregateInvestment);
240
        double totallmsAmount = 0;
241
        double totallmtdAmount = 0;
242
        double totalmtdAmount = 0;
243
        double totalTodayTertiary = 0;
244
        int totalTicketCount = 0;
26460 amit.gupta 245
 
32435 amit.gupta 246
        int currentHygieneCount = 0;
247
        int currentTotalHygieneCount = 0;
248
        if (partnerDetailModels != null && !partnerDetailModels.isEmpty()) {
249
            for (PartnerDetailModel partnerDetailModel : partnerDetailModels) {
250
                if (partnerDetailModel != null) {
251
                    PartnerDailyInvestment pdi = partnerDetailModel.getInvestment();
252
                    totallmsAmount += partnerDetailModel.getLms();
253
                    totallmtdAmount += partnerDetailModel.getLmtd();
254
                    totalmtdAmount += partnerDetailModel.getMtd();
255
                    totalTicketCount += partnerDetailModel.getTicket();
256
                    totalTodayTertiary += partnerDetailModel.getTodayTertiary();
257
                    currentHygieneCount += partnerDetailModel.getHygiene();
258
                    currentTotalHygieneCount += partnerDetailModel.getTotalHygiene();
259
                    if (pdi != null) {
260
                        aggregateInvestment.setActivatedStockAmount(
261
                                aggregateInvestment.getActivatedStockAmount() + pdi.getActivatedStockAmount());
262
                        aggregateInvestment.setGrnPendingAmount(
263
                                aggregateInvestment.getGrnPendingAmount() + pdi.getGrnPendingAmount());
264
                        aggregateInvestment
265
                                .setInStockAmount(aggregateInvestment.getInStockAmount() + pdi.getInStockAmount());
266
                        aggregateInvestment.setReturnInTransitAmount(
267
                                aggregateInvestment.getReturnInTransitAmount() + pdi.getReturnInTransitAmount());
268
                        aggregateInvestment.setSalesAmount(aggregateInvestment.getSalesAmount() + pdi.getSalesAmount());
269
                        aggregateInvestment
270
                                .setUnbilledAmount(aggregateInvestment.getUnbilledAmount() + pdi.getUnbilledAmount());
271
                        aggregateInvestment
272
                                .setWalletAmount(aggregateInvestment.getWalletAmount() + pdi.getWalletAmount());
273
                    }
274
                }
27635 tejbeer 275
 
32435 amit.gupta 276
                pdm.setHygiene(currentHygieneCount);
277
                pdm.setTotalHygiene(currentTotalHygieneCount);
278
                pdm.setLms((int) totallmsAmount);
279
                pdm.setLmtd((int) totallmtdAmount);
280
                pdm.setMtd((int) totalmtdAmount);
281
                pdm.setTicket((int) totalTicketCount);
282
                pdm.setTodayTertiary((int) totalTodayTertiary);
283
                pdm.setCount(partnerDetailModels.size());
284
            }
285
        }
286
        return pdm;
287
    }
26460 amit.gupta 288
 
289
}