Subversion Repositories SmartDukaan

Rev

Rev 4815 | Rev 4882 | 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
 
4867 rajveer 119
                if(!userClient.showCODOption(currentCartId, sourceId, address.getPin())){
3063 chandransh 120
                    addActionError("Cash on Delivery is currently not available for this pincode. Please choose a different payment option.");
3101 chandransh 121
                    return "proceed-to-pay-redirect";    
3063 chandransh 122
                }
123
            } catch (Exception e) {
124
                log.error("Unable to talk to the user context service.", e);
125
                addActionError("We are experiencing some problems. Please try later.");
3101 chandransh 126
                return "proceed-to-pay-redirect";
3063 chandransh 127
            }
128
    	}
129
 
130
    	try {
4325 mandeep.dh 131
    		if(!createOrders(addressId, currentCartId)) {
1128 rajveer 132
    			addActionError("We are experiencing some problems. Please try later.");
3101 chandransh 133
    			return "proceed-to-pay-redirect";
894 rajveer 134
    		}
3063 chandransh 135
    	} catch (Exception e) {
1128 rajveer 136
    		addActionError("We are experiencing some problems. Please try later.");
2296 chandransh 137
    		log.error("Exception in createOrders function. Something went wrong.", e);
3101 chandransh 138
    		return "proceed-to-pay-redirect";
693 rajveer 139
		}
2159 chandransh 140
 
4325 mandeep.dh 141
    	if(paymentOption.equals(IPaymentService.COD)) {
3063 chandransh 142
    	    IPaymentService codPaymentService = new CodPaymentService();
3561 rajveer 143
    	    paymentId = codPaymentService.createPayment(userinfo.getCartId(), userinfo.getUserId(), txnId, paymentOption, sourceId);
3063 chandransh 144
            if (paymentId == IPaymentService.PAYMENT_NOT_CREATED) {
145
                //Very unlikely. The only possible reason can be that the payment service is down.
146
                log.error("Unable to process the COD payment.");
147
                addActionError("We are experiencing some problems. Please try later.");
3101 chandransh 148
                return "proceed-to-pay-redirect";
3063 chandransh 149
            } else {
150
                CommonPaymentService.processCodTxn(txnId);
151
                return "cod-redirect";
152
            }
3616 chandransh 153
    	} else if(paymentOption.equals(IPaymentService.HDFC_EMI)){
154
    	    IPaymentService hdfcEmiPaymentService = new HdfcEmiPaymentService();
155
            paymentId = hdfcEmiPaymentService.createPayment(userinfo.getCartId(), userinfo.getUserId(), txnId, paymentOption, sourceId);
156
            if(paymentId == IPaymentService.PAYMENT_NOT_CREATED){
157
                addActionError("We are experiencing some problems. Please try later.");
158
                log.error("Unable to process payment through HDFC EMI.");
159
                return "proceed-to-pay-redirect";
160
            } else {
3617 chandransh 161
                this.redirectURL = ((HdfcEmiPaymentService)hdfcEmiPaymentService).getRedirectUrl();
3616 chandransh 162
                log.info(this.redirectURL);
163
                return "success";
164
            }
3063 chandransh 165
    	} else {
4401 rajveer 166
    		if(paymentOption.equals(IPaymentService.HDFC_MASTERCARD) || paymentOption.equals(IPaymentService.HDFC_VISA) || paymentOption.equals(IPaymentService.HDFC_VISA_ELECTRON)) {
3063 chandransh 167
                // User has selected Visa or MasterCard CC
168
                IPaymentService hdfcPaymentService = new HdfcPaymentService();
3561 rajveer 169
                paymentId = hdfcPaymentService.createPayment(userinfo.getCartId(), userinfo.getUserId(), txnId, paymentOption, sourceId);
3063 chandransh 170
                if (paymentId == IPaymentService.PAYMENT_NOT_CREATED) {
171
                    log.error("Unable to process payment through HDFC. Falling through to EBS.");
172
                } else {
173
                    this.redirectURL = ((HdfcPaymentService)hdfcPaymentService).getRedirectUrl();
174
                    log.info(this.redirectURL);
175
                    return "success";
176
                }
177
            }
2199 chandransh 178
 
3063 chandransh 179
            if(paymentOption.equals(IPaymentService.HDFC_VISA))
180
                paymentOption = IPaymentService.EBS_VISA;
181
            else if(paymentOption.equals(IPaymentService.HDFC_MASTERCARD))
182
                paymentOption = IPaymentService.EBS_MASTERCARD;
183
            else if(paymentOption.equals(IPaymentService.HDFC_VISA_ELECTRON))
184
                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.
185
 
186
            IPaymentService ebsPaymentService = new EbsPaymentService();
3561 rajveer 187
            paymentId = ebsPaymentService.createPayment(userinfo.getCartId(), userinfo.getUserId(), txnId, paymentOption, sourceId);
3063 chandransh 188
            if(paymentId == IPaymentService.PAYMENT_NOT_CREATED){
189
                addActionError("We are experiencing some problems. Please try later.");
3616 chandransh 190
                log.error("Unable to process payment through EBS.");
3101 chandransh 191
                return "proceed-to-pay-redirect";
3063 chandransh 192
            } else {
193
                log.info("Successfully created payment for EBS to process. Redirecting to /ebs-pay/" + paymentId);
194
                return "ebs-pay-redirect";
195
            }    	    
196
    	}
