Subversion Repositories SmartDukaan

Rev

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

Rev 34606 Rev 34619
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.CustomRetailer;
5
import com.spice.profitmandi.common.model.CustomRetailer;
5
import com.spice.profitmandi.common.model.ProfitMandiConstants;
6
import com.spice.profitmandi.common.model.ProfitMandiConstants;
-
 
7
import com.spice.profitmandi.common.util.FileUtil;
-
 
8
import com.spice.profitmandi.common.util.FormattingUtils;
-
 
9
import com.spice.profitmandi.common.util.Utils;
6
import com.spice.profitmandi.dao.cart.CartService;
10
import com.spice.profitmandi.dao.cart.CartService;
7
import com.spice.profitmandi.dao.cart.SmartCartService;
11
import com.spice.profitmandi.dao.cart.SmartCartService;
8
import com.spice.profitmandi.dao.entity.auth.AuthUser;
12
import com.spice.profitmandi.dao.entity.auth.AuthUser;
9
import com.spice.profitmandi.dao.entity.fofo.*;
13
import com.spice.profitmandi.dao.entity.fofo.*;
10
import com.spice.profitmandi.dao.entity.logistics.AST;
14
import com.spice.profitmandi.dao.entity.logistics.AST;
11
import com.spice.profitmandi.dao.entity.logistics.ASTRepository;
15
import com.spice.profitmandi.dao.entity.logistics.ASTRepository;
12
import com.spice.profitmandi.dao.entity.logistics.AreaRepository;
16
import com.spice.profitmandi.dao.entity.logistics.AreaRepository;
13
import com.spice.profitmandi.dao.entity.transaction.Loan;
17
import com.spice.profitmandi.dao.entity.transaction.*;
14
import com.spice.profitmandi.dao.entity.transaction.Order;
-
 
15
import com.spice.profitmandi.dao.entity.transaction.Transaction;
-
 
16
import com.spice.profitmandi.dao.entity.user.User;
18
import com.spice.profitmandi.dao.entity.user.User;
17
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
19
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
-
 
20
import com.spice.profitmandi.dao.enumuration.transaction.LoanReferenceType;
18
import com.spice.profitmandi.dao.model.BIRetailerModel;
21
import com.spice.profitmandi.dao.model.BIRetailerModel;
19
import com.spice.profitmandi.dao.model.BiSecondaryModel;
22
import com.spice.profitmandi.dao.model.BiSecondaryModel;
-
 
23
import com.spice.profitmandi.dao.model.BrandWiseModel;
20
import com.spice.profitmandi.dao.model.ReturnOrderInfoModel;
24
import com.spice.profitmandi.dao.model.ReturnOrderInfoModel;
21
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
25
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
22
import com.spice.profitmandi.dao.repository.cs.CsService;
26
import com.spice.profitmandi.dao.repository.cs.CsService;
23
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
27
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
24
import com.spice.profitmandi.dao.repository.fofo.*;
28
import com.spice.profitmandi.dao.repository.fofo.*;
25
import com.spice.profitmandi.dao.repository.inventory.StateRepository;
29
import com.spice.profitmandi.dao.repository.inventory.StateRepository;
26
import com.spice.profitmandi.dao.repository.transaction.LoanRepository;
30
import com.spice.profitmandi.dao.repository.transaction.*;
27
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
-
 
28
import com.spice.profitmandi.dao.repository.transaction.ReturnOrderInfoRepository;
-
 
29
import com.spice.profitmandi.dao.repository.transaction.TransactionRepository;
-
 
30
import com.spice.profitmandi.dao.repository.user.UserRepository;
31
import com.spice.profitmandi.dao.repository.user.UserRepository;
-
 
32
import com.spice.profitmandi.service.inventory.InventoryService;
31
import com.spice.profitmandi.service.transaction.SDCreditService;
33
import com.spice.profitmandi.service.transaction.SDCreditService;
32
import com.spice.profitmandi.service.user.RetailerService;
34
import com.spice.profitmandi.service.user.RetailerService;
-
 
35
import com.spice.profitmandi.service.wallet.WalletService;
33
import in.shop2020.model.v1.order.OrderStatus;
36
import in.shop2020.model.v1.order.OrderStatus;
-
 
37
import in.shop2020.model.v1.order.WalletReferenceType;
-
 
38
import org.apache.commons.io.output.ByteArrayOutputStream;
34
import org.apache.logging.log4j.LogManager;
39
import org.apache.logging.log4j.LogManager;
35
import org.apache.logging.log4j.Logger;
40
import org.apache.logging.log4j.Logger;
-
 
41
import org.apache.poi.ss.usermodel.Row;
-
 
42
import org.apache.poi.ss.usermodel.Sheet;
-
 
43
import org.apache.poi.ss.usermodel.Workbook;
-
 
44
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
36
import org.springframework.beans.factory.annotation.Autowired;
45
import org.springframework.beans.factory.annotation.Autowired;
-
 
46
import org.springframework.beans.factory.annotation.Qualifier;
37
import org.springframework.beans.factory.annotation.Value;
47
import org.springframework.beans.factory.annotation.Value;
-
 
48
import org.springframework.core.io.ByteArrayResource;
38
import org.springframework.mail.javamail.JavaMailSender;
49
import org.springframework.mail.javamail.JavaMailSender;
39
import org.springframework.mail.javamail.MimeMessageHelper;
50
import org.springframework.mail.javamail.MimeMessageHelper;
40
import org.springframework.stereotype.Component;
51
import org.springframework.stereotype.Component;
41
import org.springframework.transaction.annotation.Transactional;
52
import org.springframework.transaction.annotation.Transactional;
42
 
53
 
