Subversion Repositories SmartDukaan

Rev

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