Subversion Repositories SmartDukaan

Rev

Rev 35321 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.web.controller;

import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.CustomRetailer;
import com.spice.profitmandi.common.model.ProfitMandiConstants;
import com.spice.profitmandi.common.web.util.ResponseSender;
import com.spice.profitmandi.dao.entity.fofo.FofoPayment;
import com.spice.profitmandi.dao.entity.transaction.AddWalletRequest;
import com.spice.profitmandi.dao.entity.transaction.HdfcPayment;
import com.spice.profitmandi.dao.enumuration.fofo.Gateway;
import com.spice.profitmandi.dao.enumuration.transaction.AddWalletRequestStatus;
import com.spice.profitmandi.dao.model.PaymentOptionModel;
import com.spice.profitmandi.dao.repository.catalog.AddWalletRequestRepository;
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
import com.spice.profitmandi.dao.repository.fofo.FofoPaymentRepository;
import com.spice.profitmandi.dao.repository.transaction.HdfcPaymentRepository;
import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;
import com.spice.profitmandi.service.integrations.CCAvenuePaymentService;
import com.spice.profitmandi.service.user.RetailerService;
import com.spice.profitmandi.service.wallet.WalletService;
import com.spice.profitmandi.web.req.CreateAddMoneyRequest;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import static com.spice.profitmandi.dao.enumuration.transaction.AddWalletRequestStatus.approved;

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

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

        @Autowired
        UserWalletRepository userWalletRepository;
        
        @Autowired
        FofoPaymentRepository fofoPaymentRepository;

        @Autowired
        AddWalletRequestRepository addWalletRequestRepository;

        @Autowired
        WalletService walletService;

        @Autowired
        JavaMailSender mailSender;

        @Autowired
        @Qualifier("userRepository")
        private UserRepository userRepository;
        
        @Autowired
        private CCAvenuePaymentService ccAvenuePaymentService;

        @Autowired
        private UserAccountRepository userAccountRepository;

        @Autowired
        private RetailerService retailerService;

        @Autowired
        ResponseSender<?> responseSender;

        @RequestMapping(value = ProfitMandiConstants.URL_MY_WALLET, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        @ApiOperation(value = "")
        @Transactional(readOnly = true)
        public ResponseEntity<?> getMyWallet(HttpServletRequest request) throws ProfitMandiBusinessException {
                int userId = (int) request.getAttribute("userId");
                return responseSender.ok(walletService.getUserWalletByUserId(userId));
        }

        @RequestMapping(value = ProfitMandiConstants.URL_MY_WALLET_HISTORY, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        @Transactional(readOnly = true)
        public ResponseEntity<?> getMyWalletHistory(HttpServletRequest request) throws ProfitMandiBusinessException {
                int userId = (int) request.getAttribute("userId");
                int retailerId = userAccountRepository.selectRetailerIdByUserId(userId);
                try {
                        return responseSender.ok(walletService.getPaginatedUserWalletHistoryByRetailerId(retailerId, null, null, 0, 150));
                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
                        return responseSender.badRequest(profitMandiBusinessException);
                }
        }
        
        @RequestMapping(value = "/wallet/add-via-loan", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        public ResponseEntity<?> payViaLoan(HttpServletRequest request, @RequestParam double loanAmount, 
                        @RequestParam double surcharge,
                        @RequestParam String payMethod,  @RequestParam Gateway gateway) throws Exception {
                List<PaymentOptionModel> paymentOptionModels = ccAvenuePaymentService.getPaymentOptionModelMap().get(gateway);
                Optional<PaymentOptionModel> optPaymentOptionModel = paymentOptionModels.stream().filter(x->x.getPaymentMethod().equals(payMethod)).findFirst();
                
                if(!optPaymentOptionModel.isPresent()) {
                        return responseSender.badRequest(new ProfitMandiBusinessException("", "", "Bad parameters in request"));
                } else {
                        double interimValue = optPaymentOptionModel.get().getSurcharge() * 1.18 / 100;
                        double calculatedSurcharge = Math.round(loanAmount * interimValue / (1 - interimValue));
                        if (Math.abs(calculatedSurcharge - surcharge) >= 1) {
                                return responseSender.badRequest(new ProfitMandiBusinessException("", "", "Bad parameters in request"));
                        }
                }
                int userId = (int) request.getAttribute("userId");
                int retailerId = userAccountRepository.selectRetailerIdByUserId(userId);
                FofoPayment fofoPayment = new FofoPayment();
                fofoPayment.setCreateTimestamp(LocalDateTime.now());
                fofoPayment.setFofoId(retailerId);
                fofoPayment.setAmount(loanAmount);
                fofoPayment.setGatewayFee(surcharge);
                fofoPayment.setGateway(gateway);
                fofoPayment.setPaymentMethod(optPaymentOptionModel.get().getPaymentMethodDesctiption());
                fofoPaymentRepository.persist(fofoPayment);
                Map<String, String> returnMap = ccAvenuePaymentService.getFormParams(fofoPayment, payMethod);
                returnMap.put("status", "pending");
                return responseSender.ok(returnMap);

        }

    @Autowired
    HdfcPaymentRepository hdfcPaymentRepository;

        @RequestMapping(value = ProfitMandiConstants.URL_ADD_MONEY_TO_WALLET, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        public ResponseEntity<?> addMoneyToWallet(HttpServletRequest request,
                        @RequestBody CreateAddMoneyRequest createAddMoneyRequest) throws Exception {
                int userId = (int) request.getAttribute(ProfitMandiConstants.USER_ID);
                log.info("user_id" + userId);
        String transactionReference = createAddMoneyRequest.getTransaction_reference();
        List<AddWalletRequest> addWalletRequests = addWalletRequestRepository.selectByReference(transactionReference);
        addWalletRequests = addWalletRequests.stream().filter(x -> Arrays.asList(approved, AddWalletRequestStatus.pending).contains(x.getStatus())).collect(Collectors.toList());
        if (addWalletRequests.size() > 0) {
            throw new ProfitMandiBusinessException("Transaction Reference (UTR)", transactionReference, "Already added");
        }
        HdfcPayment hdfcPayment = hdfcPaymentRepository.selectByUtrNo(transactionReference);
        if (hdfcPayment != null) {
            throw new ProfitMandiBusinessException("Transaction Reference (UTR)", transactionReference, "Already added");
        }
                int retailerId = userAccountRepository.selectRetailerIdByUserId(userId);
                CustomRetailer customRetailer = retailerService.getFofoRetailer(retailerId);
                AddWalletRequest addWalletrequest = new AddWalletRequest();
                addWalletrequest.setRetailerId(retailerId);
                addWalletrequest.setAmount(createAddMoneyRequest.getAmount());
                addWalletrequest.setTransaction_reference(createAddMoneyRequest.getTransaction_reference());
                addWalletrequest.setReference_date(createAddMoneyRequest.getReference_date());
                addWalletrequest.setBank_name(createAddMoneyRequest.getBank_name());
                addWalletrequest.setStatus(AddWalletRequestStatus.pending);
                log.info("info" + addWalletrequest);
                addWalletRequestRepository.persist(addWalletrequest);
                log.info("fofoinfo" + customRetailer);
                String subject = "Add money to wallet request";
                String messageText = MessageFormat.format(
                                "User Id - {0}\n Name -{1}\n Email -{2}\n Reference - {3}\n Amount - Rs.{4} \n link - {5}",
                                new Integer(addWalletrequest.getRetailerId()), customRetailer.getBusinessName(),
                                customRetailer.getEmail(), addWalletrequest.getTransaction_reference(),
                                new Float(addWalletrequest.getAmount()), "http://partners.smartdukaan.com/dashboard");
                String email = "neeraj.gupta@smartdukaan.com";
                //this.sendMailWithAttachments(email, subject, messageText);

                return responseSender.ok(true);
        }
        
        @RequestMapping(value = "/wallet/add-money/{loanId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        @Transactional(readOnly = true)
        public ResponseEntity<?> addMoneyToWallet(HttpServletRequest request,@PathVariable int loanId) throws Exception {
                int userId = (int) request.getAttribute(ProfitMandiConstants.USER_ID);
                log.info("user_id" + userId);
                int retailerId = userAccountRepository.selectRetailerIdByUserId(userId);
                
                FofoPayment fofoPayment = fofoPaymentRepository.selectById(loanId);
                if(fofoPayment.getFofoId()!=retailerId) {
                        return responseSender.badRequest(new ProfitMandiBusinessException("Invalid Add Money Id", "Invalid Add money id", "Invalid Add Money"));
                }
                return responseSender.ok(fofoPayment);
        }

        private void sendMailWithAttachments(String email, String subject, String messageText) throws Exception {
                log.info("message" + messageText);
                MimeMessage message = mailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                helper.setSubject(subject);
                helper.setText(messageText);
                helper.setTo(email);
                // helper.setCc("neerajgupta2021@gmail.com");
                InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "ProfitMandi Admin");
                helper.setFrom(senderAddress);
                mailSender.send(message);

        }

        @RequestMapping(value = ProfitMandiConstants.URL_ADD_MONEY_TO_WALLET_HISTORY, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                        @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
        @Transactional(readOnly = true)
        public ResponseEntity<?> getAddMoneyToWalletHistory(HttpServletRequest request,
                        @RequestParam(name = "offset", defaultValue = "0") int offset,
                        @RequestParam(name = "limit", defaultValue = "10") int limit) throws ProfitMandiBusinessException {
                int userId = (int) request.getAttribute(ProfitMandiConstants.USER_ID);
                int retailerId = userAccountRepository.selectRetailerIdByUserId(userId);
                List<AddWalletRequest> walletRequest = addWalletRequestRepository.selectByRetailerId(offset, limit, retailerId);
                return responseSender.ok(walletRequest);
        }
        
        
        
        @RequestMapping(value = "/getPaymentOptions", method = RequestMethod.GET)
        @Transactional(readOnly = true)
        public ResponseEntity<?> getPaymentOptions(HttpServletRequest request, Model model) throws Exception {
                return responseSender.ok(ccAvenuePaymentService.getPaymentOptionModelMap());
        }

}