43
import javax.mail.MessagingException;
54
import javax.mail.MessagingException;
44
import javax.mail.internet.InternetAddress;
55
import javax.mail.internet.InternetAddress;
45
import javax.mail.internet.MimeMessage;
56
import javax.mail.internet.MimeMessage;
46
import java.io.IOException;
57
import java.io.*;
-
 
58
import java.math.BigDecimal;
47
import java.time.LocalDate;
59
import java.time.LocalDate;
48
import java.time.LocalDateTime;
60
import java.time.LocalDateTime;
49
import java.time.LocalTime;
61
import java.time.LocalTime;
50
import java.time.YearMonth;
62
import java.time.YearMonth;
51
import java.time.temporal.ChronoUnit;
63
import java.time.temporal.ChronoUnit;
52
import java.util.*;
64
import java.util.*;
53
import java.util.stream.Collectors;
65
import java.util.stream.Collectors;
-
 
66
import java.util.stream.Stream;
54
 
67
 
55
@Component
68
@Component
56
@Transactional(rollbackFor = {Throwable.class, ProfitMandiBusinessException.class})
69
@Transactional(rollbackFor = {Throwable.class, ProfitMandiBusinessException.class})
57
public class ScheduledTasksTest {
70
public class ScheduledTasksTest {
58
 
71
 
Line 60... Line 73...
60
 
73
 
61
    @Autowired
74
    @Autowired
62
    TransactionRepository transactionRepository;
75
    TransactionRepository transactionRepository;
63
 
76
 
64
    @Autowired
77
    @Autowired
-
 
78
    @Qualifier(value = "googleMailSender")
-
 
79
    private JavaMailSender googleMailSender;
-
 
80
 
-
 
81
    @Autowired
65
    LoanRepository loanRepository;
82
    LoanRepository loanRepository;
66
 
83
 
67
    @Autowired
84
    @Autowired
68
    SDCreditService sdCreditService;
85
    SDCreditService sdCreditService;
69
 
86
 
Line 110... Line 127...
110
    ReturnOrderInfoRepository returnOrderInfoRepository;
127
    ReturnOrderInfoRepository returnOrderInfoRepository;
111
 
128
 
112
    @Autowired
129
    @Autowired
113
    OrderRepository orderRepository;
130
    OrderRepository orderRepository;
114
 
131
 
-
 
132
    @Autowired
-
 
133
    FofoOrderItemRepository fofoOrderItemRepository;
-
 
134
 
-
 
135
    @Autowired
-
 
136
    InventoryService inventoryService;
-
 
137
 
-
 
138
    @Autowired
-
 
139
    UserWalletRepository userWalletRepository;
-
 
140
 
-
 
141
    @Autowired
-
 
142
    LoanStatementRepository loanStatementRepository;
-
 
143
 
-
 
144
    @Autowired
-
 
145
    WalletService walletService;
-
 
146
 
115
    public void test() throws Exception {
147
    public void test() throws Exception {
116
        System.out.println("test start");
148
        System.out.println("test start");
117
//        smartCartService.activatedButNotBilledCatalogQtyMap();
149
        //this.generateBiReportExcel();
-
 
150
        this.loanSettle();
118
        System.out.println("test end");
151
        System.out.println("test end");
119
 
152
 
120
    }
153
    }
121
 
154
 
122
    public void createLoanForBillingByTransactionIdAndInvoiceNumber(int transactionId, double invoiceAmount, String invoiceNumber) throws Exception {
155
    public void createLoanForBillingByTransactionIdAndInvoiceNumber(int transactionId, double invoiceAmount, String invoiceNumber) throws Exception {
123
        sdCreditService.createLoanForBilling(transactionId, invoiceAmount, invoiceNumber);
156
        sdCreditService.createLoanForBilling(transactionId, invoiceAmount, invoiceNumber);
124
 
157
 
125
    }
158
    }
126
 
159
 
-
 
160
    public void loanSettle() throws Exception {
-
 
161
        List<Integer> refrences = Arrays.asList(25807,36003,38938,39506,42219,45084);
-
 
162
        for(Integer ref : refrences){
-
 
163
            List<LoanStatement> loanStatements = loanStatementRepository.selectByLoanId(ref);
-
 
164
            double amountSum = loanStatements.stream().map(LoanStatement::getAmount).mapToDouble(BigDecimal::doubleValue).sum();
-
 
165
            if(amountSum > 0){
-
 
166
                walletService.addAmountToWallet(loanStatements.get(0).getFofoId(),ref, WalletReferenceType.CREDIT_LIMIT,"Amount reversal against credit limit deduction",(float) amountSum,LocalDateTime.now());
-
 
167
 
-
 
168
//                Loan statement entry
-
 
169
                    BigDecimal adjustAmount = BigDecimal.valueOf(amountSum).negate(); // or multiply by -1
-
 
170
                    LoanStatement loanStatement = new LoanStatement();
-
 
171
                    loanStatement.setAmount(adjustAmount);
-
 
172
                    loanStatement.setFofoId(loanStatements.get(0).getFofoId());
-
 
173
                    loanStatement.setLoanReferenceType(LoanReferenceType.PRINCIPAL);
-
 
174
                    loanStatement.setCreatedAt(LocalDateTime.now());
-
 
175
                    loanStatement.setDescription("Amount reversal due to access debit against limit");
-
 
176
                    loanStatement.setLoanId(ref);
-
 
177
                    loanStatement.setBusinessDate(LocalDateTime.now());
-
 
178
                    loanStatementRepository.persist(loanStatement);
-
 
179
 
-
 
180
                    Loan loan = loanRepository.selectByLoanId(ref);
-
 
181
                    loan.setPendingAmount(BigDecimal.valueOf(0));
-
 
182
                    loan.setSettledOn(LocalDateTime.now());
-
 
183
                }
-
 
184
 
-
 
185
 
-
 
186
        }
-
 
187
    }
-
 
188
 
-
 
189
 
127
 
190
 
128
    private void sendMailHtmlFormat(String email[], String body, String cc[], String bcc[], String subject)
191
    private void sendMailHtmlFormat(String email[], String body, String cc[], String bcc[], String subject)
129
            throws MessagingException, ProfitMandiBusinessException, IOException {
192
            throws MessagingException, ProfitMandiBusinessException, IOException {
130
        MimeMessage message = mailSender.createMimeMessage();
193
        MimeMessage message = mailSender.createMimeMessage();
131
        MimeMessageHelper helper = new MimeMessageHelper(message);
194
        MimeMessageHelper helper = new MimeMessageHelper(message);
Line 371... Line 434...
371
        LOGGER.info("Consolidated Sales L1 feedback summary email sent.");
434
        LOGGER.info("Consolidated Sales L1 feedback summary email sent.");
372
    }
435
    }
373
 
436
 
374
 
437
 
375
    public void generateBiReportExcel() throws Exception {
438
    public void generateBiReportExcel() throws Exception {
-
 
439
 
376
        LocalDateTime startOfToday = LocalDate.now().atStartOfDay();
440
        LocalDateTime startOfToday = LocalDate.now().atStartOfDay();
377
 
441
 
378
        Map<Integer, CustomRetailer> customRetailers = retailerService.getAllFofoRetailers();
442
        Map<Integer, CustomRetailer> customRetailers = retailerService.getAllFofoRetailersInternalFalse();
379
 
443
 
380
        List<Integer> retailerIds = customRetailers.values().stream().map(CustomRetailer::getPartnerId).collect(Collectors.toList());
444
        List<Integer> retailerIds = customRetailers.values().stream().map(CustomRetailer::getPartnerId).collect(Collectors.toList());
381
 
445
 
-
 
446
 
382
//        this month return data
447
//  this month return data
-
 
448
        YearMonth currentMonth = YearMonth.now();
-
 
449
        String currentMonthStringValue = String.valueOf(currentMonth);
383
        LocalDateTime currentMonthStartDate = YearMonth.now().atDay(1).atStartOfDay();
450
        LocalDateTime currentMonthStartDate = YearMonth.now().atDay(1).atStartOfDay();
384
        LocalDateTime currentMonthEndDate = LocalDateTime.now();
451
        LocalDateTime currentMonthEndDate = LocalDateTime.now();
385
 
452
 
386
        List<ReturnOrderInfoModel> currentMonthReturnOrderInfoModels = returnOrderInfoRepository.selectAllByBetweenDate(currentMonthStartDate, currentMonthEndDate);
453
        List<ReturnOrderInfoModel> currentMonthReturnOrderInfoModels = returnOrderInfoRepository.selectAllByBetweenDate(currentMonthStartDate, currentMonthEndDate);
387
        Map<Integer, Long> currentMonthPartnerReturnOrderInfoModelMap = currentMonthReturnOrderInfoModels.stream().collect(Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingLong(x -> Math.round(x.getRefundAmount()))));
454
        Map<Integer, Long> currentMonthPartnerReturnOrderInfoModelMap = currentMonthReturnOrderInfoModels.stream().collect(Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingLong(x -> Math.round(x.getRefundAmount()))));
388
 
455
 
389
        List<Order> currentMonthRtoRefundOrders = orderRepository.selectAllOrderDatesBetweenByStatus(currentMonthStartDate, currentMonthEndDate, OrderStatus.RTO_REFUNDED);
456
        List<Order> currentMonthRtoRefundOrders = orderRepository.selectAllOrderDatesBetweenByStatus(currentMonthStartDate, currentMonthEndDate, OrderStatus.RTO_REFUNDED);
390
        Map<Integer, Long> currentMonthRtoRefundOrderMap = currentMonthRtoRefundOrders.stream().collect(Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingLong(x -> Math.round(x.getTotalAmount()))));
457
        Map<Integer, Long> currentMonthRtoRefundOrderMap = currentMonthRtoRefundOrders.stream().collect(Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingLong(x -> Math.round(x.getTotalAmount()))));
