Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
410 rajveer 1
package in.shop2020.serving.controllers;
2
 
1981 varun.gupt 3
import java.util.ArrayList;
4
import java.util.HashMap;
5
import java.util.List;
650 rajveer 6
import java.util.Map;
7
import java.util.StringTokenizer;
8
 
2263 vikas 9
import in.shop2020.datalogger.EventType;
1981 varun.gupt 10
import in.shop2020.model.v1.catalog.Item;
11
import in.shop2020.model.v1.user.Cart;
12
import in.shop2020.model.v1.user.Line;
555 chandransh 13
import in.shop2020.model.v1.user.ShoppingCartException;
572 chandransh 14
import in.shop2020.model.v1.user.UserContextService;
410 rajveer 15
import in.shop2020.serving.controllers.BaseController;
1981 varun.gupt 16
 
17
import in.shop2020.thrift.clients.CatalogServiceClient;
1957 vikas 18
import in.shop2020.serving.utils.DataLogger;
2137 chandransh 19
import in.shop2020.serving.utils.FormattingUtils;
410 rajveer 20
import in.shop2020.thrift.clients.UserContextServiceClient;
21
 
832 rajveer 22
import org.apache.log4j.Logger;
1614 rajveer 23
import org.apache.struts2.convention.annotation.Action;
24
import org.apache.struts2.convention.annotation.InterceptorRef;
801 rajveer 25
import org.apache.struts2.convention.annotation.Result;
1614 rajveer 26
import org.apache.struts2.convention.annotation.Results;
410 rajveer 27
import org.apache.struts2.interceptor.ParameterAware;
28
import org.apache.thrift.TException;
29
 
1614 rajveer 30
 
31
@Results({
32
	@Result(name="redirect", type="redirectAction", 
33
	   		params = {"actionName" , "cart"}),
34
	@Result(name="failure", location="cart-failure.vm"),
35
	@Result(name="success", location="cart-success.vm")
36
})
37
 
38
 