197
 
572 chandransh 198
    }
3063 chandransh 199
 
200
    /**
201
     * Verifies if the recaptcha response matches the recaptcha challenge.
202
     * 
203
     * @return True if the captcha was valid, false otherwise.
204
     */
205
    private boolean verifyCaptcha() {
4609 phani.kuma 206
        String cookieCaptchaAnswer = getCookie(Captcha.NAME, true, "saholic");
207
    	String captchaReceived = (String) request.getParameter("captcha_response_field");
208
 
209
    	if (captchaReceived.equalsIgnoreCase(cookieCaptchaAnswer)) {
210
			try {
211
				DataLogger.logData(EventType.CAPTCHA_SUCCESS, getSessionId(), userinfo.getUserId(), userinfo.getEmail());
212
			} catch (Exception e1) {
213
	        	log.warn("Unable to log orders through the datalogger", e1);
214
	        }
215
			return true;
216
		} 
217
		else {
218
			try {
219
				DataLogger.logData(EventType.CAPTCHA_FAILED, getSessionId(), userinfo.getUserId(), userinfo.getEmail());
220
			} catch (Exception e1) {
221
	        	log.warn("Unable to log orders through the datalogger", e1);
222
	        }
223
			return false;
224
		}
3063 chandransh 225
    }
572 chandransh 226
 
507 rajveer 227
	public String getId(){
228
		return id;
229
	}
419 rajveer 230
 
507 rajveer 231
	public void setId(String id){
232
		this.id = id;
233
	}
419 rajveer 234
 
507 rajveer 235
	public String getMyaccountHeaderSnippet(){
236
		return htmlSnippets.get("MYACCOUNT_HEADER");
237
	}
238
 
239
	public String getOrderDetailsSnippet(){
240
		return htmlSnippets.get("ORDER_DETAILS");
241
	}
242
 
712 rajveer 243
	public long getTxn(){
244
		return this.txnId;
517 rajveer 245
	}
894 rajveer 246
 
247
	/**
248
	 * 
249
	 * @param addressId
250
	 * @param currentCartId
251
	 * @return
252
	 */