391
 
458
 
392
 
459
 
393
//        last month return data
460
//  last month return data
394
        YearMonth lastMonth = YearMonth.now().minusMonths(1);
461
        YearMonth lastMonth = YearMonth.now().minusMonths(1);
-
 
462
        String lastMonthStringValue = String.valueOf(lastMonth);
395
        LocalDateTime lastMontStartDate = lastMonth.atDay(1).atStartOfDay();
463
        LocalDateTime lastMontStartDate = lastMonth.atDay(1).atStartOfDay();
396
        LocalDateTime lastMonthEndDate = lastMonth.atEndOfMonth().atTime(23, 59, 59);
464
        LocalDateTime lastMonthEndDate = lastMonth.atEndOfMonth().atTime(23, 59, 59);
397
 
465
 
398
        List<ReturnOrderInfoModel> lastMonthReturnOrderInfoModels = returnOrderInfoRepository.selectAllByBetweenDate(lastMontStartDate, lastMonthEndDate);
466
        List<ReturnOrderInfoModel> lastMonthReturnOrderInfoModels = returnOrderInfoRepository.selectAllByBetweenDate(lastMontStartDate, lastMonthEndDate);
399
        Map<Integer, Long> lastMonthPartnerReturnOrderInfoModelMap = lastMonthReturnOrderInfoModels.stream().collect(Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingLong(x -> Math.round(x.getRefundAmount()))));
467
        Map<Integer, Long> lastMonthPartnerReturnOrderInfoModelMap = lastMonthReturnOrderInfoModels.stream().collect(Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingLong(x -> Math.round(x.getRefundAmount()))));
400
 
468
 
