Subversion Repositories SmartDukaan

Rev

Rev 7862 | Rev 8428 | 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;
7862 anupam.sin 11
import in.shop2020.serving.services.CouponPaymentService;
1905 chandransh 12
import in.shop2020.serving.services.EbsPaymentService;
3616 chandransh 13
import in.shop2020.serving.services.HdfcEmiPaymentService;
1318 rajveer 14
import in.shop2020.serving.services.HdfcPaymentService;
1905 chandransh 15
import in.shop2020.serving.services.IPaymentService;
6390 rajveer 16
import in.shop2020.serving.services.InnovitiPaymentService;
17
//import in.shop2020.serving.services.PayuPaymentService;
6050 anupam.sin 18
import in.shop2020.serving.utils.DesEncrypter;
3212 vikas 19
import in.shop2020.serving.utils.Utils;
3126 rajveer 20
import in.shop2020.thrift.clients.TransactionClient;
21
import in.shop2020.thrift.clients.UserClient;
2511 vikas 22
import in.shop2020.utils.DataLogger;
7954 manish.sha 23
import in.shop2020.utils.FedExShipAccountInfo;
517 rajveer 24
 
3394 vikas 25
import java.util.ArrayList;
7001 rajveer 26
import java.util.Arrays;
2419 vikas 27
import java.util.List;
28
 
832 rajveer 29
import org.apache.log4j.Logger;
822 vikas 30
import org.apache.struts2.convention.annotation.InterceptorRef;
31
import org.apache.struts2.convention.annotation.InterceptorRefs;
419 rajveer 32
import org.apache.struts2.convention.annotation.Result;
33
import org.apache.struts2.convention.annotation.Results;
517 rajveer 34
import org.apache.thrift.TException;
4325 mandeep.dh 35
import org.apache.thrift.transport.TTransportException;
7954 manish.sha 36
 
37
import com.ShipWebServiceClient;
38
import com.fedex.ship.stub.CompletedPackageDetail;
39
import com.fedex.ship.stub.CompletedShipmentDetail;
40
import com.fedex.ship.stub.ProcessShipmentReply;
41
import com.fedex.ship.stub.TrackingId;
42
 
4609 phani.kuma 43
import nl.captcha.Captcha;
419 rajveer 44
 
2159 chandransh 45
@SuppressWarnings("serial")
822 vikas 46
@InterceptorRefs({
47
    @InterceptorRef("myDefault"),
48
    @InterceptorRef("login")
49
})
50
 
