Subversion Repositories SmartDukaan

Rev

Rev 36402 | Rev 36975 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 36402 Rev 36973
Line 1... Line 1...
1
package com.smartdukaan.cron.scheduled;
1
package com.smartdukaan.cron.scheduled;
2
 
2
 
3
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
3
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
4
import com.spice.profitmandi.common.model.BrandStockPrice;
4
import com.spice.profitmandi.common.model.BrandStockPrice;
5
import com.spice.profitmandi.common.model.CustomRetailer;
5
import com.spice.profitmandi.common.model.CustomRetailer;
-
 
6
import com.spice.profitmandi.common.model.IdAmountModel;
6
import com.spice.profitmandi.common.model.ProfitMandiConstants;
7
import com.spice.profitmandi.common.model.ProfitMandiConstants;
7
import com.spice.profitmandi.common.util.FormattingUtils;
8
import com.spice.profitmandi.common.util.FormattingUtils;
8
import com.spice.profitmandi.common.util.Utils;
9
import com.spice.profitmandi.common.util.Utils;
9
import com.spice.profitmandi.dao.cart.SmartCartService;
10
import com.spice.profitmandi.dao.cart.SmartCartService;
10
import com.spice.profitmandi.dao.entity.auth.AuthUser;
11
import com.spice.profitmandi.dao.entity.auth.AuthUser;
Line 652... Line 653...
652
 
653
 
653
        String subject = "Weekly Sales L1 Feedback Summary - " + previousMonday.format(dateFormatter) + " to " + previousSunday.format(dateFormatter);
654
        String subject = "Weekly Sales L1 Feedback Summary - " + previousMonday.format(dateFormatter) + " to " + previousSunday.format(dateFormatter);
654
 
655
 
655
        List<String> sendTo = new ArrayList<>();
656
        List<String> sendTo = new ArrayList<>();
656
        sendTo.add("sm@smartdukaan.com");
657
        sendTo.add("sm@smartdukaan.com");
657
        sendTo.add("chiranjib.sarkar@smartdukaan.com");
-
 
658
        sendTo.add("kamini.sharma@smartdukaan.com");
658
        sendTo.add("kamini.sharma@smartdukaan.com");
659
 
659
 
660
        String[] emailRecipients = sendTo.toArray(new String[0]);
660
        String[] emailRecipients = sendTo.toArray(new String[0]);
661
 
661
 
662
        this.sendMailHtmlFormat(emailRecipients, emailContent.toString(), null, bcc, subject);
662
        this.sendMailHtmlFormat(emailRecipients, emailContent.toString(), null, bcc, subject);
Line 702... Line 702...
702
 
702
 
703
        LocalDateTime startOfToday;
703
        LocalDateTime startOfToday;
704
        LocalDateTime previousDay;
704
        LocalDateTime previousDay;
705
 
705
 
706
        if (LocalDate.now().getDayOfMonth() == 1) {
706
        if (LocalDate.now().getDayOfMonth() == 1) {
707
            // If today is 1st, go to yesterday (i.e., last day of previous month)
-
 
708
            startOfToday = LocalDate.now().minusDays(1).atStartOfDay();
707
            startOfToday = LocalDate.now().minusDays(1).atStartOfDay();
709
            previousDay = startOfToday.with(LocalTime.MAX);
708
            previousDay = startOfToday.with(LocalTime.MAX);
710
 
-
 
711
        } else {
709
        } else {
712
            // Otherwise, use today
-
 
713
            startOfToday = LocalDate.now().atStartOfDay();
710
            startOfToday = LocalDate.now().atStartOfDay();
714
            previousDay = startOfToday.with(LocalTime.MAX).minusDays(1);
711
            previousDay = startOfToday.with(LocalTime.MAX).minusDays(1);
715
        }
712
        }
716
 
713
 
717
        Map<Integer, CustomRetailer> customRetailers = retailerService.getAllFofoRetailersInternalFalse();
714
        Map<Integer, CustomRetailer> customRetailers = retailerService.getAllFofoRetailersInternalFalse();
718
 
715
 
719
        List<Integer> retailerIds = customRetailers.values().stream()
716
        List<Integer> retailerIds = customRetailers.values().stream()
720
                .filter(retailer -> {
717
                .filter(retailer -> {
721
                    String storeCode = retailer.getCode(); // adjust method name if different
718
                    String storeCode = retailer.getCode();
722
                    return !storeCode.equalsIgnoreCase("UPGBN640") && !storeCode.equalsIgnoreCase("HRYN039");
719
                    return !storeCode.equalsIgnoreCase("UPGBN640") && !storeCode.equalsIgnoreCase("HRYN039");
723
                })
720
                })
724
                .map(CustomRetailer::getPartnerId)
721
                .map(CustomRetailer::getPartnerId)
725
                .collect(Collectors.toList());
722
                .collect(Collectors.toList());
726
 
723
 
727
//        List<Integer> retailerIds = Arrays.asList(175139993,175139441,175139442,175140143,175140146);
-
 
728
//        Map<Integer,CustomRetailer> customRetailers = retailerService.getFofoRetailers(retailerIds);
724
        Set<Integer> retailerIdSet = new HashSet<>(retailerIds);
729
 
725
 
730
        //partner daily investment
726
        //partner daily investment
731
        List<Loan> defaultLoans = sdCreditService.getDefaultLoans();
727
        List<Loan> defaultLoans = sdCreditService.getDefaultLoans();
732
        Map<Integer,List<Loan>> defaultLoanMap = defaultLoans.stream().collect(Collectors.groupingBy(Loan::getFofoId));
728
        Map<Integer,List<Loan>> defaultLoanMap = defaultLoans.stream().collect(Collectors.groupingBy(Loan::getFofoId));
733
 
729
 
734
        Map<Integer, PartnerDailyInvestment> partnerDailyInvestmentMap = new HashMap<>();
730
        Map<Integer, PartnerDailyInvestment> partnerDailyInvestmentMap = new HashMap<>();
735
        List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository
731
        List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository
736
                .selectAll(new ArrayList<>(retailerIds), previousDay.toLocalDate());
732
                .selectAll(new ArrayList<>(retailerIds), previousDay.toLocalDate());
737
        if (!partnerDailyInvestments.isEmpty()) {
733
        if (!partnerDailyInvestments.isEmpty()) {
738
            partnerDailyInvestmentMap = partnerDailyInvestments.stream()
734
            partnerDailyInvestmentMap = partnerDailyInvestments.stream()
739
                    .collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
735
                    .collect(Collectors.toMap(PartnerDailyInvestment::getFofoId, x -> x));
740
        }
736
        }
741
 
737
 
742
    //  this month return data
-
 
743
 
-
 
744
        YearMonth currentMonth;
738
        YearMonth currentMonth;
745
        LocalDateTime currentMonthStartDate;
739
        LocalDateTime currentMonthStartDate;
746
        LocalDateTime currentMonthEndDate;
740
        LocalDateTime currentMonthEndDate;
747
 
741
 
748
        if (LocalDate.now().getDayOfMonth() == 1) {
742
        if (LocalDate.now().getDayOfMonth() == 1) {
749
            // If today is the 1st, use previous month
-
 
750
            currentMonth = YearMonth.now().minusMonths(1);
743
            currentMonth = YearMonth.now().minusMonths(1);
751
            currentMonthStartDate = currentMonth.atDay(1).atStartOfDay();
744
            currentMonthStartDate = currentMonth.atDay(1).atStartOfDay();
752
            currentMonthEndDate = currentMonth.atEndOfMonth().atTime(23, 59, 59);
745
            currentMonthEndDate = currentMonth.atEndOfMonth().atTime(23, 59, 59);
753
        } else {
746
        } else {
754
            // Otherwise, use this month up to yesterday
-
 
755
            currentMonth = YearMonth.now();
747
            currentMonth = YearMonth.now();
756
            currentMonthStartDate = currentMonth.atDay(1).atStartOfDay();
748
            currentMonthStartDate = currentMonth.atDay(1).atStartOfDay();
757
            currentMonthEndDate = LocalDate.now().minusDays(1).atTime(23, 59, 59);
749
            currentMonthEndDate = LocalDate.now().minusDays(1).atTime(23, 59, 59);
758
        }
750
        }
759
 
751
 
760
        String currentMonthStringValue = String.valueOf(currentMonth);
752
        String currentMonthStringValue = String.valueOf(currentMonth);
761
 
753
 
762
        List<ReturnOrderInfoModel> currentMonthReturnOrderInfoModels = returnOrderInfoRepository.selectAllByBetweenDate(currentMonthStartDate, currentMonthEndDate);
-
 
763
        Map<Integer, Long> currentMonthPartnerReturnOrderInfoModelMap = currentMonthReturnOrderInfoModels.stream().collect(Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingLong(x -> Math.round(x.getRefundAmount()))));
-
 
764
 
-
 
765
        List<Order> currentMonthRtoRefundOrders = orderRepository.selectAllRefundOrderDatesBetween(currentMonthStartDate, currentMonthEndDate);
-
 
766
        Map<Integer, Long> currentMonthRtoRefundOrderMap = currentMonthRtoRefundOrders.stream().collect(Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingLong(x -> Math.round(x.getTotalAmount()))));
-
 
767
 
-
 
768
 
-
 
769
        List<ReturnOrderInfoModel> yesterdayReturnOrderInfoModels = returnOrderInfoRepository.selectAllByBetweenDate(previousDay.toLocalDate().atStartOfDay(), previousDay);
-
 
770
        Map<Integer, Long> yesterdayReturnOrderInfoModelMap = yesterdayReturnOrderInfoModels.stream().collect(Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingLong(x -> Math.round(x.getRefundAmount()))));
-
 
771
 
-
 
772
        List<Order> yesterdayRtoRefundOrders = orderRepository.selectAllRefundOrderDatesBetween(previousDay.toLocalDate().atStartOfDay(), previousDay);
-
 
773
        Map<Integer, Long> yesterdayRtoRefundOrderMap = yesterdayRtoRefundOrders.stream().collect(Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingLong(x -> Math.round(x.getTotalAmount()))));
-
 
774
 
-
 
775
        List<ReturnOrderInfoModel> dayBeforeYesterdayReturnOrderInfoModels = returnOrderInfoRepository.selectAllByBetweenDate(previousDay.toLocalDate().atStartOfDay().minusDays(1), previousDay.minusDays(1));
-
 
776
        Map<Integer, Long> dayBeforeYesterdayReturnOrderInfoModelMap = dayBeforeYesterdayReturnOrderInfoModels.stream().collect(Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingLong(x -> Math.round(x.getRefundAmount()))));