401
        List<Order> lastMonthRtoRefundOrders = orderRepository.selectAllOrderDatesBetweenByStatus(lastMontStartDate, lastMonthEndDate, OrderStatus.RTO_REFUNDED);
469
        List<Order> lastMonthRtoRefundOrders = orderRepository.selectAllOrderDatesBetweenByStatus(lastMontStartDate, lastMonthEndDate, OrderStatus.RTO_REFUNDED);
402
        Map<Integer, Long> lastMonthRtoRefundOrderMap = lastMonthRtoRefundOrders.stream().collect(Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingLong(x -> Math.round(x.getTotalAmount()))));
470
        Map<Integer, Long> lastMonthRtoRefundOrderMap = lastMonthRtoRefundOrders.stream().collect(Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingLong(x -> Math.round(x.getTotalAmount()))));
403
 
471
 
404
 
472
 
405
//        twoMonthsAgo return data
473
//  twoMonthsAgo return data
406
        YearMonth twoMonthsAgo = YearMonth.now().minusMonths(2);
474
        YearMonth twoMonthsAgo = YearMonth.now().minusMonths(2);
-
 
475
        String twoMonthAgoStringValue = String.valueOf(twoMonthsAgo);
407
        LocalDateTime twoMonthsAgoStartDate = twoMonthsAgo.atDay(1).atStartOfDay();
476
        LocalDateTime twoMonthsAgoStartDate = twoMonthsAgo.atDay(1).atStartOfDay();
408
        LocalDateTime twoMonthsAgoEndDate = twoMonthsAgo.atEndOfMonth().atTime(23, 59, 59);
477
        LocalDateTime twoMonthsAgoEndDate = twoMonthsAgo.atEndOfMonth().atTime(23, 59, 59);
409
 
478
 
410
        List<ReturnOrderInfoModel> twoMonthAgoReturnOrderInfoModels = returnOrderInfoRepository.selectAllByBetweenDate(twoMonthsAgoStartDate, twoMonthsAgoEndDate);
479
        List<ReturnOrderInfoModel> twoMonthAgoReturnOrderInfoModels = returnOrderInfoRepository.selectAllByBetweenDate(twoMonthsAgoStartDate, twoMonthsAgoEndDate);
411
        Map<Integer, Long> twoMonthAgoPartnerReturnOrderInfoModelMap = twoMonthAgoReturnOrderInfoModels.stream().collect(Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingLong(x -> Math.round(x.getRefundAmount()))));
480
        Map<Integer, Long> twoMonthAgoPartnerReturnOrderInfoModelMap = twoMonthAgoReturnOrderInfoModels.stream().collect(Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingLong(x -> Math.round(x.getRefundAmount()))));
412
 
481
 
413
        List<Order> twoMonthRtoRefundOrders = orderRepository.selectAllOrderDatesBetweenByStatus(twoMonthsAgoStartDate, twoMonthsAgoEndDate, OrderStatus.RTO_REFUNDED);
482
        List<Order> twoMonthRtoRefundOrders = orderRepository.selectAllOrderDatesBetweenByStatus(twoMonthsAgoStartDate, twoMonthsAgoEndDate, OrderStatus.RTO_REFUNDED);
414
        Map<Integer, Long> twoMonthRtoRefundOrderMap = twoMonthRtoRefundOrders.stream().collect(Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingLong(x -> Math.round(x.getTotalAmount()))));
483
        Map<Integer, Long> twoMonthAgoRtoRefundOrderMap = twoMonthRtoRefundOrders.stream().collect(Collectors.groupingBy(x -> x.getRetailerId(), Collectors.summingLong(x -> Math.round(x.getTotalAmount()))));
415
 
484
 
416
 
485
 
417
        List<BIRetailerModel> biRetailerModels = new ArrayList<>();
486
        Map<Integer , BIRetailerModel> biRetailerModelMap = new HashMap<>();
418
 
487
 
419
        List<BiSecondaryModel> biSecondaryModels = new ArrayList<>();
488
        Map<Integer, Map<YearMonth, BiSecondaryModel>> allRetailerMonthlyData = new HashMap<>();
420
 
489
 
421
        for(Integer fofoId: retailerIds){
490
        Map<Integer,Double> fofoTotalStockPriceMap = new HashMap<>();
422
 
491
 
423
            int rbmL1 = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_RBM,EscalationType.L1,fofoId);
492
        Map<Integer,Map<String, BrandStockPrice>> fofoBrandStockPriceMap = new HashMap<>();
-
 
493
 
-
 
494
 
-
 
495
        Map<Integer,Double> fofoTotalTertiaryMap = new HashMap<>();
-
 
496
 
424
            String rbmName = authRepository.selectById(rbmL1).getFullName();
497
        Map<Integer,Map<String, Double>> fofoBrandTertiaryMap = new HashMap<>();
425
 
498
 
-
 
499
        for(Integer fofoId: retailerIds){
-
 
500
            String rbmName = "";
-
 
501
            int rbmL1 = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_RBM,EscalationType.L1,fofoId);
-
 
502
            if(rbmL1 != 0){
-
 
503
                 rbmName = authRepository.selectById(rbmL1).getFullName();
-
 
504
            }
-
 
505
            String bmName ="";
426
            int bmId = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_SALES,EscalationType.L2,fofoId);
506
            int bmId = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_SALES,EscalationType.L2,fofoId);
-
 
507
            if(bmId !=0){
427
            String bmName = authRepository.selectById(bmId).getFullName();
508
                bmName = authRepository.selectById(bmId).getFullName();
-
 
509
            }
428
 
510
 
429
            int managerId = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_SALES,EscalationType.L1,fofoId);
511
            int managerId = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_SALES,EscalationType.L1,fofoId);
430
            String managerName = " ";
