Subversion Repositories SmartDukaan

Rev

Rev 2958 | Rev 3101 | 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;
3063 chandransh 14
import in.shop2020.thrift.clients.LogisticsServiceClient;
2183 vikas 15
import in.shop2020.thrift.clients.TransactionServiceClient;
517 rajveer 16
import in.shop2020.thrift.clients.UserContextServiceClient;
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({
693 rajveer 41
    @Result(name="shipping-redirect", type="redirectAction", 
1905 chandransh 42
    		params = {"actionName" , "shipping"}),
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.");
786 rajveer 80
    		return "shipping-redirect";
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.");
87
    		return "shipping-redirect";
88
    	}
89
 
90
 
786 rajveer 91
    	long addressId = Long.parseLong(addressIdString);
572 chandransh 92
    	long currentCartId = userinfo.getCartId();
3063 chandransh 93
 
94
    	if(paymentOption.equals(IPaymentService.COD)){
95
    	    if(!verifyCaptcha()){
96
    	        addActionError("Invalid captcha");
97
    	        return "shipping-redirect";    
98
    	    }
99
 
100
    	    //Check that this address is eligible for COD shipping.
101
    	    UserContextServiceClient userServiceClient = null;
102
            try {
103
                userServiceClient = new UserContextServiceClient();
104
                in.shop2020.model.v1.user.UserContextService.Client userClient = userServiceClient.getClient();
105
                Address address = userClient.getAddressById(addressId);
106
 
107
                LogisticsServiceClient logisticsServiceClient = new LogisticsServiceClient();
108
                if(!logisticsServiceClient.getClient().isCodAllowed(address.getPin())){
109
                    addActionError("Cash on Delivery is currently not available for this pincode. Please choose a different payment option.");
110
                    return "shipping-redirect";    
111
                }
112
            } catch (Exception e) {
113
                log.error("Unable to talk to the user context service.", e);
114
                addActionError("We are experiencing some problems. Please try later.");
115
                return "shipping-redirect";
116
            }
117
    	}
118
 
119
    	try {
1318 rajveer 120
    		if(!createOrders(addressId, currentCartId)){
1128 rajveer 121
    			addActionError("We are experiencing some problems. Please try later.");
894 rajveer 122
    			return "shipping-redirect";
123
    		}
3063 chandransh 124
    	} catch (Exception e) {
1128 rajveer 125
    		addActionError("We are experiencing some problems. Please try later.");
2296 chandransh 126
    		log.error("Exception in createOrders function. Something went wrong.", e);
894 rajveer 127
    		return "shipping-redirect";
693 rajveer 128
		}
2159 chandransh 129
 
3063 chandransh 130
    	if(paymentOption.equals(IPaymentService.COD)){
131
    	    IPaymentService codPaymentService = new CodPaymentService();
132
    	    paymentId = codPaymentService.createPayment(userinfo.getCartId(), userinfo.getUserId(), txnId, paymentOption);
133
            if (paymentId == IPaymentService.PAYMENT_NOT_CREATED) {
134
                //Very unlikely. The only possible reason can be that the payment service is down.
135
                log.error("Unable to process the COD payment.");
136
                addActionError("We are experiencing some problems. Please try later.");
137
                return "shipping-redirect";
138
            } else {
139
                CommonPaymentService.processCodTxn(txnId);
140
                return "cod-redirect";
141
            }
142
    	} else {
143
            if(paymentOption.equals(IPaymentService.HDFC_MASTERCARD) || paymentOption.equals(IPaymentService.HDFC_VISA) || paymentOption.equals(IPaymentService.HDFC_VISA_ELECTRON)) {
144
                // User has selected Visa or MasterCard CC
145
                IPaymentService hdfcPaymentService = new HdfcPaymentService();
146
                paymentId = hdfcPaymentService.createPayment(userinfo.getCartId(), userinfo.getUserId(), txnId, paymentOption);
147
                if (paymentId == IPaymentService.PAYMENT_NOT_CREATED) {
148
                    log.error("Unable to process payment through HDFC. Falling through to EBS.");
149
                } else {
150
                    this.redirectURL = ((HdfcPaymentService)hdfcPaymentService).getRedirectUrl();
151
                    log.info(this.redirectURL);
152
                    return "success";
153
                }
154
            }
2199 chandransh 155
 
3063 chandransh 156
            if(paymentOption.equals(IPaymentService.HDFC_VISA))
157
                paymentOption = IPaymentService.EBS_VISA;
158
            else if(paymentOption.equals(IPaymentService.HDFC_MASTERCARD))
159
                paymentOption = IPaymentService.EBS_MASTERCARD;
160
            else if(paymentOption.equals(IPaymentService.HDFC_VISA_ELECTRON))
161
                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.
162
 
163
            IPaymentService ebsPaymentService = new EbsPaymentService();
164
            paymentId = ebsPaymentService.createPayment(userinfo.getCartId(), userinfo.getUserId(), txnId, paymentOption);
165
            if(paymentId == IPaymentService.PAYMENT_NOT_CREATED){
166
                addActionError("We are experiencing some problems. Please try later.");
167
                return "shipping-redirect";
168
            } else {
169
                log.info("Successfully created payment for EBS to process. Redirecting to /ebs-pay/" + paymentId);
170
                return "ebs-pay-redirect";
171
            }    	    
172
    	}
173
 
572 chandransh 174
    }