-
 
777
 
-
 
778
        List<Order> dayBeforeYesterdayRtoRefundOrders = orderRepository.selectAllRefundOrderDatesBetween(previousDay.toLocalDate().atStartOfDay().minusDays(1), previousDay.minusDays(1));
-
 
779
        Map<Integer, Long> dayBeforeYesterdayRtoRefundOrderMap = dayBeforeYesterdayRtoRefundOrders.stream().collect(Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingLong(x -> Math.round(x.getTotalAmount()))));
-
 
780
 
-
 
781
 
-
 
782
 
-
 
783
        //  last month return data
-
 
784
        YearMonth lastMonth = currentMonth.minusMonths(1);
754
        YearMonth lastMonth = currentMonth.minusMonths(1);
785
        String lastMonthStringValue = String.valueOf(lastMonth);
755
        String lastMonthStringValue = String.valueOf(lastMonth);
786
        LocalDateTime lastMontStartDate = lastMonth.atDay(1).atStartOfDay();
756
        LocalDateTime lastMontStartDate = lastMonth.atDay(1).atStartOfDay();
787
        LocalDateTime lastMonthEndDate = lastMonth.atEndOfMonth().atTime(23, 59, 59);
757
        LocalDateTime lastMonthEndDate = lastMonth.atEndOfMonth().atTime(23, 59, 59);
788
 
758
 
789
        List<ReturnOrderInfoModel> lastMonthReturnOrderInfoModels = returnOrderInfoRepository.selectAllByBetweenDate(lastMontStartDate, lastMonthEndDate);
-
 
790
        Map<Integer, Long> lastMonthPartnerReturnOrderInfoModelMap = lastMonthReturnOrderInfoModels.stream().collect(Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingLong(x -> Math.round(x.getRefundAmount()))));
-
 
791
 
-
 
792
        List<Order> lastMonthRtoRefundOrders = orderRepository.selectAllRefundOrderDatesBetween(lastMontStartDate, lastMonthEndDate);
-
 
793
        Map<Integer, Long> lastMonthRtoRefundOrderMap = lastMonthRtoRefundOrders.stream().collect(Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingLong(x -> Math.round(x.getTotalAmount()))));
-
 
794
 
-
 
795
 
-
 
796
    //  twoMonthsAgo return data
-
 
797
        YearMonth twoMonthsAgo = currentMonth.minusMonths(2);
759
        YearMonth twoMonthsAgo = currentMonth.minusMonths(2);
798
        String twoMonthAgoStringValue = String.valueOf(twoMonthsAgo);
760
        String twoMonthAgoStringValue = String.valueOf(twoMonthsAgo);
799
        LocalDateTime twoMonthsAgoStartDate = twoMonthsAgo.atDay(1).atStartOfDay();
761
        LocalDateTime twoMonthsAgoStartDate = twoMonthsAgo.atDay(1).atStartOfDay();
800
        LocalDateTime twoMonthsAgoEndDate = twoMonthsAgo.atEndOfMonth().atTime(23, 59, 59);
762
        LocalDateTime twoMonthsAgoEndDate = twoMonthsAgo.atEndOfMonth().atTime(23, 59, 59);
801
 
763
 
-
 
764
        LocalDateTime dayBeforeStart = previousDay.toLocalDate().atStartOfDay().minusDays(1);
-
 
765
        LocalDateTime dayBeforeEnd = previousDay.minusDays(1);
-
 
766
        LocalDateTime yesterdayStart = previousDay.toLocalDate().atStartOfDay();
-
 
767
 
-
 
768
        // Returns / RTO — already batched
-
 
769
        Map<Integer, Long> currentMonthPartnerReturnOrderInfoModelMap = returnOrderInfoRepository.selectAllByBetweenDate(currentMonthStartDate, currentMonthEndDate)
-
 
770
                .stream().collect(Collectors.groupingBy(ReturnOrderInfoModel::getRetailerId, Collectors.summingLong(x -> Math.round(x.getRefundAmount()))));
-
 
771
        Map<Integer, Long> currentMonthRtoRefundOrderMap = orderRepository.selectAllRefundOrderDatesBetween(currentMonthStartDate, currentMonthEndDate)
-
 
772
                .stream().collect(Collectors.groupingBy(Order::getRetailerId, Collectors.summingLong(x -> Math.round(x.getTotalAmount()))));
-
 
773
        Map<Integer, Long> yesterdayReturnOrderInfoModelMap = returnOrderInfoRepository.selectAllByBetweenDate(yesterdayStart, previousDay)
-
 
774
                .stream().collect(Collectors.groupingBy(ReturnOrderInfoModel::getRetailerId, Collectors.summingLong(x -> Math.round(x.getRefundAmount()))));
-
 
775
        Map<Integer, Long> yesterdayRtoRefundOrderMap = orderRepository.selectAllRefundOrderDatesBetween(yesterdayStart, previousDay)
-
 
776
                .stream().collect(Collectors.groupingBy(Order::getRetailerId, Collectors.summingLong(x -> Math.round(x.getTotalAmount()))));
-
 
777
        Map<Integer, Long> dayBeforeYesterdayReturnOrderInfoModelMap = returnOrderInfoRepository.selectAllByBetweenDate(dayBeforeStart, dayBeforeEnd)
-
 
778
                .stream().collect(Collectors.groupingBy(ReturnOrderInfoModel::getRetailerId, Collectors.summingLong(x -> Math.round(x.getRefundAmount()))));
-
 
779
        Map<Integer, Long> dayBeforeYesterdayRtoRefundOrderMap = orderRepository.selectAllRefundOrderDatesBetween(dayBeforeStart, dayBeforeEnd)
-
 
780
                .stream().collect(Collectors.groupingBy(Order::getRetailerId, Collectors.summingLong(x -> Math.round(x.getTotalAmount()))));
-
 
781
        Map<Integer, Long> lastMonthPartnerReturnOrderInfoModelMap = returnOrderInfoRepository.selectAllByBetweenDate(lastMontStartDate, lastMonthEndDate)
-
 
782
                .stream().collect(Collectors.groupingBy(ReturnOrderInfoModel::getRetailerId, Collectors.summingLong(x -> Math.round(x.getRefundAmount()))));
-
 
783
        Map<Integer, Long> lastMonthRtoRefundOrderMap = orderRepository.selectAllRefundOrderDatesBetween(lastMontStartDate, lastMonthEndDate)
-
 
784
                .stream().collect(Collectors.groupingBy(Order::getRetailerId, Collectors.summingLong(x -> Math.round(x.getTotalAmount()))));
802
        List<ReturnOrderInfoModel> twoMonthAgoReturnOrderInfoModels = returnOrderInfoRepository.selectAllByBetweenDate(twoMonthsAgoStartDate, twoMonthsAgoEndDate);
785
        Map<Integer, Long> twoMonthAgoPartnerReturnOrderInfoModelMap = returnOrderInfoRepository.selectAllByBetweenDate(twoMonthsAgoStartDate, twoMonthsAgoEndDate)
-
 
786
                .stream().collect(Collectors.groupingBy(ReturnOrderInfoModel::getRetailerId, Collectors.summingLong(x -> Math.round(x.getRefundAmount()))));
-
 
787
        Map<Integer, Long> twoMonthAgoRtoRefundOrderMap = orderRepository.selectAllRefundOrderDatesBetween(twoMonthsAgoStartDate, twoMonthsAgoEndDate)
803
        Map<Integer, Long> twoMonthAgoPartnerReturnOrderInfoModelMap = twoMonthAgoReturnOrderInfoModels.stream().collect(Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingLong(x -> Math.round(x.getRefundAmount()))));
788
                .stream().collect(Collectors.groupingBy(Order::getRetailerId, Collectors.summingLong(x -> Math.round(x.getTotalAmount()))));
-
 
789
 
-
 
790
        // ---- Batch pre-fetch everything else that was previously per-fofo ----
-
 
791
 
-
 
792
        // Auth hierarchy (BM / SalesManager / RBM L1+L2 fallback / ABM L1+L2+L3 fallback)
-
 
793
        Map<Integer, Integer> rbmL1Map = csService.getAuthUserIdsWithoutTicketAssigneeByFofoIds(ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L1, retailerIdSet);
-
 
794
        Map<Integer, Integer> rbmL2Map = csService.getAuthUserIdsWithoutTicketAssigneeByFofoIds(ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L2, retailerIdSet);
-
 
795
        Map<Integer, Integer> bmMap = csService.getAuthUserIdsWithoutTicketAssigneeByFofoIds(ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L2, retailerIdSet);
-
 
796
        Map<Integer, Integer> salesManagerMap = csService.getAuthUserIdsWithoutTicketAssigneeByFofoIds(ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L1, retailerIdSet);
-
 
797
        Map<Integer, Integer> abmL1Map = csService.getAuthUserIdsWithoutTicketAssigneeByFofoIds(ProfitMandiConstants.TICKET_CATEGORY_ABM, EscalationType.L1, retailerIdSet);
-
 
798
        Map<Integer, Integer> abmL2Map = csService.getAuthUserIdsWithoutTicketAssigneeByFofoIds(ProfitMandiConstants.TICKET_CATEGORY_ABM, EscalationType.L2, retailerIdSet);
-
 
799
        Map<Integer, Integer> abmL3Map = csService.getAuthUserIdsWithoutTicketAssigneeByFofoIds(ProfitMandiConstants.TICKET_CATEGORY_ABM, EscalationType.L3, retailerIdSet);
-
 
800
 
-
 
801
        Set<Integer> allAuthUserIds = new HashSet<>();
-
 
802
        for (Map<Integer, Integer> m : Arrays.asList(rbmL1Map, rbmL2Map, bmMap, salesManagerMap, abmL1Map, abmL2Map, abmL3Map)) {
-
 
803
            m.values().stream().filter(v -> v != null && v != 0).forEach(allAuthUserIds::add);
-
 
804
        }
-
 
805
        Map<Integer, AuthUser> authUserMap = allAuthUserIds.isEmpty() ? new HashMap<>()
-
 
806
                : authRepository.selectByIds(new ArrayList<>(allAuthUserIds)).stream()
-
 
807
                    .collect(Collectors.toMap(AuthUser::getId, u -> u, (a, b) -> a));
-
 
808
 
-
 
809
        // AST batch
-
 
810
        Set<Integer> astIds = customRetailers.values().stream()
-
 
811
                .map(CustomRetailer::getAstId).filter(id -> id != null && id != 0).collect(Collectors.toSet());
