Subversion Repositories SmartDukaan

Rev

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

package com.spice.profitmandi.web.controller;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.ProfitMandiConstants;
import com.spice.profitmandi.common.util.Utils;
import com.spice.profitmandi.dao.entity.User;
import com.spice.profitmandi.dao.entity.UserAccounts;
import com.spice.profitmandi.dao.enumuration.AccountType;
import com.spice.profitmandi.dao.repository.UserAccountRepository;
import com.spice.profitmandi.dao.repository.UserRepository;
import com.spice.profitmandi.thrift.clients.TransactionClient;
import com.spice.profitmandi.thrift.clients.PaymentClient;
import com.spice.profitmandi.web.model.ProfitMandiResponse;
import com.spice.profitmandi.web.model.ResponseStatus;
import com.spice.profitmandi.web.req.CreateRechargeRequest;
import com.spice.profitmandi.web.res.ConfirmRechargeResponse;
import com.spice.profitmandi.web.res.CreateRechargeResponse;
import com.spice.profitmandi.web.res.MyRechargesResponse;
import com.spice.profitmandi.web.res.RechargeResultPojo;

import in.shop2020.model.v1.order.DenominationType;
import in.shop2020.model.v1.order.DeviceNumberInfo;
import in.shop2020.model.v1.order.OrderType;
import in.shop2020.model.v1.order.RechargeDenomination;
import in.shop2020.model.v1.order.RechargeOrder;
import in.shop2020.model.v1.order.RechargeOrderStatus;
import in.shop2020.model.v1.order.RechargeType;
import in.shop2020.model.v1.order.TransactionServiceException;
import in.shop2020.model.v1.order.UserWallet;
import in.shop2020.payments.Payment;
import in.shop2020.payments.PaymentException;
import in.shop2020.payments.PaymentStatus;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@Controller
@Transactional
public class RechargeController {

        private static final Logger log=LoggerFactory.getLogger(RechargeController.class);
        private static final String HEADER_X_FORWARDED_FOR = "X-FORWARDED-FOR";

        @Autowired
        UserAccountRepository userAccountRepository;

        @Autowired
        UserRepository userRepository;

