Subversion Repositories SmartDukaan

Rev

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