-
 
812
        Map<Integer, AST> astMap = astIds.isEmpty() ? new HashMap<>()
-
 
813
                : astRepository.selectByIds(new ArrayList<>(astIds)).stream()
-
 
814
                    .collect(Collectors.toMap(AST::getId, a -> a, (a, b) -> a));
-
 
815
 
-
 
816
        // FofoStore batch (replaces the two duplicate per-fofo calls)
-
 
817
        Map<Integer, FofoStore> fofoStoreMap = fofoStoreRepository.selectByRetailerIds(retailerIds).stream()
-
 
818
                .collect(Collectors.toMap(FofoStore::getId, s -> s, (a, b) -> a));
-
 
819
 
-
 
820
        // Users + wallet-creation dates
-
 
821
        Map<Integer, User> userMap = userRepository.selectByIds(retailerIds).stream()
-
 
822
                .collect(Collectors.toMap(User::getId, u -> u, (a, b) -> a));
-
 
823
        Map<Integer, LocalDateTime> walletFirstCreatedMap = userWalletHistoryRepository.selectFirstCreatedDatesForFofoIds(retailerIds);
-
 
824
 
-
 
825
        // Partner type for today
-
 
826
        Map<Integer, PartnerType> partnerTypeMap = partnerTypeChangeService.getTypesForFofoIds(retailerIds, LocalDate.now());
-
 
827
 
-
 
828
        // Monthly targets
-
 
829
        Map<Integer, Double> currentTargetMap = monthlyTargetRepository.selectByDateAndFofoIds(currentMonth, retailerIds).stream()
-
 
830
                .collect(Collectors.toMap(MonthlyTarget::getFofoId, MonthlyTarget::getPurchaseTarget, (a, b) -> a));
-
 
831
        Map<Integer, Double> lastTargetMap = monthlyTargetRepository.selectByDateAndFofoIds(lastMonth, retailerIds).stream()
-
 
832
                .collect(Collectors.toMap(MonthlyTarget::getFofoId, MonthlyTarget::getPurchaseTarget, (a, b) -> a));
-
 
833
        Map<Integer, Double> twoMonthAgoTargetMap = monthlyTargetRepository.selectByDateAndFofoIds(twoMonthsAgo, retailerIds).stream()
-
 
834
                .collect(Collectors.toMap(MonthlyTarget::getFofoId, MonthlyTarget::getPurchaseTarget, (a, b) -> a));
-
 
835
 
-
 
836
        // DRR target: RbmTargetService.calculateFofoIdTodayTarget always uses YearMonth.now() internally, regardless of
-
 
837
        // the date arg. On the 1st this differs from currentMonth (previous month) — preserve original semantics.
-
 
838
        Map<Integer, Double> drrTargetMap = YearMonth.now().equals(currentMonth) ? currentTargetMap
-
 
839
                : monthlyTargetRepository.selectByDateAndFofoIds(YearMonth.now(), retailerIds).stream()
-
 
840
                    .collect(Collectors.toMap(MonthlyTarget::getFofoId, MonthlyTarget::getPurchaseTarget, (a, b) -> a));
-
 
841
 
-
 
842
        // Monthly secondary (order value) — batched
-
 
843
        Map<Integer, Double> mtdSecondaryMap = orderRepository.selectOrderValueBetweenBillingDatesGroupByFofoId(retailerIds,
-
 
844
                startOfToday.withDayOfMonth(1), previousDay).stream()
-
 
845
                .collect(Collectors.toMap(IdAmountModel::getId, IdAmountModel::getAmount, (a, b) -> a));
-
 
846
        Map<Integer, Double> yesterDaySecondaryMap = orderRepository.selectOrderValueBetweenBillingDatesGroupByFofoId(retailerIds,
-
 
847
                yesterdayStart, previousDay).stream()
-
 
848
                .collect(Collectors.toMap(IdAmountModel::getId, IdAmountModel::getAmount, (a, b) -> a));
-
 
849
        Map<Integer, Double> dayBeforeSecondaryMap = orderRepository.selectOrderValueBetweenBillingDatesGroupByFofoId(retailerIds,
-
 
850
                dayBeforeStart, dayBeforeEnd).stream()
-
 
851
                .collect(Collectors.toMap(IdAmountModel::getId, IdAmountModel::getAmount, (a, b) -> a));
-
 
852
        Map<Integer, Double> lastMonthSecondaryMap = orderRepository.selectOrderValueBetweenBillingDatesGroupByFofoId(retailerIds,
-
 
853
                lastMontStartDate, lastMonthEndDate).stream()
-
 
854
                .collect(Collectors.toMap(IdAmountModel::getId, IdAmountModel::getAmount, (a, b) -> a));
-
 
855
        Map<Integer, Double> twoMonthAgoSecondaryMap = orderRepository.selectOrderValueBetweenBillingDatesGroupByFofoId(retailerIds,
-
 
856
                twoMonthsAgoStartDate, twoMonthsAgoEndDate).stream()
-
 
857
                .collect(Collectors.toMap(IdAmountModel::getId, IdAmountModel::getAmount, (a, b) -> a));
804
 
858
 
-
 
859
        // Tertiary MTD / last-month / two-months-ago (all-partners scan via fofoId=0)
-
 
860
        LocalDateTime now = LocalDateTime.now();
-
 
861
        Map<Integer, Double> mtdSaleTillYesterdayMap = fofoOrderItemRepository.selectSumMopGroupByRetailer(startOfToday.withDayOfMonth(1), previousDay, 0, false);
-
 
862
        Map<Integer, Double> lastMonthSaleMap = fofoOrderItemRepository.selectSumMopGroupByRetailer(lastMontStartDate, lastMonthEndDate, 0, false);
805
        List<Order> twoMonthRtoRefundOrders = orderRepository.selectAllRefundOrderDatesBetween(twoMonthsAgoStartDate, twoMonthsAgoEndDate);
863
        Map<Integer, Double> twoMonthAgoSaleMap = fofoOrderItemRepository.selectSumMopGroupByRetailer(twoMonthsAgoStartDate, twoMonthsAgoEndDate, 0, false);
-
 
864
 
-
 
865
        // Monthly activated-but-not-billed
-
 
866
        Map<Integer, Map<YearMonth, PartnerWiseActivatedNotBilledTotal>> activatedNotBilledByFofo = new HashMap<>();
-
 
867
        for (PartnerWiseActivatedNotBilledTotal t : activatedImeiRepository.getTotalMonthlyActivatedNotBilledForFofoIds(retailerIds, twoMonthsAgoStartDate)) {
-
 
868
            activatedNotBilledByFofo.computeIfAbsent(t.getFofoId(), k -> new HashMap<>())
-
 
869
                    .put(YearMonth.parse(t.getYearMonth()), t);
-
 
870
        }
-
 
871
 
-
 
872
        // Brand-wise tertiary MTD (per fofo → brand → amount)
806
        Map<Integer, Long> twoMonthAgoRtoRefundOrderMap = twoMonthRtoRefundOrders.stream().collect(Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingLong(x -> Math.round(x.getTotalAmount()))));
873
        Map<Integer, Map<String, Double>> brandTertiaryByFofo = fofoOrderItemRepository.selectSumAmountGroupByBrandForFofoIds(currentMonthStartDate, currentMonthEndDate, retailerIds);
807
 
874
 
-
 
875
        // Brand-wise secondary billed (MTD)
-
 
876
        Map<Integer, Map<String, Long>> brandBilledByFofo = new HashMap<>();
-
 
877
        for (BrandWiseModel m : orderRepository.selectAllBilledByCategoryOrderGroupByBrandFofoIds(retailerIds, currentMonthStartDate, currentMonthEndDate, Arrays.asList(10006, 10001))) {
-
 
878
            brandBilledByFofo.computeIfAbsent(m.getFofoId(), k -> new HashMap<>()).merge(m.getBrand(), m.getAmount(), Long::sum);
-
 
879
        }
-
 
880
        // Brand-wise returns + RTO returns (MTD)
-
 
881
        Map<Integer, Map<String, Double>> brandReturnByFofo = new HashMap<>();
-
 
882
        for (BrandWiseReturnInfo r : returnOrderInfoRepository.selectAllBrandWiseByBetweenDateForFofoIds(currentMonthStartDate, currentMonthEndDate.plusDays(1), retailerIds)) {
-
 
883
            brandReturnByFofo.computeIfAbsent(r.getRetailerId(), k -> new HashMap<>()).merge(r.getBrand(), r.getReturnAmount(), Double::sum);
-
 
884
        }
-
 
885
        Map<Integer, Map<String, Double>> brandRtoReturnByFofo = new HashMap<>();
-
 
886
        for (BrandWiseReturnInfo r : returnOrderInfoRepository.selectAllBrandWiseRTORefundByBetweenDateForFofoIds(currentMonthStartDate, currentMonthEndDate.plusDays(1), retailerIds)) {
-
 
887
            brandRtoReturnByFofo.computeIfAbsent(r.getRetailerId(), k -> new HashMap<>()).merge(r.getBrand(), r.getReturnAmount(), Double::sum);
-
 
888
        }
-
 
889
 
-
 
890
        // Active loans grouped per fofo, plus batched loanId → sum.
-
 
891
        // The single-fofo selectAllActiveLoan(fofoId) additionally filters pendingAmount > 0 — must preserve.
-
 
892
        Map<Integer, List<Loan>> activeLoansByFofo = loanRepository.selectAllActiveLoan().stream()
-
 
893
                .filter(l -> retailerIdSet.contains(l.getFofoId())
-
 
894
                        && l.getPendingAmount() != null
-
 
895
                        && l.getPendingAmount().doubleValue() > 0)
-
 
896
                .collect(Collectors.groupingBy(Loan::getFofoId));
-
 
897
        Set<Integer> loanIdsForSum = new HashSet<>();
-
 
898
        activeLoansByFofo.values().forEach(list -> list.forEach(l -> loanIdsForSum.add(l.getId())));
-
 
899
        defaultLoans.forEach(l -> loanIdsForSum.add(l.getId()));
-
 
900
        Map<Integer, Double> loanStatementSumByLoanId = loanStatementRepository.sumAmountByLoanIds(new ArrayList<>(loanIdsForSum));
-
 
901
 
-
 
902
        // Last order per fofo (batched)
-
 
903
        Map<Integer, Integer> lastOrderIdByFofo = orderRepository.getLastOrderByFofoIds(retailerIds);
-
 
