Subversion Repositories SmartDukaan

Rev

Rev 35823 | Go to most recent revision | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.web.controller;

import java.math.BigDecimal;
import java.time.LocalDateTime;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.ProfitMandiConstants;
import com.spice.profitmandi.common.services.mandii.AccountStatusResponseOut;
import com.spice.profitmandi.common.services.mandii.EligibilityStatusEnum;
import com.spice.profitmandi.common.services.mandii.MandiiService;
import com.spice.profitmandi.common.web.util.ResponseSender;
import com.spice.profitmandi.dao.entity.dtr.CreditAccount;
import com.spice.profitmandi.dao.entity.dtr.CreditStatus;
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
import com.spice.profitmandi.dao.entity.transaction.Loan;
import com.spice.profitmandi.dao.entity.transaction.SDCreditRequirement;
import com.spice.profitmandi.dao.enumuration.fofo.Gateway;
import com.spice.profitmandi.dao.model.CreditSummary;
import com.spice.profitmandi.dao.model.SDCreditResponseOut;
import com.spice.profitmandi.dao.repository.catalog.AddWalletRequestRepository;
import com.spice.profitmandi.dao.repository.dtr.CreditAccountRepository;
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
import com.spice.profitmandi.dao.repository.transaction.LoanRepository;
import com.spice.profitmandi.dao.repository.transaction.PaymentRepository;
import com.spice.profitmandi.dao.repository.transaction.SDCreditRequirementRepository;
import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;
import com.spice.profitmandi.service.transaction.SDCreditService;
import com.spice.profitmandi.service.wallet.WalletService;

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

        private static final Logger log = LogManager.getLogger(GatewayController.class);

        @Autowired
        UserWalletRepository userWalletRepository;

        @Autowired
        PaymentRepository paymentRepository;

        @Autowired
        AddWalletRequestRepository addWalletRequestRepository;

        @Autowired
        WalletService walletService;

        @Autowired
        FofoStoreRepository fofoStoreRepository;

        @Autowired
        private UserAccountRepository userAccountRepository;

        @Autowired
        private MandiiService mandiiService;

        @Autowired
        ResponseSender<?> responseSender;

        @Autowired
        CreditAccountRepository creditAccountRepository;

        @Autowired
        SDCreditService sdCreditService;

        @Autowired
        SDCreditRequirementRepository sdCreditRequirementRepository;

        @Autowired
        LoanRepository loanRepository;

        @RequestMapping(value = "payment/gateway/status/{gateway}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        public ResponseEntity<?> getLoanStatus(HttpServletRequest request, @PathVariable Gateway gateway)
                        throws ProfitMandiBusinessException {
                int userId = (int) request.getAttribute(ProfitMandiConstants.USER_ID);
                int retailerId = userAccountRepository.selectRetailerIdByUserId(userId);
                FofoStore fs = fofoStoreRepository.selectByRetailerId(retailerId);
                if (gateway != null && gateway.equals(Gateway.MANDII)) {
                        try {

                                AccountStatusResponseOut accountStatusResponseOut = mandiiService.getStatus(fs.getPan());

                                CreditAccount creditAccount = creditAccountRepository.selectByFofoIdAndGateway(retailerId,
                                                Gateway.MANDII);

                                if (creditAccount == null) {

                                        creditAccount = new CreditAccount();

                                        creditAccount.setFofoId(retailerId);
                                        creditAccount.setGateway(Gateway.MANDII);

                                }

                                if (accountStatusResponseOut == null) {
                                        creditAccount.setCreditStatus(CreditStatus.UNKNOWN);
                                        creditAccount.setDescription("User company not found");

                                } else {
                                        creditAccount.setSanctionedAmount(accountStatusResponseOut.getSanctionLimit().floatValue());
                                        creditAccount.setInterestRate(accountStatusResponseOut.getRateOfInterest());
                                        creditAccount.setAvailableAmount(accountStatusResponseOut.getBalanceAmount().floatValue());
                                        creditAccount.setDescription(accountStatusResponseOut.getCurrentStage().toString());
                                        if (accountStatusResponseOut.getStatus().equals(EligibilityStatusEnum.SANCTION_AVAILABLE)) {
                                                creditAccount.setCreditStatus(CreditStatus.SANCTIONED);
                                        } else if (accountStatusResponseOut.getStatus().equals(EligibilityStatusEnum.IN_ELIGIBLE)) {
                                                creditAccount.setCreditStatus(CreditStatus.INELIGIBLE);
                                        } else {

                                                creditAccount.setCreditStatus(CreditStatus.TO_BE_EVALUATED);
                                        }
                                }

                                creditAccount.setUpdatedOn(LocalDateTime.now());

                                creditAccountRepository.persist(creditAccount);
                                return responseSender.ok(accountStatusResponseOut);
                        } catch (Exception e) {
                                log.info("Trace {}\n{}", e.getMessage(), e);
                                throw new ProfitMandiBusinessException("Loan Provider", gateway, "Can't fetch details for provider");
                        }
                } else if (gateway != null && gateway.equals(Gateway.SDDIRECT)) {
                        CreditAccount creditAccount = creditAccountRepository.selectByFofoIdAndGateway(retailerId,
                                        Gateway.SDDIRECT);

                        com.spice.profitmandi.dao.model.CreditSummary creditSummary = sdCreditService.getCreditSummary(retailerId);

                        SDCreditRequirement sdCreditRequirement = sdCreditRequirementRepository.selectByFofoId(retailerId);

                        AccountStatusResponseOut accountStatusResponseOut = new AccountStatusResponseOut();
                        BigDecimal availability = BigDecimal.ZERO;
                        if (creditAccount != null) {

                                availability = sdCreditService.getAvailableAmount(retailerId);
                                creditAccount.setAvailableAmount(availability.floatValue());

                                log.info("availability {}", availability);
                                accountStatusResponseOut.setBalanceAmount(availability);

                        }

                        if (availability.signum() == 1 && creditAccount.isActive() && creditSummary.getOverdueCount() == 0) {
                                accountStatusResponseOut.setStatus(EligibilityStatusEnum.SANCTION_AVAILABLE);
                                accountStatusResponseOut.setRateOfInterest(creditAccount.getInterestRate());
                                accountStatusResponseOut.setPenalRateOfInterest(ProfitMandiConstants.NEW_DELAYED_INTEREST_RATE);
                                accountStatusResponseOut.setCreditDays(sdCreditRequirement.getCreditDays());
                        } else if (creditAccount != null && creditAccount.isActive() && creditSummary.getOverdueCount() > 0) {
                                CreditSummary orderSummary = sdCreditService.getCreditSummaryForOrder(retailerId, 0);
                                if (orderSummary.isCanPlaceOrder() && availability.signum() == 1) {
                                        // Exception partner or has fresh money — allow ordering
                                        accountStatusResponseOut.setStatus(EligibilityStatusEnum.SANCTION_AVAILABLE);
                                        accountStatusResponseOut.setRateOfInterest(creditAccount.getInterestRate());
                                        accountStatusResponseOut.setPenalRateOfInterest(ProfitMandiConstants.NEW_DELAYED_INTEREST_RATE);
                                        accountStatusResponseOut.setCreditDays(sdCreditRequirement.getCreditDays());
                                        if (orderSummary.getFreshMoneyAvailable() > 0) {
                                                BigDecimal effectiveLimit = availability.min(BigDecimal.valueOf(orderSummary.getFreshMoneyAvailable()));
                                                accountStatusResponseOut.setBalanceAmount(effectiveLimit);
                                                accountStatusResponseOut.setStatusDescription(String.format(
                                                                "%d loan(s) overdue. Purchase restricted up to Rs. %.0f",
                                                                creditSummary.getOverdueCount(), effectiveLimit));
                                        }
                                } else {
                                        accountStatusResponseOut.setStatus(EligibilityStatusEnum.IN_ELIGIBLE);
                                        accountStatusResponseOut.setStatusDescription(String.format(
                                                        "Due date have been exceeded for %d loans. Pls clear the overdues to utilize balance credit",
                                                        creditSummary.getOverdueCount()));
                                }
                        } else {
                                accountStatusResponseOut.setStatus(EligibilityStatusEnum.IN_ELIGIBLE);
                        }
                        return responseSender.ok(accountStatusResponseOut);
                }

                else {
                        throw new ProfitMandiBusinessException("Provider", "Empty", "Provider can't be empty");
                }
        }

        @RequestMapping(value = "payment/gateway/sddirect/summary", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        public ResponseEntity<?> getSdDirectLoan(HttpServletRequest request) throws ProfitMandiBusinessException {
                int userId = (int) request.getAttribute(ProfitMandiConstants.USER_ID);
                int retailerId = userAccountRepository.selectRetailerIdByUserId(userId);
                SDCreditResponseOut sdCreditResponseOut = sdCreditService.sdDirectService(retailerId);
                return responseSender.ok(sdCreditResponseOut);
        }
        @RequestMapping(value = "payment/gateway/sddirect/settle-loan/{loanId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
        public ResponseEntity<?> settleLoan(HttpServletRequest request, @PathVariable int loanId) throws ProfitMandiBusinessException {
                int userId = (int) request.getAttribute(ProfitMandiConstants.USER_ID);
                int retailerId = userAccountRepository.selectRetailerIdByUserId(userId);
                Loan loan = loanRepository.selectByLoanId(loanId);
                if(loan.getFofoId()!=retailerId) {
                        throw new ProfitMandiBusinessException("Unauthorised", "Unauthorised", "Unauthorised");
                }
                sdCreditService.settleLoan(loan);
                return responseSender.ok(walletService.getWalletAmount(retailerId));
        }

}