Subversion Repositories SmartDukaan

Rev

Rev 7853 | Rev 8942 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
3101 chandransh 1
package in.shop2020.serving.controllers;
2
 
3209 vikas 3
import in.shop2020.datalogger.EventType;
6390 rajveer 4
import in.shop2020.model.v1.order.EmiScheme;
5
import in.shop2020.model.v1.order.TransactionService.Client;
3101 chandransh 6
import in.shop2020.model.v1.user.Address;
7
import in.shop2020.model.v1.user.Cart;
6302 amit.gupta 8
import in.shop2020.model.v1.user.PromotionService;
3101 chandransh 9
import in.shop2020.serving.utils.FormattingUtils;
3209 vikas 10
import in.shop2020.serving.utils.Utils;
6302 amit.gupta 11
import in.shop2020.thrift.clients.PromotionClient;
6390 rajveer 12
import in.shop2020.thrift.clients.TransactionClient;
3126 rajveer 13
import in.shop2020.thrift.clients.UserClient;
3209 vikas 14
import in.shop2020.utils.DataLogger;
3101 chandransh 15
 
6407 amit.gupta 16
import java.util.ArrayList;
3101 chandransh 17
import java.util.Collection;
7853 amit.gupta 18
import java.util.HashMap;
6390 rajveer 19
import java.util.List;
7853 amit.gupta 20
import java.util.Map;
3101 chandransh 21
import java.util.ResourceBundle;
22
 
6309 amit.gupta 23
import org.apache.commons.lang.StringUtils;
3101 chandransh 24
import org.apache.log4j.Logger;
25
import org.apache.struts2.convention.annotation.InterceptorRef;
26
import org.apache.struts2.convention.annotation.InterceptorRefs;
27
import org.apache.struts2.convention.annotation.Result;
28
import org.apache.struts2.convention.annotation.Results;
6390 rajveer 29
import org.apache.thrift.TException;
30
import org.apache.thrift.transport.TTransportException;
3101 chandransh 31
 
6407 amit.gupta 32
import com.google.gson.Gson;
33
 
3101 chandransh 34
@SuppressWarnings("serial")
35
@InterceptorRefs({
36
    @InterceptorRef("myDefault"),
37
    @InterceptorRef("login")
38
})
39
 
40
@Results({
41
    @Result(name="shipping-redirect", type="redirectAction", params = {"actionName" , "shipping"})
42
})
43
 
