Subversion Repositories SmartDukaan

Rev

Rev 1957 | Rev 2036 | 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 = "";
410 rajveer 50
 
1981 varun.gupt 51
	private String pincode = "110001";
52
 
53
	private String couponCode = null;
54
 
55
	private double discountedAmount;
56
 
410 rajveer 57
	public CartController(){
507 rajveer 58
		super();
59
	}
60
 
61
	 // GET /cart
1614 rajveer 62
 
63
	@Action(value="cart",interceptorRefs={@InterceptorRef("myDefault")})
650 rajveer 64
	 public String index() {
572 chandransh 65
    	try {
66
			UserContextService.Client userClient = (new UserContextServiceClient()).getClient();
1466 ankur.sing 67
			errorMsg = userClient.validateCart(userinfo.getCartId());
572 chandransh 68
		} catch (Exception e) {
69
			// This exception can be ignored for showing the cart. Not so
70
			// innocent when this occurs at the time of checkout or when the
71
			// user is proceeding to pay.
72
			e.printStackTrace();
73
		}
650 rajveer 74
    	return "index";
507 rajveer 75
	 }
572 chandransh 76
	// POST /entity
1614 rajveer 77
 
78
	@Action(value="addtocart",interceptorRefs={@InterceptorRef("createuser"),@InterceptorRef("myDefault")})
572 chandransh 79
	public String create() {
80
		log.info("CartController.create");
555 chandransh 81
 
572 chandransh 82
		printParams();
83
 
84
		long userId = userinfo.getUserId();
85
		long cartId = userinfo.getCartId();
86
 
1614 rajveer 87
		log.info("user id is " + userId);
88
		log.info("cart id is " + cartId);
89
 
572 chandransh 90
		log.info("item id is " + this.reqparams.get("productid"));
1614 rajveer 91
 
637 rajveer 92
		String itemIds = "";
572 chandransh 93
		if (this.reqparams.get("productid") != null) {
94
			itemIds = this.reqparams.get("productid")[0];
637 rajveer 95
		}else{
96
			return "failure";
572 chandransh 97
		}
637 rajveer 98
 
572 chandransh 99
		StringTokenizer tokenizer = new StringTokenizer(itemIds, "_");
100
		while (tokenizer.hasMoreTokens()) {
101
			long itemId = Long.parseLong(tokenizer.nextToken());
102
 
103
			try {
104
				UserContextServiceClient userServiceClient = new UserContextServiceClient();
105
				UserContextService.Client userClient = userServiceClient.getClient();
762 rajveer 106
				if (cartId == 0){
555 chandransh 107
					cartId = userClient.createCart(userId);
762 rajveer 108
				}
572 chandransh 109
				userClient.addItemToCart(cartId, itemId, 1);
762 rajveer 110
				userinfo.setCartId(cartId);
111
				int totalItems = userClient.getCart(cartId).getLinesSize();
112
				userinfo.setTotalItems(totalItems);
572 chandransh 113
			} catch (TException e) {
114
				e.printStackTrace();
115
			} catch (Exception e) {
116
				e.printStackTrace();
507 rajveer 117
			}
118
 
572 chandransh 119
		}
1957 vikas 120
		dataLog.info(StringUtils.join(new String[] { Event.ADD_TO_CART.name(),
121
                userinfo.getEmail(), Long.toString(cartId), itemIds }, ", "));
572 chandransh 122
		return "success";
123
	}		
124
 
1614 rajveer 125
 
507 rajveer 126
		// DELETE /entity
127
		public String destroy() {
128
	    	log.info("CartController.destroy");
129
	    	printParams();
130
	    	log.info("item id is " + this.request.getParameter("productid"));
131
			String itemIdString = this.request.getParameter("productid");
132
			long itemId = Long.parseLong(itemIdString);
517 rajveer 133
			if(userinfo.getCartId() == -1){
134
				log.info("Cart does not exist. Nothing to delete.");
135
			}else{
1957 vikas 136
				if(deleteItemFromCart(userinfo.getCartId(), itemId, userinfo.getUserId(), userinfo.isSessionId()))
137
				{
762 rajveer 138
					userinfo.setTotalItems(getNumberOfItemsInCart(userinfo.getCartId()));
1957 vikas 139
                    dataLog.info(StringUtils.join(new String[] {
140
                            Event.DELETE_FROM_CART.name(), userinfo.getEmail(),
141
                            Long.toString(userinfo.getCartId()), itemIdString },
142
                            ", "));
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)){
1957 vikas 164
				    dataLog.info(StringUtils.join(new String[] {
165
                            Event.UPDATE_CART_QUANTITY.name(), userinfo.getEmail(),
166
                            Long.toString(userinfo.getCartId()), Long.toString(itemId), Long.toString(quantity) },
167
                            ", "));
801 rajveer 168
					return "redirect";	
517 rajveer 169
				}
507 rajveer 170
			}
1957 vikas 171
			dataLog.info(StringUtils.join(new String[] {
172
                    Event.UPDATE_CART_QUANTITY_FAILED.name(), userinfo.getEmail(),
173
                    Long.toString(userinfo.getCartId()), Long.toString(itemId), Long.toString(quantity) },
174
                    ", "));
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
 
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()) + "");
275
                    itemdetail.put("MRP", ((int)item.getMrp()) + "");
276
                    itemdetail.put("SELLING_PRICE", ((int)item.getSellingPrice()) + "");
277
                    itemdetail.put("TOTAL_PRICE", ((int)((item.getSellingPrice() * line.getQuantity()))) + "");
278
                    itemdetail.put("SHIPPING_TIME", line.getEstimate() + "");
279
 
280
                    totalamount = totalamount + line.getQuantity() * item.getSellingPrice();
281
                    items.add(itemdetail);
282
                }
283
            }
284
            couponCode = cart.getCouponCode() == null ? "" : cart.getCouponCode();
285
            discountedAmount = cart.getDiscountedPrice();
286
        } catch (Exception e)  {
287
            e.printStackTrace();
288
        }
289
        return items;
507 rajveer 290
	}
1981 varun.gupt 291
 
292
	public double getTotalAmount() {
293
	    return totalamount;
294
	}
507 rajveer 295
 
1981 varun.gupt 296
	public String getPinCode() {
297
	    return pincode;
507 rajveer 298
	}
299
 
1981 varun.gupt 300
	public String getCouponCode()  {
301
	    return couponCode;
302
	}
303
 
304
	public String getDiscountedAmount()   {
305
	    return discountedAmount + "";
306
	}
307
 
308
	public String getErrorMsg()    {
309
	    return errorMsg;
310
	}
311
 
507 rajveer 312
	public long getNumberOfItems(){
313
		return userinfo.getTotalItems();
314
	}
650 rajveer 315
 
316
	@Override
317
	public void setParameters(Map<String, String[]> parameters) {
318
		this.reqparams = parameters;	
319
	}
507 rajveer 320
}