Subversion Repositories SmartDukaan

Rev

Rev 3394 | Rev 3616 | 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
 
3394 vikas 20
import java.util.ArrayList;
2419 vikas 21
import java.util.List;
3063 chandransh 22
import java.util.ResourceBundle;
2419 vikas 23
 
2817 vikas 24
import javax.servlet.http.Cookie;
25
 
3063 chandransh 26
import net.tanesha.recaptcha.ReCaptchaImpl;
27
import net.tanesha.recaptcha.ReCaptchaResponse;
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;
419 rajveer 35
 
2159 chandransh 36
@SuppressWarnings("serial")
822 vikas 37
@InterceptorRefs({
38
    @InterceptorRef("myDefault"),
39
    @InterceptorRef("login")
40
})
41
 
419 rajveer 42
@Results({
3101 chandransh 43
    @Result(name="shipping-redirect", type="redirectAction", params = {"actionName" , "shipping"}),
44
    @Result(name="proceed-to-pay-redirect", type="redirectAction", params = {"actionName" , "proceed-to-pay"}),
3063 chandransh 45
	@Result(name="ebs-pay-redirect", type="redirect", location="/ebs-pay/${paymentId}"),
46
	@Result(name="cod-redirect", type="redirect", location="/pay-success?paymentId=${paymentId}")
419 rajveer 47
})
650 rajveer 48
public class OrderController extends BaseController {
419 rajveer 49
 
1905 chandransh 50
	public long getPaymentId() {
51
		return paymentId;
52
	}
419 rajveer 53
 
832 rajveer 54
	private static Logger log = Logger.getLogger(Class.class);
3063 chandransh 55
	private static final ResourceBundle resource = ResourceBundle.getBundle(OrderController.class.getName());
56
	private static final String RECAPTCHA_PRIVATE_KEY = resource.getString("recaptcha_private_key");
57
 
507 rajveer 58
	private String id;
712 rajveer 59
	private long txnId = 0;
650 rajveer 60
 
1905 chandransh 61
	private long paymentId;
62
 
1318 rajveer 63
	private String redirectURL;
681 rajveer 64
 
419 rajveer 65
	public OrderController(){
507 rajveer 66
		super();
419 rajveer 67
	}
68
 
507 rajveer 69
    // GET /order/ orderid
70
    public String show() {
71
    	log.info("id=" + id);
822 vikas 72
    	htmlSnippets.put("MYACCOUNT_HEADER", pageLoader.getMyaccountHeaderHtml());
1527 ankur.sing 73
    	htmlSnippets.put("ORDER_DETAILS", pageLoader.getOrderDetailsHtml(Long.parseLong(id), userinfo.getUserId()));
507 rajveer 74
    	return "show";
419 rajveer 75
    }
517 rajveer 76
 
572 chandransh 77
    // POST /order/
78
    public String create(){
786 rajveer 79
    	String addressIdString = this.request.getParameter("addressid");
80
    	if(addressIdString == null){
894 rajveer 81
    		addActionError("Please specify shipping address to continue.");
3101 chandransh 82
    		return "proceed-to-pay-redirect";
786 rajveer 83
    	}
2159 chandransh 84
 
85
    	String paymentOption = request.getParameter("payment_option");
86
    	log.info("Payment Option Selected: " + paymentOption);
87
    	if(paymentOption == null || paymentOption.equals("")){
88
    		addActionError("Please select a payment method to continue.");
3101 chandransh 89
    		return "proceed-to-pay-redirect";
2159 chandransh 90
    	}
91
 
92
 
3101 chandransh 93
    	long addressId;
94
    	try {
95
    	    addressId = Long.parseLong(addressIdString);   
96
    	} catch(NumberFormatException nfe){
97
    	    log.error("Unable to get address id", nfe);
98
    	    addActionError("Invalid address. Please add an address to the cart.");
99
    	    return "shipping-redirect";
100
    	}
101
 
572 chandransh 102
    	long currentCartId = userinfo.getCartId();
3063 chandransh 103
 
104
    	if(paymentOption.equals(IPaymentService.COD)){
105
    	    if(!verifyCaptcha()){
106
    	        addActionError("Invalid captcha");
3101 chandransh 107
    	        return "proceed-to-pay-redirect";    
3063 chandransh 108
    	    }
109
 
110
    	    //Check that this address is eligible for COD shipping.
3126 rajveer 111
    	    UserClient userServiceClient = null;
3063 chandransh 112
            try {
3126 rajveer 113
                userServiceClient = new UserClient();
3063 chandransh 114
                in.shop2020.model.v1.user.UserContextService.Client userClient = userServiceClient.getClient();
115
                Address address = userClient.getAddressById(addressId);
116
 
3126 rajveer 117
                LogisticsClient logisticsServiceClient = new LogisticsClient();
3063 chandransh 118
                if(!logisticsServiceClient.getClient().isCodAllowed(address.getPin())){
119
                    addActionError("Cash on Delivery is currently not available for this pincode. Please choose a different payment option.");
3101 chandransh 120
                    return "proceed-to-pay-redirect";    
3063 chandransh 121
                }
122
            } catch (Exception e) {
123
                log.error("Unable to talk to the user context service.", e);
124
                addActionError("We are experiencing some problems. Please try later.");
3101 chandransh 125
                return "proceed-to-pay-redirect";
3063 chandransh 126
            }
127
    	}
128
 
129
    	try {
1318 rajveer 130
    		if(!createOrders(addressId, currentCartId)){
1128 rajveer 131
    			addActionError("We are experiencing some problems. Please try later.");
3101 chandransh 132
    			return "proceed-to-pay-redirect";
894 rajveer 133
    		}
3063 chandransh 134
    	} catch (Exception e) {
1128 rajveer 135
    		addActionError("We are experiencing some problems. Please try later.");
2296 chandransh 136
    		log.error("Exception in createOrders function. Something went wrong.", e);
3101 chandransh 137
    		return "proceed-to-pay-redirect";
693 rajveer 138
		}
2159 chandransh 139
 
3063 chandransh 140
    	if(paymentOption.equals(IPaymentService.COD)){
141
    	    IPaymentService codPaymentService = new CodPaymentService();
3561 rajveer 142
    	    paymentId = codPaymentService.createPayment(userinfo.getCartId(), userinfo.getUserId(), txnId, paymentOption, sourceId);
3063 chandransh 143
            if (paymentId == IPaymentService.PAYMENT_NOT_CREATED) {
144
                //Very unlikely. The only possible reason can be that the payment service is down.
145
                log.error("Unable to process the COD payment.");
146
                addActionError("We are experiencing some problems. Please try later.");
3101 chandransh 147
                return "proceed-to-pay-redirect";
3063 chandransh 148
            } else {
149
                CommonPaymentService.processCodTxn(txnId);
150
                return "cod-redirect";
151
            }
152
    	} else {
153
            if(paymentOption.equals(IPaymentService.HDFC_MASTERCARD) || paymentOption.equals(IPaymentService.HDFC_VISA) || paymentOption.equals(IPaymentService.HDFC_VISA_ELECTRON)) {
154
                // User has selected Visa or MasterCard CC
155
                IPaymentService hdfcPaymentService = new HdfcPaymentService();
3561 rajveer 156
                paymentId = hdfcPaymentService.createPayment(userinfo.getCartId(), userinfo.getUserId(), txnId, paymentOption, sourceId);
3063 chandransh 157
                if (paymentId == IPaymentService.PAYMENT_NOT_CREATED) {
158
                    log.error("Unable to process payment through HDFC. Falling through to EBS.");
159
                } else {
160
                    this.redirectURL = ((HdfcPaymentService)hdfcPaymentService).getRedirectUrl();
161
                    log.info(this.redirectURL);
162
                    return "success";
163
                }
164
            }
2199 chandransh 165
 
3063 chandransh 166
            if(paymentOption.equals(IPaymentService.HDFC_VISA))
167
                paymentOption = IPaymentService.EBS_VISA;
168
            else if(paymentOption.equals(IPaymentService.HDFC_MASTERCARD))
169
                paymentOption = IPaymentService.EBS_MASTERCARD;
170
            else if(paymentOption.equals(IPaymentService.HDFC_VISA_ELECTRON))
171
                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.
172
 
173
            IPaymentService ebsPaymentService = new EbsPaymentService();
3561 rajveer 174
            paymentId = ebsPaymentService.createPayment(userinfo.getCartId(), userinfo.getUserId(), txnId, paymentOption, sourceId);
3063 chandransh 175
            if(paymentId == IPaymentService.PAYMENT_NOT_CREATED){
176
                addActionError("We are experiencing some problems. Please try later.");
3101 chandransh 177
                return "proceed-to-pay-redirect";
3063 chandransh 178
            } else {
179
                log.info("Successfully created payment for EBS to process. Redirecting to /ebs-pay/" + paymentId);
180
                return "ebs-pay-redirect";
181
            }    	    
182
    	}
183
 
572 chandransh 184
    }
3063 chandransh 185
 
186
    /**
187
     * Verifies if the recaptcha response matches the recaptcha challenge.
188
     * 
189
     * @return True if the captcha was valid, false otherwise.
190
     */
191
    private boolean verifyCaptcha() {
192
        String remoteAddr = request.getRemoteAddr();
193
        ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
194
        reCaptcha.setPrivateKey(RECAPTCHA_PRIVATE_KEY);
195
 
196
        String challenge = request.getParameter("recaptcha_challenge_field");
197
        String uresponse = request.getParameter("recaptcha_response_field");
198
        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);
199
 
3264 chandransh 200
        log.info("Recaptcha Response:" + reCaptchaResponse.isValid());
201
        return reCaptchaResponse.isValid();
3063 chandransh 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 {
3561 rajveer 252
			String errorMsg = userClient.validateCart(currentCartId, sourceId); 
1466 ankur.sing 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) {
3394 vikas 297
                List<Order> tmpOrders = new ArrayList<Order>();
298
                tmpOrders.add(order);
299
                String itemIdString = Utils.getItemIdStringFromOrders(tmpOrders);
3209 vikas 300
                DataLogger.logData(EventType.ORDER_CREATION, getSessionId(), userinfo.getUserId(), userinfo.getEmail(), 
3212 vikas 301
                        Long.toString(order.getId()), Long.toString(currentCartId), itemIdString);
2183 vikas 302
            }
303
        } catch (Exception e1) {
2296 chandransh 304
        	log.warn("Unable to log orders through the datalogger", e1);
2183 vikas 305
        }
894 rajveer 306
 
307
		return true;
308
	}
1318 rajveer 309
 
310
	public String getRedirectURL(){
311
		return this.redirectURL;
312
	}
419 rajveer 313
}