Subversion Repositories SmartDukaan

Rev

Rev 3617 | Rev 4325 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
419 rajveer 1
package in.shop2020.serving.controllers;
2
 
2263 vikas 3
import in.shop2020.datalogger.EventType;
2183 vikas 4
import in.shop2020.model.v1.order.Order;
3063 chandransh 5
import in.shop2020.model.v1.user.Address;
894 rajveer 6
import in.shop2020.model.v1.user.ShoppingCartException;
2817 vikas 7
import in.shop2020.serving.interceptors.TrackingInterceptor;
3063 chandransh 8
import in.shop2020.serving.services.CodPaymentService;
9
import in.shop2020.serving.services.CommonPaymentService;
1905 chandransh 10
import in.shop2020.serving.services.EbsPaymentService;
3616 chandransh 11
import in.shop2020.serving.services.HdfcEmiPaymentService;
1318 rajveer 12
import in.shop2020.serving.services.HdfcPaymentService;
1905 chandransh 13
import in.shop2020.serving.services.IPaymentService;
3212 vikas 14
import in.shop2020.serving.utils.Utils;
3126 rajveer 15
import in.shop2020.thrift.clients.LogisticsClient;
16
import in.shop2020.thrift.clients.TransactionClient;
17
import in.shop2020.thrift.clients.UserClient;
2511 vikas 18
import in.shop2020.utils.DataLogger;
517 rajveer 19
 
3394 vikas 20
import java.util.ArrayList;
2419 vikas 21
import java.util.List;
3063 chandransh 22
import java.util.ResourceBundle;
2419 vikas 23
 
3063 chandransh 24
import net.tanesha.recaptcha.ReCaptchaImpl;
25
import net.tanesha.recaptcha.ReCaptchaResponse;
26
 
832 rajveer 27
import org.apache.log4j.Logger;
822 vikas 28
import org.apache.struts2.convention.annotation.InterceptorRef;
29
import org.apache.struts2.convention.annotation.InterceptorRefs;
419 rajveer 30
import org.apache.struts2.convention.annotation.Result;
31
import org.apache.struts2.convention.annotation.Results;
517 rajveer 32
import org.apache.thrift.TException;
419 rajveer 33
 
2159 chandransh 34
@SuppressWarnings("serial")
822 vikas 35
@InterceptorRefs({
36
    @InterceptorRef("myDefault"),
37
    @InterceptorRef("login")
38
})
39
 
