Subversion Repositories SmartDukaan

Rev

Rev 4325 | Rev 4401 | 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
 
4396 rajveer 65
	private double totalAmount;
66
 
419 rajveer 67
	public OrderController(){
507 rajveer 68
		super();
419 rajveer 69
	}
70
 
507 rajveer 71
    // GET /order/ orderid
72
    public String show() {
73
    	log.info("id=" + id);
822 vikas 74
    	htmlSnippets.put("MYACCOUNT_HEADER", pageLoader.getMyaccountHeaderHtml());
1527 ankur.sing 75
    	htmlSnippets.put("ORDER_DETAILS", pageLoader.getOrderDetailsHtml(Long.parseLong(id), userinfo.getUserId()));
507 rajveer 76
    	return "show";
419 rajveer 77
    }
517 rajveer 78
 
572 chandransh 79
    // POST /order/
80
    public String create(){
786 rajveer 81
    	String addressIdString = this.request.getParameter("addressid");
82
    	if(addressIdString == null){
894 rajveer 83
    		addActionError("Please specify shipping address to continue.");
3101 chandransh 84
    		return "proceed-to-pay-redirect";
786 rajveer 85
    	}
2159 chandransh 86
 
87
    	String paymentOption = request.getParameter("payment_option");
88
    	log.info("Payment Option Selected: " + paymentOption);
89
    	if(paymentOption == null || paymentOption.equals("")){
90
    		addActionError("Please select a payment method to continue.");
3101 chandransh 91
    		return "proceed-to-pay-redirect";
2159 chandransh 92
    	}
93
 
94
 
3101 chandransh 95
    	long addressId;
96
    	try {
97
    	    addressId = Long.parseLong(addressIdString);   
98
    	} catch(NumberFormatException nfe){
99
    	    log.error("Unable to get address id", nfe);
100
    	    addActionError("Invalid address. Please add an address to the cart.");
101
    	    return "shipping-redirect";
102
    	}
103
 
572 chandransh 104
    	long currentCartId = userinfo.getCartId();
3063 chandransh 105
 
106
    	if(paymentOption.equals(IPaymentService.COD)){
107
    	    if(!verifyCaptcha()){
108
    	        addActionError("Invalid captcha");
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 {
4396 rajveer 167
    		//FIXME Remove the hardcoding
168
 
169
            if( totalAmount > 100 && (paymentOption.equals(IPaymentService.HDFC_MASTERCARD) || paymentOption.equals(IPaymentService.HDFC_VISA) || paymentOption.equals(IPaymentService.HDFC_VISA_ELECTRON))) {
3063 chandransh 170
                // User has selected Visa or MasterCard CC
171
                IPaymentService hdfcPaymentService = new HdfcPaymentService();
3561 rajveer 172
                paymentId = hdfcPaymentService.createPayment(userinfo.getCartId(), userinfo.getUserId(), txnId, paymentOption, sourceId);
3063 chandransh 173
                if (paymentId == IPaymentService.PAYMENT_NOT_CREATED) {
174
                    log.error("Unable to process payment through HDFC. Falling through to EBS.");
175
                } else {
176
                    this.redirectURL = ((HdfcPaymentService)hdfcPaymentService).getRedirectUrl();
177
                    log.info(this.redirectURL);
178
                    return "success";
179
                }
180
            }
2199 chandransh 181
 
3063 chandransh 182
            if(paymentOption.equals(IPaymentService.HDFC_VISA))
183
                paymentOption = IPaymentService.EBS_VISA;
184
            else if(paymentOption.equals(IPaymentService.HDFC_MASTERCARD))
185
                paymentOption = IPaymentService.EBS_MASTERCARD;
186
            else if(paymentOption.equals(IPaymentService.HDFC_VISA_ELECTRON))
187
                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.
188
 
189
            IPaymentService ebsPaymentService = new EbsPaymentService();
3561 rajveer 190
            paymentId = ebsPaymentService.createPayment(userinfo.getCartId(), userinfo.getUserId(), txnId, paymentOption, sourceId);
3063 chandransh 191
            if(paymentId == IPaymentService.PAYMENT_NOT_CREATED){
192
                addActionError("We are experiencing some problems. Please try later.");
3616 chandransh 193
                log.error("Unable to process payment through EBS.");
3101 chandransh 194
                return "proceed-to-pay-redirect";
3063 chandransh 195
            } else {
196
                log.info("Successfully created payment for EBS to process. Redirecting to /ebs-pay/" + paymentId);
197
                return "ebs-pay-redirect";
198
            }    	    
199
    	}
200
 
572 chandransh 201
    }
3063 chandransh 202
 
203
    /**
204
     * Verifies if the recaptcha response matches the recaptcha challenge.
205
     * 
206
     * @return True if the captcha was valid, false otherwise.
207
     */
208
    private boolean verifyCaptcha() {
209
        String remoteAddr = request.getRemoteAddr();
210
        ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
211
        reCaptcha.setPrivateKey(RECAPTCHA_PRIVATE_KEY);
212
 
213
        String challenge = request.getParameter("recaptcha_challenge_field");
214
        String uresponse = request.getParameter("recaptcha_response_field");
215
        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);
216
 
3264 chandransh 217
        log.info("Recaptcha Response:" + reCaptchaResponse.isValid());
218
        return reCaptchaResponse.isValid();
3063 chandransh 219
    }
572 chandransh 220
 
507 rajveer 221
	public String getId(){
222
		return id;
223
	}
419 rajveer 224
 
507 rajveer 225
	public void setId(String id){
226
		this.id = id;
227
	}
419 rajveer 228
 
507 rajveer 229
	public String getMyaccountHeaderSnippet(){
230
		return htmlSnippets.get("MYACCOUNT_HEADER");
231
	}
232
 
233
	public String getOrderDetailsSnippet(){
234
		return htmlSnippets.get("ORDER_DETAILS");
235
	}
236
 
712 rajveer 237
	public long getTxn(){
238
		return this.txnId;
517 rajveer 239
	}
894 rajveer 240
 
241
	/**
242
	 * 
243
	 * @param addressId
244
	 * @param currentCartId
245
	 * @return
246
	 */
1318 rajveer 247
	private boolean createOrders(long addressId, long currentCartId){
3126 rajveer 248
		UserClient userServiceClient = null;
894 rajveer 249
		try {
3126 rajveer 250
			userServiceClient = new UserClient();
894 rajveer 251
		} catch (Exception e) {
2296 chandransh 252
			log.error("Unable to talk to the user context service.", e);
894 rajveer 253
			return false;
254
		}
255
 
256
		in.shop2020.model.v1.user.UserContextService.Client userClient = userServiceClient.getClient();
257
		try {
258
			userClient.addAddressToCart(currentCartId, addressId);
259
		} catch (ShoppingCartException e1) {
2296 chandransh 260
			log.error("Not able to set address in the cart.", e1);
894 rajveer 261
			return false;
262
		} catch (TException e1) {
2296 chandransh 263
			log.error("Thrift exception while setting address in cart.", e1);
894 rajveer 264
			return false;
265
		}
266
 
267
 
268
		try {
3561 rajveer 269
			String errorMsg = userClient.validateCart(currentCartId, sourceId); 
1466 ankur.sing 270
			if(!errorMsg.isEmpty()){
271
				addActionError(errorMsg);
894 rajveer 272
				return false;
273
			}
274
		} catch (ShoppingCartException e1) {
2296 chandransh 275
			log.error("Error while validating shopping cart.", e1);
894 rajveer 276
			return false;
277
		} catch (TException e) {
2296 chandransh 278
			log.error("Thrift exception while validating cart.", e);
894 rajveer 279
			return false;
280
		}
281
 
282
 
283
		try {
3859 vikas 284
		    String sessionSrc = getCookie(TrackingInterceptor.SESSION_SRC_COOKIE, true, TrackingInterceptor.ENCRIPTION_STRING);
285
		    String firstSrc = getCookie(TrackingInterceptor.SRC_COOKIE, true, TrackingInterceptor.ENCRIPTION_STRING);
2817 vikas 286
 
3859 vikas 287
		    long sessionTime = 0;
288
            try {
289
                sessionTime = Long.parseLong(getCookie(TrackingInterceptor.SESSION_SRC_TIME_COOKIE, false, null));
290
            } catch (Exception e) {
291
                log.warn("Unable to parse session src time cookie.", e);
2817 vikas 292
            }
3859 vikas 293
            long firstSrcTime = 0;
294
            try {
295
                firstSrcTime = Long.parseLong(getCookie(TrackingInterceptor.SRC_TIME_COOKIE, false, null));
296
            } catch (Exception e) {
297
                log.warn("Unable to parse session src time cookie.", e);
298
            }
299
            txnId = userClient.createOrders(currentCartId, sessionSrc, sessionTime, firstSrc, firstSrcTime);
894 rajveer 300
		} catch (ShoppingCartException e1) {
2296 chandransh 301
			log.error("Error while creating orders from cart.", e1);
894 rajveer 302
			return false;
303
		} catch (TException e) {
2296 chandransh 304
			log.error("Thrift exception while creating orders from cart.", e);
894 rajveer 305
			return false;
306
		}
307
 
3126 rajveer 308
		TransactionClient transactionServiceClient = null;
4325 mandeep.dh 309
 
2183 vikas 310
        try {
3126 rajveer 311
            transactionServiceClient = new TransactionClient();
2183 vikas 312
            List<Order> orders = transactionServiceClient.getClient().getOrdersForTransaction(txnId, userinfo.getUserId());
313
            for (Order order : orders) {
3394 vikas 314
                List<Order> tmpOrders = new ArrayList<Order>();
4396 rajveer 315
                //FIXME Remove hardcoding
316
                totalAmount = totalAmount + order.getTotal_amount();
3394 vikas 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
	}
419 rajveer 359
}