904
        Set<Integer> lastOrderIds = lastOrderIdByFofo.values().stream().filter(id -> id != null && id != 0).collect(Collectors.toSet());
-
 
905
        Map<Integer, Order> lastOrderById = new HashMap<>();
-
 
906
        for (Integer oid : lastOrderIds) {
-
 
907
            Order o = orderRepository.selectById(oid);
-
 
908
            if (o != null) lastOrderById.put(oid, o);
-
 
909
        }
-
 
910
 
-
 
911
        // DRR precomputation — the two dates we ever call with
-
 
912
        long day1RemainingDays = rbmTargetService.getRemainingDaysInMonth(currentMonth.atDay(1));
-
 
913
        long todayRemainingDays = rbmTargetService.getRemainingDaysInMonth(startOfToday.toLocalDate());
808
 
914
 
809
        Map<Integer , String> assessmentMap = new HashMap<>();
915
        Map<Integer , String> assessmentMap = new HashMap<>();
810
        Map<Integer , String> zeroBillingMap = new HashMap<>();
916
        Map<Integer , String> zeroBillingMap = new HashMap<>();
811
        Map<Integer , Float> billingNeededMap = new HashMap<>();
917
        Map<Integer , Float> billingNeededMap = new HashMap<>();
812
        Map<Integer , Integer> countAMap = new HashMap<>();
918
        Map<Integer , Integer> countAMap = new HashMap<>();
813
 
-
 
814
        Map<Integer , BIRetailerModel> biRetailerModelMap = new HashMap<>();
919
        Map<Integer , BIRetailerModel> biRetailerModelMap = new HashMap<>();
815
 
-
 
816
        Map<Integer , FofoInvestmentModel> biInvestmentModelMap = new HashMap<>();
920
        Map<Integer , FofoInvestmentModel> biInvestmentModelMap = new HashMap<>();
817
 
-
 
818
        Map<Integer, Map<YearMonth, BiSecondaryModel>> allRetailerMonthlyData = new HashMap<>();
921
        Map<Integer, Map<YearMonth, BiSecondaryModel>> allRetailerMonthlyData = new HashMap<>();
819
 
-
 
820
        Map<Integer,Double> fofoTotalStockPriceMap = new HashMap<>();
922
        Map<Integer,Double> fofoTotalStockPriceMap = new HashMap<>();
821
 
-
 
822
        Map<Integer,Map<String, BrandStockPrice>> fofoBrandStockPriceMap = new HashMap<>();
923
        Map<Integer,Map<String, BrandStockPrice>> fofoBrandStockPriceMap = new HashMap<>();
823
 
-
 
824
        Map<Integer,Long> fofoTotalMtdSecondaryMap = new HashMap<>();
924
        Map<Integer,Long> fofoTotalMtdSecondaryMap = new HashMap<>();
825
 
-
 
826
        Map<Integer,Long> fofoYesterdaySecondaryMap = new HashMap<>();
925
        Map<Integer,Long> fofoYesterdaySecondaryMap = new HashMap<>();
827
 
-
 
828
        Map<Integer,Long> fofoDayBeforeYesterdaySecondaryMap = new HashMap<>();
926
        Map<Integer,Long> fofoDayBeforeYesterdaySecondaryMap = new HashMap<>();
829
 
-
 
830
        Map<Integer,Map<String, Long>> fofoBrandWiseMtdSecondaryMap = new HashMap<>();
927
        Map<Integer,Map<String, Long>> fofoBrandWiseMtdSecondaryMap = new HashMap<>();
831
 
-
 
832
        Map<Integer,Double> fofoTotalMtdTertiaryMap = new HashMap<>();
928
        Map<Integer,Double> fofoTotalMtdTertiaryMap = new HashMap<>();
833
 
-
 
834
        Map<Integer,Map<String, Double>> fofoBrandMtdTertiaryMap = new HashMap<>();
929
        Map<Integer,Map<String, Double>> fofoBrandMtdTertiaryMap = new HashMap<>();
835
 
930
 
836
        for(Integer fofoId: retailerIds){
931
        for (Integer fofoId : retailerIds) {
-
 
932
            // resolve auth-user names from batched maps
837
            String rbmName = "";
933
            String rbmName = "";
838
            int rbmL1 = csService.getAuthUserIdWithoutTicketAssignee(ProfitMandiConstants.TICKET_CATEGORY_RBM,EscalationType.L1,fofoId);
934
            int rbmL1 = rbmL1Map.getOrDefault(fofoId, 0);
839
            if(rbmL1 != 0){
935
            if (rbmL1 != 0 && authUserMap.get(rbmL1) != null) {
840
                 rbmName = authRepository.selectById(rbmL1).getFullName();
936
                rbmName = authUserMap.get(rbmL1).getFullName();
841
            }else {
937
            } else {
842
                int rbmL2 = csService.getAuthUserIdWithoutTicketAssignee(ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L2, fofoId);
938
                int rbmL2 = rbmL2Map.getOrDefault(fofoId, 0);
843
                if(rbmL2 != 0){
939
                if (rbmL2 != 0 && authUserMap.get(rbmL2) != null) {
844
                    rbmName = authRepository.selectById(rbmL2).getFullName();
940
                    rbmName = authUserMap.get(rbmL2).getFullName();
845
                }
941
                }
846
            }
942
            }
847
            String bmName ="";
943
            String bmName = "";
848
            int bmId = csService.getAuthUserIdWithoutTicketAssignee(ProfitMandiConstants.TICKET_CATEGORY_SALES,EscalationType.L2,fofoId);
944
            int bmId = bmMap.getOrDefault(fofoId, 0);
849
            if(bmId !=0){
945
            if (bmId != 0 && authUserMap.get(bmId) != null) {
850
                bmName = authRepository.selectById(bmId).getFullName();
946
                bmName = authUserMap.get(bmId).getFullName();
851
            }
947
            }
852
 
-
 
853
            int managerId = csService.getAuthUserIdWithoutTicketAssignee(ProfitMandiConstants.TICKET_CATEGORY_SALES,EscalationType.L1,fofoId);
948
            int managerId = salesManagerMap.getOrDefault(fofoId, 0);
854
            String managerName = " ";
949
            String managerName;
855
            LOGGER.info("managerId {}",managerId);
950
            if (managerId != 0 && authUserMap.get(managerId) != null) {
856
            if(managerId != 0){
-
 
857
                 managerName = authRepository.selectById(managerId).getFullName();
951
                managerName = authUserMap.get(managerId).getFullName();
858
            }else {
952
            } else {
859
                managerName = bmName;
953
                managerName = bmName;
860
            }
954
            }
861
            String abmName ="";
955
            String abmName = "";
862
            int abmId = csService.getAuthUserIdWithoutTicketAssignee(ProfitMandiConstants.TICKET_CATEGORY_ABM,EscalationType.L1,fofoId);
956
            int abmId = abmL1Map.getOrDefault(fofoId, 0);
863
            int abmL2Id = csService.getAuthUserIdWithoutTicketAssignee(ProfitMandiConstants.TICKET_CATEGORY_ABM,EscalationType.L2,fofoId);
957
            int abmL2Id = abmL2Map.getOrDefault(fofoId, 0);
864
            int abmL3Id = csService.getAuthUserIdWithoutTicketAssignee(ProfitMandiConstants.TICKET_CATEGORY_ABM,EscalationType.L3,fofoId);
958
            int abmL3Id = abmL3Map.getOrDefault(fofoId, 0);
865
            if(abmId !=0){
959
            if (abmId != 0 && authUserMap.get(abmId) != null) {
866
                abmName = authRepository.selectById(abmId).getFullName();
960
                abmName = authUserMap.get(abmId).getFullName();
867
            }else if(abmL2Id != 0){
961
            } else if (abmL2Id != 0 && authUserMap.get(abmL2Id) != null) {
868
                abmName = authRepository.selectById(abmL2Id).getFullName();
962
                abmName = authUserMap.get(abmL2Id).getFullName();
869
            }else if(abmL3Id != 0){
963
            } else if (abmL3Id != 0 && authUserMap.get(abmL3Id) != null) {
870
                abmName = authRepository.selectById(abmL3Id).getFullName();
964
                abmName = authUserMap.get(abmL3Id).getFullName();
871
            }
965
            }
872
            AST ast = astRepository.selectById(customRetailers.get(fofoId).getAstId());
-
 
873
 
-
 
874
            LOGGER.info("fofoID--11 {}",fofoId);
-
 
875
            PartnerType partnerTypeThisMonth = partnerTypeChangeService.getTypeOnDate(fofoId, LocalDate.now());
-
 
876
 
966
 
877
//            generate retaile detail
967
            AST ast = astMap.get(customRetailers.get(fofoId).getAstId());
-
 
968
            PartnerType partnerTypeThisMonth = partnerTypeMap.get(fofoId);
878
 
969
 
879
            BIRetailerModel biRetailerModel = new BIRetailerModel();
970
            BIRetailerModel biRetailerModel = new BIRetailerModel();
880
            biRetailerModel.setBmName(bmName);
971
            biRetailerModel.setBmName(bmName);
881
            biRetailerModel.setCode(customRetailers.get(fofoId).getCode());
972
            biRetailerModel.setCode(customRetailers.get(fofoId).getCode());
882
            if(ast != null){
973
            biRetailerModel.setArea(ast != null ? ast.getArea() : "-");
-
 
974
 
883
                biRetailerModel.setArea(ast.getArea());
975
            FofoStore fofoStore = fofoStoreMap.get(fofoId);
884
            }else {
976
            String retailerStatus;
885
                biRetailerModel.setArea("-");
977
            if (fofoStore == null) {
886
            }
-
 
887
            String retailerStatus = "";
978
                retailerStatus = "-";
888
            FofoStore fofoStore1 = fofoStoreRepository.selectByRetailerId(fofoId);
-
 
889
            if(!fofoStore1.isActive()){
979
            } else if (!fofoStore.isActive()) {
890
                retailerStatus = "INACTIVE";
980
                retailerStatus = "INACTIVE";
891
            }else{
981
            } else {
892
                retailerStatus =  String.valueOf(fofoStore1.getActivationType());
982
                retailerStatus = String.valueOf(fofoStore.getActivationType());
893
            }
983
            }
894
            biRetailerModel.setCity(customRetailers.get(fofoId).getAddress().getCity());
984
            biRetailerModel.setCity(customRetailers.get(fofoId).getAddress().getCity());
895
            biRetailerModel.setStoreName(customRetailers.get(fofoId).getBusinessName());
985
            biRetailerModel.setStoreName(customRetailers.get(fofoId).getBusinessName());
896
            biRetailerModel.setStatus(retailerStatus);
986
            biRetailerModel.setStatus(retailerStatus);
897
            biRetailerModel.setCategory(String.valueOf(partnerTypeThisMonth));
987
            biRetailerModel.setCategory(String.valueOf(partnerTypeThisMonth));
898
            biRetailerModel.setSalesManager(managerName);
988
            biRetailerModel.setSalesManager(managerName);
899
            biRetailerModel.setRbm(rbmName);
989
            biRetailerModel.setRbm(rbmName);
900
            biRetailerModel.setAbm(abmName);
990
            biRetailerModel.setAbm(abmName);
-
 
991
            biRetailerModelMap.put(fofoId, biRetailerModel);
901
 
992
 
902
            biRetailerModelMap.put(fofoId,biRetailerModel);
-
 
903
 
-
 
904
 
-
 
905
//            generate secondary data
-
 
906
 
-
 
907
            List<PartnerWiseActivatedNotBilledTotal> partnerWiseActivatedNotBilledMonthlyTotals = activatedImeiRepository.getTotalMonthlyActivatedNotBilled(fofoId,twoMonthsAgoStartDate);
993
            Map<YearMonth, PartnerWiseActivatedNotBilledTotal> partnerWiseActivatedNotBilledTotalMap =
908
            Map<YearMonth , PartnerWiseActivatedNotBilledTotal> partnerWiseActivatedNotBilledTotalMap = partnerWiseActivatedNotBilledMonthlyTotals.stream().collect(Collectors.toMap(x-> YearMonth.parse(x.getYearMonth()),x->x));
-
 
909
 
-
 
910
//            this month secondary target
-
 
911
 
-
 
912
            double currentSecondaryTarget =  monthlyTargetRepository.selectByDateAndFofoId(currentMonth, fofoId) != null ? monthlyTargetRepository.selectByDateAndFofoId(currentMonth, fofoId).getPurchaseTarget() : 0;
-
 
913
 
-
 
914
 
-
 
915
            long currentMonthReturn = currentMonthPartnerReturnOrderInfoModelMap.getOrDefault(fofoId, 0L) + currentMonthRtoRefundOrderMap.getOrDefault(fofoId, 0L);
994
                    activatedNotBilledByFofo.getOrDefault(fofoId, new HashMap<>());
916
 
995
 
-
 
996
            // Current-month secondary
-
 
997
            double currentSecondaryTarget = currentTargetMap.getOrDefault(fofoId, 0d);
-
 
998
            long currentMonthReturn = currentMonthPartnerReturnOrderInfoModelMap.getOrDefault(fofoId, 0L)
-
 
999
                    + currentMonthRtoRefundOrderMap.getOrDefault(fofoId, 0L);
917
 
1000
 
918
            Map<Integer, Double> secondaryMtd = orderRepository.selectOrderValueBetweenBillingDatesGroupByFofoId(Arrays.asList(fofoId),
-
 
919
                    startOfToday.withDayOfMonth(1), previousDay).stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getAmount()));
