Subversion Repositories SmartDukaan

Rev

Rev 12978 | Blame | Compare with Previous | Last modification | View Log | RSS feed

package in.shop2020.serving.controllers;

import in.shop2020.datalogger.EventType;
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.user.PromotionException;
import in.shop2020.payments.PaymentException;
import in.shop2020.serving.utils.FormattingUtils;
import in.shop2020.thrift.clients.PaymentClient;
import in.shop2020.thrift.clients.PromotionClient;
import in.shop2020.thrift.clients.TransactionClient;
import in.shop2020.utils.DataLogger;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;

public class RechargeResultController extends BaseController {
    private static final long serialVersionUID = 1L;

//    private static final String SHOOGLOO_AFF_NAME = "shoogloo";

    private static Logger log = Logger.getLogger(Class.class);
    private FormattingUtils formattingUtils = new FormattingUtils();

    //private boolean isShooglooAff  = false;
    
    private static Map<Long,String> allProviders;
    private static List<Long> asyncOperators = Arrays.asList(9l);
    private boolean rechargeModeAsynchronous = false;
    private String rechargeOrderId;
    private String isFinal;
    private String newStatus;

    public String getIsFinal() {
        return isFinal;
    }

    public void setIsFinal(String isFinal) {
        this.isFinal = isFinal;
    }