1318 rajveer 253
	private boolean createOrders(long addressId, long currentCartId){
3126 rajveer 254
		UserClient userServiceClient = null;
894 rajveer 255
		try {
3126 rajveer 256
			userServiceClient = new UserClient();
894 rajveer 257
		} catch (Exception e) {
2296 chandransh 258
			log.error("Unable to talk to the user context service.", e);
894 rajveer 259
			return false;
260
		}
261
 
262
		in.shop2020.model.v1.user.UserContextService.Client userClient = userServiceClient.getClient();
263
		try {
264
			userClient.addAddressToCart(currentCartId, addressId);
265
		} catch (ShoppingCartException e1) {
2296 chandransh 266
			log.error("Not able to set address in the cart.", e1);
894 rajveer 267
			return false;
268
		} catch (TException e1) {
2296 chandransh 269
			log.error("Thrift exception while setting address in cart.", e1);
894 rajveer 270
			return false;
271
		}
272
 
273
 
274
		try {
3561 rajveer 275
			String errorMsg = userClient.validateCart(currentCartId, sourceId); 
1466 ankur.sing 276
			if(!errorMsg.isEmpty()){
277
				addActionError(errorMsg);
894 rajveer 278
				return false;
279
			}
280
		} catch (ShoppingCartException e1) {
2296 chandransh 281
			log.error("Error while validating shopping cart.", e1);
894 rajveer 282
			return false;
283
		} catch (TException e) {
2296 chandransh 284
			log.error("Thrift exception while validating cart.", e);
894 rajveer 285
			return false;
286
		}
287
 
288
 
289
		try {
3859 vikas 290
		    String sessionSrc = getCookie(TrackingInterceptor.SESSION_SRC_COOKIE, true, TrackingInterceptor.ENCRIPTION_STRING);
291
		    String firstSrc = getCookie(TrackingInterceptor.SRC_COOKIE, true, TrackingInterceptor.ENCRIPTION_STRING);
2817 vikas 292
 
3859 vikas 293
		    long sessionTime = 0;
294
            try {
295
                sessionTime = Long.parseLong(getCookie(TrackingInterceptor.SESSION_SRC_TIME_COOKIE, false, null));
296
            } catch (Exception e) {
297
                log.warn("Unable to parse session src time cookie.", e);
2817 vikas 298
            }
3859 vikas 299
            long firstSrcTime = 0;
300
            try {
301
                firstSrcTime = Long.parseLong(getCookie(TrackingInterceptor.SRC_TIME_COOKIE, false, null));
302
            } catch (Exception e) {
303
                log.warn("Unable to parse session src time cookie.", e);
304
            }
305
            txnId = userClient.createOrders(currentCartId, sessionSrc, sessionTime, firstSrc, firstSrcTime);
894 rajveer 306
		} catch (ShoppingCartException e1) {
2296 chandransh 307
			log.error("Error while creating orders from cart.", e1);
894 rajveer 308
			return false;
309
		} catch (TException e) {
2296 chandransh 310
			log.error("Thrift exception while creating orders from cart.", e);
894 rajveer 311
			return false;
312
		}
313
 
3126 rajveer 314
		TransactionClient transactionServiceClient = null;
4325 mandeep.dh 315
 
2183 vikas 316
        try {
3126 rajveer 317
            transactionServiceClient = new TransactionClient();
2183 vikas 318
            List<Order> orders = transactionServiceClient.getClient().getOrdersForTransaction(txnId, userinfo.getUserId());
319
            for (Order order : orders) {
3394 vikas 320
                List<Order> tmpOrders = new ArrayList<Order>();
321
                tmpOrders.add(order);
322
                String itemIdString = Utils.getItemIdStringFromOrders(tmpOrders);
3209 vikas 323
                DataLogger.logData(EventType.ORDER_CREATION, getSessionId(), userinfo.getUserId(), userinfo.getEmail(), 
3212 vikas 324
                        Long.toString(order.getId()), Long.toString(currentCartId), itemIdString);
2183 vikas 325
            }
326
        } catch (Exception e1) {
2296 chandransh 327
        	log.warn("Unable to log orders through the datalogger", e1);
2183 vikas 328
        }
894 rajveer 329
 
330
		return true;
331
	}
4325 mandeep.dh 332
 
333
	/**
334
	 * This method updates address of a given order.
335
	 *
336
	 * @return
337
	 */
338
	public String modifyAddress() {
339
        long orderId   = Long.parseLong(request.getParameter("orderId"));
340
        long addressId = Long.valueOf(request.getParameter("addressId"));
341
 
342
		try {
343
		    TransactionClient transactionServiceClient = new TransactionClient();
344
			in.shop2020.model.v1.order.TransactionService.Client transactionClient
345
			    = transactionServiceClient.getClient();			
346
			transactionClient.updateShipmentAddress(orderId, addressId);
347
		} catch (TTransportException e) {
348
		    log.error("Could not update address: " + addressId + " for orderId: " + orderId, e);
349
		} catch (NumberFormatException e) {
350
		    log.error("Could not update address: " + addressId + " for orderId: " + orderId, e);
351
		} catch (TransactionServiceException e) {
352
		    log.error("Could not update address: " + addressId + " for orderId: " + orderId, e);
353
		} catch (TException e) {
354
		    log.error("Could not update address: " + addressId + " for orderId: " + orderId, e);
355
		}			
356
 
357
		return "index";
358
	}
359
 
1318 rajveer 360
	public String getRedirectURL(){
361
		return this.redirectURL;
362
	}
419 rajveer 363
}