Subversion Repositories SmartDukaan

Rev

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