512
            String managerName = " ";
431
            if(managerId != 0){
513
            if(managerId != 0){
432
                 managerName = authRepository.selectById(managerId).getFullName();
514
                 managerName = authRepository.selectById(managerId).getFullName();
Line 441... Line 523...
441
//            generate retaile detail
523
//            generate retaile detail
442
 
524
 
443
            BIRetailerModel biRetailerModel = new BIRetailerModel();
525
            BIRetailerModel biRetailerModel = new BIRetailerModel();
444
            biRetailerModel.setBmName(bmName);
526
            biRetailerModel.setBmName(bmName);
445
            biRetailerModel.setCode(customRetailers.get(fofoId).getCode());
527
            biRetailerModel.setCode(customRetailers.get(fofoId).getCode());
-
 
528
            if(ast != null){
446
            biRetailerModel.setArea(ast.getArea());
529
                biRetailerModel.setArea(ast.getArea());
-
 
530
            }else {
-
 
531
                biRetailerModel.setArea("-");
-
 
532
            }
447
            biRetailerModel.setCity(customRetailers.get(fofoId).getAddress().getCity());
533
            biRetailerModel.setCity(customRetailers.get(fofoId).getAddress().getCity());
448
            biRetailerModel.setStoreName(customRetailers.get(fofoId).getBusinessName());
534
            biRetailerModel.setStoreName(customRetailers.get(fofoId).getBusinessName());
449
            biRetailerModel.setStoreName(String.valueOf(customRetailers.get(fofoId).getActivationType()));
535
            biRetailerModel.setStatus(String.valueOf(customRetailers.get(fofoId).getActivationType()));
450
            biRetailerModel.setCategory(String.valueOf(partnerTypeThisMonth));
536
            biRetailerModel.setCategory(String.valueOf(partnerTypeThisMonth));
451
            biRetailerModel.setSalesManager(managerName);
537
            biRetailerModel.setSalesManager(managerName);
452
            biRetailerModel.setRbm(rbmName);
538
            biRetailerModel.setRbm(rbmName);
-
 
539
 
453
            biRetailerModels.add(biRetailerModel);
540
            biRetailerModelMap.put(fofoId,biRetailerModel);
454
 
541
 
455
//            generate secondary data
542
//            generate secondary data
456
 
543
 
457
//            this month secondary target
544
//            this month secondary target
458
 
545
 
459
            MonthlyTarget secondaryTarget = monthlyTargetRepository.selectByDateAndFofoId(YearMonth.now(), fofoId);
546
            double currentSecondaryTarget =  monthlyTargetRepository.selectByDateAndFofoId(YearMonth.now(), fofoId) != null ? monthlyTargetRepository.selectByDateAndFofoId(YearMonth.now(), fofoId).getPurchaseTarget() : 0;
-
 
547
 
-
 
548
 
-
 
549
            long currentMonthReturn = currentMonthPartnerReturnOrderInfoModelMap.getOrDefault(fofoId, 0L) + currentMonthRtoRefundOrderMap.getOrDefault(fofoId, 0L);
-
 
550
 
460
 
551
 
461
            Map<Integer, Double> secondaryMtd = orderRepository.selectOrderValueBetweenDatesGroupByFofoId(Arrays.asList(fofoId),
552
            Map<Integer, Double> secondaryMtd = orderRepository.selectOrderValueBetweenDatesGroupByFofoId(Arrays.asList(fofoId),
462
                    Arrays.asList(OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.DELIVERY_SUCCESS, OrderStatus.ACCEPTED, OrderStatus.SUBMITTED_FOR_PROCESSING),
553
                    Arrays.asList(OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.DELIVERY_SUCCESS, OrderStatus.ACCEPTED, OrderStatus.SUBMITTED_FOR_PROCESSING),
463
                    startOfToday.withDayOfMonth(1), startOfToday.with(LocalTime.MAX)).stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getAmount()));
554
                    startOfToday.withDayOfMonth(1), startOfToday.with(LocalTime.MAX)).stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getAmount()));
464
 
555
 
465
            double secondaryAchievedMtd = secondaryMtd.getOrDefault(fofoId, 0.0);
556
            double secondaryAchievedMtd = secondaryMtd.getOrDefault(fofoId, 0.0);
466
 
557
 
-
 
558
            double currentMonthNetSecondary = secondaryAchievedMtd - currentMonthReturn;
-
 
559
 
-
 
560
            double currentMonthSecondaryPercent = currentSecondaryTarget == 0 ? 0.0 : (secondaryAchievedMtd / currentSecondaryTarget) * 100;
-
 
561
 
-
 
562
            double currentMonthUnbilled = 0;
-
 
563
 
-
 
564
//          this month tertiary----------
-
 
565
 
-
 
566
            LocalDateTime now = LocalDateTime.now();
-
 
567
            double todaySale = fofoOrderItemRepository.selectSumMopGroupByRetailer(startOfToday, now, fofoId, false).get(fofoId);
-
 
568
            double mtdSaleTillYesterDay = fofoOrderItemRepository.selectSumMopGroupByRetailer(startOfToday.withDayOfMonth(1), startOfToday, fofoId, false).get(fofoId);
-
 
569
            double mtdSale = mtdSaleTillYesterDay + todaySale;
-
 
570
 
467
 
571
 
468
//            last month secondary target
572
//            last month secondary target
469
 
573
 
470
            MonthlyTarget lastMonthSecondaryTarget = monthlyTargetRepository.selectByDateAndFofoId(lastMonth, fofoId);
574
            double lastMonthSecondaryTarget = monthlyTargetRepository.selectByDateAndFofoId(lastMonth, fofoId) != null ?  monthlyTargetRepository.selectByDateAndFofoId(lastMonth, fofoId).getPurchaseTarget() : 0;