44
public class ProceedToPayController extends BaseController {
45
 
46
    private static Logger logger = Logger.getLogger(ProceedToPayController.class);
47
    private static final ResourceBundle resource = ResourceBundle.getBundle(ProceedToPayController.class.getName());
48
    private static final boolean SHOW_EBS_TEST_GATEWAY = Boolean.parseBoolean(resource.getString("show_ebs_test_gateway"));
49
 
6390 rajveer 50
    private static List<EmiScheme> emiSchemes;
7853 amit.gupta 51
    private static String emiSchemesInJSON;
6302 amit.gupta 52
    private boolean hasGiftVoucher = false;
3101 chandransh 53
    private long addressId = -1;
54
    private String totalAmount = "";
6407 amit.gupta 55
    private double totalAmountD = 0l;
3101 chandransh 56
    private boolean showCodOption = true;
3616 chandransh 57
    private boolean showEmiOption = false;
3101 chandransh 58
    private String errorMsg = "";
5716 anupam.sin 59
    private String deliveryLocation = ""; //This could be set as myLocation or HotSpot
60
    private boolean showStorePickUpOption = false;
61
    private long hotSpotAddressId = 1;
7862 anupam.sin 62
    private boolean amountZero = false;
3101 chandransh 63
 
6407 amit.gupta 64
 
3101 chandransh 65
    public String index(){
66
        return processPaymentOptions();
67
    }
68
 
69
    public String create(){
70
        String addressIdString = this.request.getParameter("addressid");
71
        if(addressIdString == null){
72
            addActionError("Please specify shipping address to continue.");
73
            return "shipping-redirect";
74
        }
75
 
76
        try {
77
            addressId = Long.parseLong(addressIdString);
78
        } catch(NumberFormatException nfe) {
79
            logger.error("Unable to parse address id", nfe);
80
            addActionError("Please specify shipping address to continue.");
81
            return "shipping-redirect";
82
        }
83
        return processPaymentOptions();
84
    }
85
 
86
    private String processPaymentOptions() {
6390 rajveer 87
    	if(emiSchemes == null){
88
    		populateEmiSchemes();
89
    	}
90
 
3616 chandransh 91
        String showEmiOptionStr = this.request.getParameter("showEmiOption");
92
        if(showEmiOptionStr!=null){
93
            try{
94
                showEmiOption = Boolean.parseBoolean(showEmiOptionStr);
95
            }catch(Exception e){
96
                logger.info("A non-boolean value passed for showing EMI option");
97
            }
98
        }
99
 
3126 rajveer 100
        UserClient userContextServiceClient = null;
3101 chandransh 101
        in.shop2020.model.v1.user.UserContextService.Client userClient = null;
102
 
103
        Address address;
3209 vikas 104
        String itemIdString = "";
3101 chandransh 105
        try {
3126 rajveer 106
            userContextServiceClient = new UserClient();
3101 chandransh 107
            userClient = userContextServiceClient.getClient();
108
 
109
            long cartId = userinfo.getCartId();
5716 anupam.sin 110
            if(deliveryLocation.equals("myLocation")) {
111
                userClient.addStoreToCart(cartId, 0);
112
            }
3101 chandransh 113
            // Validate the cart to ensure that we are not accepting payment for
114
            // an invalid order.
6736 amit.gupta 115
            errorMsg = userClient.validateCart(cartId, sourceId).get(0);
3101 chandransh 116
 
117
            Cart cart = userClient.getCart(cartId);
4516 varun.gupt 118
            String couponCode = cart.getCouponCode();
119
            logger.info("Coupon: " + couponCode);
120
 
7862 anupam.sin 121
            setTotalAmount(cart);
122
            itemIdString = Utils.getItemIdStringInCart(cart);
123
 
6302 amit.gupta 124
            PromotionService.Client pc = new PromotionClient().getClient();
7862 anupam.sin 125
            /*
126
             * If a gift voucher is used such that all of the amount is paid by the gift voucher then we
127
             * do not need set the hasGiftVoucher flag.
128
             */
129
            if(StringUtils.isNotEmpty(couponCode) && pc.isGiftVoucher(couponCode) && getTotalAmountL() > 0){
6302 amit.gupta 130
            	hasGiftVoucher = true;
131
            }
132
 
133
            if (!hasGiftVoucher && deliveryLocation.equals("HotSpot")) {
134
            	userClient.addStoreToCart(cartId, hotSpotAddressId);
135
            	showStorePickUpOption = true;
136
            }
3101 chandransh 137
 
138
            // Get the address to check if COD option is available for this
139
            // address.
140
            if(addressId == -1){
141
                addressId = cart.getAddressId();
142
            }
143
            address = userClient.getAddressById(addressId);
4668 varun.gupt 144
 
5614 rajveer 145
            try {
6356 amit.gupta 146
                showCodOption = userClient.showCODOption(cartId, sourceId, address.getPin());
5614 rajveer 147
            } catch(Exception e) {
148
                logger.error("Error while checking if COD is available for: " + showCodOption, e);
149
                showCodOption = false; //Not a critical error, proceeding with defensive behaviour.
4668 varun.gupt 150
            }
151
 
6353 rajveer 152
            showStorePickUpOption = showStorePickUpOption && showCodOption;
153
 
3209 vikas 154
            DataLogger.logData(EventType.PROCEED_TO_PAY, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
155
                    Long.toString(cartId), itemIdString);
3101 chandransh 156
        } catch(Exception e) {
157
            logger.error("Error while either validating the cart or getting the address", e);
158
            addActionError("We are experiencing some problem. Please try again.");
159
            return "shipping-redirect";
160
        }
161
 
162
        Collection<String> actionErrors = getActionErrors();
163
        if(actionErrors != null && !actionErrors.isEmpty()){
164
            for (String str : actionErrors) {
6903 anupam.sin 165
                errorMsg += str + "<BR/>";
3101 chandransh 166
            }
167
        }
168
 
169
        return "index";
170
    }
171
 
7853 amit.gupta 172
    public static void populateEmiSchemes(){
6390 rajveer 173
    	try {
174
			Client tClient = new TransactionClient().getClient();
175
			emiSchemes = tClient.getAvailableEmiSchemes();
176
		} catch (TTransportException e) {
177
			logger.error("Error while getting EMI schemes: ", e);
178
		} catch (TException e) {
179
			logger.error("Error while getting EMI schemes: ", e);
180
		}
181
    }
182
 
3101 chandransh 183
    private void setTotalAmount(Cart cart) {
6407 amit.gupta 184
    	String couponCode = cart.getCouponCode();
3101 chandransh 185
        if(couponCode == null || "".equals(couponCode))
6407 amit.gupta 186
        	totalAmountD = cart.getTotalPrice();
3101 chandransh 187
        else
6407 amit.gupta 188
            totalAmountD = cart.getDiscountedPrice();
189
 
190
        FormattingUtils formattingUtils = new FormattingUtils();
191
        totalAmount = formattingUtils.formatPrice(totalAmountD);
7862 anupam.sin 192
        if(totalAmountD == 0) {
193
            amountZero = true;
194
        }
3101 chandransh 195
    }
196
 
197
    public long getAddressId(){
198
        return this.addressId;
199
    }
200
 
201
    public String getErrorMsg(){
4815 phani.kuma 202
    	logger.info("added error msg:" + this.errorMsg);
3101 chandransh 203
        return this.errorMsg;
204
    }
205
 
206
    public boolean shouldShowCodOption() {
207
        return showCodOption;
208
    }
209
 
3616 chandransh 210
    public boolean shouldShowEmiOption() {
211
        return showEmiOption;
212
    }
213
 
3101 chandransh 214
    public String getTotalAmount(){
215
        return totalAmount;
216
    }
217
 
6407 amit.gupta 218
    public double getTotalAmountL(){
219
    	return totalAmountD;
220
    }
221
 
3101 chandransh 222
    public boolean shouldShowEbsTestGateway() {
223
        return SHOW_EBS_TEST_GATEWAY;
224
    }
225
 
3903 varun.gupt 226
	@Override
227
	public String getHeaderSnippet() {
228
		String url = request.getQueryString();
229
		if (url == null) {
230
			url = "";
231
		} else {
232
			url = "?" + url;
233
		}
234
		url = request.getRequestURI() + url;
6152 amit.gupta 235
		return pageLoader.getHeaderHtml(userinfo.isLoggedIn(), userinfo.getEmail(), userinfo.getTotalItems(), url , 0, false);
3903 varun.gupt 236
	}
5716 anupam.sin 237
 
238
    public String getDeliveryLocation() {
239
        return deliveryLocation;
240
    }
241
 
242
    public void setDeliveryLocation(String deliveryLocation) {
243
        this.deliveryLocation = deliveryLocation;
244
    }
245
 
246
    public long getHotSpotAddressId() {
247
        return hotSpotAddressId;
248
    }
249
 
250
    public void setHotSpotAddressId(long hotSpotAddressId) {
251
        this.hotSpotAddressId = hotSpotAddressId;
252
    }
253
 
254
    public boolean shouldShowStorePickUpOption() {
255
        return showStorePickUpOption;
256
    }
6390 rajveer 257
 
6407 amit.gupta 258
    public String getJSONEmiSchemes(){
259
    	getEmiSchemes();
260
    	Double totalAmount = getTotalAmountL();
261
    	List<EmiScheme> schemes = new ArrayList<EmiScheme>();
262
    	for(EmiScheme emiScheme : emiSchemes) {
263
    		if(emiScheme.getMinAmount() <= totalAmount ) {
264
    			schemes.add(emiScheme);
265
    		}
266
    	}
267
    	Gson gson  = new Gson();
268
    	return gson.toJson(schemes);
269
    }
270
 
6736 amit.gupta 271
    public String getJSONEmiDiscountSchemes(){
272
    	try {
273
    	PromotionService.Client pc = new PromotionClient().getClient();
274
    	Gson gson  = new Gson();
275
    	return gson.toJson(pc.getEmiDiscount(userinfo.getCartId()));
276
    	}catch (Exception e){
277
    		logger.warn("Could not retrive emi based promotions for cart: " + userinfo.getCartId() + ".\n" + e);
278
    		return "{}";
279
    	}
280
    }
281
 
7853 amit.gupta 282
    public static List<EmiScheme> getEmiSchemes(){
283
    	if (emiSchemes != null) { 
284
    		return emiSchemes;
285
    	} else {
286
    		populateEmiSchemes();
287
    		return emiSchemes;
288
    	}
6390 rajveer 289
    }
290
 
291
    public static long getGatewayId(long emiSchemeId){
292
    	for(EmiScheme scheme: emiSchemes){
293
    		if(scheme.getId() == emiSchemeId){
294
    			return scheme.getGatewayId();
295
    		}
296
    	}
297
    	return 0;
298
    }
6442 rajveer 299
 
300
    public static double getInterestRate(long emiSchemeId){
301
    	for(EmiScheme scheme: emiSchemes){
302
    		if(scheme.getId() == emiSchemeId){
303
    			return scheme.getChargeValue();
304
    		}
305
    	}
306
    	return 0;
307
    }
7862 anupam.sin 308
 
309
    public void setAmountZero(boolean amountZero) {
310
        this.amountZero = amountZero;
311
    }
312
 
313
    public boolean isAmountZero() {
314
        return amountZero;
315
    }
7853 amit.gupta 316
 
317
    public static String getEmiSchemesInJSON(){
318
    	if(emiSchemesInJSON==null){
319
    		List<Map<String, Object>> schemeList = new ArrayList<Map<String,Object>>();
320
    		for(EmiScheme scheme: getEmiSchemes()){
321
    			Map<String,Object> arrayMap = new HashMap<String, Object>();
322
    			arrayMap.put("bankId",scheme.getBankId());
323
    			arrayMap.put("bankName",scheme.getBankName());
324
    			arrayMap.put("chargeType",scheme.getChargeType());
325
    			arrayMap.put("chargeValue",scheme.getChargeValue());
326
    			arrayMap.put("gatewayId",scheme.getGatewayId());
327
    			arrayMap.put("minAmount",scheme.getMinAmount());
328
    			arrayMap.put("tenure",scheme.getTenure());
329
    			arrayMap.put("tenureDescription",scheme.getTenureDescription());
330
    			arrayMap.put("id",scheme.getId());
331
    			schemeList.add(arrayMap);
332
    		}
333
    		return new Gson().toJson(schemeList);
334
    	} else {
335
    		return emiSchemesInJSON;
336
    	}
337
    }
3903 varun.gupt 338
}