Subversion Repositories SmartDukaan

Rev

Rev 35394 | 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;
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
 
35460 amit 158
        // Bulk fetch partner types to avoid N+1 queries
159
        Map<Integer, PartnerType> partnerTypeMap = partnerTypeChangeService.getTypesForFofoIds(new ArrayList<>(fofoIds), LocalDate.now());
160
 
32435 amit.gupta 161
        for (FofoStore store : fofoStores) {
162
            int fofoId = store.getId();
32421 amit.gupta 163
 
35394 amit 164
            // Use batch-fetched hygiene counts instead of N+1 queries
165
            int hygieneCount = validHygieneCountMap.getOrDefault(fofoId, 0L).intValue();
166
            int invalidHygieneCount = invalidHygieneCountMap.getOrDefault(fofoId, 0L).intValue();
32435 amit.gupta 167
            int totalHygieneCount = hygieneCount + invalidHygieneCount;
35460 amit 168
            PartnerType partnerType = partnerTypeMap.get(fofoId);
27548 tejbeer 169
 
32435 amit.gupta 170
            Map<EscalationType, AuthUser> authuserEsclationTypeMap = csService
171
                    .getAuthUserAndEsclationByPartnerId(fofoId);
172
            PartnerDetailModel pm = new PartnerDetailModel();
173
            pm.setFofoId(fofoId);
174
            pm.setLmtd(lmtdSale.get(fofoId) == null ? 0 : lmtdSale.get(fofoId).intValue());
175
            pm.setMtd(mtdSale.get(fofoId) == null ? 0 : mtdSale.get(fofoId).intValue());
176
            pm.setLms(lmsSale.get(fofoId) == null ? 0 : lmsSale.get(fofoId).intValue());
177
            pm.setSecondarymtd(secondaryMtd.get(fofoId) == null ? 0 : secondaryMtd.get(fofoId).intValue());
178
            pm.setSecondarylmtd(secondarylmtd.get(fofoId) == null ? 0 : secondarylmtd.get(fofoId).intValue());
179
            pm.setSecondarylms(secondarylms.get(fofoId) == null ? 0 : secondarylms.get(fofoId).intValue());
180
            pm.setTodayTertiary(todaytertiary.get(fofoId) == null ? 0 : todaytertiary.get(fofoId).intValue());
181
            pm.setLastThreeDaytertiary(last3daystertiary.get(fofoId) == null ? 0 : last3daystertiary.get(fofoId));
182
            pm.setWalletAmount(userWallet.get(fofoId) == null ? 0 : userWallet.get(fofoId).getAmount());
183
            pm.setInvestment(investmentMap.get(fofoId));
184
            pm.setTicket(ticketMap.get(fofoId) == null ? 0 : ticketMap.get(fofoId).intValue());
185
            pm.setHygiene(hygieneCount);
186
            pm.setInvestment_ok(
187
                    investmentMaintainedDaysMap.get(fofoId) == null ? 0 : investmentMaintainedDaysMap.get(fofoId));
188
            pm.setPartnerType(partnerType);
189
            if (authuserEsclationTypeMap.get(EscalationType.L1) != null) {
190
                pm.setAuthUser(authuserEsclationTypeMap.get(EscalationType.L1).getName());
191
            } else if (authuserEsclationTypeMap.get(EscalationType.L2) != null) {
192
                pm.setAuthUser(authuserEsclationTypeMap.get(EscalationType.L2).getName());
193
            } else if (authuserEsclationTypeMap.get(EscalationType.L3) != null) {
194
                pm.setAuthUser(authuserEsclationTypeMap.get(EscalationType.L3).getName());
195
            } else if (authuserEsclationTypeMap.get(EscalationType.L4) != null) {
196
                pm.setAuthUser(authuserEsclationTypeMap.get(EscalationType.L4).getName());
197
            } else {
198
                pm.setAuthUser(" - ");
199
            }
200
            pm.setTotalHygiene(totalHygieneCount);
26460 amit.gupta 201
 
32435 amit.gupta 202
            pm.setTicket(ticketMap.get(fofoId) == null ? 0 : ticketMap.get(fofoId).intValue());
203
            Set<AuthUser> rbmAuths = partnerRbmsMap.get(fofoId);
204
            if (rbmAuths == null) {
205
                pm.setRbms("-");
206
            } else {
207
                pm.setRbms(rbmAuths.stream().filter(x -> l1Rbms.contains(x.getId())).map(x -> x.getFullName()).collect(Collectors.joining(",")));
208
                if (pm.getRbms().equals("")) {
209
                    pm.setRbms(rbmAuths.stream().filter(x -> l2Rbms.contains(x.getId())).map(x -> x.getFullName()).collect(Collectors.joining(",")));
210
                }
211
                if (pm.getRbms().equals("")) {
212
                    pm.setRbms("-");
213
                }
214
            }
215
            allPartnerStats.put(fofoId, pm);
33505 amit.gupta 216
            //LOGGER.info("pm {}", pm);
27545 tejbeer 217
 
32435 amit.gupta 218
        }
