Subversion Repositories SmartDukaan

Rev

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