-
 
920
 
-
 
921
 
-
 
922
            //yesterday secondary
-
 
923
            Map<Integer, Double> dayBeforeYesterdaySecondary = orderRepository.selectOrderValueBetweenBillingDatesGroupByFofoId(Arrays.asList(fofoId),
1001
            double dayBeforeYesterdayAfterReturnSecondary = dayBeforeSecondaryMap.getOrDefault(fofoId, 0d)
924
                    previousDay.toLocalDate().atStartOfDay().minusDays(1), previousDay.minusDays(1)).stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getAmount()));
-
 
925
            double dayBeforeYesterdayAfterReturnSecondary = dayBeforeYesterdaySecondary.getOrDefault(fofoId,0d) - (dayBeforeYesterdayReturnOrderInfoModelMap.getOrDefault(fofoId,0l) + dayBeforeYesterdayRtoRefundOrderMap.getOrDefault(fofoId,0l));
1002
                    - (dayBeforeYesterdayReturnOrderInfoModelMap.getOrDefault(fofoId, 0L) + dayBeforeYesterdayRtoRefundOrderMap.getOrDefault(fofoId, 0L));
926
            fofoDayBeforeYesterdaySecondaryMap.put(fofoId, (long) dayBeforeYesterdayAfterReturnSecondary);
1003
            fofoDayBeforeYesterdaySecondaryMap.put(fofoId, (long) dayBeforeYesterdayAfterReturnSecondary);
927
 
1004
 
928
 
-
 
929
            //day before secondary
-
 
930
            Map<Integer, Double> yesterDaySecondary = orderRepository.selectOrderValueBetweenBillingDatesGroupByFofoId(Arrays.asList(fofoId),
1005
            double yesterDayAfterReturnSecondary = yesterDaySecondaryMap.getOrDefault(fofoId, 0d)
931
                    previousDay.toLocalDate().atStartOfDay(), previousDay).stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getAmount()));
-
 
932
            double yesterDayAfterReturnSecondary = yesterDaySecondary.getOrDefault(fofoId,0d) - (yesterdayReturnOrderInfoModelMap.getOrDefault(fofoId,0l) + yesterdayRtoRefundOrderMap.getOrDefault(fofoId,0l));
1006
                    - (yesterdayReturnOrderInfoModelMap.getOrDefault(fofoId, 0L) + yesterdayRtoRefundOrderMap.getOrDefault(fofoId, 0L));
933
            fofoYesterdaySecondaryMap.put(fofoId, (long) yesterDayAfterReturnSecondary);
1007
            fofoYesterdaySecondaryMap.put(fofoId, (long) yesterDayAfterReturnSecondary);
934
 
1008
 
935
            double secondaryAchievedMtd = secondaryMtd.getOrDefault(fofoId, 0.0);
1009
            double secondaryAchievedMtd = mtdSecondaryMap.getOrDefault(fofoId, 0.0);
936
 
-
 
937
            double currentMonthNetSecondary = secondaryAchievedMtd - currentMonthReturn;
1010
            double currentMonthNetSecondary = secondaryAchievedMtd - currentMonthReturn;
938
 
-
 
939
            double currentMonthSecondaryPercent = currentSecondaryTarget == 0 ? 0.0 : Math.round(Math.abs((secondaryAchievedMtd / currentSecondaryTarget) * 100));
1011
            double currentMonthSecondaryPercent = currentSecondaryTarget == 0 ? 0.0
940
 
-
 
941
            double currentMonthUnbilled = partnerWiseActivatedNotBilledTotalMap.get(currentMonth) != null ? partnerWiseActivatedNotBilledTotalMap.get(currentMonth).getTotalUnbilledAmount() : 0d;
-
 
942
 
-
 
943
//          this month tertiary----------
-
 
944
 
-
 
945
            LocalDateTime now = LocalDateTime.now();
1012
                    : Math.round(Math.abs((secondaryAchievedMtd / currentSecondaryTarget) * 100));
946
            double todaySale = fofoOrderItemRepository.selectSumMopGroupByRetailer(startOfToday, now, fofoId, false).get(fofoId);
1013
            double currentMonthUnbilled = partnerWiseActivatedNotBilledTotalMap.get(currentMonth) != null
947
            double mtdSaleTillYesterDay = fofoOrderItemRepository.selectSumMopGroupByRetailer(startOfToday.withDayOfMonth(1), previousDay, fofoId, false).get(fofoId);
1014
                    ? partnerWiseActivatedNotBilledTotalMap.get(currentMonth).getTotalUnbilledAmount() : 0d;
948
            double mtdSale = mtdSaleTillYesterDay;
1015
            double mtdSale = mtdSaleTillYesterdayMap.getOrDefault(fofoId, 0d);
949
 
-
 
950
 
1016
 
951
//            last month secondary target
1017
            // Last month secondary
952
 
-
 
953
            double lastMonthSecondaryTarget = monthlyTargetRepository.selectByDateAndFofoId(lastMonth, fofoId) != null ?  monthlyTargetRepository.selectByDateAndFofoId(lastMonth, fofoId).getPurchaseTarget() : 0;
1018
            double lastMonthSecondaryTarget = lastTargetMap.getOrDefault(fofoId, 0d);
954
 
-
 
955
            long lastMonthReturn = (lastMonthPartnerReturnOrderInfoModelMap.getOrDefault(fofoId,0L) + lastMonthRtoRefundOrderMap.getOrDefault(fofoId,0L));
1019
            long lastMonthReturn = lastMonthPartnerReturnOrderInfoModelMap.getOrDefault(fofoId, 0L)
956
 
-
 
957
            Map<Integer, Double> lastMonthSecondary = orderRepository.selectOrderValueBetweenBillingDatesGroupByFofoId(Arrays.asList(fofoId),
-
 
958
                    lastMontStartDate, lastMonthEndDate).stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getAmount()));
1020
                    + lastMonthRtoRefundOrderMap.getOrDefault(fofoId, 0L);
959
 
-
 
960
            double lastMonthSecondaryAchieved = lastMonthSecondary.getOrDefault(fofoId, 0.0);
1021
            double lastMonthSecondaryAchieved = lastMonthSecondaryMap.getOrDefault(fofoId, 0.0);
961
 
-
 
962
            double lastMonthNetSecondary = lastMonthSecondaryAchieved - lastMonthReturn;
1022
            double lastMonthNetSecondary = lastMonthSecondaryAchieved - lastMonthReturn;
963
 
-
 
-
 
1023
            double lastMonthSecondaryPercent = lastMonthSecondaryTarget == 0 ? 0.0
964
            double lastMonthSecondaryPercent = lastMonthSecondaryTarget == 0 ? 0.0 : Math.round(Math.abs((lastMonthSecondaryAchieved / lastMonthSecondaryTarget) * 100));
1024
                    : Math.round(Math.abs((lastMonthSecondaryAchieved / lastMonthSecondaryTarget) * 100));
965
 
-
 
966
            double lastMonthUnbilled = partnerWiseActivatedNotBilledTotalMap.get(lastMonth) != null ? partnerWiseActivatedNotBilledTotalMap.get(lastMonth).getTotalUnbilledAmount() : 0d;
1025
            double lastMonthUnbilled = partnerWiseActivatedNotBilledTotalMap.get(lastMonth) != null
967
 
-
 
968
//           last month tertiary
-
 
969
            Double lastMonthSale = fofoOrderItemRepository.selectSumMopGroupByRetailer(
1026
                    ? partnerWiseActivatedNotBilledTotalMap.get(lastMonth).getTotalUnbilledAmount() : 0d;
970
                    lastMontStartDate, lastMonthEndDate, fofoId, false).get(fofoId);