419 rajveer 40
@Results({
3101 chandransh 41
    @Result(name="shipping-redirect", type="redirectAction", params = {"actionName" , "shipping"}),
42
    @Result(name="proceed-to-pay-redirect", type="redirectAction", params = {"actionName" , "proceed-to-pay"}),
3063 chandransh 43
	@Result(name="ebs-pay-redirect", type="redirect", location="/ebs-pay/${paymentId}"),
44
	@Result(name="cod-redirect", type="redirect", location="/pay-success?paymentId=${paymentId}")
419 rajveer 45
})
650 rajveer 46
public class OrderController extends BaseController {
419 rajveer 47
 
1905 chandransh 48
	public long getPaymentId() {
49
		return paymentId;
50
	}
419 rajveer 51
 
832 rajveer 52
	private static Logger log = Logger.getLogger(Class.class);
3063 chandransh 53
	private static final ResourceBundle resource = ResourceBundle.getBundle(OrderController.class.getName());
54
	private static final String RECAPTCHA_PRIVATE_KEY = resource.getString("recaptcha_private_key");
55
 
507 rajveer 56
	private String id;
712 rajveer 57
	private long txnId = 0;
650 rajveer 58
 
1905 chandransh 59
	private long paymentId;
60
 
1318 rajveer 61
	private String redirectURL;
681 rajveer 62
 
419 rajveer 63
	public OrderController(){
507 rajveer 64
		super();
419 rajveer 65
	}
66
 
507 rajveer 67
    // GET /order/ orderid
68
    public String show() {
69
    	log.info("id=" + id);
822 vikas 70
    	htmlSnippets.put("MYACCOUNT_HEADER", pageLoader.getMyaccountHeaderHtml());
1527 ankur.sing 71
    	htmlSnippets.put("ORDER_DETAILS", pageLoader.getOrderDetailsHtml(Long.parseLong(id), userinfo.getUserId()));
507 rajveer 72
    	return "show";
419 rajveer 73
    }
517 rajveer 74
 
572 chandransh 75
    // POST /order/
76
    public String create(){
786 rajveer 77
    	String addressIdString = this.request.getParameter("addressid");
78
    	if(addressIdString == null){
894 rajveer 79
    		addActionError("Please specify shipping address to continue.");
3101 chandransh 80
    		return "proceed-to-pay-redirect";
786 rajveer 81
    	}
2159 chandransh 82
 
83
    	String paymentOption = request.getParameter("payment_option");
84
    	log.info("Payment Option Selected: " + paymentOption);
85
    	if(paymentOption == null || paymentOption.equals("")){
86
    		addActionError("Please select a payment method to continue.");
3101 chandransh 87
    		return "proceed-to-pay-redirect";
2159 chandransh 88
    	}
89
 
90
 
3101 chandransh 91
    	long addressId;
92
    	try {
93
    	    addressId = Long.parseLong(addressIdString);   
94
    	} catch(NumberFormatException nfe){
95
    	    log.error("Unable to get address id", nfe);
96
    	    addActionError("Invalid address. Please add an address to the cart.");
97
    	    return "shipping-redirect";
98
    	}
99
 
572 chandransh 100
    	long currentCartId = userinfo.getCartId();
3063 chandransh 101
 
102
    	if(paymentOption.equals(IPaymentService.COD)){
103
    	    if(!verifyCaptcha()){
104
    	        addActionError("Invalid captcha");
3101 chandransh 105
    	        return "proceed-to-pay-redirect";    
3063 chandransh 106
    	    }
107
 
108
    	    //Check that this address is eligible for COD shipping.
3126 rajveer 109
    	    UserClient userServiceClient = null;
3063 chandransh 110
            try {
3126 rajveer 111
                userServiceClient = new UserClient();
3063 chandransh 112
                in.shop2020.model.v1.user.UserContextService.Client userClient = userServiceClient.getClient();
113
                Address address = userClient.getAddressById(addressId);
114
 
3126 rajveer 115
                LogisticsClient logisticsServiceClient = new LogisticsClient();
3063 chandransh 116
                if(!logisticsServiceClient.getClient().isCodAllowed(address.getPin())){
117
                    addActionError("Cash on Delivery is currently not available for this pincode. Please choose a different payment option.");
3101 chandransh 118
                    return "proceed-to-pay-redirect";    
3063 chandransh 119
                }
120
            } catch (Exception e) {
121
                log.error("Unable to talk to the user context service.", e);
122
                addActionError("We are experiencing some problems. Please try later.");
3101 chandransh 123
                return "proceed-to-pay-redirect";
3063 chandransh 124
            }
125
    	}
126
 
127
    	try {
1318 rajveer 128
    		if(!createOrders(addressId, currentCartId)){
1128 rajveer 129
    			addActionError("We are experiencing some problems. Please try later.");
3101 chandransh 130
    			return "proceed-to-pay-redirect";
894 rajveer 131
    		}
3063 chandransh 132
    	} catch (Exception e) {
1128 rajveer 133
    		addActionError("We are experiencing some problems. Please try later.");
2296 chandransh 134
    		log.error("Exception in createOrders function. Something went wrong.", e);
3101 chandransh 135
    		return "proceed-to-pay-redirect";
693 rajveer 136
		}
2159 chandransh 137
 
3063 chandransh 138
    	if(paymentOption.equals(IPaymentService.COD)){
139
    	    IPaymentService codPaymentService = new CodPaymentService();
3561 rajveer 140
    	    paymentId = codPaymentService.createPayment(userinfo.getCartId(), userinfo.getUserId(), txnId, paymentOption, sourceId);
3063 chandransh 141
            if (paymentId == IPaymentService.PAYMENT_NOT_CREATED) {
142
                //Very unlikely. The only possible reason can be that the payment service is down.
143
                log.error("Unable to process the COD payment.");
144
                addActionError("We are experiencing some problems. Please try later.");
3101 chandransh 145
                return "proceed-to-pay-redirect";
3063 chandransh 146
            } else {
147
                CommonPaymentService.processCodTxn(txnId);
148
                return "cod-redirect";
149
            }
3616 chandransh 150
    	} else if(paymentOption.equals(IPaymentService.HDFC_EMI)){
151
    	    IPaymentService hdfcEmiPaymentService = new HdfcEmiPaymentService();
152
            paymentId = hdfcEmiPaymentService.createPayment(userinfo.getCartId(), userinfo.getUserId(), txnId, paymentOption, sourceId);
153
            if(paymentId == IPaymentService.PAYMENT_NOT_CREATED){
154
                addActionError("We are experiencing some problems. Please try later.");
155
                log.error("Unable to process payment through HDFC EMI.");
156
                return "proceed-to-pay-redirect";
157
            } else {
3617 chandransh 158
                this.redirectURL = ((HdfcEmiPaymentService)hdfcEmiPaymentService).getRedirectUrl();
3616 chandransh 159
                log.info(this.redirectURL);
160
                return "success";
161
            }
3063 chandransh 162
    	} else {
163
            if(paymentOption.equals(IPaymentService.HDFC_MASTERCARD) || paymentOption.equals(IPaymentService.HDFC_VISA) || paymentOption.equals(IPaymentService.HDFC_VISA_ELECTRON)) {
164
                // User has selected Visa or MasterCard CC
165
                IPaymentService hdfcPaymentService = new HdfcPaymentService();
3561 rajveer 166
                paymentId = hdfcPaymentService.createPayment(userinfo.getCartId(), userinfo.getUserId(), txnId, paymentOption, sourceId);
3063 chandransh 167
                if (paymentId == IPaymentService.PAYMENT_NOT_CREATED) {
168
                    log.error("Unable to process payment through HDFC. Falling through to EBS.");
169
                } else {
170
                    this.redirectURL = ((HdfcPaymentService)hdfcPaymentService).getRedirectUrl();
171
                    log.info(this.redirectURL);
172
                    return "success";
173
                }
174
            }
2199 chandransh 175
 
3063 chandransh 176
            if(paymentOption.equals(IPaymentService.HDFC_VISA))
177
                paymentOption = IPaymentService.EBS_VISA;
178
            else if(paymentOption.equals(IPaymentService.HDFC_MASTERCARD))
179
                paymentOption = IPaymentService.EBS_MASTERCARD;
180
            else if(paymentOption.equals(IPaymentService.HDFC_VISA_ELECTRON))
181
                paymentOption = null;           //Since we don't know the bank's name in this case, we'll let the user select the bank on the EBS page.
182
 
183
            IPaymentService ebsPaymentService = new EbsPaymentService();
3561 rajveer 184
            paymentId = ebsPaymentService.createPayment(userinfo.getCartId(), userinfo.getUserId(), txnId, paymentOption, sourceId);
3063 chandransh 185
            if(paymentId == IPaymentService.PAYMENT_NOT_CREATED){
186
                addActionError("We are experiencing some problems. Please try later.");
3616 chandransh 187
                log.error("Unable to process payment through EBS.");
3101 chandransh 188
                return "proceed-to-pay-redirect";
3063 chandransh 189
            } else {
190
                log.info("Successfully created payment for EBS to process. Redirecting to /ebs-pay/" + paymentId);
191
                return "ebs-pay-redirect";
192
            }    	    
193
    	}
194
 
572 chandransh 195
    }
3063 chandransh 196
 
197
    /**
198
     * Verifies if the recaptcha response matches the recaptcha challenge.
199
     * 
200
     * @return True if the captcha was valid, false otherwise.
201
     */
202
    private boolean verifyCaptcha() {
203
        String remoteAddr = request.getRemoteAddr();
204
        ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
205
        reCaptcha.setPrivateKey(RECAPTCHA_PRIVATE_KEY);
206
 
207
        String challenge = request.getParameter("recaptcha_challenge_field");
208
        String uresponse = request.getParameter("recaptcha_response_field");
209
        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);
210
 
3264 chandransh 211
        log.info("Recaptcha Response:" + reCaptchaResponse.isValid());
212
        return reCaptchaResponse.isValid();
3063 chandransh 213
    }
