Subversion Repositories SmartDukaan

Rev

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