3063 chandransh 175
 
176
    /**
177
     * Verifies if the recaptcha response matches the recaptcha challenge.
178
     * 
179
     * @return True if the captcha was valid, false otherwise.
180
     */
181
    private boolean verifyCaptcha() {
182
        String remoteAddr = request.getRemoteAddr();
183
        ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
184
        reCaptcha.setPrivateKey(RECAPTCHA_PRIVATE_KEY);
185
 
186
        String challenge = request.getParameter("recaptcha_challenge_field");
187
        String uresponse = request.getParameter("recaptcha_response_field");
188
        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);
189
 
190
        if(reCaptchaResponse.isValid())
191
          return true;
192
        else
193
          return false;
194
    }
572 chandransh 195
 
507 rajveer 196
	public String getId(){
197
		return id;
198
	}
419 rajveer 199
 
507 rajveer 200
	public void setId(String id){
201
		this.id = id;
202
	}
419 rajveer 203
 
507 rajveer 204
	public String getMyaccountHeaderSnippet(){
205
		return htmlSnippets.get("MYACCOUNT_HEADER");
206
	}
207
 
208
	public String getOrderDetailsSnippet(){
209
		return htmlSnippets.get("ORDER_DETAILS");
210
	}
211
 
712 rajveer 212
	public long getTxn(){
213
		return this.txnId;
517 rajveer 214
	}
894 rajveer 215
 
216
	/**
217
	 * 
218
	 * @param addressId
219
	 * @param currentCartId
220
	 * @return
221
	 */
1318 rajveer 222
	private boolean createOrders(long addressId, long currentCartId){
894 rajveer 223
		UserContextServiceClient userServiceClient = null;
224
		try {
225
			userServiceClient = new UserContextServiceClient();
226
		} catch (Exception e) {
2296 chandransh 227
			log.error("Unable to talk to the user context service.", e);
894 rajveer 228
			return false;
229
		}
230
 
231
		in.shop2020.model.v1.user.UserContextService.Client userClient = userServiceClient.getClient();
232
		try {
233
			userClient.addAddressToCart(currentCartId, addressId);
234
		} catch (ShoppingCartException e1) {
2296 chandransh 235
			log.error("Not able to set address in the cart.", e1);
894 rajveer 236
			return false;
237
		} catch (TException e1) {
2296 chandransh 238
			log.error("Thrift exception while setting address in cart.", e1);
894 rajveer 239
			return false;
240
		}
241
 
242
 
243
		try {
1466 ankur.sing 244
			String errorMsg = userClient.validateCart(currentCartId); 
245
			if(!errorMsg.isEmpty()){
246
				addActionError(errorMsg);
894 rajveer 247
				return false;
248
			}
249
		} catch (ShoppingCartException e1) {
2296 chandransh 250
			log.error("Error while validating shopping cart.", e1);
894 rajveer 251
			return false;
252
		} catch (TException e) {
2296 chandransh 253
			log.error("Thrift exception while validating cart.", e);
894 rajveer 254
			return false;
255
		}
256
 
257
 
258
		try {
2817 vikas 259
		    String sessionSrc = null;
260
		    Cookie sessionSrcCookie = (Cookie) cookiesMap.get(TrackingInterceptor.SESSION_SRC_COOKIE);
261
            if (sessionSrcCookie != null) {
262
                DesEncrypter desEncrypter = new DesEncrypter(TrackingInterceptor.ENCRIPTION_STRING);
263
                sessionSrc = desEncrypter.decrypt(sessionSrcCookie.getValue());
264
            }
265
 
266
            Cookie sessionSrcTimeCookie = (Cookie) cookiesMap.get(TrackingInterceptor.SESSION_SRC_TIME_COOKIE);
267
            long sessionTime = 0;
268
            if (sessionSrcTimeCookie != null) {
269
                try {
270
                    sessionTime = Long.parseLong(sessionSrcTimeCookie.getValue());
2958 chandransh 271
                } catch (Exception e) {
272
                    log.warn("Unable to parse session src time cookie.", e);
2817 vikas 273
                }
274
            }
275
		    txnId = userClient.createOrders(currentCartId, sessionSrc, sessionTime);
894 rajveer 276
		} catch (ShoppingCartException e1) {
2296 chandransh 277
			log.error("Error while creating orders from cart.", e1);
894 rajveer 278
			return false;
279
		} catch (TException e) {
2296 chandransh 280
			log.error("Thrift exception while creating orders from cart.", e);
894 rajveer 281
			return false;
282
		}
283
 
2183 vikas 284
		TransactionServiceClient transactionServiceClient = null;
285
        try {
286
            transactionServiceClient = new TransactionServiceClient();
287
            List<Order> orders = transactionServiceClient.getClient().getOrdersForTransaction(txnId, userinfo.getUserId());
288
            for (Order order : orders) {
2419 vikas 289
                DataLogger.logData(EventType.ORDER_CREATION, session.getId(),
290
                        userinfo.getUserId(), userinfo.getEmail(), Long.toString(order.getId()));
2183 vikas 291
            }
292
        } catch (Exception e1) {
2296 chandransh 293
        	log.warn("Unable to log orders through the datalogger", e1);
2183 vikas 294
        }
894 rajveer 295
 
296
		return true;
297
	}
1318 rajveer 298
 
299
	public String getRedirectURL(){
300
		return this.redirectURL;
301
	}
419 rajveer 302
}