Subversion Repositories SmartDukaan

Rev

Rev 30278 | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.web.controller;

import com.spice.profitmandi.common.enumuration.FofoType;
import com.spice.profitmandi.common.model.CustomRetailer;
import com.spice.profitmandi.common.services.fundfina.*;
import com.spice.profitmandi.dao.entity.dtr.CreditAccount;
import com.spice.profitmandi.dao.entity.dtr.CreditStatus;
import com.spice.profitmandi.dao.entity.dtr.Document;
import com.spice.profitmandi.dao.entity.dtr.FundFinaPreApproval;
import com.spice.profitmandi.dao.entity.fofo.FofoKyc;
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
import com.spice.profitmandi.dao.entity.fofo.PartnerOnBoardingPanel;
import com.spice.profitmandi.dao.entity.user.User;
import com.spice.profitmandi.dao.enumuration.fofo.Gateway;
import com.spice.profitmandi.dao.model.UserWalletCountVolumeModel;
import com.spice.profitmandi.dao.model.WalletMinMaxAmountModel;
import com.spice.profitmandi.dao.repository.dtr.*;
import com.spice.profitmandi.dao.repository.fofo.PartnerDailyInvestmentRepository;
import com.spice.profitmandi.dao.repository.transaction.UserWalletHistoryRepository;
import com.spice.profitmandi.dao.repository.user.AddressRepository;
import com.spice.profitmandi.dao.repository.user.FofoKycRepository;
import com.spice.profitmandi.dao.repository.user.UserRepository;
import com.spice.profitmandi.service.user.RetailerService;
import com.spice.profitmandi.web.util.MVCResponseSender;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

@Controller
@Transactional(rollbackFor = Throwable.class)
public class FundFinaController {

        @Autowired
        private RetailerService retailerService;

        @Autowired
        private UserWalletHistoryRepository userWalletHistoryRepository;

        @Autowired
        private PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;

        @Autowired
        private FofoStoreRepository fofoStoreRepository;

        @Autowired
        private UserRepository userRepository;

        @Autowired
        private AddressRepository addressRepository;

        @Autowired
        private MVCResponseSender mvcResponseSender;

        @Autowired
        private PartnerOnBoardingPanelRepository partnerOnBoardingPanelRepository;

        @Autowired
        private FofoKycRepository fofoKycRepository;

        @Autowired
        private DocumentRepository documentRepository;

        @Autowired
        private FundFinaPreApprovalRepository fundFinaPreApprovalRepository;

        @Autowired
        private CreditAccountRepository creditAccountRepository;
        private static final Logger logger = LogManager.getLogger(FundFinaController.class);

        private String authKey = "$mart@123";