1027
            double lastMonthSale = lastMonthSaleMap.getOrDefault(fofoId, 0d);
971
 
-
 
972
 
1028
 
973
//            two month ago secondary target
1029
            // Two months ago secondary
974
 
-
 
975
            double twoMonthAgoSecondaryTarget = monthlyTargetRepository.selectByDateAndFofoId(twoMonthsAgo, fofoId) != null ? monthlyTargetRepository.selectByDateAndFofoId(twoMonthsAgo, fofoId).getPurchaseTarget() : 0;
1030
            double twoMonthAgoSecondaryTarget = twoMonthAgoTargetMap.getOrDefault(fofoId, 0d);
976
 
-
 
977
            long twoMonthAgoReturn = (twoMonthAgoPartnerReturnOrderInfoModelMap.getOrDefault(fofoId,0L) + twoMonthAgoRtoRefundOrderMap.getOrDefault(fofoId,0L));
1031
            long twoMonthAgoReturn = twoMonthAgoPartnerReturnOrderInfoModelMap.getOrDefault(fofoId, 0L)
978
 
-
 
979
            Map<Integer, Double> twoMonthAgoSecondary = orderRepository.selectOrderValueBetweenBillingDatesGroupByFofoId(Arrays.asList(fofoId),
-
 
980
                    twoMonthsAgoStartDate, twoMonthsAgoEndDate).stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getAmount()));
1032
                    + twoMonthAgoRtoRefundOrderMap.getOrDefault(fofoId, 0L);
981
 
-
 
982
            double twoMonthAgoSecondaryAchieved = twoMonthAgoSecondary.getOrDefault(fofoId, 0.0);
1033
            double twoMonthAgoSecondaryAchieved = twoMonthAgoSecondaryMap.getOrDefault(fofoId, 0.0);
983
 
-
 
984
            double twoMonthAgoNetSecondary = twoMonthAgoSecondaryAchieved - twoMonthAgoReturn;
1034
            double twoMonthAgoNetSecondary = twoMonthAgoSecondaryAchieved - twoMonthAgoReturn;
985
 
-
 
-
 
1035
            double twoMonthAgoSecondaryPercent = twoMonthAgoSecondaryTarget == 0 ? 0.0
986
            double twoMonthAgoSecondaryPercent = twoMonthAgoSecondaryTarget == 0 ? 0.0 : Math.round(Math.abs((twoMonthAgoSecondaryAchieved / twoMonthAgoSecondaryTarget) * 100));
1036
                    : Math.round(Math.abs((twoMonthAgoSecondaryAchieved / twoMonthAgoSecondaryTarget) * 100));
987
 
-
 
988
            double twoMonthAgoUnbilled = partnerWiseActivatedNotBilledTotalMap.get(twoMonthsAgo) != null ? partnerWiseActivatedNotBilledTotalMap.get(twoMonthsAgo).getTotalUnbilledAmount() : 0d;
1037
            double twoMonthAgoUnbilled = partnerWiseActivatedNotBilledTotalMap.get(twoMonthsAgo) != null
989
 
-
 
990
//          second Month Tertiary
-
 
991
            double twoMonthAgoSale = fofoOrderItemRepository.selectSumMopGroupByRetailer(
1038
                    ? partnerWiseActivatedNotBilledTotalMap.get(twoMonthsAgo).getTotalUnbilledAmount() : 0d;
992
                    twoMonthsAgoStartDate, twoMonthsAgoEndDate, fofoId, false).get(fofoId);
1039
            double twoMonthAgoSale = twoMonthAgoSaleMap.getOrDefault(fofoId, 0d);
993
 
-
 
994
 
1040
 
995
            Map<YearMonth, BiSecondaryModel> monthlySecondaryModels = new HashMap<>();
1041
            Map<YearMonth, BiSecondaryModel> monthlySecondaryModels = new HashMap<>();
996
 
-
 
997
            BiSecondaryModel currentMonthSecondaryModel = new BiSecondaryModel(
1042
            monthlySecondaryModels.put(currentMonth, new BiSecondaryModel(
998
                    currentSecondaryTarget,
-
 
999
                    secondaryAchievedMtd,
-
 
1000
                    currentMonthReturn,
-
 
1001
                    currentMonthNetSecondary,
-
 
1002
                    currentMonthSecondaryPercent,
1043
                    currentSecondaryTarget, secondaryAchievedMtd, currentMonthReturn,
1003
                    mtdSale,
-
 
1004
                    currentMonthUnbilled // for now, unbilled tertiary value
1044
                    currentMonthNetSecondary, currentMonthSecondaryPercent, mtdSale, currentMonthUnbilled));
1005
            );
-
 
1006
 
-
 
1007
            BiSecondaryModel lastMonthSecondaryModel = new BiSecondaryModel(
1045
            monthlySecondaryModels.put(lastMonth, new BiSecondaryModel(
1008
                    lastMonthSecondaryTarget,
-
 
1009
                    lastMonthSecondaryAchieved,
1046
                    lastMonthSecondaryTarget, lastMonthSecondaryAchieved, lastMonthReturn,
1010
                    lastMonthReturn,
-
 
1011
                    lastMonthNetSecondary,
-
 
1012
                    lastMonthSecondaryPercent,
-
 
1013
                    lastMonthSale,
-
 
1014
                    lastMonthUnbilled // for now, unbilled tertiary value
1047
                    lastMonthNetSecondary, lastMonthSecondaryPercent, lastMonthSale, lastMonthUnbilled));
1015
            );
-
 
1016
 
-
 
1017
            BiSecondaryModel twoMonthAgoSecondaryModel = new BiSecondaryModel(
1048
            monthlySecondaryModels.put(twoMonthsAgo, new BiSecondaryModel(
1018
                    twoMonthAgoSecondaryTarget,
-
 
1019
                    twoMonthAgoSecondaryAchieved,
-
 
1020
                    twoMonthAgoReturn,
-
 
1021
                    twoMonthAgoNetSecondary,
-
 
1022
                    twoMonthAgoSecondaryPercent,
-
 
1023
                    twoMonthAgoSale,
-
 
1024
                    twoMonthAgoUnbilled // for now, unbilled tertiary value
1049
                    twoMonthAgoSecondaryTarget, twoMonthAgoSecondaryAchieved, twoMonthAgoReturn,
1025
            );
-
 
1026
 
-
 
1027
            monthlySecondaryModels.put(currentMonth, currentMonthSecondaryModel);
-
 
1028
            monthlySecondaryModels.put(lastMonth, lastMonthSecondaryModel);
-
 
1029
            monthlySecondaryModels.put(twoMonthsAgo, twoMonthAgoSecondaryModel);
1050
                    twoMonthAgoNetSecondary, twoMonthAgoSecondaryPercent, twoMonthAgoSale, twoMonthAgoUnbilled));
1030
 
-
 
1031
            allRetailerMonthlyData.put(fofoId, monthlySecondaryModels);
1051
            allRetailerMonthlyData.put(fofoId, monthlySecondaryModels);
1032
 
1052
 
1033
//            brandwiseStock value price
1053
            // Brand-wise stock value — still per-fofo (per-fofo pricing service, not batchable trivially)
1034
 
-
 
1035
            Map<String, BrandStockPrice> brandStockPriceMap = inventoryService.getBrandWiseStockValue(fofoId);
1054
            Map<String, BrandStockPrice> brandStockPriceMap = inventoryService.getBrandWiseStockValue(fofoId);
-
 
1055
            fofoBrandStockPriceMap.put(fofoId, brandStockPriceMap);
-
 
1056
            fofoTotalStockPriceMap.put(fofoId, brandStockPriceMap.values().stream().mapToDouble(BrandStockPrice::getTotalValue).sum());
1036
 
1057
 
1037
            fofoBrandStockPriceMap.put(fofoId,brandStockPriceMap);
-
 
1038
 
-
 
1039
            double totalStockPrice = brandStockPriceMap.values().stream().mapToDouble(x->x.getTotalValue()).sum();
1058
            Map<String, Double> brandMtdTertiaryAmount = brandTertiaryByFofo.getOrDefault(fofoId, new HashMap<>());
1040
 
-
 
1041
            fofoTotalStockPriceMap.put(fofoId,totalStockPrice);
1059
            fofoBrandMtdTertiaryMap.put(fofoId, brandMtdTertiaryAmount);
1042
 
-
 
1043
            Map<String, Double> brandMtdTertiaryAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(
1060
            fofoTotalMtdTertiaryMap.put(fofoId, brandMtdTertiaryAmount.values().stream().mapToDouble(Double::doubleValue).sum());
1044
                    currentMonthStartDate, currentMonthEndDate, fofoId);
-
 
1045
 
-
 
1046
 
1061
 
1047
            fofoBrandMtdTertiaryMap.put(fofoId,brandMtdTertiaryAmount);
1062
            Map<String, Long> brandWiseMtdSecondaryMap = brandBilledByFofo.getOrDefault(fofoId, new HashMap<>());
1048
 
-
 
1049
            double totalMtdTertiaryAmount = brandMtdTertiaryAmount.values().stream().mapToDouble(Double::doubleValue).sum();
1063
            Map<String, Double> brandWiseReturnInfoMap = brandReturnByFofo.getOrDefault(fofoId, new HashMap<>());
1050
 
-
 
1051
            fofoTotalMtdTertiaryMap.put(fofoId,totalMtdTertiaryAmount);
1064
            Map<String, Double> brandWiseRTOReturnInfoMap = brandRtoReturnByFofo.getOrDefault(fofoId, new HashMap<>());
1052
 
1065
 
1053
            List<BrandWiseModel> brandWiseMtdSecondary = orderRepository.selectAllBilledByCategoryOrderGroupByBrandFofoId(fofoId, currentMonthStartDate,currentMonthEndDate, Arrays.asList(10006,10001));
-
 
1054
            Map<String,Long> brandWiseMtdSecondaryMap = brandWiseMtdSecondary.stream().collect(Collectors.toMap(BrandWiseModel::getBrand,BrandWiseModel::getAmount));
-
 
1055
 
-
 
1056
            //retrunInfo
-
 
1057
            List<BrandWiseReturnInfo> brandWiseReturnInfos = returnOrderInfoRepository.selectAllBrandWiseByBetweenDate(currentMonthStartDate,currentMonthEndDate.plusDays(1),fofoId);
-
 
1058
            Map<String,Double> brandWiseReturnInfoMap = brandWiseReturnInfos.stream().collect(Collectors.toMap(BrandWiseReturnInfo::getBrand, x->x.getReturnAmount()));
