Subversion Repositories SmartDukaan

Rev

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