507 rajveer 39
public class CartController extends BaseController implements ParameterAware{
410 rajveer 40
 
41
	private static final long serialVersionUID = 1L;
1957 vikas 42
	private static Logger log = Logger.getLogger(Class.class);
507 rajveer 43
	Map<String, String[]> reqparams = null;
1981 varun.gupt 44
 
2137 chandransh 45
    private String totalamount;
410 rajveer 46
 
572 chandransh 47
	private String errorMsg = "";
2099 rajveer 48
	private String cartMsg = ""; 
410 rajveer 49
 
1981 varun.gupt 50
	private String pincode = "110001";
51
 
52
	private String couponCode = null;
53
 
2137 chandransh 54
	private String discountedAmount;
1981 varun.gupt 55
 
410 rajveer 56
	public CartController(){
507 rajveer 57
		super();
58
	}
59
 
60
	 // GET /cart
1614 rajveer 61
 
62
	@Action(value="cart",interceptorRefs={@InterceptorRef("myDefault")})
650 rajveer 63
	 public String index() {
572 chandransh 64
    	try {
65
			UserContextService.Client userClient = (new UserContextServiceClient()).getClient();
1466 ankur.sing 66
			errorMsg = userClient.validateCart(userinfo.getCartId());
572 chandransh 67
		} catch (Exception e) {
68
			// This exception can be ignored for showing the cart. Not so
69
			// innocent when this occurs at the time of checkout or when the
70
			// user is proceeding to pay.
71
			e.printStackTrace();
72
		}
650 rajveer 73
    	return "index";
507 rajveer 74
	 }
572 chandransh 75
	// POST /entity
1614 rajveer 76
 
77
	@Action(value="addtocart",interceptorRefs={@InterceptorRef("createuser"),@InterceptorRef("myDefault")})
572 chandransh 78
	public String create() {
79
		log.info("CartController.create");
555 chandransh 80
 
572 chandransh 81
		printParams();
82
 
83
		long userId = userinfo.getUserId();
84
		long cartId = userinfo.getCartId();
85
 
1614 rajveer 86
		log.info("user id is " + userId);
87
		log.info("cart id is " + cartId);
88
 
572 chandransh 89
		log.info("item id is " + this.reqparams.get("productid"));
1614 rajveer 90
 
637 rajveer 91
		String itemIds = "";
572 chandransh 92
		if (this.reqparams.get("productid") != null) {
93
			itemIds = this.reqparams.get("productid")[0];
637 rajveer 94
		}else{
95
			return "failure";
572 chandransh 96
		}
637 rajveer 97
 
572 chandransh 98
		StringTokenizer tokenizer = new StringTokenizer(itemIds, "_");
99
		while (tokenizer.hasMoreTokens()) {
100
			long itemId = Long.parseLong(tokenizer.nextToken());
101
 
102
			try {
103
				UserContextServiceClient userServiceClient = new UserContextServiceClient();
104
				UserContextService.Client userClient = userServiceClient.getClient();
762 rajveer 105
				if (cartId == 0){
555 chandransh 106
					cartId = userClient.createCart(userId);
762 rajveer 107
				}
2099 rajveer 108
				if(cartMsg.equals("")){
2036 rajveer 109
				    cartMsg = userClient.addItemToCart(cartId, itemId, 1);
110
			    }else{
111
			        userClient.addItemToCart(cartId, itemId, 1);
112
			    }
762 rajveer 113
				userinfo.setCartId(cartId);
114
				int totalItems = userClient.getCart(cartId).getLinesSize();
115
				userinfo.setTotalItems(totalItems);
572 chandransh 116
			} catch (TException e) {
117
				e.printStackTrace();
118
			} catch (Exception e) {
119
				e.printStackTrace();
507 rajveer 120
			}
121
 
572 chandransh 122
		}
2263 vikas 123
        DataLogger.logData(EventType.ADD_TO_CART.name(), session.getId(), Long.toString(userinfo.getUserId()), userinfo.getEmail(),
2157 vikas 124
                Long.toString(cartId), itemIds);
572 chandransh 125
		return "success";
126
	}		
127
 
1614 rajveer 128
 
507 rajveer 129
		// DELETE /entity
130
		public String destroy() {
131
	    	log.info("CartController.destroy");
132
	    	printParams();
133
	    	log.info("item id is " + this.request.getParameter("productid"));
134
			String itemIdString = this.request.getParameter("productid");
135
			long itemId = Long.parseLong(itemIdString);
517 rajveer 136
			if(userinfo.getCartId() == -1){
137
				log.info("Cart does not exist. Nothing to delete.");
138
			}else{
1957 vikas 139
				if(deleteItemFromCart(userinfo.getCartId(), itemId, userinfo.getUserId(), userinfo.isSessionId()))
140
				{
762 rajveer 141
					userinfo.setTotalItems(getNumberOfItemsInCart(userinfo.getCartId()));
2263 vikas 142
                DataLogger.logData(EventType.DELETE_FROM_CART.name(), session.getId(),
2157 vikas 143
                        Long.toString(userinfo.getUserId()), userinfo.getEmail(),
144
                        Long.toString(userinfo.getCartId()), itemIdString);
801 rajveer 145
					return "redirect";	
517 rajveer 146
				}
507 rajveer 147
			}
801 rajveer 148
			return "redirect";
507 rajveer 149
		}
150
 
151
 
152
		// DELETE /entity
153
		public String update() {
154
	    	log.info("CartController.update");
155
	    	printParams();
156
	    	log.info("item id is " + this.request.getParameter("productid"));
157
	    	log.info("item id is " + this.request.getParameter("quantity"));
158
			String itemIdString = this.request.getParameter("productid");
159
			String quantityString = this.request.getParameter("quantity");
160
			long itemId = Long.parseLong(itemIdString);
161
			long quantity = Long.parseLong(quantityString);
517 rajveer 162
			if(quantity <= 0){
163
				log.info("Not valid item quantity. Unable to change item quantity.");
164
			}else{
762 rajveer 165
				if(updateItemQuantityInCart(userinfo.getCartId(), itemId, quantity)){
2263 vikas 166
                DataLogger.logData(EventType.UPDATE_CART_QUANTITY.name(), session.getId(),
2157 vikas 167
                        Long.toString(userinfo.getUserId()), userinfo.getEmail(),
168
                        Long.toString(userinfo.getCartId()),
169
                        Long.toString(itemId), Long.toString(quantity));
801 rajveer 170
					return "redirect";	
517 rajveer 171
				}
507 rajveer 172
			}
2263 vikas 173
			DataLogger.logData(EventType.UPDATE_CART_QUANTITY_FAILED.name(), session.getId(), Long.toString(userinfo.getUserId()), userinfo.getEmail(),
2157 vikas 174
                    Long.toString(userinfo.getCartId()), Long.toString(itemId), Long.toString(quantity));
801 rajveer 175
			addActionError("Unable to update the quantity");
176
			return "redirect";
507 rajveer 177
		}
178
 
179
 
180
    public void printParams(){
181
    	for(String param : reqparams.keySet()) {
182
    		log.info("param name is " + param);
183
    		log.info("param first is " + reqparams.get(param)[0]);
184
    	}
185
    	log.info(this.reqparams);
186
    }
187
 
762 rajveer 188
	private boolean updateItemQuantityInCart(long cartId, long itemId, long quantity){
189
		try {
190
			UserContextServiceClient userContextServiceClient = new UserContextServiceClient();
191
			in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
192
 
193
			userClient.changeQuantity(cartId, itemId, quantity);
194
			return true;
195
		} catch (ShoppingCartException e) {
196
			e.printStackTrace();
197
		} catch (TException e) {
198
			e.printStackTrace();
199
		} catch (Exception e) {
200
			e.printStackTrace();
201
		}
202
		return false;
203
	}
204
 
205
	private boolean deleteItemFromCart(long cartId, long catalogItemId, long userId, boolean isSessionId){
206
		try {
207
			UserContextServiceClient userContextServiceClient = new UserContextServiceClient();
208
			in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
209
 
210
			userClient.deleteItemFromCart(cartId, catalogItemId);
211
			return true;	
212
		} catch (ShoppingCartException e) {
213
			e.printStackTrace();
214
		} catch (TException e) {
215
			e.printStackTrace();
216
		} catch (Exception e) {
217
			e.printStackTrace();
218
		}
219
 
220
		return false;
221
	}
222
 
223
	private int getNumberOfItemsInCart(long cartId) {
224
		int numberOfItems = 0;
225
		UserContextServiceClient userContextServiceClient = null;
226
		try {
227
			userContextServiceClient = new UserContextServiceClient();
228
			in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
229
 
230
			numberOfItems = userClient.getCart(cartId).getLinesSize();
231
		} catch (ShoppingCartException e) {
232
			e.printStackTrace();
233
		} catch (TException e) {
234
			e.printStackTrace();
235
		} catch (Exception e) {
236
			e.printStackTrace();
237
		}
238
		return numberOfItems;
239
	}
1981 varun.gupt 240
 
241
	public List<Map<String,String>> getCartItems() {
242
	    List<Map<String,String>> items = null;
762 rajveer 243
 
1981 varun.gupt 244
        UserContextServiceClient userServiceClient = null;
245
        in.shop2020.model.v1.user.UserContextService.Client userClient = null;
246
        CatalogServiceClient catalogServiceClient  = null;
247
        in.shop2020.model.v1.catalog.InventoryService.Client catalogClient = null;
762 rajveer 248
 
2137 chandransh 249
        FormattingUtils formattingUtils = new FormattingUtils();
250
 
1981 varun.gupt 251
        try    {
252
            catalogServiceClient = new CatalogServiceClient();
253
            catalogClient = catalogServiceClient.getClient();
254
            userServiceClient = new UserContextServiceClient();
255
            userClient = userServiceClient.getClient();
256
 
257
            pincode = userClient.getDefaultPincode(userinfo.getUserId());
258
            Cart cart = userClient.getCart(userinfo.getCartId());
259
            List<Line> lineItems = cart.getLines();
260
 
261
            if(lineItems.size() != 0)  {
262
                items = new ArrayList<Map<String,String>>();
263
 
264
                for (Line line : lineItems)    {
265
                    Map<String, String> itemdetail = new HashMap<String, String>();
266
                    Item item = catalogClient.getItem(line.getItemId());
267
 
268
                    String itemName = ((item.getBrand() != null) ? item.getBrand() + " " : "")
269
                                            + ((item.getModelName() != null) ? item.getModelName() + " " : "") 
270
                                            + (( item.getModelNumber() != null ) ? item.getModelNumber() + " " : "" )
271
                                            + (( (item.getColor() != null && !item.getColor().trim().equals("NA"))) ? "("+item.getColor()+")" : "" );
272
 
273
                    itemdetail.put("ITEM_NAME", itemName);
274
                    itemdetail.put("ITEM_ID", line.getItemId() + "");
275
                    itemdetail.put("CATALOG_ID", item.getCatalogItemId() + "");
276
                    itemdetail.put("ITEM_QUANTITY", ((int)line.getQuantity()) + "");
2137 chandransh 277
                    itemdetail.put("MRP", formattingUtils.formatPrice(item.getMrp()));
278
                    itemdetail.put("SELLING_PRICE", formattingUtils.formatPrice(item.getSellingPrice()));
279
                    itemdetail.put("TOTAL_PRICE", formattingUtils.formatPrice(((item.getSellingPrice() * line.getQuantity()))));
1981 varun.gupt 280
                    itemdetail.put("SHIPPING_TIME", line.getEstimate() + "");
281
 
282
                    items.add(itemdetail);
283
                }
284
            }
2137 chandransh 285
 
286
            totalamount = formattingUtils.formatPrice(cart.getTotalPrice());
1981 varun.gupt 287
            couponCode = cart.getCouponCode() == null ? "" : cart.getCouponCode();
2137 chandransh 288
            discountedAmount = formattingUtils.formatPrice(cart.getDiscountedPrice());
1981 varun.gupt 289
        } catch (Exception e)  {
290
            e.printStackTrace();
291
        }
292
        return items;
507 rajveer 293
	}
1981 varun.gupt 294
 
2137 chandransh 295
	public String getTotalAmount() {
1981 varun.gupt 296
	    return totalamount;
297
	}
507 rajveer 298
 
1981 varun.gupt 299
	public String getPinCode() {
300
	    return pincode;
507 rajveer 301
	}
302
 
1981 varun.gupt 303
	public String getCouponCode()  {
304
	    return couponCode;
305
	}
306
 
307
	public String getDiscountedAmount()   {
2137 chandransh 308
	    return discountedAmount;
1981 varun.gupt 309
	}
310
 
311
	public String getErrorMsg()    {
312
	    return errorMsg;
313
	}
314
 
507 rajveer 315
	public long getNumberOfItems(){
316
		return userinfo.getTotalItems();
317
	}
650 rajveer 318
 
2036 rajveer 319
	public String getCartMsg(){
2099 rajveer 320
	    if(cartMsg.equals("")){
321
	        return null;
322
	    }
323
	    return cartMsg;
2036 rajveer 324
	}
325
 
650 rajveer 326
	@Override
327
	public void setParameters(Map<String, String[]> parameters) {
328
		this.reqparams = parameters;	
329
	}
507 rajveer 330
}