-
 
1059
 
-
 
1060
            LOGGER.info("brandWiseReturnInfos {}",brandWiseReturnInfos);
-
 
1061
 
-
 
1062
            //Rto retrunInfo
-
 
1063
            List<BrandWiseReturnInfo> brandWiseRTOReturnInfos = returnOrderInfoRepository.selectAllBrandWiseRTORefundByBetweenDate(currentMonthStartDate,currentMonthEndDate.plusDays(1),fofoId);
-
 
1064
            Map<String,Double> brandWiseRTOReturnInfoMap = brandWiseRTOReturnInfos.stream().collect(Collectors.toMap(BrandWiseReturnInfo::getBrand, x->x.getReturnAmount()));
-
 
1065
 
-
 
1066
            // Step 1: Get union of all brand keys
-
 
1067
            Set<String> allBrands = new HashSet<>();
1066
            Set<String> allBrands = new HashSet<>();
1068
            allBrands.addAll(brandWiseMtdSecondaryMap.keySet());
1067
            allBrands.addAll(brandWiseMtdSecondaryMap.keySet());
1069
            allBrands.addAll(brandWiseReturnInfoMap.keySet());
1068
            allBrands.addAll(brandWiseReturnInfoMap.keySet());
1070
            allBrands.addAll(brandWiseRTOReturnInfoMap.keySet());
1069
            allBrands.addAll(brandWiseRTOReturnInfoMap.keySet());
1071
 
-
 
1072
            // Step 2: Calculate net secondary for each brand
-
 
1073
            Map<String, Long> brandWiseMtdNetSecondaryMap = new HashMap<>();
1070
            Map<String, Long> brandWiseMtdNetSecondaryMap = new HashMap<>();
1074
 
-
 
1075
            for (String brand : allBrands) {
1071
            for (String brand : allBrands) {
1076
                Long billedAmount = brandWiseMtdSecondaryMap.getOrDefault(brand, 0L);
1072
                long billedAmount = brandWiseMtdSecondaryMap.getOrDefault(brand, 0L);
1077
                Double returnAmount = brandWiseReturnInfoMap.getOrDefault(brand, 0d);
1073
                double returnAmount = brandWiseReturnInfoMap.getOrDefault(brand, 0d);
1078
                Double rtoReturnAmount = brandWiseRTOReturnInfoMap.getOrDefault(brand, 0d);
1074
                double rtoReturnAmount = brandWiseRTOReturnInfoMap.getOrDefault(brand, 0d);
1079
 
-
 
1080
                double netSecondary = billedAmount - (returnAmount + rtoReturnAmount);
1075
                brandWiseMtdNetSecondaryMap.put(brand, Math.round(billedAmount - (returnAmount + rtoReturnAmount)));
1081
                brandWiseMtdNetSecondaryMap.put(brand, (long) Math.round(netSecondary));
-
 
1082
            }
1076
            }
-
 
1077
            fofoBrandWiseMtdSecondaryMap.put(fofoId, brandWiseMtdNetSecondaryMap);
-
 
1078
            fofoTotalMtdSecondaryMap.put(fofoId, brandWiseMtdNetSecondaryMap.values().stream().mapToLong(Long::longValue).sum());
1083
 
1079
 
-
 
1080
            // Investment info
-
 
1081
            PartnerDailyInvestment pdi = partnerDailyInvestmentMap.get(fofoId);
-
 
1082
            float shortInvestment = pdi != null ? pdi.getShortInvestment() : 0f;
-
 
1083
            float agreedInvestment = pdi != null ? pdi.getMinInvestment() : 0f;
-
 
1084
            float investmentLevel = pdi != null ? Math.abs(((shortInvestment - agreedInvestment) / agreedInvestment) * 100) : 0f;
1084
 
1085
 
1085
            LOGGER.info("brandWiseMtdNetSecondaryMap {}",brandWiseMtdNetSecondaryMap );
-
 
1086
 
-
 
1087
 
-
 
1088
            fofoBrandWiseMtdSecondaryMap.put(fofoId,brandWiseMtdNetSecondaryMap);
-
 
1089
 
-
 
1090
            long mtdTotalSecondary = brandWiseMtdNetSecondaryMap.values().stream().mapToLong(Long::longValue).sum();
-
 
1091
 
-
 
1092
            fofoTotalMtdSecondaryMap.put(fofoId,mtdTotalSecondary);
-
 
1093
 
-
 
1094
            //            generate investment info
-
 
1095
            FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
-
 
1096
            float shortInvestment = partnerDailyInvestmentMap.get(fofoId) != null ? partnerDailyInvestmentMap.get(fofoId).getShortInvestment() : 0f;
-
 
1097
            float agreedInvestment = partnerDailyInvestmentMap.get(fofoId) != null ? partnerDailyInvestmentMap.get(fofoId).getMinInvestment() : 0f;
-
 
1098
            float investmentLevel = partnerDailyInvestmentMap.get(fofoId) != null
-
 
1099
                    ? Math.abs(((shortInvestment - agreedInvestment) / agreedInvestment) * 100)
-
 
1100
                    : 0f;
-
 
1101
 
-
 
1102
 
-
 
1103
            List<Loan> fofoDefaultLoans = new ArrayList<>();
-
 
1104
            if(defaultLoanMap != null){
-
 
1105
                 fofoDefaultLoans  =  defaultLoanMap.get(fofoId);
1086
            List<Loan> fofoDefaultLoans = defaultLoanMap.get(fofoId);
1106
                LOGGER.info("fofoDefaultLoans {}",fofoDefaultLoans);
-
 
1107
            }
-
 
1108
 
-
 
1109
            float defaultLoanAmount = 0f;
1087
            float defaultLoanAmount = 0f;
1110
            if(fofoDefaultLoans != null ){
1088
            if (fofoDefaultLoans != null) {
1111
                if (!fofoDefaultLoans.isEmpty()) {
-
 
1112
                    for (Loan entry : fofoDefaultLoans) {
1089
                for (Loan entry : fofoDefaultLoans) {
1113
 
-
 
1114
                        List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(entry.getId());
1090
                    double amount = loanStatementSumByLoanId.getOrDefault(entry.getId(), 0d);
1115
 
-
 
1116
                        double amount = loanStatements.stream().map(x -> x.getAmount()).collect(Collectors.summingDouble(x -> x.doubleValue()));
-
 
1117
 
-
 
1118
                        defaultLoanAmount += amount;
1091
                    defaultLoanAmount += amount;
1119
                    }
-
 
1120
                }
1092
                }
1121
            }
1093
            }
1122
 
-
 
1123
            List<Loan> activeLoans = loanRepository.selectAllActiveLoan(fofoId);
1094
            List<Loan> activeLoans = activeLoansByFofo.getOrDefault(fofoId, Collections.emptyList());
1124
 
-
 
1125
            LOGGER.info("activeLoans- {}",activeLoans);
-
 
1126
 
-
 
1127
            float activeLoan = 0f;
1095
            float activeLoan = 0f;
1128
 
-
 
1129
            for (Loan entry : activeLoans) {
1096
            for (Loan entry : activeLoans) {
1130
 
-
 
1131
                List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(entry.getId());
1097
                double pendingAmount = loanStatementSumByLoanId.getOrDefault(entry.getId(), 0d);
1132
 
-
 
1133
                double pendingAmount = loanStatements.stream().map(x -> x.getAmount()).collect(Collectors.summingDouble(x -> x.doubleValue()));
-
 
1134
 
-
 
1135
                activeLoan += pendingAmount;
1098
                activeLoan += pendingAmount;
1136
            }
1099
            }
1137
 
1100
 
1138
            float poValue = partnerDailyInvestmentMap.get(fofoId) != null ?  partnerDailyInvestmentMap.get(fofoId).getUnbilledAmount() : 0f;
1101
            float poValue = pdi != null ? pdi.getUnbilledAmount() : 0f;
1139
 
-
 
1140
            float poAndBilledValue = (float) (currentMonthNetSecondary + poValue);
1102
            float poAndBilledValue = (float) (currentMonthNetSecondary + poValue);
1141
 
1103
 
1142
            double monthDay1Drr = rbmTargetService.calculateFofoIdTodayTarget(fofoId,0d,currentMonth.atDay(1));
1104
            // DRR — inlined equivalent of RbmTargetService.calculateFofoIdTodayTarget.
-
 
1105
            // Note: original always looks up YearMonth.now() target (not currentMonth). On the 1st these differ.
-
 
1106
            double drrTarget = drrTargetMap.getOrDefault(fofoId, 0d);
1143
            double todayRequiredDrr = 0;
1107
            double monthDay1Drr = 0d;
1144
 
-
 
1145
            if(monthDay1Drr != 0d){
1108
            if (drrTarget != 0d) {
-
 
1109
                double remainingTarget = drrTarget;
1146
                todayRequiredDrr = rbmTargetService.calculateFofoIdTodayTarget(fofoId, currentMonthNetSecondary,startOfToday.toLocalDate());
1110
                monthDay1Drr = day1RemainingDays == 0 ? remainingTarget : (int) Math.ceil(remainingTarget / day1RemainingDays);
1147
            }
1111
            }
-
 
1112
            double todayRequiredDrr = 0d;
-
 
1113
            if (monthDay1Drr != 0d) {
-
 
1114
                double remainingTarget = drrTarget - currentMonthNetSecondary;
-
 
1115
                todayRequiredDrr = todayRemainingDays == 0 ? remainingTarget : (int) Math.ceil(remainingTarget / todayRemainingDays);
1148
 
1116
            }
1149
            double gotDrrPercent = (todayRequiredDrr / monthDay1Drr) * 100;
1117
            double gotDrrPercent = monthDay1Drr == 0 ? 0 : (todayRequiredDrr / monthDay1Drr) * 100;
1150
 
-
 
1151
            long drrPercentDisplay = Math.round(Math.abs(gotDrrPercent));
1118
            long drrPercentDisplay = Math.round(Math.abs(gotDrrPercent));
1152
 
1119
 
1153
 
-
 
1154
            int orderId = orderRepository.getLastOrderByFofoId(fofoId);
1120
            int orderId = lastOrderIdByFofo.getOrDefault(fofoId, 0);
1155
 
-
 
1156
            // Determine alert level
-
 
1157
            String alertLevel = "-";
1121
            String alertLevel = "-";
1158
            int lastPurchaseDays = 0;
1122
            int lastPurchaseDays = 0;