    static {
        try {
                        allProviders = new TransactionClient().getClient().getServiceProviders(RechargeType.DTH, true);
                        allProviders.putAll(new TransactionClient().getClient().getServiceProviders(RechargeType.MOBILE, true));
                } catch (TTransportException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                } catch (TException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
    }
    
    private static Map<String, String> FailureReasonMap;
    static {
        FailureReasonMap = new HashMap<String, String>();
        FailureReasonMap.put("Invalid Amount", "the amount you tried seems to be invalid. Please try another amount.");
        FailureReasonMap.put("Customer Exceeded Daily Limit", "you have exceeded daily recharge limit for this number. Please try after 12 hours.");
        FailureReasonMap.put("Invalid Device Number", "it seems that your device number is not being recognized by selected operator. Please make sure the number you tried is correct.");
    }
    
    long merchantPaymentId;
    RechargeOrder rechargeOrder = null;
    String message = null;

    public RechargeResultController(){
        super();
    }
    
    public String index() {
        PaymentClient paymentServiceClient = null;
        TransactionClient transactionServiceClient = null;
        //UserClient userServiceClient = null;

        try {
            paymentServiceClient = new PaymentClient();
            transactionServiceClient = new TransactionClient();
          //  userServiceClient = new UserClient();
        } catch (Exception e1) {
            // TODO Nothing to worry
            log.error("Unable to initialize the client for either payment or transaction or user service", e1);
        }

        String returningPayIdString = this.request.getParameter("paymentId");
        if (returningPayIdString == null || returningPayIdString.isEmpty()) {
            this.message = "Payment Failed at payment gateway. Please try again.";
            return "index";
        }
        merchantPaymentId = Long.parseLong(this.request.getParameter("paymentId"));
        long txnId;
        try {
            txnId = paymentServiceClient.getClient().getPayment(merchantPaymentId).getMerchantTxnId();
            rechargeOrder = transactionServiceClient.getClient().getRechargeOrdersForTransaction(txnId);

            this.message = "You have successfully recharged your mobile.";

            /*if (cookiesMap.containsKey(TrackingInterceptor.AFF_COOKIE)) {
                long affId = Long.parseLong(cookiesMap.get(TrackingInterceptor.AFF_COOKIE).getValue());
                userServiceClient.getClient().addTrackLog(affId, userinfo.getUserId(), TrackLogType.PAYMENT_SUCCESS, "",
                        Long.toString(merchantPaymentId), (new Date()).getTime());
                Affiliate aff = userServiceClient.getClient().getAffiliateById(affId);
                if (aff.getName().equals(SHOOGLOO_AFF_NAME)) {
                    isShooglooAff = true;
                }
            }*/

        } catch (PaymentException e) {
            log.error("Payment service not responding. Payment id is" + merchantPaymentId, e);
        } catch (TException e) {
            log.error("Thrift service exception. Payment id is" + merchantPaymentId, e);
        } catch (TransactionServiceException e) {
            log.error("Transaction service exception. Payment id is" + merchantPaymentId, e);
        }
        
//        catch (UserAffiliateException e) {
//            log.error("Affiliate service exception. Payment id is" + merchantPaymentId, e);
//        }

        return "index";
    }

    public String formatPrice(double price)    {
        return formattingUtils.formatPrice(price);
    }

    public String getMessage(){
        return this.message;
    }

//    public boolean getIsShooglooAff() {
//        return this.isShooglooAff;
//    }

    public long getMerchantPaymentId() {
        return merchantPaymentId;
    }

    public static String formatDate(long timestamp){
        SimpleDateFormat dateformat = new SimpleDateFormat("dd MMMM yyyy");
        return dateformat.format(new Date(timestamp));  
    }


    @Override
    public String getHeaderSnippet() {
        String url = request.getQueryString();
        if (url == null) {
            url = "";
        } else {
            url = "?" + url;
        }
        url = request.getRequestURI() + url;
        return pageLoader.getHeaderHtml(userinfo.isLoggedIn(), userinfo.getEmail(), userinfo.getTotalItems(), url , 0, false, userinfo.isPrivateDealUser());
    }

    public RechargeOrder getRechargeOrder() {
        return rechargeOrder;
    }

    public void setRechargeOrder(RechargeOrder rechargeOrder) {
        this.rechargeOrder = rechargeOrder;
    }
    

    public boolean isDTH() {
        return rechargeOrder.getRechargeType().equals(RechargeType.DTH);
    }
    
    public String getProvider() {
        return allProviders.get(rechargeOrder.getOperatorId());
    }
    
    public String[] getOrderStatus(){
        RechargeOrderStatus status = null;
        if(rechargeOrder == null) {
            status = RechargeOrderStatus.INIT;
        } else {
            status = rechargeOrder.getStatus();
        }
        
        if(status.equals(RechargeOrderStatus.PAYMENT_FAILED)||status.equals(RechargeOrderStatus.PAYMENT_PENDING)){
//              DataLogger.logData(EventType.RECHARGE_PAYMENT_FAILED, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
//                              Long.toString(rechargeOrder.getOperatorId()), Long.toString(rechargeOrder.getTotalAmount()), Long.toString(rechargeOrder.getWalletAmount()),
//                    rechargeOrder.getRechargeType().toString());
                return new String[]{"red", "PAYMENT FAILED", "Payment failed at the payment gateway. Try to <a href='/recharge'>recharge again</a>"};
        }
        else if(status.equals(RechargeOrderStatus.PAYMENT_SUCCESSFUL) || status.equals(RechargeOrderStatus.RECHARGE_UNKNOWN)) {
            if (status.equals(RechargeOrderStatus.PAYMENT_SUCCESSFUL)){
//          DataLogger.logData(EventType.RECHARGE_PAYMENT_SUCCESSFUL, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
//                    Long.toString(rechargeOrder.getOperatorId()), Long.toString(rechargeOrder.getTotalAmount()), Long.toString(rechargeOrder.getWalletAmount()),
//                    rechargeOrder.getRechargeType().toString());
            return new String[]{"red", "RECHARGE IN PROCESS", "Your Payment was successful but due to some internal error with the operator's system we are not sure if the recharge was successful.<br>" +
                    "We have put your recharge under process. As soon as we get a confirmation on this transaction, we will notify you.<br>" +
                    "In case of recharge failure your entire amount will be credited to your " +
                    "<a href='/my-wallet'>recharge wallet</a>.<br><br> You " +
                    "will need to <a href='/login?redirectUrl=/recharge'>login</a> to use your Wallet.<br> If you are registered on" + 
                    " Saholic.com please use your username and password to Login.<br> In case you are " +
                    "a first time user, we have sent your login details on the emailId you gave us. " +
                    "<br>For more information <a href='/static/recharge-faq'>click here</a>"};
            }
            else{
                setRechargeModeAsynchronous(true);
                return new String[]{"green", "RECHARGE IN PROCESS", "Your Payment is successful.We have put your recharge under process." +
                        "Please wait while we check with the operator.<b>Please do not close</b> this window or click the Back button on your browser.<br>"};
            }
        }
        else if (status.equals(RechargeOrderStatus.RECHARGE_FAILED) || status.equals(RechargeOrderStatus.RECHARGE_FAILED_REFUNDED)){
//              DataLogger.logData(EventType.RECHARGE_PAYMENT_SUCCESSFUL, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
//                              Long.toString(rechargeOrder.getOperatorId()), Long.toString(rechargeOrder.getTotalAmount()), Long.toString(rechargeOrder.getWalletAmount()),
//                              rechargeOrder.getRechargeType().toString());
                String displayReason = FailureReasonMap.get(rechargeOrder.getDescription());
                if (!(displayReason == null || displayReason.isEmpty())) {
                    displayReason = "Your Payment was successful but unfortunately the recharge failed because " + displayReason + "<br>";
                } else {
                    displayReason = "Your Payment was successful but unfortunately the recharge failed.<br>";
                }
                        return new String[]{"red", "RECHARGE FAILED", displayReason +
                                        "Don't worry your payment is safe with us. The entire Amount has been refunded to your " +
                                        "<a href='/my-wallet'>recharge wallet</a>.<br><br> You " +
                                        "will need to <a href='/login?redirectUrl=/recharge'>login</a> to use your Wallet.<br> If you are registered on" + 
                                        " Saholic.com please use your username and password to Login.<br> In case you are " +
                                        "a first time user, we have sent your login details on the emailId you gave us. " +
                                        "<br>For more information <a href='/static/recharge-faq'>click here</a>"};
        } else if(status.equals(RechargeOrderStatus.RECHARGE_SUCCESSFUL)){
//              DataLogger.logData(EventType.RECHARGE_SUCCESSFUL, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
//                              Long.toString(rechargeOrder.getOperatorId()), Long.toString(rechargeOrder.getTotalAmount()), Long.toString(rechargeOrder.getWalletAmount()),
//                              rechargeOrder.getRechargeType().toString());
                
                String operator = "";
                if(isDTH()) {
                    operator = getProvider();
                } else {
                    operator = getProvider() + " mobile";
                }
                
                String original_referer = "http://www.saholic.com/recharge-result?paymentId=" + this.request.getParameter("paymentId");
                String fbUrl = "";
                String twitterUrl = "";
                String shareMsg = "";
                String giftMessage = "Congratulations! Your device is successfully recharged.";
            shareMsg = "I just recharged my " + operator + " at Saholic.com and am happy with their services.";
                        fbUrl = "http://www.facebook.com/dialog/feed?app_id=291830044248933&link=www.saholic.com/recharge?afid=61&picture=http://i1074.photobucket.com/albums/w407/amathur2k/logo_saholic.png&name=" + shareMsg + "&caption=One Click Hassle Free Mobile and DTH Recharges&description=&redirect_uri=http://saholic.com/?shared=1";
                        twitterUrl = "https://twitter.com/intent/tweet?hashtags=saholic&original_referer=" + original_referer + "&related=saholic&source=saholic.com&text=" + shareMsg + "&url=http://www.saholic.com/recharge/afid?64&via=saholic";
                        giftMessage = "Congratulations! Your device is successfully recharged. Do visit us again to recharge, or to buy Mobile Phones, Cameras, Laptops and Accessories." +
                                        "<br><br>" +
                    "Advertising is expensive ! If you like our site, please help us spread the word by Tweeting and posting to Facebook." +
                                        "<div style=\"margin-top: 40px;text-align: center;\">" +
                                        "<a target='_blank' href='" + twitterUrl + "'>" + 
                                                        "<input type='button' onclick=\"trackEventWithGA('Recharge', 'Twitter Share', '')\" style=\"background: url('/unversioned/images/tweet-about-us.png') 0px 1px;width: 160px;height: 40px;margin-right: 40px;\"></a>" +
                                        "<a target='_blank' href='" + fbUrl + "'>" +
                                                        "<input type=\"button\" onclick=\"trackEventWithGA('Recharge', 'Facebook Share', '');\" style=\"background:url('/unversioned/images/Post-On-Facebook.jpg');width: 160px;height: 40px;\">" +
                                                        "</a></div>";
                return new String[] {"", "SUCCESS", giftMessage};
        } else if (status.equals(RechargeOrderStatus.PARTIALLY_REFUNDED) || status.equals(RechargeOrderStatus.REFUNDED)) {
            return new String[]{"red", "PAYMENT REFUNDED",
                    "The payment associated with this recharge order has been refunded. You can check the details by " +
                    "<a href='/my-recharges'>clicking here</a>.<br><br>"};
        } else {
            return new String[]{"red", "ERROR", "INVALID INPUT"};
        }
    }
    
    public String getRechargeStatus() throws NumberFormatException, TException{
        TransactionClient transactionServiceClient = null;
        transactionServiceClient = new TransactionClient();
        RechargeOrder t_rechargeOrder = transactionServiceClient.getClient().getRcgOrderStatus(Long.valueOf(rechargeOrderId), Boolean.valueOf(isFinal));
        setNewStatus(t_rechargeOrder.getStatus().name());
        return "recharge-status";
    }

    public void setRechargeModeAsynchronous(boolean rechargeModeAsynchronous) {
        this.rechargeModeAsynchronous = rechargeModeAsynchronous;
    }

    public boolean isRechargeModeAsynchronous() {
        return rechargeModeAsynchronous;
    }
    
    public String getRechargeOrderId() {
        return rechargeOrderId;
    }

    public void setRechargeOrderId(String rechargeOrderId) {
        this.rechargeOrderId = rechargeOrderId;
    }

    public void setNewStatus(String newStatus) {
        this.newStatus = newStatus;
    }

    public String getNewStatus() {
        return newStatus;
    }
}