Subversion Repositories SmartDukaan

Rev

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