-
 
575
 
-
 
576
            long lastMonthReturn = (lastMonthPartnerReturnOrderInfoModelMap.getOrDefault(fofoId,0L) + lastMonthRtoRefundOrderMap.getOrDefault(fofoId,0L));
471
 
577
 
472
            Map<Integer, Double> lastMonthSecondary = orderRepository.selectOrderValueBetweenDatesGroupByFofoId(Arrays.asList(fofoId),
578
            Map<Integer, Double> lastMonthSecondary = orderRepository.selectOrderValueBetweenDatesGroupByFofoId(Arrays.asList(fofoId),
473
                    Arrays.asList(OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.DELIVERY_SUCCESS, OrderStatus.ACCEPTED, OrderStatus.SUBMITTED_FOR_PROCESSING),
579
                    Arrays.asList(OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.DELIVERY_SUCCESS, OrderStatus.ACCEPTED, OrderStatus.SUBMITTED_FOR_PROCESSING),
474
                    lastMontStartDate, lastMonthEndDate).stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getAmount()));
580
                    lastMontStartDate, lastMonthEndDate).stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getAmount()));
475
 
581
 
476
            double lastMonthSecondaryAchieved = lastMonthSecondary.getOrDefault(fofoId, 0.0);
582
            double lastMonthSecondaryAchieved = lastMonthSecondary.getOrDefault(fofoId, 0.0);
477
 
583
 
-
 
584
            double lastMonthNetSecondary = lastMonthSecondaryAchieved - lastMonthReturn;
478
 
585
 
-
 
586
            double lastMonthSecondaryPercent = lastMonthSecondaryTarget == 0 ? 0.0 : (lastMonthSecondaryAchieved / lastMonthSecondaryTarget) * 100;
-
 
587
 
-
 
588
            double lastMonthUnbilled = 0;
-
 
589
 
479
//            last month secondary target
590
//           last month tertiary
-
 
591
            Double lastMonthSale = fofoOrderItemRepository.selectSumMopGroupByRetailer(
-
 
592
                    lastMontStartDate, lastMonthEndDate, fofoId, false).get(fofoId);
480
 
593
 
-
 
594
 
-
 
595
//            two month ago secondary target
-
 
596
 
481
            MonthlyTarget twoMonthAgoSecondaryTarget = monthlyTargetRepository.selectByDateAndFofoId(lastMonth, fofoId);
597
            double twoMonthAgoSecondaryTarget = monthlyTargetRepository.selectByDateAndFofoId(lastMonth, fofoId) != null ? monthlyTargetRepository.selectByDateAndFofoId(lastMonth, fofoId).getPurchaseTarget() : 0;
-
 
598
 
-
 
599
            long twoMonthAgoReturn = (twoMonthAgoPartnerReturnOrderInfoModelMap.getOrDefault(fofoId,0L) + twoMonthAgoRtoRefundOrderMap.getOrDefault(fofoId,0L));
482
 
600
 
483
            Map<Integer, Double> twoMonthAgoSecondary = orderRepository.selectOrderValueBetweenDatesGroupByFofoId(Arrays.asList(fofoId),
601
            Map<Integer, Double> twoMonthAgoSecondary = orderRepository.selectOrderValueBetweenDatesGroupByFofoId(Arrays.asList(fofoId),
484
                    Arrays.asList(OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.DELIVERY_SUCCESS, OrderStatus.ACCEPTED, OrderStatus.SUBMITTED_FOR_PROCESSING),
602
                    Arrays.asList(OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.DELIVERY_SUCCESS, OrderStatus.ACCEPTED, OrderStatus.SUBMITTED_FOR_PROCESSING),
485
                    twoMonthsAgoStartDate, twoMonthsAgoEndDate).stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getAmount()));
603
                    twoMonthsAgoStartDate, twoMonthsAgoEndDate).stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getAmount()));
486
 
604
 
487
            double twoMonthAgoSecondaryAchieved = twoMonthAgoSecondary.getOrDefault(fofoId, 0.0);
605
            double twoMonthAgoSecondaryAchieved = twoMonthAgoSecondary.getOrDefault(fofoId, 0.0);
488
 
606
 
-
 
607
            double twoMonthAgoNetSecondary = twoMonthAgoSecondaryAchieved - twoMonthAgoReturn;
-
 
608
 
-
 
609
            double twoMonthAgoSecondaryPercent = twoMonthAgoSecondaryTarget == 0 ? 0.0 : (twoMonthAgoSecondaryAchieved / twoMonthAgoSecondaryTarget) * 100;
489
//
610
 
-
 
611
            double twoMonthAgoUnbilled = 0;
-
 
612
 
490
////            this month tertiary
613
//          second Month Tertiary
491
//            Double todaySale = fofoOrderItemRepository.selectSumMopGroupByRetailer(startOfToday, now, fofoId, false).get(fofoId);
614
            double twoMonthAgoSale = fofoOrderItemRepository.selectSumMopGroupByRetailer(
492
//            Double mtdSaleTillYesterDay = fofoOrderItemRepository.selectSumMopGroupByRetailer(startOfToday.withDayOfMonth(1), startOfToday, fofoId, false).get(fofoId);
615
                    twoMonthsAgoStartDate, twoMonthsAgoEndDate, fofoId, false).get(fofoId);
-
 
616
 
-
 
617
 
493
//            Double mtdSale = mtdSaleTillYesterDay + todaySale;
618
            Map<YearMonth, BiSecondaryModel> monthlySecondaryModels = new HashMap<>();
-
 
619
 