        @RequestMapping(value = "/fundfina/getTransactions", method = RequestMethod.POST)
        public String getTransactions(HttpServletRequest request, @RequestBody TransactionRequest transactionRequest,
                        Model model) throws Exception {

                TransactionResponse tr = new TransactionResponse();

                String key = request.getHeader("auth-key");
                logger.info("authKey {}", authKey);

                if (key.equals(authKey)) {
                        int offset = 0;
                        offset = ((0 + transactionRequest.getPageNumber() - 1) * 100) + 1;

                        List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores().stream()
                                        .filter(x -> x.getFofoType().equals(FofoType.FRANCHISE)).collect(Collectors.toList());
                        int remainder = fofoStores.size() / 100;
                        int modulas = fofoStores.size() % 100;
                        if (modulas != 0) {
                                tr.setTotalPages(remainder + 1);

                        } else {
                                tr.setTotalPages(remainder);
                        }

                        logger.info("offset {}", offset);

                        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getFofoRetailersPaginated(true, offset,
                                        100, FofoType.FRANCHISE);

                        tr.setStatus("success");
                        tr.setRequestRef(String.valueOf(Timestamp.valueOf(LocalDateTime.now()).getTime()));
                        tr.setTotalRecords(fofoStores.size());
                        tr.setCurrentPage(transactionRequest.getPageNumber());
                        tr.setCurrentPageRecords(customRetailerMap.size());

                        List<TransactionalData> transactionData = new ArrayList<>();

                        for (Entry<Integer, CustomRetailer> customRetailerEntry : customRetailerMap.entrySet()) {

                                int fofoId = customRetailerEntry.getKey();

                                User user = userRepository.selectById(fofoId);
                                TransactionalData td = new TransactionalData();
                                td.setJoinedOn(user.getCreateTimestamp().toLocalDate().toString());
                                td.setRegistrationDate(user.getCreateTimestamp().toLocalDate().toString());
                                td.setUserId(Integer.toString(user.getId()));
                                td.setMerchantType("Retailer");
                                td.setEmailId(user.getEmailId());
                                td.setMobileNo(user.getMobileNumber());
                                td.setShopType("Mobile Shop");
                                td.setIpAddress("50.116.3.101");
                                td.setPincode(Integer.parseInt(addressRepository.selectById(user.getAddressId()).getPinCode()));
                                List<UserWalletCountVolumeModel> countVolumeModels = userWalletHistoryRepository
                                                .selectCountVolumeTransactionByYearMonth(fofoId);

                                Map<YearMonth, WalletMinMaxAmountModel> walletMinMaxModel = partnerDailyInvestmentRepository
                                                .selectMinMaxWalletBalanceGroupByYearMonth(fofoId).stream()
                                                .collect(Collectors.toMap(x -> YearMonth.of(Integer.parseInt(x.getYear()),
                                                                Month.of(Integer.parseInt(x.getMonth()))), x -> x));

                                List<TransactionSummary> transactionSummmary = new ArrayList<>();

                                for (UserWalletCountVolumeModel uwcm : countVolumeModels) {
                                        TransactionSummary ts = new TransactionSummary();
                                        ts.setCount(String.valueOf(uwcm.getCount()));
                                        ts.setVolume(uwcm.getAmount());
                                        ts.setYear(Integer.parseInt(uwcm.getYear()));

                                        YearMonth yearMonthObject = YearMonth.of(Integer.parseInt(uwcm.getYear()),
                                                        Month.of(Integer.parseInt(uwcm.getMonth())));
                                        int daysInMonth = yearMonthObject.lengthOfMonth();
                                        ts.setTotalDays(daysInMonth);

                                        LocalDate result = yearMonthObject.atDay(1);
                                        int activeDays = 0;
                                        while (activeDays < daysInMonth) {
                                                result = result.plusDays(1);

                                                logger.info("result {}", result);

                                                if (!(result.getDayOfWeek() == DayOfWeek.SATURDAY
                                                                || result.getDayOfWeek() == DayOfWeek.SUNDAY)) {
                                                        ++activeDays;
                                                }
                                        }

                                        ts.setActiveDays(activeDays);

                                        ts.setMonth(Integer.parseInt(uwcm.getMonth()));
                                        if (walletMinMaxModel.get(yearMonthObject) != null) {
                                                ts.setMinWalletBalance(walletMinMaxModel.get(yearMonthObject).getMin());
                                                ts.setMaxWalletBalance(walletMinMaxModel.get(yearMonthObject).getMax());
                                        }
                                        transactionSummmary.add(ts);

                                }

                                td.setTransactionSummary(transactionSummmary);

                                transactionData.add(td);

                        }
                        tr.setTransactionalData(transactionData);
                } else {
                        tr.setErrCode("401");
                        tr.setDesc("auth key is not valid");

                }

                model.addAttribute("response1", mvcResponseSender.createResponseString(tr));
                return "response";
        }

        @RequestMapping(value = "/fundfina/getUserData/{userId}", method = RequestMethod.GET)
        public String getUserData(HttpServletRequest request, @PathVariable int userId, Model model) throws Exception {

                FofoStore fs = fofoStoreRepository.selectByRetailerId(userId);

                User user = userRepository.selectById(fs.getId());
                String key = request.getHeader("auth-key");
                logger.info("authKey {}", authKey);
                PartnerUserData pud = new PartnerUserData();

                if (key.equals(authKey)) {
                        PartnerOnBoardingPanel pobp = partnerOnBoardingPanelRepository.selectByCode(fs.getCode());
                        CustomRetailer customRetailer = retailerService.getFofoRetailer(fs.getId());
                        List<FofoKyc> fofoKycs = fofoKycRepository.selectByPartnerOnBoardingId(pobp.getId());
                        FofoKyc fk = fofoKycs.get(0);
                        pud.setName(fk.getFirstName() + " " + fk.getLastName());
                        pud.setShopName(customRetailer.getBusinessName());
                        pud.setShopType("Mobile Store");
                        pud.setDob(fk.getDob().toString());
                        pud.setShopOwnership("rented");
                        pud.setShopPincode(customRetailer.getAddress().getPinCode());
                        pud.setShopAddress(customRetailer.getAddress().getLine1() + " " + customRetailer.getAddress().getLine2());
                        pud.setShopCity(customRetailer.getAddress().getCity());
                        pud.setShopState(customRetailer.getAddress().getState());
                        pud.setMobile("9816068341");
                        pud.setCity(fk.getCity());
                        pud.setAddress(fk.getAddress1() + " " + fk.getAddress2() + " " + fk.getAddress3());
                        pud.setEmailId(customRetailer.getEmail());
                        pud.setPan(fk.getPan());
                        pud.setPincode(fk.getPincode());
                        pud.setBusinessActivationDate(user.getCreateTimestamp().toString());
                        pud.setState(fk.getState());

                        if (fk.getPanDoc() != 0) {
                                Document document = documentRepository.selectById(fk.getPanDoc());
                                pud.setPanFront(
                                                "http://shop2020.in:8080/profitmandi-web/open-attachment?documentId=" + document.getId());
                        }
                        pud.setRequestRef(String.valueOf(Timestamp.valueOf(LocalDateTime.now()).getTime()));
                        pud.setStatus("success");
                } else {
                        pud.setErrCode("401");
                        pud.setDesc("auth key is not valid");

                }
                model.addAttribute("response1", mvcResponseSender.createResponseString(pud));

                return "response";

        }