        @RequestMapping(value = ProfitMandiConstants.URL_GET_SERVICE_PROVIDER, method=RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", 
                                required = true, dataType = "string", paramType = "header")
        })
        @ApiOperation(value = "")
        public ResponseEntity<?> getServiceProvider(HttpServletRequest request, @RequestParam(value="deviceNumber") String deviceNumber, @RequestParam(value="rechargeType") String rechargeType){
                DeviceNumberInfo deviceInfo = null;
                TransactionClient tcl;
                try {
                        tcl = new TransactionClient();
                        deviceInfo = tcl.getClient().getServiceProviderForDevice(RechargeType.valueOf(rechargeType), deviceNumber.substring(0,4));
                } catch (Exception e) {
                        log.error("Unable to get service provider for Device number " + deviceNumber + " and rechargeType : " +  rechargeType, e);
                }
                final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.OK.toString(), HttpStatus.OK, ResponseStatus.SUCCESS, deviceInfo);
                return new ResponseEntity<>(profitMandiResponse,HttpStatus.OK);
        }

        @RequestMapping(value = ProfitMandiConstants.URL_GET_ALL_DENOMINATIONS, method=RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", 
                                required = true, dataType = "string", paramType = "header")
        })
        @ApiOperation(value = "")
        public ResponseEntity<?> getAllDenominations(HttpServletRequest request, @RequestParam(value="operatorId") long operatorId, @RequestParam(value="circleCode") String circleCode, @RequestParam(value="denominationType") String denominationType){
                List<RechargeDenomination> rechargeDenominations = new ArrayList<RechargeDenomination>();
                TransactionClient tcl;
                try {
                        tcl = new TransactionClient();
                        rechargeDenominations =  tcl.getClient().getRechargeDenominations(operatorId, circleCode, DenominationType.valueOf(denominationType));
                } catch (Exception e) {
                        log.error("Unable to get rechargeDenominations for operatorId " + operatorId + " and circleCode : " +  circleCode + " and DenominationType : " + denominationType, e);
                }
                final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.OK.toString(), HttpStatus.OK, ResponseStatus.SUCCESS, rechargeDenominations);
                return new ResponseEntity<>(profitMandiResponse,HttpStatus.OK);
        }

        @RequestMapping(value = ProfitMandiConstants.URL_MOBILE_OPERATORS, method=RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", 
                                required = true, dataType = "string", paramType = "header")
        })
        @ApiOperation(value = "")
        public ResponseEntity<?> getAllMobileOperators(HttpServletRequest request){
                Map<Long, String> mobileProviderMap = Utils.getMobileProvidersMap();
                final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.OK.toString(), HttpStatus.OK, ResponseStatus.SUCCESS, mobileProviderMap);
                return new ResponseEntity<>(profitMandiResponse,HttpStatus.OK);
        }

        @RequestMapping(value = ProfitMandiConstants.URL_DTH_OPERATORS, method=RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", 
                                required = true, dataType = "string", paramType = "header")
        })
        @ApiOperation(value = "")
        public ResponseEntity<?> getAllDTHOperators(HttpServletRequest request){
                Map<Long, String> dthProviderMap = Utils.getDthProvidersMap();
                final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.OK.toString(), HttpStatus.OK, ResponseStatus.SUCCESS, dthProviderMap);
                return new ResponseEntity<>(profitMandiResponse,HttpStatus.OK);
        }

        @RequestMapping(value = ProfitMandiConstants.URL_RECHARGE_CONFIRM, method=RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", 
                                required = true, dataType = "string", paramType = "header")
        })
        @ApiOperation(value = "")
        public ResponseEntity<?> confirmRecharge(HttpServletRequest request, @RequestParam(value="rechargeAmount") long rechargeAmount){
                int userId = (int)request.getAttribute("userId");
                UserAccounts userAccount = null;
                UserWallet wallet = null;
                if (rechargeAmount <=0){
                        final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.BAD_REQUEST.toString(), HttpStatus.BAD_REQUEST, ResponseStatus.SUCCESS, null);
                        return new ResponseEntity<>(profitMandiResponse,HttpStatus.BAD_REQUEST);
                }

                try {
                        userAccount = userAccountRepository.getUserAccountByType(userId, AccountType.saholic);
                } catch (ProfitMandiBusinessException e) {
                        final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.INTERNAL_SERVER_ERROR.toString(), HttpStatus.INTERNAL_SERVER_ERROR, ResponseStatus.SUCCESS, null);
                        return new ResponseEntity<>(profitMandiResponse,HttpStatus.INTERNAL_SERVER_ERROR);
                }
                try {
                        TransactionClient tc = new TransactionClient();
                        wallet = tc.getClient().getUserWallet(Long.valueOf(userAccount.getAccount_key()));
                } catch (NumberFormatException | TException e) {
                        final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.INTERNAL_SERVER_ERROR.toString(), HttpStatus.INTERNAL_SERVER_ERROR, ResponseStatus.SUCCESS, null);
                        return new ResponseEntity<>(profitMandiResponse,HttpStatus.INTERNAL_SERVER_ERROR);
                }

                ConfirmRechargeResponse crr = new ConfirmRechargeResponse();
                crr.setWalletAmount(wallet.getAmount());
                crr.setWalletAmountLeft(wallet.getAmount() - rechargeAmount);
                crr.setCanProceed(true);
                if (crr.getWalletAmountLeft() < 0){
                        crr.setCanProceed(false);
                        crr.setReason("You don't have sufficient wallet balance");
                }
                final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.OK.toString(), HttpStatus.OK, ResponseStatus.SUCCESS, crr);
                return new ResponseEntity<>(profitMandiResponse,HttpStatus.OK);
        }

        @RequestMapping(value = ProfitMandiConstants.URL_CREATE_RECHARGE , method=RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", 
                                required = true, dataType = "string", paramType = "header")
        })
        public ResponseEntity<?> createRecharge(HttpServletRequest request, @RequestBody CreateRechargeRequest createRechargeRequest){
                String ipAddress  = remoteAddr(request);
                String errorMessage = validateRecharge(RechargeType.valueOf(createRechargeRequest.getRechargeType()), createRechargeRequest.getNumber(), createRechargeRequest.getOperatorId(), ipAddress);
                CreateRechargeResponse crr =  new CreateRechargeResponse();
                if(!errorMessage.equals("SUCCESS")){
                        crr.setReason(errorMessage);
                        crr.setResult(false);
                        final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.BAD_REQUEST.toString(), HttpStatus.BAD_REQUEST, ResponseStatus.SUCCESS, crr);
                        return new ResponseEntity<>(profitMandiResponse,HttpStatus.BAD_REQUEST);
                }
                int userId = (int)request.getAttribute("userId");
                UserAccounts userAccount = null;
                UserWallet wallet = null;
                if (createRechargeRequest.getRechargeAmount() <=0){
                        crr.setReason("Illegal recharge amount");
                        crr.setResult(false);
                        final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.BAD_REQUEST.toString(), HttpStatus.BAD_REQUEST, ResponseStatus.SUCCESS, crr);
                        return new ResponseEntity<>(profitMandiResponse,HttpStatus.BAD_REQUEST);
                }

                try {
                        userAccount = userAccountRepository.getUserAccountByType(userId, AccountType.saholic);
                } catch (ProfitMandiBusinessException e) {
                        log.error("Unable to get user account ",e);
                        crr.setReason("We are experiencing some problem right now.");
                        crr.setResult(false);
                        final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.INTERNAL_SERVER_ERROR.toString(), HttpStatus.INTERNAL_SERVER_ERROR, ResponseStatus.SUCCESS, crr);
                        return new ResponseEntity<>(profitMandiResponse,HttpStatus.INTERNAL_SERVER_ERROR);
                }
                try {
                        TransactionClient tc = new TransactionClient();
                        wallet = tc.getClient().getUserWallet(Long.valueOf(userAccount.getAccount_key()));
                } catch (NumberFormatException | TException e) {
                        log.error("Unable to get user wallet ",e);
                        crr.setReason("We are experiencing some problem right now.");
                        crr.setResult(false);
                        final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.INTERNAL_SERVER_ERROR.toString(), HttpStatus.INTERNAL_SERVER_ERROR, ResponseStatus.SUCCESS, crr);
                        return new ResponseEntity<>(profitMandiResponse,HttpStatus.INTERNAL_SERVER_ERROR);
                }

                if (wallet.getAmount() < createRechargeRequest.getRechargeAmount()){
                        crr.setReason("You don't have sufficient wallet balance.");
                        crr.setResult(false);
                        final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.BAD_REQUEST.toString(), HttpStatus.BAD_REQUEST, ResponseStatus.SUCCESS, crr);
                        return new ResponseEntity<>(profitMandiResponse,HttpStatus.BAD_REQUEST);
                }

                User user = null;
                try {
                        user = userRepository.selectById(userId);
                } catch (ProfitMandiBusinessException e) {
                        log.error("Unable to get user",e);
                        crr.setReason("We are experiencing some problem right now.");
                        crr.setResult(false);
                        final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.INTERNAL_SERVER_ERROR.toString(), HttpStatus.INTERNAL_SERVER_ERROR, ResponseStatus.SUCCESS, crr);
                        return new ResponseEntity<>(profitMandiResponse,HttpStatus.INTERNAL_SERVER_ERROR);
                }


                RechargeOrder t_rechargeOrder = new RechargeOrder();
                t_rechargeOrder.setTotalAmount(createRechargeRequest.getRechargeAmount());
                t_rechargeOrder.setUserEmailId(user.getEmailId());
                t_rechargeOrder.setUserId(Long.valueOf(userAccount.getAccount_key()));
                t_rechargeOrder.setDeviceNumber(createRechargeRequest.getNumber());
                t_rechargeOrder.setPlan(createRechargeRequest.getPlan()==null?"":createRechargeRequest.getPlan());
                t_rechargeOrder.setOperatorId(createRechargeRequest.getOperatorId());
                t_rechargeOrder.setRechargeType(RechargeType.valueOf(createRechargeRequest.getRechargeType()));
                t_rechargeOrder.setStatus(RechargeOrderStatus.PAYMENT_PENDING);
                t_rechargeOrder.setOrderType(OrderType.B2C);
                t_rechargeOrder.setWalletAmount(createRechargeRequest.getRechargeAmount());
                t_rechargeOrder.setCouponAmount(0);
                t_rechargeOrder.setCouponCode("");
                t_rechargeOrder.setIpAddress(ipAddress);
                TransactionClient tc = null;
                RechargeOrder rechargeOrder;
                try {
                        tc = new TransactionClient();
                        rechargeOrder = tc.getClient().createRechargeOrder(t_rechargeOrder);
                } catch (TransactionServiceException | TException e) {
                        log.error("Unable to create recharge order",e);
                        crr.setReason("We are experiencing some problem right now.");
                        crr.setResult(false);
                        final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.INTERNAL_SERVER_ERROR.toString(), HttpStatus.INTERNAL_SERVER_ERROR, ResponseStatus.SUCCESS, crr);
                        return new ResponseEntity<>(profitMandiResponse,HttpStatus.INTERNAL_SERVER_ERROR);
                }

                log.info("Recharge Order:" + rechargeOrder);
                PaymentClient paymentServiceClient = null;
                try {
                        paymentServiceClient = new PaymentClient();
                } catch (TTransportException e) {
                        log.error("Unable to create payment client",e);
                        crr.setReason("We are experiencing some problem right now.");
                        crr.setResult(false);
                        final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.INTERNAL_SERVER_ERROR.toString(), HttpStatus.INTERNAL_SERVER_ERROR, ResponseStatus.SUCCESS, crr);
                        return new ResponseEntity<>(profitMandiResponse,HttpStatus.INTERNAL_SERVER_ERROR);
                }
                try {
                        RechargeOrder d_rechargeOrder = tc.getClient().getRechargeOrder(rechargeOrder.getId());
                        List<Payment> payments = paymentServiceClient.getClient().getPaymentForRechargeTxnId(d_rechargeOrder.getTransactionId());
                        if(payments.size() > 0) {
                                throw new PaymentException(d_rechargeOrder.getId(), "Payment already exists for recharge");
                        }
                        Long merchantPaymentId = 0l;
                        if (d_rechargeOrder.getWalletAmount() +  d_rechargeOrder.getCouponAmount() != d_rechargeOrder.getTotalAmount()) {
                                log.error("Wallet amount : " + d_rechargeOrder.getWalletAmount() + ", coupon amount : " + d_rechargeOrder.getCouponAmount() + " and total amount : " + d_rechargeOrder.getTotalAmount());
                                merchantPaymentId = paymentServiceClient.getClient().createPayment(d_rechargeOrder.getUserId(), d_rechargeOrder.getTotalAmount(), 8, d_rechargeOrder.getTransactionId(), true);
                                paymentServiceClient.getClient().updatePaymentDetails(merchantPaymentId, "","", "0", "", "", "", "", "", PaymentStatus.FAILED, "", null);
                                tc.getClient().updateRechargeOrderStatus(d_rechargeOrder.getId(),  RechargeOrderStatus.PAYMENT_FAILED);
                        } else {
                                merchantPaymentId = paymentServiceClient.getClient().createPayment(d_rechargeOrder.getUserId(), d_rechargeOrder.getTotalAmount(), 8, d_rechargeOrder.getTransactionId(), true);
                                //Update payment status as authorized
                                paymentServiceClient.getClient().updatePaymentDetails(merchantPaymentId, "","", "0", "", "", "", "", "", PaymentStatus.SUCCESS, "", null);
                                tc.getClient().updateRechargeOrderStatus(d_rechargeOrder.getId(),  RechargeOrderStatus.PAYMENT_SUCCESSFUL);
                        }
                        crr.setRechargeOrderId(d_rechargeOrder.getId());
                        crr.setResult(true);
                } catch (Exception e) {
                        log.error("Unable to mark the payment as authorized", e);
                        crr.setReason("We are experiencing some problem right now.");
                        crr.setResult(false);
                        final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.INTERNAL_SERVER_ERROR.toString(), HttpStatus.INTERNAL_SERVER_ERROR, ResponseStatus.SUCCESS, crr);
                        return new ResponseEntity<>(profitMandiResponse,HttpStatus.INTERNAL_SERVER_ERROR);
                }
                final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.OK.toString(), HttpStatus.OK, ResponseStatus.SUCCESS, crr);
                return new ResponseEntity<>(profitMandiResponse,HttpStatus.OK);
        }

        @RequestMapping(value = ProfitMandiConstants.URL_RECHARGE_RESULT , method=RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", 
                                required = true, dataType = "string", paramType = "header")
        })
        public ResponseEntity<?> rechargeResult(HttpServletRequest request, @RequestParam(value="rechargeOrderId") long rechargeOrderId){
                TransactionClient tc=null;
                RechargeOrder rechargeOrder = null;
                RechargeResultPojo rrp = null;
                try {
                        tc = new TransactionClient();
                        rechargeOrder = tc.getClient().getRechargeOrder(rechargeOrderId);
                } catch (TransactionServiceException | TException e) {
                        // return with internal server error
                        e.printStackTrace();
                        rrp = new RechargeResultPojo();
                        rrp.setIsError(true);
                        rrp.setDetailDisplayMessage("We are experiencing some problem right now.");
                        final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.INTERNAL_SERVER_ERROR.toString(), HttpStatus.INTERNAL_SERVER_ERROR, ResponseStatus.SUCCESS, rrp);
                        return new ResponseEntity<>(profitMandiResponse,HttpStatus.INTERNAL_SERVER_ERROR);
                }
                if (rechargeOrder == null){
                        rrp = new RechargeResultPojo();
                        rrp.setIsError(true);
                        rrp.setDetailDisplayMessage("Recharge order doesnot exist in our system.");
                        final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.BAD_REQUEST.toString(), HttpStatus.BAD_REQUEST, ResponseStatus.SUCCESS, rrp);
                        return new ResponseEntity<>(profitMandiResponse,HttpStatus.BAD_REQUEST);
                }
                String[] os = Utils.getOrderStatus(rechargeOrder.getStatus());
                rrp = new RechargeResultPojo();
                rrp.setRechargeDeviceNumber(rechargeOrder.getDeviceNumber());
                rrp.setRechargeDisplayId(rechargeOrder.getDisplayId());
                rrp.setTotalAmount(rechargeOrder.getTotalAmount() + "");
                rrp.setRechargeProvider(Utils.getProvider(rechargeOrder.getOperatorId()));
                rrp.setIsError(Boolean.parseBoolean(os[0]));
                rrp.setRechargeStatus(os[1]);
                rrp.setDetailDisplayMessage(os[2]);
                if (rechargeOrder.getStatus().equals(RechargeOrderStatus.RECHARGE_UNKNOWN)){
                        rrp.setPoll(true);
                }
                final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.OK.toString(), HttpStatus.OK, ResponseStatus.SUCCESS, rrp);
                return new ResponseEntity<>(profitMandiResponse,HttpStatus.OK);
        }

        @RequestMapping(value = ProfitMandiConstants.URL_POLL_RECHARGE , method=RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", 
                                required = true, dataType = "string", paramType = "header")
        })
        public ResponseEntity<?> pollRechargeResult(HttpServletRequest request, @RequestParam(value="rechargeOrderId") long rechargeOrderId, @RequestParam(value="finalCall") boolean finalCall){
                TransactionClient transactionServiceClient = null;
                RechargeOrder t_rechargeOrder = null;
                RechargeResultPojo rrp = null;
                try{
                        transactionServiceClient = new TransactionClient();
                        t_rechargeOrder = transactionServiceClient.getClient().getRcgOrderStatus(rechargeOrderId, finalCall);
                }
                catch(Exception e){
                        rrp = new RechargeResultPojo();
                        rrp.setRechargeStatus("");
                        final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.INTERNAL_SERVER_ERROR.toString(), HttpStatus.INTERNAL_SERVER_ERROR, ResponseStatus.SUCCESS, rrp);
                        return new ResponseEntity<>(profitMandiResponse,HttpStatus.INTERNAL_SERVER_ERROR);      
                }
                if (t_rechargeOrder == null){
                        rrp = new RechargeResultPojo();
                        rrp.setRechargeStatus("");
                        final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.INTERNAL_SERVER_ERROR.toString(), HttpStatus.INTERNAL_SERVER_ERROR, ResponseStatus.SUCCESS, new RechargeResultPojo());
                        return new ResponseEntity<>(profitMandiResponse,HttpStatus.INTERNAL_SERVER_ERROR);      
                }
                rrp = new RechargeResultPojo();
                rrp.setRechargeStatus(t_rechargeOrder.getStatus().name());
                final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.OK.toString(), HttpStatus.OK, ResponseStatus.SUCCESS, rrp);
                return new ResponseEntity<>(profitMandiResponse,HttpStatus.OK);
        }
        
        @RequestMapping(value = ProfitMandiConstants.URL_MY_RECHARGES , method=RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
        @ApiImplicitParams({
                @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", 
                                required = true, dataType = "string", paramType = "header")
        })
        public ResponseEntity<?> myRecharges(HttpServletRequest request, @RequestParam(value="offset") int offset, @RequestParam(value="limit") int limit){
                TransactionClient tc=null;
                int userId = (int)request.getAttribute("userId");
                UserAccounts userAccount;
                List<RechargeOrder> rechargeOrders = null;
                try {
                        userAccount = userAccountRepository.getUserAccountByType(userId, AccountType.saholic);
                } catch (ProfitMandiBusinessException e) {
                        log.error("Unable to get user account ",e);
                        final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.INTERNAL_SERVER_ERROR.toString(), HttpStatus.INTERNAL_SERVER_ERROR, ResponseStatus.SUCCESS, new ArrayList<MyRechargesResponse>());
                        return new ResponseEntity<>(profitMandiResponse,HttpStatus.INTERNAL_SERVER_ERROR);
                }
                try {
                        tc = new TransactionClient();
                        rechargeOrders = tc.getClient().getPaginatedRechargeOrders(Long.valueOf(userAccount.getAccount_key()), offset, limit);
                } catch (Exception e) {
                        log.error("Unable to get recharge order list",e);
                        final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.INTERNAL_SERVER_ERROR.toString(), HttpStatus.INTERNAL_SERVER_ERROR, ResponseStatus.SUCCESS, new ArrayList<MyRechargesResponse>());
                        return new ResponseEntity<>(profitMandiResponse,HttpStatus.INTERNAL_SERVER_ERROR);
                }
                List<MyRechargesResponse> myRechargesList = new ArrayList<MyRechargesResponse>();
                for (RechargeOrder rechargeOrder : rechargeOrders){
                        MyRechargesResponse rp = new MyRechargesResponse();
                        if(rechargeOrder.getRechargeType() == RechargeType.MOBILE){
                        rp.setOperator(Utils.getProvider(rechargeOrder.getOperatorId()));
                        rp.setOperatorType("MOBILE");
                }
                if(rechargeOrder.getRechargeType() == RechargeType.DTH){
                        rp.setOperator(Utils.getProvider(rechargeOrder.getOperatorId()));
                        rp.setOperatorType("DTH");
                }
                rp.setOrderId(rechargeOrder.getId());
                rp.setOperatorId(rechargeOrder.getOperatorId());
                rp.setDate(rechargeOrder.getCreationTimestamp());
                rp.setNumber(rechargeOrder.getDeviceNumber());
                rp.setAmount(rechargeOrder.getTotalAmount());
                rp.setStatus(Utils.getRechargeDisplayStatus(rechargeOrder.getStatus()));
                rp.setDisplayOrderId(rechargeOrder.getDisplayId());
                myRechargesList.add(rp);
                }
                final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.OK.toString(), HttpStatus.OK, ResponseStatus.SUCCESS, myRechargesList);
                return new ResponseEntity<>(profitMandiResponse,HttpStatus.OK);
        }

        
        private String remoteAddr(HttpServletRequest request) {
                String remoteAddr = "";
                String x;
                x = request.getHeader(HEADER_X_FORWARDED_FOR);
                if (x != null && !x.isEmpty()) {
                        remoteAddr = x;
                        int idx = remoteAddr.lastIndexOf(',');
                        if (idx > -1) {
                                remoteAddr = remoteAddr.substring(idx + 1).trim();
                        }
                } else {
                        remoteAddr = request.getRemoteAddr();
                }
                return remoteAddr;
        }

        private String validateRecharge(RechargeType rechargeType, String number, long operatorId, String ipAddress){
                TransactionClient tcl;
                try {
                        tcl = new TransactionClient();
                        String result = tcl.getClient().validateRecharge(rechargeType, number, operatorId, ipAddress);
                        log.info("validateRecharge Called" + number + " and rechargeType : " +  rechargeType + ", IP:" + ipAddress + ", Operator:" + operatorId + ", Result:" + result);
                        return result;
                } catch (Exception e) {
                        log.error("Unable to get service provider for Device number " + number + " and rechargeType : " +  rechargeType, e);
                }
                return "Oops! There seems to be a problem. Please try after some time";
        }


}