494
//            Double lmtdSale = fofoOrderItemRepository.selectSumMopGroupByRetailer(
620
            BiSecondaryModel currentMonthSecondaryModel = new BiSecondaryModel(
-
 
621
                    currentSecondaryTarget,
-
 
622
                    secondaryAchievedMtd,
-
 
623
                    currentMonthReturn,
-
 
624
                    currentMonthNetSecondary,
-
 
625
                    currentMonthSecondaryPercent,
-
 
626
                    mtdSale,
495
//                    startOfToday.withDayOfMonth(1).minusMonths(1), now.minusMonths(1), fofoId, false).get(fofoId);
627
                    currentMonthUnbilled // for now, unbilled tertiary value
-
 
628
            );
496
//
629
 
-
 
630
            BiSecondaryModel lastMonthSecondaryModel = new BiSecondaryModel(
-
 
631
                    lastMonthSecondaryTarget,
-
 
632
                    lastMonthSecondaryAchieved,
-
 
633
                    lastMonthReturn,
-
 
634
                    lastMonthNetSecondary,
-
 
635
                    lastMonthSecondaryPercent,
-
 
636
                    lastMonthSale,
-
 
637
                    lastMonthUnbilled // for now, unbilled tertiary value
-
 
638
            );
497
//
639
 
498
//            BiSecondaryModel biSecondaryModel = new BiSecondaryModel();
640
            BiSecondaryModel twoMonthAgoSecondaryModel = new BiSecondaryModel(
-
 
641
                    twoMonthAgoSecondaryTarget,
-
 
642
                    twoMonthAgoSecondaryAchieved,
-
 
643
                    twoMonthAgoReturn,
-
 
644
                    twoMonthAgoNetSecondary,
-
 
645
                    twoMonthAgoSecondaryPercent,
-
 
646
                    twoMonthAgoSale,
-
 
647
                    twoMonthAgoUnbilled // for now, unbilled tertiary value
-
 
648
            );
-
 
649
 
-
 
650
            monthlySecondaryModels.put(currentMonth, currentMonthSecondaryModel);
-
 
651
            monthlySecondaryModels.put(lastMonth, lastMonthSecondaryModel);
-
 
652
            monthlySecondaryModels.put(twoMonthsAgo, twoMonthAgoSecondaryModel);
-
 
653
 
-
 
654
            allRetailerMonthlyData.put(fofoId, monthlySecondaryModels);
-
 
655
 
-
 
656
//            brandwiseStock value price
-
 
657
 
-
 
658
            Map<String, BrandStockPrice> brandStockPriceMap = inventoryService.getBrandWiseStockValue(fofoId);
-
 
659
 
-
 
660
            fofoBrandStockPriceMap.put(fofoId,brandStockPriceMap);
-
 
661
 
-
 
662
            double totalStockPrice = brandStockPriceMap.values().stream().mapToDouble(x->x.getTotalValue()).sum();
-
 
663
 
-
 
664
            fofoTotalStockPriceMap.put(fofoId,totalStockPrice);
-
 
665
 
-
 
666
            Map<String, Double> brandMtdTertiaryAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(
-
 
667
                    currentMonthStartDate, currentMonthEndDate, fofoId);
-
 
668
 
-
 
669
            fofoBrandTertiaryMap.put(fofoId,brandMtdTertiaryAmount);
-
 
670
 
-
 
671
            double totalMtdTertiaryAmount = brandMtdTertiaryAmount.values().stream().mapToDouble(Double::doubleValue).sum();
-
 
672
 
-
 
673
            fofoTotalTertiaryMap.put(fofoId,totalMtdTertiaryAmount);
-
 
674
 
-
 
675
//            List<BrandWiseModel> brandMtdSecondary = orderRepository.selectAllBilledOrderGroupByBrandFofoId(fofoId, curDate.withDayOfMonth(1).minusMonths(6));
-
 
676
 
499
 
677
 
500
        }
678
        }
501
 
679
 
502
        LOGGER.info("biRetailerModels {}",biRetailerModels);
680
        LOGGER.info("Total BI Retailers processed: {}", biRetailerModelMap.size());
503
 
681
 
-
 
682
        //generate excel and sent to mail
-
 
683
        List<List<String>> headerGroup = new ArrayList<>();
504
 
684
 
-
 
685
        List<String> headers1 = Arrays.asList(
-
 
686
                "Retailer Detail", "", "", "", "", "", "", "", "", "",
-
 
687
                currentMonthStringValue, "", "", "", "", "", "",
-
 
688
                lastMonthStringValue, "", "", "", "", "", "",
-
 
689
                twoMonthAgoStringValue, "", "", "", "", "", ""
-
 
690
        );
-
 
691
 
-
 
692
        List<String> headers2 = Arrays.asList(
-
 
693
                "Code", "Store Name", "City", "Area", "BM", "Sales Manager", "RBM", "Status", "Category",
-
 
694
                "Secondary Target", "Secondary Achieved", "Returns", "Net Secondary", "Secondary %",
-
 
695
                "Tertiary Sale", "Unbilled",
-
 
696
                "Secondary Target", "Secondary Achieved", "Returns", "Net Secondary", "Secondary %",
-
 
697
                "Tertiary Sale", "Unbilled",
-
 
698
                "Secondary Target", "Secondary Achieved", "Returns", "Net Secondary", "Secondary %",
-
 
699
                "Tertiary Sale", "Unbilled",
-
 
700
 
-
 
701
              "Total Stock",  "Apple","Xiaomi","Vivo","Tecno","Samsung","Realme","Oppo","OnePlus","Poco","Lava","Itel","Almost New"
-
 
702
        );
-
 
703
 
-
 
704
        headerGroup.add(headers1);
-
 
705
        headerGroup.add(headers2);
-
 
706
 
-
 
707
 
-
 
708
        List<List<?>> rows = new ArrayList<>();
-
 