        @RequestMapping(value = "/fundfina/pushPreApproval", method = RequestMethod.POST)
        public String pushPreApproval(HttpServletRequest request, @RequestBody PreApprovalRequest preApprovalRequest,
                        Model model) throws Exception {

                List<PreApprovals> preApprovals = preApprovalRequest.getPreApprovals();
                String key = request.getHeader("auth-key");
                logger.info("authKey {}", authKey);
                PreApprovalResponse par = new PreApprovalResponse();

                if (key.equals(authKey)) {

                        par.setStatus("success");
                        par.setRequestRef(String.valueOf(Timestamp.valueOf(LocalDateTime.now()).getTime()));

                        List<PreApprovalsResponse> pars = new ArrayList<>();

                        for (PreApprovals pa : preApprovals) {

                                if (pa.getProductId() != null) {
                                        FundFinaPreApproval fpa = fundFinaPreApprovalRepository
                                                        .selectByUserIdAndProductId(Integer.parseInt(pa.getUserId()), pa.getProductId());

                                        logger.info("fpa {}", fpa);

                                        CreditAccount creditAccount = creditAccountRepository
                                                        .selectByFofoIdAndGateway(Integer.parseInt(pa.getUserId()), Gateway.FUNDFINA);

                                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

                                        if (creditAccount == null) {
                                                creditAccount = new CreditAccount();
                                                creditAccount.setLoanReferenceId(pa.getProductId());

                                        } else {

                                                if (!pa.getProductId().equals(creditAccount.getLoanReferenceId())) {
                                                        creditAccount.setLoanReferenceId(pa.getProductId());

                                                }
                                        }

                                        creditAccount.setExpiredOn(LocalDateTime.parse(pa.getExpiryDate(), formatter));
                                        creditAccount.setProcessingFee(pa.getProcessingFee());
                                        creditAccount.setSanctionedAmount(Float.parseFloat(pa.getApprovedAmount()));
                                        creditAccount.setGateway(Gateway.FUNDFINA);

                                        String in[] = pa.getAnnualInterestRate().split("%");
                                        creditAccount.setInterestRate(Float.parseFloat(in[0]));
                                        creditAccount.setFofoId(Integer.parseInt(pa.getUserId()));
                                        creditAccount.setUpdatedOn(LocalDateTime.now());

                                        creditAccount.setCreditStatus(CreditStatus.SANCTIONED);

                                        creditAccountRepository.persist(creditAccount);

                                        if (fpa == null) {
                                                fpa = new FundFinaPreApproval();
                                                fpa.setFofoId(Integer.parseInt(pa.getUserId()));
                                                fpa.setProductId(pa.getProductId());
                                                fpa.setTenureInDays(pa.getTenureInDays());
                                                fpa.setProcessingFee(pa.getProcessingFee());
                                                fpa.setAnnualInterestRate(pa.getAnnualInterestRate());
                                                fpa.setApprovedAmount(pa.getApprovedAmount());
                                                fpa.setEmiAmount(pa.getEmiAmount());
                                                fpa.setExpiryDate(LocalDateTime.parse(pa.getExpiryDate(), formatter));
                                                fpa.setCreateTimestamp(LocalDateTime.now());
                                                fpa.setUpdateTimestamp(LocalDateTime.now());
                                                fundFinaPreApprovalRepository.persist(fpa);

                                        }

                                        PreApprovalsResponse paar = new PreApprovalsResponse();
                                        paar.setUserId(pa.getUserId());
                                        paar.setProductId(pa.getProductId());
                                        pars.add(paar);

                                }
                        }

                        par.setPreApprvalsRes(pars);

                        model.addAttribute("response1", mvcResponseSender.createResponseString(par));
                } else {
                        par.setErrCode("401");
                        par.setDesc("auth key is not valid");
                }
                return "response";

        }

        @RequestMapping(value = "/fundfina/pushNotification", method = RequestMethod.POST)
        public String pushNotification(HttpServletRequest request,
                        @RequestBody PushNotificationRequest pushNotificationRequest, Model model) throws Exception {

                logger.info("pushNotificationRequest {}", pushNotificationRequest);
                PushNotificationResponse pnr = new PushNotificationResponse();
                pnr.setRequestRef(String.valueOf(Timestamp.valueOf(LocalDateTime.now()).getTime()));
                pnr.setStatus("success");

                model.addAttribute("response1", mvcResponseSender.createResponseString(pnr));

                return "response";
        }

}