Subversion Repositories SmartDukaan

Rev

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