Subversion Repositories SmartDukaan

Rev

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