572 chandransh 214
 
507 rajveer 215
	public String getId(){
216
		return id;
217
	}
419 rajveer 218
 
507 rajveer 219
	public void setId(String id){
220
		this.id = id;
221
	}
419 rajveer 222
 
507 rajveer 223
	public String getMyaccountHeaderSnippet(){
224
		return htmlSnippets.get("MYACCOUNT_HEADER");
225
	}
226
 
227
	public String getOrderDetailsSnippet(){
228
		return htmlSnippets.get("ORDER_DETAILS");
229
	}
230
 
712 rajveer 231
	public long getTxn(){
232
		return this.txnId;
517 rajveer 233
	}
894 rajveer 234
 
235
	/**
236
	 * 
237
	 * @param addressId
238
	 * @param currentCartId
239
	 * @return
240
	 */
1318 rajveer 241
	private boolean createOrders(long addressId, long currentCartId){
3126 rajveer 242
		UserClient userServiceClient = null;
894 rajveer 243
		try {
3126 rajveer 244
			userServiceClient = new UserClient();
894 rajveer 245
		} catch (Exception e) {
2296 chandransh 246
			log.error("Unable to talk to the user context service.", e);
894 rajveer 247
			return false;
248
		}
249
 
250
		in.shop2020.model.v1.user.UserContextService.Client userClient = userServiceClient.getClient();
251
		try {
252
			userClient.addAddressToCart(currentCartId, addressId);
253
		} catch (ShoppingCartException e1) {
2296 chandransh 254
			log.error("Not able to set address in the cart.", e1);
894 rajveer 255
			return false;
256
		} catch (TException e1) {
2296 chandransh 257
			log.error("Thrift exception while setting address in cart.", e1);
894 rajveer 258
			return false;
259
		}
260
 
261
 
262
		try {
3561 rajveer 263
			String errorMsg = userClient.validateCart(currentCartId, sourceId); 
1466 ankur.sing 264
			if(!errorMsg.isEmpty()){
265
				addActionError(errorMsg);
894 rajveer 266
				return false;
267
			}
268
		} catch (ShoppingCartException e1) {
2296 chandransh 269
			log.error("Error while validating shopping cart.", e1);
894 rajveer 270
			return false;
271
		} catch (TException e) {
2296 chandransh 272
			log.error("Thrift exception while validating cart.", e);
894 rajveer 273
			return false;
274
		}
275
 
276
 
277
		try {
3859 vikas 278
		    String sessionSrc = getCookie(TrackingInterceptor.SESSION_SRC_COOKIE, true, TrackingInterceptor.ENCRIPTION_STRING);
279
		    String firstSrc = getCookie(TrackingInterceptor.SRC_COOKIE, true, TrackingInterceptor.ENCRIPTION_STRING);
2817 vikas 280
 
3859 vikas 281
		    long sessionTime = 0;
282
            try {
283
                sessionTime = Long.parseLong(getCookie(TrackingInterceptor.SESSION_SRC_TIME_COOKIE, false, null));
284
            } catch (Exception e) {
285
                log.warn("Unable to parse session src time cookie.", e);
2817 vikas 286
            }
3859 vikas 287
            long firstSrcTime = 0;
288
            try {
289
                firstSrcTime = Long.parseLong(getCookie(TrackingInterceptor.SRC_TIME_COOKIE, false, null));
290
            } catch (Exception e) {
291
                log.warn("Unable to parse session src time cookie.", e);
292
            }
293
            txnId = userClient.createOrders(currentCartId, sessionSrc, sessionTime, firstSrc, firstSrcTime);
894 rajveer 294
		} catch (ShoppingCartException e1) {
2296 chandransh 295
			log.error("Error while creating orders from cart.", e1);
894 rajveer 296
			return false;
297
		} catch (TException e) {
2296 chandransh 298
			log.error("Thrift exception while creating orders from cart.", e);
894 rajveer 299
			return false;
300
		}
301
 
3126 rajveer 302
		TransactionClient transactionServiceClient = null;
2183 vikas 303
        try {
3126 rajveer 304
            transactionServiceClient = new TransactionClient();
2183 vikas 305
            List<Order> orders = transactionServiceClient.getClient().getOrdersForTransaction(txnId, userinfo.getUserId());
306
            for (Order order : orders) {
3394 vikas 307
                List<Order> tmpOrders = new ArrayList<Order>();
308
                tmpOrders.add(order);
309
                String itemIdString = Utils.getItemIdStringFromOrders(tmpOrders);
3209 vikas 310
                DataLogger.logData(EventType.ORDER_CREATION, getSessionId(), userinfo.getUserId(), userinfo.getEmail(), 
3212 vikas 311
                        Long.toString(order.getId()), Long.toString(currentCartId), itemIdString);
2183 vikas 312
            }
313
        } catch (Exception e1) {
2296 chandransh 314
        	log.warn("Unable to log orders through the datalogger", e1);
2183 vikas 315
        }
894 rajveer 316
 
317
		return true;
318
	}
1318 rajveer 319
 
320
	public String getRedirectURL(){
321
		return this.redirectURL;
322
	}
419 rajveer 323
}