219
        return allPartnerStats;
220
    }
26460 amit.gupta 221
 
32435 amit.gupta 222
    @Override
223
    // @Cacheable(value = "partnerAggregateStats", cacheManager =
224
    // "oneDayCacheManager")
225
    public PartnerDetailModel getAggregateStats(List<PartnerDetailModel> partnerDetailModels)
226
            throws ProfitMandiBusinessException {
227
        PartnerDetailModel pdm = new PartnerDetailModel();
228
        PartnerDailyInvestment aggregateInvestment = new PartnerDailyInvestment();
229
        pdm.setInvestment(aggregateInvestment);
230
        double totallmsAmount = 0;
231
        double totallmtdAmount = 0;
232
        double totalmtdAmount = 0;
233
        double totalTodayTertiary = 0;
234
        int totalTicketCount = 0;
26460 amit.gupta 235
 
32435 amit.gupta 236
        int currentHygieneCount = 0;
237
        int currentTotalHygieneCount = 0;
238
        if (partnerDetailModels != null && !partnerDetailModels.isEmpty()) {
239
            for (PartnerDetailModel partnerDetailModel : partnerDetailModels) {
240
                if (partnerDetailModel != null) {
241
                    PartnerDailyInvestment pdi = partnerDetailModel.getInvestment();
242
                    totallmsAmount += partnerDetailModel.getLms();
243
                    totallmtdAmount += partnerDetailModel.getLmtd();
244
                    totalmtdAmount += partnerDetailModel.getMtd();
245
                    totalTicketCount += partnerDetailModel.getTicket();
246
                    totalTodayTertiary += partnerDetailModel.getTodayTertiary();
247
                    currentHygieneCount += partnerDetailModel.getHygiene();
248
                    currentTotalHygieneCount += partnerDetailModel.getTotalHygiene();
249
                    if (pdi != null) {
250
                        aggregateInvestment.setActivatedStockAmount(
251
                                aggregateInvestment.getActivatedStockAmount() + pdi.getActivatedStockAmount());
252
                        aggregateInvestment.setGrnPendingAmount(
253
                                aggregateInvestment.getGrnPendingAmount() + pdi.getGrnPendingAmount());
254
                        aggregateInvestment
255
                                .setInStockAmount(aggregateInvestment.getInStockAmount() + pdi.getInStockAmount());
256
                        aggregateInvestment.setReturnInTransitAmount(
257
                                aggregateInvestment.getReturnInTransitAmount() + pdi.getReturnInTransitAmount());
258
                        aggregateInvestment.setSalesAmount(aggregateInvestment.getSalesAmount() + pdi.getSalesAmount());
259
                        aggregateInvestment
260
                                .setUnbilledAmount(aggregateInvestment.getUnbilledAmount() + pdi.getUnbilledAmount());
261
                        aggregateInvestment
262
                                .setWalletAmount(aggregateInvestment.getWalletAmount() + pdi.getWalletAmount());
263
                    }
264
                }
27635 tejbeer 265
 
32435 amit.gupta 266
                pdm.setHygiene(currentHygieneCount);
267
                pdm.setTotalHygiene(currentTotalHygieneCount);
268
                pdm.setLms((int) totallmsAmount);
269
                pdm.setLmtd((int) totallmtdAmount);
270
                pdm.setMtd((int) totalmtdAmount);
271
                pdm.setTicket((int) totalTicketCount);
272
                pdm.setTodayTertiary((int) totalTodayTertiary);
273
                pdm.setCount(partnerDetailModels.size());
274
            }
275
        }
276
        return pdm;
277
    }
26460 amit.gupta 278
 
279
}