419 rajveer 51
@Results({
3101 chandransh 52
    @Result(name="shipping-redirect", type="redirectAction", params = {"actionName" , "shipping"}),
5716 anupam.sin 53
    @Result(name="proceed-to-pay-redirect", type="redirectAction", params = {"actionName" , "proceed-to-pay", "deliveryLocation", "${deliveryLocation}"}),
3063 chandransh 54
	@Result(name="ebs-pay-redirect", type="redirect", location="/ebs-pay/${paymentId}"),
6060 rajveer 55
	@Result(name="payu-pay-redirect", type="redirect", location="/payu-pay/${paymentId}"),
6390 rajveer 56
	@Result(name="innoviti-pay-redirect", type="redirect", location="/innoviti-pay/${paymentId}"),
3063 chandransh 57
	@Result(name="cod-redirect", type="redirect", location="/pay-success?paymentId=${paymentId}")
419 rajveer 58
})
650 rajveer 59
public class OrderController extends BaseController {
419 rajveer 60
 
1905 chandransh 61
	public long getPaymentId() {
62
		return paymentId;
63
	}
419 rajveer 64
 
832 rajveer 65
	private static Logger log = Logger.getLogger(Class.class);
3063 chandransh 66
 
507 rajveer 67
	private String id;
712 rajveer 68
	private long txnId = 0;
650 rajveer 69
 
1905 chandransh 70
	private long paymentId;
71
 
1318 rajveer 72
	private String redirectURL;
5716 anupam.sin 73
	private String deliveryLocation = "";
681 rajveer 74
 
419 rajveer 75
	public OrderController(){
507 rajveer 76
		super();
419 rajveer 77
	}
78
 
507 rajveer 79
    // GET /order/ orderid
80
    public String show() {
81
    	log.info("id=" + id);
822 vikas 82
    	htmlSnippets.put("MYACCOUNT_HEADER", pageLoader.getMyaccountHeaderHtml());
4815 phani.kuma 83
    	htmlSnippets.put("ORDER_DETAILS", pageLoader.getOrderDetailsHtml(Long.parseLong(id), userinfo));
507 rajveer 84
    	return "show";
419 rajveer 85
    }
517 rajveer 86
 
572 chandransh 87
    // POST /order/
88
    public String create(){
786 rajveer 89
    	String addressIdString = this.request.getParameter("addressid");
90
    	if(addressIdString == null){
894 rajveer 91
    		addActionError("Please specify shipping address to continue.");
3101 chandransh 92
    		return "proceed-to-pay-redirect";
786 rajveer 93
    	}
2159 chandransh 94
 
95
    	String paymentOption = request.getParameter("payment_option");
96
    	log.info("Payment Option Selected: " + paymentOption);
97
    	if(paymentOption == null || paymentOption.equals("")){
98
    		addActionError("Please select a payment method to continue.");
3101 chandransh 99
    		return "proceed-to-pay-redirect";
2159 chandransh 100
    	}
101
 
102
 
3101 chandransh 103
    	long addressId;
104
    	try {
105
    	    addressId = Long.parseLong(addressIdString);   
106
    	} catch(NumberFormatException nfe){
107
    	    log.error("Unable to get address id", nfe);
108
    	    addActionError("Invalid address. Please add an address to the cart.");
109
    	    return "shipping-redirect";
110
    	}
111
 
572 chandransh 112
    	long currentCartId = userinfo.getCartId();
5326 rajveer 113
    	long currentUserId = userinfo.getUserId();
3063 chandransh 114
 
115
    	if(paymentOption.equals(IPaymentService.COD)){
116
    	    if(!verifyCaptcha()){
117
    	        addActionError("Invalid captcha");
4815 phani.kuma 118
    	        log.info("Invalid captcha error msg has been added");
3101 chandransh 119
    	        return "proceed-to-pay-redirect";    
3063 chandransh 120
    	    }
121
 
6353 rajveer 122
	        //Check that this address is eligible for COD shipping.
123
    	    UserClient userServiceClient = null;
124
            try {
125
                userServiceClient = new UserClient();
126
                in.shop2020.model.v1.user.UserContextService.Client userClient = userServiceClient.getClient();
127
                Address address = userClient.getAddressById(addressId);
128
 
129
                if(!userClient.showCODOption(currentCartId, sourceId, address.getPin())){
130
                    addActionError("Cash on Delivery is currently not available for this pincode. Please choose a different payment option.");
131
                    return "proceed-to-pay-redirect";    
132
                }
133
            } catch (Exception e) {
134
                log.error("Unable to talk to the user context service.", e);
135
                addActionError("We are experiencing some problems. Please try later.");
136
                return "proceed-to-pay-redirect";
137
            }
3063 chandransh 138
    	}
139
 
7862 anupam.sin 140
    	if(paymentOption.equals(IPaymentService.COUPON)) {
141
    	    if(!verifyCaptcha()){
142
                addActionError("Invalid captcha");
143
                log.info("Invalid captcha error msg has been added");
144
                return "proceed-to-pay-redirect";    
145
            }
146
    	}
147
 
3063 chandransh 148
    	try {
6390 rajveer 149
    		if(!createOrders(addressId, currentCartId, currentUserId, Long.parseLong(paymentOption))) {
1128 rajveer 150
    			addActionError("We are experiencing some problems. Please try later.");
3101 chandransh 151
    			return "proceed-to-pay-redirect";
894 rajveer 152
    		}
3063 chandransh 153
    	} catch (Exception e) {
1128 rajveer 154
    		addActionError("We are experiencing some problems. Please try later.");
2296 chandransh 155
    		log.error("Exception in createOrders function. Something went wrong.", e);
3101 chandransh 156
    		return "proceed-to-pay-redirect";
693 rajveer 157
		}
2159 chandransh 158
 
6390 rajveer 159
    	int gatewayId = (int)findGatewayId(paymentOption);
160
    	switch (gatewayId) {
6419 rajveer 161
    	case 4:
162
    		IPaymentService codPaymentService = new CodPaymentService();
163
    	    paymentId = codPaymentService.createPayment(userinfo.getUserId(), txnId, paymentOption, 4);
164
            if (paymentId == IPaymentService.PAYMENT_NOT_CREATED) {
165
                //Very unlikely. The only possible reason can be that the payment service is down.
166
                log.error("Unable to process the COD payment.");
167
                addActionError("We are experiencing some problems. Please try later.");
168
                return "proceed-to-pay-redirect";
169
            } else {
170
                CommonPaymentService.processCodTxn(txnId);
171
                return "cod-redirect";
172
            }
173
 
174
    	case 5:
6390 rajveer 175
    	case 10:
176
    	case 11:
177
    	case 12:
7001 rajveer 178
    	case 14:
6390 rajveer 179
			IPaymentService hdfcEmiPaymentService = new HdfcEmiPaymentService();
180
            paymentId = hdfcEmiPaymentService.createPayment(userinfo.getUserId(), txnId, paymentOption, gatewayId);
181
            if(paymentId == IPaymentService.PAYMENT_NOT_CREATED){
182
                addActionError("We are experiencing some problems. Please try later.");
183
                log.error("Unable to process payment through HDFC EMI.");
184
                return "proceed-to-pay-redirect";
185
            } else {
186
                this.redirectURL = ((HdfcEmiPaymentService)hdfcEmiPaymentService).getRedirectUrl();
187
                log.info(this.redirectURL);
188
                return "success";
189
            }
6419 rajveer 190
 
191
    	case 13:
192
			IPaymentService innovitiPaymentService = new InnovitiPaymentService();
193
			paymentId = innovitiPaymentService.createPayment(userinfo.getUserId(), txnId, paymentOption, gatewayId);
194
			if (paymentId == IPaymentService.PAYMENT_NOT_CREATED) {
195
				//Very unlikely. The only possible reason can be that the payment service is down.
196
				log.error("Unable to process the COD payment.");
197
				addActionError("We are experiencing some problems. Please try later.");
198
				return "proceed-to-pay-redirect";
199
			} else {
200
	            log.info("Successfully created payment for Innoviti to process. Redirecting to /innoviti-pay/" + paymentId);
201
				return "innoviti-pay-redirect";
202
			}
203
 
7862 anupam.sin 204
    	case 16:
205
            IPaymentService couponPaymentService = new CouponPaymentService();
206
            paymentId = couponPaymentService.createPayment(userinfo.getUserId(), txnId, paymentOption, 16);
207
            if (paymentId == IPaymentService.PAYMENT_NOT_CREATED) {
208
                //Very unlikely. The only possible reason can be that the payment service is down.
209
                log.error("Unable to process the Coupon payment.");
210
                addActionError("We are experiencing some problems. Please try later.");
211
                return "proceed-to-pay-redirect";
212
            } else {
213
                CommonPaymentService.processCouponTxn(txnId);
214
                return "cod-redirect";
215
            }
6390 rajveer 216
		default:
217
			break;
218
		}
219
 
220
 
221
		if(paymentOption.equals(IPaymentService.HDFC_MASTERCARD_CREDIT) || paymentOption.equals(IPaymentService.HDFC_MASTERCARD_DEBIT) || 
222
		        paymentOption.equals(IPaymentService.HDFC_VISA) || paymentOption.equals(IPaymentService.HDFC_VISA_ELECTRON)) {
223
            // User has selected Visa or MasterCard
224
            IPaymentService hdfcPaymentService = new HdfcPaymentService();
225
            paymentId = hdfcPaymentService.createPayment(userinfo.getUserId(), txnId, paymentOption, 1);
226
            if (paymentId == IPaymentService.PAYMENT_NOT_CREATED) {
227
                log.error("Unable to process payment through HDFC. Falling through to EBS.");
3616 chandransh 228
            } else {
6390 rajveer 229
                this.redirectURL = ((HdfcPaymentService)hdfcPaymentService).getRedirectUrl();
3616 chandransh 230
                log.info(this.redirectURL);
231
                return "success";
232
            }
6390 rajveer 233
        }
2199 chandransh 234
 
6390 rajveer 235
        if(paymentOption.equals(IPaymentService.HDFC_VISA))
236
            paymentOption = IPaymentService.EBS_VISA;
237
        else if(paymentOption.equals(IPaymentService.HDFC_MASTERCARD_DEBIT) || paymentOption.equals(IPaymentService.HDFC_MASTERCARD_CREDIT))
238
            paymentOption = IPaymentService.EBS_MASTERCARD;
239
        else if(paymentOption.equals(IPaymentService.HDFC_VISA_ELECTRON))
240
            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.
241
 
242
//        if(paymentOption.equals(IPaymentService.PAYU_CC)){
243
//        	paymentOption = IPaymentService.PAYU_CC;
244
//        	IPaymentService payuPaymentService = new PayuPaymentService();
245
//        	paymentId = payuPaymentService.createPayment(userinfo.getUserId(), txnId, paymentOption, gatewayId);
246
//        	return "payu-pay-redirect";
247
//        }
248
 
249
        IPaymentService ebsPaymentService = new EbsPaymentService();
250
        paymentId = ebsPaymentService.createPayment(userinfo.getUserId(), txnId, paymentOption, 2);
251
        if(paymentId == IPaymentService.PAYMENT_NOT_CREATED){
252
            addActionError("We are experiencing some problems. Please try later.");
253
            log.error("Unable to process payment through EBS.");
254
            return "proceed-to-pay-redirect";
255
        } else {
256
            log.info("Successfully created payment for EBS to process. Redirecting to /ebs-pay/" + paymentId);
257
            return "ebs-pay-redirect";
258
        }    	    
259
	}
260
 
261
    private long findGatewayId(String paymentOption){
262
    	long gatewayId = 0;
263
    	gatewayId = ProceedToPayController.getGatewayId(Long.parseLong(paymentOption));
264
    	if(gatewayId==0){
265
    		if(paymentOption.equals(IPaymentService.COD)){
6419 rajveer 266
    			gatewayId = 4;
6390 rajveer 267
    		}
7862 anupam.sin 268
    		if(paymentOption.equals(IPaymentService.COUPON)){
269
                gatewayId = 16;
270
            }
3063 chandransh 271
    	}
6390 rajveer 272
    	return gatewayId;
572 chandransh 273
    }
6390 rajveer 274
 
3063 chandransh 275
    /**
276
     * Verifies if the recaptcha response matches the recaptcha challenge.
277
     * 
278
     * @return True if the captcha was valid, false otherwise.
279
     */
280
    private boolean verifyCaptcha() {
4609 phani.kuma 281
        String cookieCaptchaAnswer = getCookie(Captcha.NAME, true, "saholic");
282
    	String captchaReceived = (String) request.getParameter("captcha_response_field");
283
 
284
    	if (captchaReceived.equalsIgnoreCase(cookieCaptchaAnswer)) {
285
			try {
286
				DataLogger.logData(EventType.CAPTCHA_SUCCESS, getSessionId(), userinfo.getUserId(), userinfo.getEmail());
287
			} catch (Exception e1) {
288
	        	log.warn("Unable to log orders through the datalogger", e1);
289
	        }
290
			return true;
291
		} 
292
		else {
293
			try {
294
				DataLogger.logData(EventType.CAPTCHA_FAILED, getSessionId(), userinfo.getUserId(), userinfo.getEmail());
295
			} catch (Exception e1) {
296
	        	log.warn("Unable to log orders through the datalogger", e1);
297
	        }
298
			return false;
299
		}
3063 chandransh 300
    }
572 chandransh 301
 
507 rajveer 302
	public String getId(){
303
		return id;
304
	}
419 rajveer 305
 
507 rajveer 306
	public void setId(String id){
307
		this.id = id;
308
	}
419 rajveer 309
 
507 rajveer 310
	public String getMyaccountHeaderSnippet(){
311
		return htmlSnippets.get("MYACCOUNT_HEADER");
312
	}
313
 
314
	public String getOrderDetailsSnippet(){
315
		return htmlSnippets.get("ORDER_DETAILS");
316
	}
317
 
712 rajveer 318
	public long getTxn(){
319
		return this.txnId;
517 rajveer 320
	}
894 rajveer 321
 
322
	/**
323
	 * 
324
	 * @param addressId
325
	 * @param currentCartId
326
	 * @return
327
	 */
6390 rajveer 328
	private boolean createOrders(long addressId, long currentCartId, long currentUserId, long emiSchemeId){
3126 rajveer 329
		UserClient userServiceClient = null;
894 rajveer 330
		try {
3126 rajveer 331
			userServiceClient = new UserClient();
894 rajveer 332
		} catch (Exception e) {
2296 chandransh 333
			log.error("Unable to talk to the user context service.", e);
894 rajveer 334
			return false;
335
		}
336
 
337
		in.shop2020.model.v1.user.UserContextService.Client userClient = userServiceClient.getClient();
338
		try {
339
			userClient.addAddressToCart(currentCartId, addressId);
340
		} catch (ShoppingCartException e1) {
2296 chandransh 341
			log.error("Not able to set address in the cart.", e1);
894 rajveer 342
			return false;
343
		} catch (TException e1) {
2296 chandransh 344
			log.error("Thrift exception while setting address in cart.", e1);
894 rajveer 345
			return false;
346
		}
347
 
348
 
349
		try {
6736 amit.gupta 350
			String errorMsg = userClient.validateCart(currentCartId, sourceId).get(0); 
1466 ankur.sing 351
			if(!errorMsg.isEmpty()){
352
				addActionError(errorMsg);
894 rajveer 353
				return false;
354
			}
355
		} catch (ShoppingCartException e1) {
2296 chandransh 356
			log.error("Error while validating shopping cart.", e1);
894 rajveer 357
			return false;
358
		} catch (TException e) {
2296 chandransh 359
			log.error("Thrift exception while validating cart.", e);
894 rajveer 360
			return false;
361
		}
362
 
363
 
364
		try {
3859 vikas 365
		    String sessionSrc = getCookie(TrackingInterceptor.SESSION_SRC_COOKIE, true, TrackingInterceptor.ENCRIPTION_STRING);
366
		    String firstSrc = getCookie(TrackingInterceptor.SRC_COOKIE, true, TrackingInterceptor.ENCRIPTION_STRING);
2817 vikas 367
 
3859 vikas 368
		    long sessionTime = 0;
369
            try {
370
                sessionTime = Long.parseLong(getCookie(TrackingInterceptor.SESSION_SRC_TIME_COOKIE, false, null));
371
            } catch (Exception e) {
372
                log.warn("Unable to parse session src time cookie.", e);
2817 vikas 373
            }
3859 vikas 374
            long firstSrcTime = 0;
375
            try {
376
                firstSrcTime = Long.parseLong(getCookie(TrackingInterceptor.SRC_TIME_COOKIE, false, null));
377
            } catch (Exception e) {
378
                log.warn("Unable to parse session src time cookie.", e);
379
            }
6390 rajveer 380
            txnId = userClient.createOrders(currentCartId, sessionSrc, sessionTime, firstSrc, firstSrcTime, currentUserId, emiSchemeId);
894 rajveer 381
		} catch (ShoppingCartException e1) {
2296 chandransh 382
			log.error("Error while creating orders from cart.", e1);
894 rajveer 383
			return false;
384
		} catch (TException e) {
2296 chandransh 385
			log.error("Thrift exception while creating orders from cart.", e);
894 rajveer 386
			return false;
387
		}
388
 
3126 rajveer 389
		TransactionClient transactionServiceClient = null;
4325 mandeep.dh 390
 
2183 vikas 391
        try {
3126 rajveer 392
            transactionServiceClient = new TransactionClient();
2183 vikas 393
            List<Order> orders = transactionServiceClient.getClient().getOrdersForTransaction(txnId, userinfo.getUserId());
394
            for (Order order : orders) {
3394 vikas 395
                List<Order> tmpOrders = new ArrayList<Order>();
396
                tmpOrders.add(order);
397
                String itemIdString = Utils.getItemIdStringFromOrders(tmpOrders);
3209 vikas 398
                DataLogger.logData(EventType.ORDER_CREATION, getSessionId(), userinfo.getUserId(), userinfo.getEmail(), 
3212 vikas 399
                        Long.toString(order.getId()), Long.toString(currentCartId), itemIdString);
2183 vikas 400
            }
401
        } catch (Exception e1) {
2296 chandransh 402
        	log.warn("Unable to log orders through the datalogger", e1);
2183 vikas 403
        }
894 rajveer 404
 
405
		return true;
406
	}
4325 mandeep.dh 407
 
408
	/**
409
	 * This method updates address of a given order.
410
	 *
411
	 * @return
412
	 */
413
	public String modifyAddress() {
414
        long orderId   = Long.parseLong(request.getParameter("orderId"));
415
        long addressId = Long.valueOf(request.getParameter("addressId"));
416
 
417
		try {
418
		    TransactionClient transactionServiceClient = new TransactionClient();
419
			in.shop2020.model.v1.order.TransactionService.Client transactionClient
420
			    = transactionServiceClient.getClient();			
421
			transactionClient.updateShipmentAddress(orderId, addressId);
7954 manish.sha 422
			in.shop2020.model.v1.order.Order t_order = transactionClient.getOrder(orderId);
423
			if(t_order.getLogistics_provider_id()==7L){
424
				FedExShipAccountInfo fedexAccountInfo = FedExShipAccountInfo.getFedExInfo();
425
				ProcessShipmentReply  processShipmentReply = ShipWebServiceClient.getShipmentCreationReply(t_order,fedexAccountInfo.getClientDetail(),fedexAccountInfo.getWad(),fedexAccountInfo.getEndPointAddress());
426
				CompletedShipmentDetail completedShipmentDetails = processShipmentReply.getCompletedShipmentDetail();
427
				CompletedPackageDetail completedPackageDetails =  completedShipmentDetails.getCompletedPackageDetails(0);
428
				TrackingId  trackId= completedPackageDetails.getTrackingIds(0);
429
				t_order = transactionClient.updateOrderAWB(t_order.getId(), trackId.getTrackingNumber());
430
			}
4325 mandeep.dh 431
		} catch (TTransportException e) {
432
		    log.error("Could not update address: " + addressId + " for orderId: " + orderId, e);
433
		} catch (NumberFormatException e) {
434
		    log.error("Could not update address: " + addressId + " for orderId: " + orderId, e);
435
		} catch (TransactionServiceException e) {
436
		    log.error("Could not update address: " + addressId + " for orderId: " + orderId, e);
437
		} catch (TException e) {
438
		    log.error("Could not update address: " + addressId + " for orderId: " + orderId, e);
439
		}			
440
 
441
		return "index";
442
	}
443
 
1318 rajveer 444
	public String getRedirectURL(){
445
		return this.redirectURL;
446
	}
5716 anupam.sin 447
 
448
    public String getDeliveryLocation() {
449
        return deliveryLocation;
450
    }
451
 
452
    public void setDeliveryLocation(String deliveryLocation) {
453
        this.deliveryLocation = deliveryLocation;
454
    }
6050 anupam.sin 455
 
456
    public static void main(String[] args) {
457
        DesEncrypter d = new DesEncrypter("shop2020");
458
        System.out.println(d.decrypt("pmkcWEzhf4IFRLyHce89Cg"));
7001 rajveer 459
    	long[] HDFC_EMI_GATEWAY_IDS = {5,10,11,12};
460
    	List<Long> stooges = Arrays.asList(5L,10L,11L,12L);
461
    	List<Long> lista = new ArrayList<Long>();
462
    	lista.add(5L);
463
    	lista.add(10L);
464
    	lista.add(11L);
465
    	lista.add(12L);
466
    	long gatewayId = 10;
467
    	if(stooges.contains(gatewayId)){
468
    		System.out.println("true");
469
    	}else{
470
    		System.out.println("false");
471
    	}
6050 anupam.sin 472
    }
419 rajveer 473
}