Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
507 rajveer 1
package in.shop2020.serving.controllers;
2
 
2263 vikas 3
import in.shop2020.datalogger.EventType;
1429 varun.gupt 4
import in.shop2020.model.v1.catalog.Item;
507 rajveer 5
import in.shop2020.model.v1.user.Address;
6
import in.shop2020.model.v1.user.AddressType;
841 vikas 7
import in.shop2020.model.v1.user.Cart;
1429 varun.gupt 8
import in.shop2020.model.v1.user.Line;
1774 varun.gupt 9
import in.shop2020.model.v1.user.User;
572 chandransh 10
import in.shop2020.model.v1.user.UserContextService;
2137 chandransh 11
import in.shop2020.serving.utils.FormattingUtils;
839 vikas 12
import in.shop2020.serving.utils.Utils;
1429 varun.gupt 13
import in.shop2020.thrift.clients.CatalogServiceClient;
3063 chandransh 14
import in.shop2020.thrift.clients.LogisticsServiceClient;
507 rajveer 15
import in.shop2020.thrift.clients.UserContextServiceClient;
2511 vikas 16
import in.shop2020.utils.DataLogger;
507 rajveer 17
 
2419 vikas 18
import java.util.ArrayList;
19
import java.util.Collection;
20
import java.util.HashMap;
21
import java.util.List;
22
import java.util.Map;
3063 chandransh 23
import java.util.ResourceBundle;
507 rajveer 24
 
832 rajveer 25
import org.apache.log4j.Logger;
822 vikas 26
import org.apache.struts2.convention.annotation.InterceptorRef;
27
import org.apache.struts2.convention.annotation.InterceptorRefs;
637 rajveer 28
import org.apache.struts2.convention.annotation.Result;
29
import org.apache.struts2.convention.annotation.Results;
1429 varun.gupt 30
import org.apache.velocity.VelocityContext;
507 rajveer 31
 
3076 chandransh 32
@SuppressWarnings("serial")
822 vikas 33
@InterceptorRefs({
34
    @InterceptorRef("myDefault"),
35
    @InterceptorRef("login")
36
})
37
 