1159
            if (orderId != 0) {
1123
            if (orderId != 0) {
1160
                Order order = orderRepository.selectById(orderId);
1124
                Order order = lastOrderById.get(orderId);
1161
 
-
 
1162
                LOGGER.info("last billing order - {}",order);
1125
                if (order != null) {
1163
 
-
 
1164
                // Calculate the number of days since the last purchase (billing)
-
 
1165
                lastPurchaseDays = (int) Duration.between(order.getCreateTimestamp().plusDays(1), LocalDateTime.now()).toDays();
1126
                    lastPurchaseDays = (int) Duration.between(order.getCreateTimestamp().plusDays(1), LocalDateTime.now()).toDays();
1166
 
-
 
1167
                if (lastPurchaseDays >= 11) {
-
 
1168
                    alertLevel = "Alert for Management";
1127
                    if (lastPurchaseDays >= 11) alertLevel = "Alert for Management";
1169
                } else if (lastPurchaseDays >= 10) {
-
 
1170
                    alertLevel = " Alert for RSM/SH";
1128
                    else if (lastPurchaseDays >= 10) alertLevel = " Alert for RSM/SH";
1171
                } else if (lastPurchaseDays >= 7) {
-
 
1172
                    alertLevel = "Must be Billed";
1129
                    else if (lastPurchaseDays >= 7) alertLevel = "Must be Billed";
1173
                } else if (lastPurchaseDays >= 3) {
-
 
1174
                    alertLevel = "OK";
-
 
1175
                } else {
-
 
1176
                    alertLevel = "OK";
1130
                    else alertLevel = "OK";
1177
                }
1131
                }
1178
            }
1132
            }
1179
 
1133
 
1180
            //investment modal set all related value
-
 
1181
            FofoInvestmentModel fofoInvestmentModel = new FofoInvestmentModel();
1134
            FofoInvestmentModel fofoInvestmentModel = new FofoInvestmentModel();
1182
 
-
 
1183
            fofoInvestmentModel.setCounterPotential(fofoStore.getCounterPotential());
1135
            fofoInvestmentModel.setCounterPotential(fofoStore != null ? fofoStore.getCounterPotential() : 0);
1184
            fofoInvestmentModel.setShortInvestment(shortInvestment);
1136
            fofoInvestmentModel.setShortInvestment(shortInvestment);
1185
            fofoInvestmentModel.setDefaultLoan(defaultLoanAmount);
1137
            fofoInvestmentModel.setDefaultLoan(defaultLoanAmount);
1186
            fofoInvestmentModel.setInvestmentLevel(investmentLevel);
1138
            fofoInvestmentModel.setInvestmentLevel(investmentLevel);
1187
            fofoInvestmentModel.setActiveLoan(activeLoan);
1139
            fofoInvestmentModel.setActiveLoan(activeLoan);
1188
            fofoInvestmentModel.setPoValue(poValue);
1140
            fofoInvestmentModel.setPoValue(poValue);
1189
            fofoInvestmentModel.setPoAndBilled(poAndBilledValue);
1141
            fofoInvestmentModel.setPoAndBilled(poAndBilledValue);
1190
            fofoInvestmentModel.setAgreedInvestment(agreedInvestment);
1142
            fofoInvestmentModel.setAgreedInvestment(agreedInvestment);
1191
            fofoInvestmentModel.setWallet(partnerDailyInvestmentMap.get(fofoId) != null ? partnerDailyInvestmentMap.get(fofoId).getWalletAmount() : 0);
1143
            fofoInvestmentModel.setWallet(pdi != null ? pdi.getWalletAmount() : 0);
1192
            fofoInvestmentModel.setMonthBeginingDrr(monthDay1Drr);
1144
            fofoInvestmentModel.setMonthBeginingDrr(monthDay1Drr);
1193
            fofoInvestmentModel.setRequiredDrr(todayRequiredDrr);
1145
            fofoInvestmentModel.setRequiredDrr(todayRequiredDrr);
1194
            fofoInvestmentModel.setDrrPercent(drrPercentDisplay);
1146
            fofoInvestmentModel.setDrrPercent(drrPercentDisplay);
1195
            fofoInvestmentModel.setLastBillingDone(lastPurchaseDays);
1147
            fofoInvestmentModel.setLastBillingDone(lastPurchaseDays);
1196
            fofoInvestmentModel.setSlab(alertLevel);
1148
            fofoInvestmentModel.setSlab(alertLevel);
1197
 
-
 
1198
            biInvestmentModelMap.put(fofoId, fofoInvestmentModel);
1149
            biInvestmentModelMap.put(fofoId, fofoInvestmentModel);
1199
                String assessment = "";
-
 
1200
                if(defaultLoanAmount < 0 ){
-
 
1201
                    assessment = "Loan Default";
-
 
1202
                }else if(investmentLevel <= 75 && defaultLoanAmount >= 0){
-
 
1203
                    assessment = "Low Invest";
-
 
1204
                }else {
-
 
1205
                    assessment = "-";
-
 
1206
                }
-
 
1207
                assessmentMap.put(fofoId,assessment);
-
 
1208
 
-
 
1209
                String zeroBilling = "";
-
 
1210
                if(currentMonthNetSecondary <= 100000 ){
-
 
1211
                    zeroBilling = "Zero Billing";
-
 
1212
                }else {
-
 
1213
                    zeroBilling = "-";
-
 
1214
                }
-
 
1215
                zeroBillingMap.put(fofoId,zeroBilling);
-
 
1216
 
-
 
1217
                float billingNeeded = 0f;
-
 
1218
                if(drrPercentDisplay >= 110 && todayRequiredDrr > 0 ){
-
 
1219
                    billingNeeded = (float) todayRequiredDrr;
-
 
1220
                }else {
-
 
1221
                    billingNeeded = 0f;
-
 
1222
                }
-
 
1223
                billingNeededMap.put(fofoId,billingNeeded);
-
 
1224
 
-
 
1225
                int counta = 0;
-
 
1226
                if(defaultLoanAmount > 0 || investmentLevel <= 75 || currentMonthNetSecondary <= 100000 || drrPercentDisplay >= 110 ){
-
 
1227
                    counta = 1;
-
 
1228
                }else {
-
 
1229
                    counta = 0;
-
 
1230
                }
-
 
1231
                countAMap.put(fofoId,counta);
-
 
1232
 
1150
 
-
 
1151
            String assessment;
-
 
1152
            if (defaultLoanAmount < 0) assessment = "Loan Default";
-
 
1153
            else if (investmentLevel <= 75 && defaultLoanAmount >= 0) assessment = "Low Invest";
-
 
1154
            else assessment = "-";
-
 
1155
            assessmentMap.put(fofoId, assessment);
-
 
1156
            zeroBillingMap.put(fofoId, currentMonthNetSecondary <= 100000 ? "Zero Billing" : "-");
-
 
1157
            billingNeededMap.put(fofoId, drrPercentDisplay >= 110 && todayRequiredDrr > 0 ? (float) todayRequiredDrr : 0f);
-
 
1158
            countAMap.put(fofoId, (defaultLoanAmount > 0 || investmentLevel <= 75 || currentMonthNetSecondary <= 100000 || drrPercentDisplay >= 110) ? 1 : 0);
1233
        }
1159
        }
1234
 
1160
 
1235
        LOGGER.info("Total BI Retailers processed: {}", biRetailerModelMap.size());
1161
        LOGGER.info("Total BI Retailers processed: {}", biRetailerModelMap.size());
1236
 
1162
 
1237
        //generate excel and sent to mail
1163
        //generate excel and sent to mail
Line 1273... Line 1199...
1273
        headerGroup.add(headers1);
1199
        headerGroup.add(headers1);
1274
        headerGroup.add(headers2);
1200
        headerGroup.add(headers2);
1275
 
1201
 
1276
 
1202
 
1277
        List<List<?>> rows = new ArrayList<>();
1203
        List<List<?>> rows = new ArrayList<>();
-
 
1204
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
1278
        for (Map.Entry<Integer, BIRetailerModel> entry : biRetailerModelMap.entrySet()) {
1205
        for (Map.Entry<Integer, BIRetailerModel> entry : biRetailerModelMap.entrySet()) {
1279
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
-
 
1280
            Integer fofoId = entry.getKey();
1206
            Integer fofoId = entry.getKey();
1281
            User user = userRepository.selectById(fofoId);
1207
            User user = userMap.get(fofoId);
1282
            LocalDateTime walletCreationDate = userWalletHistoryRepository.selectFirstCreatedDate(fofoId);
1208
            LocalDateTime walletCreationDate = walletFirstCreatedMap.get(fofoId);
1283
            if(walletCreationDate == null){
1209
            if (walletCreationDate == null && user != null) {
1284
                walletCreationDate = user.getCreateTimestamp();
1210
                walletCreationDate = user.getCreateTimestamp();
1285
            }
1211
            }
1286
            BIRetailerModel retailer = entry.getValue();
1212
            BIRetailerModel retailer = entry.getValue();
1287
 
1213
 
1288
            Map<YearMonth, BiSecondaryModel> monthlyData = allRetailerMonthlyData.get(fofoId);
1214
            Map<YearMonth, BiSecondaryModel> monthlyData = allRetailerMonthlyData.get(fofoId);
Line 1300... Line 1226...
1300
                    billingNeededMap.get(fofoId),
1226
                    billingNeededMap.get(fofoId),
1301
                    countAMap.get(fofoId),
1227
                    countAMap.get(fofoId),
1302
                    retailer.getBmName(),
1228
                    retailer.getBmName(),
1303
                    fofoId ,
1229
                    fofoId ,
1304
                    "https://partners.smartdukaan.com/partnerPerformance?fofoId="+fofoId,
1230
                    "https://partners.smartdukaan.com/partnerPerformance?fofoId="+fofoId,
1305
                    walletCreationDate.format(formatter),
1231
                    walletCreationDate != null ? walletCreationDate.format(formatter) : "-",
1306
                    user.getCreateTimestamp() != null ? (user.getCreateTimestamp()).format(formatter) : "-",
1232
                    (user != null && user.getCreateTimestamp() != null) ? user.getCreateTimestamp().format(formatter) : "-",
1307
                    retailer.getCode(),
1233
                    retailer.getCode(),
1308
                    retailer.getArea(),
1234
                    retailer.getArea(),
1309
                    retailer.getCity(),
1235
                    retailer.getCity(),
1310
                    retailer.getStoreName(),
1236
                    retailer.getStoreName(),
1311
                    retailer.getStatus(),
1237
                    retailer.getStatus(),