709
        for (Map.Entry<Integer, BIRetailerModel> entry : biRetailerModelMap.entrySet()) {
-
 
710
            Integer fofoId = entry.getKey();
-
 
711
            BIRetailerModel retailer = entry.getValue();
-
 
712
            Map<YearMonth, BiSecondaryModel> monthlyData = allRetailerMonthlyData.get(fofoId);
-
 
713
 
-
 
714
            BiSecondaryModel current = monthlyData.getOrDefault(YearMonth.now(), new BiSecondaryModel(0,0,0,0,0,0,0));
-
 
715
            BiSecondaryModel last = monthlyData.getOrDefault(YearMonth.now().minusMonths(1), new BiSecondaryModel(0,0,0,0,0,0,0));
-
 
716
            BiSecondaryModel twoAgo = monthlyData.getOrDefault(YearMonth.now().minusMonths(2), new BiSecondaryModel(0,0,0,0,0,0,0));
-
 
717
 
-
 
718
            List<Object> row = new ArrayList<>();
-
 
719
            row.addAll(Arrays.asList(
-
 
720
                    retailer.getCode(), retailer.getStoreName(), retailer.getCity(), retailer.getArea(),
-
 
721
                    retailer.getBmName(), retailer.getSalesManager(), retailer.getRbm(),
-
 
722
                    retailer.getStatus(), retailer.getCategory()
-
 
723
            ));
-
 
724
 
-
 
725
            // Current Month
-
 
726
            row.addAll(Arrays.asList(
-
 
727
                    current.getSecondaryTarget(),
-
 
728
                    current.getSecondaryAchieved(),
-
 
729
                    current.getSecondaryReturn(),
-
 
730
                    current.getNetSecondary(),
-
 
731
                    current.getSecondaryAchievedPercent(),
-
 
732
                    current.getTertiary(),
-
 
733
                    current.getTertiaryUnBilled()
-
 
734
            ));
-
 
735
 
-
 
736
            // Last Month
-
 
737
            row.addAll(Arrays.asList(
-
 
738
                    last.getSecondaryTarget(),
-
 
739
                    last.getSecondaryAchieved(),
-
 
740
                    last.getSecondaryReturn(),
-
 
741
                    last.getNetSecondary(),
-
 
742
                    last.getSecondaryAchievedPercent(),
-
 
743
                    last.getTertiary(),
-
 
744
                    last.getTertiaryUnBilled()
-
 
745
            ));
-
 
746
 
-
 
747
            // Two Months Ago
-
 
748
            row.addAll(Arrays.asList(
-
 
749
                    twoAgo.getSecondaryTarget(),
-
 
750
                    twoAgo.getSecondaryAchieved(),
-
 
751
                    twoAgo.getSecondaryReturn(),
-
 
752
                    twoAgo.getNetSecondary(),
-
 
753
                    twoAgo.getSecondaryAchievedPercent(),
-
 
754
                    twoAgo.getTertiary(),
-
 
755
                    twoAgo.getTertiaryUnBilled()
-
 
756
            ));
-
 
757
            Map<String, BrandStockPrice> brandMap = fofoBrandStockPriceMap.get(fofoId);
-
 
758
            row.addAll(Arrays.asList(
-
 
759
                    fofoTotalStockPriceMap.getOrDefault(fofoId, 0.0),
-
 
760
                    brandMap.get("Apple") != null ? brandMap.get("Apple").getTotalValue() : 0.0,
-
 
761
                    brandMap.get("Xiaomi") != null ? brandMap.get("Xiaomi").getTotalValue() : 0.0,
-
 
762
                    brandMap.get("Vivo") != null ? brandMap.get("Vivo").getTotalValue() : 0.0,
-
 
763
                    brandMap.get("Tecno") != null ? brandMap.get("Tecno").getTotalValue() : 0.0,
-
 
764
                    brandMap.get("Samsung") != null ? brandMap.get("Samsung").getTotalValue() : 0.0,
-
 
765
                    brandMap.get("Realme") != null ? brandMap.get("Realme").getTotalValue() : 0.0,
-
 
766
                    brandMap.get("Oppo") != null ? brandMap.get("Oppo").getTotalValue() : 0.0,
-
 
767
                    brandMap.get("OnePlus") != null ? brandMap.get("OnePlus").getTotalValue() : 0.0,
-
 
768
                    brandMap.get("Poco") != null ? brandMap.get("Poco").getTotalValue() : 0.0,
-
 
769
                    brandMap.get("Lava") != null ? brandMap.get("Lava").getTotalValue() : 0.0,
-
 
770
                    brandMap.get("Itel") != null ? brandMap.get("Itel").getTotalValue() : 0.0,
-
 
771
                    brandMap.get("Almost New") != null ? brandMap.get("Almost New").getTotalValue() : 0.0
-
 
772
            ));
-
 
773
 
-
 
774
            rows.add(row);
-
 
775
        }
-
 
776
 
-
 
777
 
-
 
778
// Send to email
-
 
779
        ByteArrayOutputStream csvStream = FileUtil.getCSVByteStreamWithMultiHeaders(headerGroup, rows);
-
 
780
        String fileName = "BI-Retailer-Monthly-Report-" + FormattingUtils.formatDate(LocalDateTime.now()) + ".csv";
-
 
781
        String[] sendToArray = new String[]{"ranu.rajput@smartdukaan.com"};
-
 
782
 
-
 
783
        Utils.sendMailWithAttachment(googleMailSender, sendToArray, new String[]{}, "BI Retailer Monthly Report", "Please find attached the BI retailer secondary/tertiary monthly report.", fileName, new ByteArrayResource(csvStream.toByteArray()));
505
 
784
 
506
 
785
 
507
    }
786
    }
508
 
787
 
509
 
788
 
510
 
789
 
511
 
790
 
-
 
791
 
512
}
792
}