637 rajveer 38
@Results({
39
    @Result(name="redirect", type="redirectAction", 
822 vikas 40
    		params = {"actionName" , "shipping"})
637 rajveer 41
})
822 vikas 42
public class ShippingController extends BaseController{
507 rajveer 43
 
832 rajveer 44
	private static Logger log = Logger.getLogger(Class.class);
507 rajveer 45
 
3063 chandransh 46
	private static final ResourceBundle resource = ResourceBundle.getBundle(ShippingController.class.getName());
47
	private static final double COD_CUTOFF_AMOUNT = Double.parseDouble(resource.getString("cod_cutoff_amount")); 
48
	private static final String RECAPTCHA_PUBLIC_KEY = resource.getString("recaptcha_public_key");
49
 
517 rajveer 50
	private long addressId = 0;
572 chandransh 51
	private String errorMsg = "";
507 rajveer 52
 
822 vikas 53
	private String name;
54
	private String line1;
55
	private String line2;
56
	private String city;
839 vikas 57
	private String state = "";
822 vikas 58
	private String pincode;
59
	private String phone;
60
	private String country;
61
 
3063 chandransh 62
	private boolean showCodOption = true;
63
 
507 rajveer 64
	public ShippingController(){
65
		super();
66
	}
67
 
68
	 // GET /shipping
637 rajveer 69
	 public String index() {
555 chandransh 70
    	long userId = userinfo.getUserId();
692 chandransh 71
    	long cartId = userinfo.getCartId();
572 chandransh 72
    	try {
73
			UserContextService.Client userClient = (new UserContextServiceClient()).getClient();
692 chandransh 74
			userClient.checkOut(cartId);
841 vikas 75
			Cart cart = userClient.getCart(cartId);
76
			long defaultAddressId = cart.getAddressId();
77
			if (defaultAddressId == 0) {
78
			    defaultAddressId = userClient.getDefaultAddressId(userId);
79
			}
637 rajveer 80
			log.info("The default address id of this user is: " + defaultAddressId);
81
			if(defaultAddressId > 0)
692 chandransh 82
				userClient.addAddressToCart(cartId, defaultAddressId);
1466 ankur.sing 83
			errorMsg = userClient.validateCart(cartId);
572 chandransh 84
 
85
		} catch (Exception e) {
2949 chandransh 86
			// This exception can be ignored for showing the shipping page. Not so
572 chandransh 87
			// innocent when this occurs at the time of checkout or when the
88
			// user is proceeding to pay.
2949 chandransh 89
			log.error("Unable to get all the data required for displaying the shipping page", e);
572 chandransh 90
		}
712 rajveer 91
    	// in case this page is redirected from payment failure
822 vikas 92
 
839 vikas 93
		Collection<String> actionErrors = getActionErrors();
94
		if(actionErrors != null && !actionErrors.isEmpty()){
95
			for (String str : actionErrors) {
96
			    errorMsg += "<BR/>" + str;
97
			}
712 rajveer 98
		}
2419 vikas 99
        DataLogger.logData(EventType.SHIPPINIG_ACCESS, session.getId(), userinfo.getUserId(), userinfo.getEmail(),
2157 vikas 100
                Long.toString(cartId));
822 vikas 101
 
637 rajveer 102
    	return "index";
507 rajveer 103
	 }
104
 
105
	// POST /entity
637 rajveer 106
	public String create(){
555 chandransh 107
		UserContextServiceClient userContextServiceClient = null;
108
		in.shop2020.model.v1.user.UserContextService.Client userClient = null;
109
 
637 rajveer 110
    	String action = this.request.getParameter("action");
517 rajveer 111
		if(action == null){
637 rajveer 112
			return "failure";
517 rajveer 113
		}
507 rajveer 114
 
555 chandransh 115
		try {
116
			userContextServiceClient = new UserContextServiceClient();
117
			userClient = userContextServiceClient.getClient();
517 rajveer 118
 
637 rajveer 119
			if(action != null){
120
				if(action.equals("add")){
839 vikas 121
					boolean invalidInput = false;
122
					if (!Utils.validatePin(this.pincode)) {
123
						addActionError("Invalid pincode.");
124
						invalidInput = true;
125
					}
126
					if (!Utils.validatePhone(this.phone)) {
127
						addActionError("Invalid phone number.");
128
						invalidInput = true;
129
					}
130
					if (this.line1.isEmpty()) {
131
						addActionError("Address line1 is empty.");
132
						invalidInput = true;
133
					}
134
					if (this.city.isEmpty()) {
135
						addActionError("City name is empty.");
136
						invalidInput = true;
137
					}
138
					if (this.state.isEmpty()) {
139
						addActionError("State name is empty.");
140
						invalidInput = true;
141
					}
142
					if (!invalidInput) {
143
						Address address = new Address();
144
						address.setName(this.name);
145
						address.setLine1(this.line1);
146
						address.setLine2(this.line2);
147
						address.setCity(this.city);
148
						address.setState(this.state);
149
						address.setPin(this.pincode);
150
						address.setPhone(this.phone);
151
						address.setCountry(this.country);
152
						address.setEnabled(true);
153
						address.setType(AddressType.HOME);
1446 varun.gupt 154
						long addressId = userClient.addAddressForUser(userinfo.getUserId(), address, false);
155
						userClient.addAddressToCart(userinfo.getCartId(), addressId);
839 vikas 156
						addActionMessage("Address added successfully.");
2419 vikas 157
                        DataLogger.logData(EventType.SHIPPINIG_ADD_ADDRESS, session.getId(), userinfo.getUserId(), userinfo.getEmail(), address.getName(),
2157 vikas 158
                                        address.getCity(), address.getPhone(), address.getPin());
839 vikas 159
					}
160
					return "redirect";				
517 rajveer 161
				}
162
 
1446 varun.gupt 163
				if(action.equals("change"))	{
841 vikas 164
					addressId = Long.parseLong(this.request.getParameter("addressid"));
637 rajveer 165
					userClient.addAddressToCart(userinfo.getCartId(), addressId);
1446 varun.gupt 166
 
1466 ankur.sing 167
					errorMsg = userClient.validateCart(userinfo.getCartId());
2419 vikas 168
                    DataLogger.logData(EventType.SHIPPINIG_ADD_CHANGE, session.getId(), userinfo.getUserId(), userinfo.getEmail(),
2157 vikas 169
                            Long.toString(userinfo.getCartId()), Long.toString(addressId));
1446 varun.gupt 170
					return "index";
637 rajveer 171
				}
517 rajveer 172
			}
637 rajveer 173
		} catch (Exception e) {
3076 chandransh 174
		    log.error("Error while adding address to the cart", e);
637 rajveer 175
			return "failure";
517 rajveer 176
		}
637 rajveer 177
		return null;
507 rajveer 178
	}
179
 
1429 varun.gupt 180
	public String getShippingHeaderSnippet() {
181
		String htmlString = "";
182
		VelocityContext context = new VelocityContext();
183
		String templateFile = "templates/shippingheader.vm";
184
		htmlString = pageLoader.getHtmlFromVelocity(templateFile, context);
185
		return htmlString;
507 rajveer 186
	}
187
 
1429 varun.gupt 188
	public String getShippingDetailsSnippet() {
189
 
190
		long cartId = userinfo.getCartId();
191
		String htmlString = "";
192
		VelocityContext context = new VelocityContext();
193
		String templateFile = "templates/shippingdetails.vm";
194
		List<Map<String,String>> items = null;
195
		double totalamount= 0.0;
196
		List<Address> addresses = null;
197
		long defaultAddressId = 0;
1774 varun.gupt 198
		String fullName = "";
199
		String phoneNumber = "";
1429 varun.gupt 200
 
201
		CatalogServiceClient catalogServiceClient  = null;
202
		in.shop2020.model.v1.catalog.InventoryService.Client catalogClient = null;
203
		UserContextServiceClient userContextServiceClient = null;
204
		in.shop2020.model.v1.user.UserContextService.Client userClient = null;
205
 
2137 chandransh 206
		FormattingUtils formattingUtils = new FormattingUtils();
207
 
1429 varun.gupt 208
		try {
209
			catalogServiceClient = new CatalogServiceClient();
210
			catalogClient = catalogServiceClient.getClient();
211
			userContextServiceClient = new UserContextServiceClient();
212
			userClient = userContextServiceClient.getClient();
213
 
214
			Cart cart = userClient.getCart(cartId);
215
			List<Line> lineItems = cart.getLines();
216
 
217
			if( ! lineItems.isEmpty())	{
218
				items = new ArrayList<Map<String,String>>();
219
 
220
				for (Line line : lineItems) {
221
					Map<String, String> itemdetail = new HashMap<String, String>();
222
					Item item = catalogClient.getItem(line.getItemId());
223
					String itemName = ((item.getBrand() != null) ? item.getBrand() + " " : "")
224
										+ ((item.getModelName() != null) ? item.getModelName() + " " : "") 
225
										+ (( item.getModelNumber() != null ) ? item.getModelNumber() + " " : "" )
226
										+ (( (item.getColor() != null && !item.getColor().trim().equals("NA"))) ? "("+item.getColor()+")" : "" );
227
 
228
					itemdetail.put("ITEM_NAME", itemName);
229
					itemdetail.put("ITEM_ID", line.getItemId()+"");
230
					itemdetail.put("ITEM_QUANTITY", ((int)line.getQuantity())+"");
2137 chandransh 231
					itemdetail.put("MRP", formattingUtils.formatPrice(item.getMrp()));
232
					itemdetail.put("SELLING_PRICE", formattingUtils.formatPrice(item.getSellingPrice()));
3063 chandransh 233
					if(item.getSellingPrice() > COD_CUTOFF_AMOUNT)
234
					    showCodOption = false;
2137 chandransh 235
					itemdetail.put("TOTAL_PRICE", formattingUtils.formatPrice((item.getSellingPrice()*line.getQuantity())));
1429 varun.gupt 236
					itemdetail.put("SHIPPING_TIME", line.getEstimate()+"");
2137 chandransh 237
					items.add(itemdetail);
1429 varun.gupt 238
				}
239
			}
2137 chandransh 240
			totalamount = cart.getTotalPrice();
1429 varun.gupt 241
			addresses = userClient.getAllAddressesForUser(cart.getUserId());
1774 varun.gupt 242
			User user = userClient.getUserById(cart.getUserId());
243
 
244
			fullName = user.getName();
245
			phoneNumber = user.getMobileNumber();
1429 varun.gupt 246
 
247
			if(cart.isSetAddressId())	{
248
				defaultAddressId = cart.getAddressId();
249
			} else	{
250
				defaultAddressId = userClient.getDefaultAddressId(cart.getUserId());
251
			}
3063 chandransh 252
 
253
	        for(Address address : addresses){
254
	            if(address.getId() == defaultAddressId){
255
	                try {
256
	                    LogisticsServiceClient lClient = new LogisticsServiceClient();
257
	                    showCodOption = showCodOption && lClient.getClient().isCodAllowed(address.getPin());
258
	                } catch(Exception e) {
3076 chandransh 259
	                    log.error("Error while checking if COD is available for: " + showCodOption, e);
3063 chandransh 260
	                    showCodOption = false; //Defaulting to defensive behaviour
261
	                }
262
	            }
263
	        }
1981 varun.gupt 264
 
265
			String couponCode = cart.getCouponCode();
266
	        context.put("couponcode", couponCode == null ? "" : couponCode);
2137 chandransh 267
	        context.put("discountedamount", formattingUtils.formatPrice(cart.getDiscountedPrice()));
1981 varun.gupt 268
 
1429 varun.gupt 269
		} catch (Exception e)	{
2949 chandransh 270
			log.error("Unable to get the shipping details", e);
1429 varun.gupt 271
		}
1774 varun.gupt 272
		System.out.println(fullName + " | " + phoneNumber);
1981 varun.gupt 273
 
1774 varun.gupt 274
		context.put("fullname", fullName);
275
		context.put("phonenumber", phoneNumber);
1429 varun.gupt 276
 
277
		context.put("items", items);
2137 chandransh 278
		context.put("totalamount", formattingUtils.formatPrice(totalamount));
1429 varun.gupt 279
		context.put("addresses", addresses);
280
		context.put("defaultAddressId", defaultAddressId+"");
281
		context.put("errorMsg", errorMsg);
282
		htmlString = pageLoader.getHtmlFromVelocity(templateFile, context);
283
		return htmlString;
507 rajveer 284
	}
285
 
517 rajveer 286
	public long getAddressId(){
287
		return this.addressId;
288
	}
572 chandransh 289
 
290
	public String getErrorMsg(){
291
		return this.errorMsg;
292
	}
822 vikas 293
 
294
	public String getName() {
295
		return name;
296
	}
297
 
298
	public void setName(String name) {
299
		this.name = name;
300
	}
301
 
302
	public String getLine1() {
303
		return line1;
304
	}
305
 
306
	public void setLine1(String line1) {
307
		this.line1 = line1;
308
	}
309
 
310
	public String getLine2() {
311
		return line2;
312
	}
313
 
314
	public void setLine2(String line2) {
315
		this.line2 = line2;
316
	}
317
 
318
	public String getCity() {
319
		return city;
320
	}
321
 
322
	public void setCity(String city) {
323
		this.city = city;
324
	}
325
 
326
	public String getState() {
327
		return state;
328
	}
329
 
330
	public void setState(String state) {
331
		this.state = state;
332
	}
333
 
334
	public String getPincode() {
335
		return pincode;
336
	}
337
 
338
	public void setPincode(String pincode) {
339
		this.pincode = pincode;
340
	}
341
 
342
	public String getCountry() {
343
		return country;
344
	}
345
 
346
	public void setCountry(String country) {
347
		this.country = country;
348
	}
349
 
350
	public String getPhone() {
351
		return phone;
352
	}
353
 
354
	public void setPhone(String phone) {
355
		this.phone = phone;
356
	}
3063 chandransh 357
 
358
    public boolean shouldShowCodOption() {
359
        return showCodOption;
360
    }
361
 
362
    public String getPublicKey(){
363
        return RECAPTCHA_PUBLIC_KEY;
364
    }
1429 varun.gupt 365
}