Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
21378 kshitij.so 1
package com.spice.profitmandi.web.controller;
2
 
3
import java.util.ArrayList;
4
import java.util.Arrays;
5
import java.util.List;
6
 
7
import javax.servlet.http.HttpServletRequest;
8
 
23959 amit.gupta 9
import org.apache.logging.log4j.LogManager;
10
import org.apache.logging.log4j.Logger;
21378 kshitij.so 11
import org.apache.thrift.TException;
12
import org.json.JSONArray;
13
import org.json.JSONException;
14
import org.json.JSONObject;
15
import org.springframework.beans.factory.annotation.Autowired;
16
import org.springframework.http.MediaType;
17
import org.springframework.http.ResponseEntity;
18
import org.springframework.stereotype.Controller;
21707 amit.gupta 19
import org.springframework.transaction.annotation.Transactional;
21378 kshitij.so 20
import org.springframework.web.bind.annotation.RequestBody;
21
import org.springframework.web.bind.annotation.RequestMapping;
22
import org.springframework.web.bind.annotation.RequestMethod;
21393 amit.gupta 23
import org.springframework.web.bind.annotation.RequestParam;
21378 kshitij.so 24
 
25
import com.google.gson.Gson;
24166 amit.gupta 26
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
21378 kshitij.so 27
import com.spice.profitmandi.common.model.ProfitMandiConstants;
21741 ashik.ali 28
import com.spice.profitmandi.common.web.util.ResponseSender;
23360 amit.gupta 29
import com.spice.profitmandi.dao.entity.catalog.Item;
23273 ashik.ali 30
import com.spice.profitmandi.dao.entity.dtr.UserAccount;
21735 ashik.ali 31
import com.spice.profitmandi.dao.enumuration.dtr.AccountType;
21378 kshitij.so 32
import com.spice.profitmandi.dao.model.ProductPojo;
21738 amit.gupta 33
import com.spice.profitmandi.dao.model.UserCart;
23360 amit.gupta 34
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
21735 ashik.ali 35
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
21643 ashik.ali 36
import com.spice.profitmandi.dao.util.ContentPojoPopulator;
37
import com.spice.profitmandi.dao.util.LogisticsService;
21378 kshitij.so 38
import com.spice.profitmandi.thrift.clients.UserClient;
39
import com.spice.profitmandi.web.req.AddCartRequest;
23965 amit.gupta 40
import com.spice.profitmandi.web.req.CartItems;
21378 kshitij.so 41
import com.spice.profitmandi.web.res.CartResponse;
42
import com.spice.profitmandi.web.res.ValidateCartResponse;
43
 
44
import in.shop2020.logistics.DeliveryType;
45
import in.shop2020.model.v1.user.ItemQuantity;
21393 amit.gupta 46
import in.shop2020.model.v1.user.UserContextService;
21378 kshitij.so 47
import in.shop2020.model.v1.user.UserContextService.Client;
48
import io.swagger.annotations.ApiImplicitParam;
49
import io.swagger.annotations.ApiImplicitParams;
50
import io.swagger.annotations.ApiOperation;
51
 
52
@Controller
24199 amit.gupta 53
@Transactional(rollbackFor = Throwable.class)
21378 kshitij.so 54
public class CartController {
55
 
24199 amit.gupta 56
	private static final Logger logger = LogManager.getLogger(CartController.class);
57
 
21440 ashik.ali 58
	@Autowired
22931 ashik.ali 59
	private ResponseSender<?> responseSender;
21378 kshitij.so 60
 
61
	@Autowired
22931 ashik.ali 62
	private UserAccountRepository userAccountRepository;
24199 amit.gupta 63
 
22173 amit.gupta 64
	@Autowired
22931 ashik.ali 65
	private ContentPojoPopulator contentPojoPopulator;
24199 amit.gupta 66
 
23360 amit.gupta 67
	@Autowired
68
	private ItemRepository itemRepository;
21378 kshitij.so 69
 
24199 amit.gupta 70
	@RequestMapping(value = ProfitMandiConstants.URL_CART, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
21378 kshitij.so 71
	@ApiImplicitParams({
24199 amit.gupta 72
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21378 kshitij.so 73
	@ApiOperation(value = "Add items to cart")
24199 amit.gupta 74
	public ResponseEntity<?> validateCart(HttpServletRequest request, @RequestBody AddCartRequest cartRequest,
75
			@RequestParam(value = "pincode", defaultValue = "110001") String pincode) throws Throwable {
23273 ashik.ali 76
		UserAccount userAccount = null;
21378 kshitij.so 77
		ValidateCartResponse vc = null;
24199 amit.gupta 78
		int userId = (int) request.getAttribute("userId");
79
 
23273 ashik.ali 80
		userAccount = userAccountRepository.selectByUserIdType(userId, AccountType.cartId);
24199 amit.gupta 81
		logger.info("UserAccount................." + userAccount);
21378 kshitij.so 82
 
83
		List<ItemQuantity> itemQuantities = new ArrayList<ItemQuantity>();
84
		CartItems[] cartItems = cartRequest.getCartItems();
85
		List<Integer> itemsList = new ArrayList<Integer>();
24199 amit.gupta 86
		// Only Keep Billable Stock if partner adds both
87
		boolean nogst = false;
88
		for (CartItems ci : cartItems) {
24166 amit.gupta 89
			if (itemRepository.selectById(ci.getItemId()).getHsnCode().equals("NOGST")) {
24199 amit.gupta 90
				nogst = true;
24153 amit.gupta 91
			}
92
		}
24199 amit.gupta 93
 
94
		JSONObject cartMessage = null;
95
		for (CartItems ci : cartItems) {
96
			if (nogst && !itemRepository.selectById(ci.getItemId()).getHsnCode().equals("NOGST")) {
97
				if (cartMessage == null) {
24198 amit.gupta 98
					cartMessage = new JSONObject();
99
					cartMessage.put("messageText", "Billable items can't be billed along with non Billable items");
100
				}
101
				continue;
24199 amit.gupta 102
 
24153 amit.gupta 103
			}
21378 kshitij.so 104
			itemsList.add(ci.getItemId());
105
			ItemQuantity iq = new ItemQuantity(ci.getItemId(), ci.getQuantity());
106
			itemQuantities.add(iq);
107
		}
24199 amit.gupta 108
		if (cartMessage == null)
109
 
110
		{
24198 amit.gupta 111
			cartMessage = new JSONObject();
112
		}
113
 
21378 kshitij.so 114
		Client userClient = null;
115
		try {
116
			userClient = new UserClient().getClient();
23273 ashik.ali 117
			userClient.addItemsToCart(Integer.valueOf(userAccount.getAccountKey()), itemQuantities, null);
21383 kshitij.so 118
		} catch (Exception e) {
24199 amit.gupta 119
			vc = new ValidateCartResponse(null, "Error", "Problem occurred while updating cart");
23021 ashik.ali 120
			return responseSender.internalServerError(vc);
21378 kshitij.so 121
		}
24199 amit.gupta 122
		String cartString = null;
123
		// Use source id temporarily for purpose of tag id as it is just one lets
124
		// hardcode the tag id
22568 amit.gupta 125
		int source = -1;
23273 ashik.ali 126
		cartString = userClient.validateCartNew(Integer.valueOf(userAccount.getAccountKey()), pincode, source);
21378 kshitij.so 127
		JSONObject cartObj = new JSONObject(cartString);
128
		JSONArray arr = cartObj.getJSONArray("cartItems");
24199 amit.gupta 129
		int maxEstimate = -2;
130
		boolean allSame = true;
21378 kshitij.so 131
		int removedCount = 0;
132
		cartObj.put("cartMessagesMerged", 0);
24199 amit.gupta 133
		for (int j = 0; j < arr.length(); j++) {
134
			JSONObject itemObj = arr.getJSONObject(j - removedCount);
135
			if (!itemsList.contains(itemObj.getInt("itemId"))) {
136
				if (itemObj.getInt("quantity") == 0) {
137
					arr.remove(j - removedCount);
21378 kshitij.so 138
					removedCount++;
24199 amit.gupta 139
					if (itemObj.has("estimate") && itemObj.getInt("estimate") == -1) {
21378 kshitij.so 140
						cartObj.put("cartMessageUndeliverable", cartObj.getInt("cartMessageUndeliverable") - 1);
141
					} else {
142
						cartObj.put("cartMessageOOS", cartObj.getInt("cartMessageOOS") - 1);
143
					}
144
					continue;
145
				} else {
146
					JSONArray messagesArray = new JSONArray();
147
					itemObj.put("cartItemMessages", messagesArray);
24199 amit.gupta 148
					if (itemsList.size() > 0) {
149
						JSONObject message = new JSONObject();
150
						message.put("type", "info");
151
						message.put("messageText", "Added from earlier cart");
21378 kshitij.so 152
						messagesArray.put(message);
153
						cartObj.put("cartMessagesMerged", cartObj.getInt("cartMessagesMerged") + 1);
154
					}
155
				}
156
			}
23360 amit.gupta 157
			try {
24199 amit.gupta 158
				ProductPojo pp = contentPojoPopulator.getShortContent(itemObj.getLong("catalogItemId"));
21389 kshitij.so 159
//			String productProperties = ContentServingService.getSnippet(Utils.PRODUCT_PROPERTIES_SNIPPET, pp.getId() +"", -1);
160
//			JSONObject productPropertiesInJson = new JSONObject(productProperties);
161
//			pp.setCategoryName(productPropertiesInJson.getString("categoryName"));
21378 kshitij.so 162
 
24199 amit.gupta 163
				if (itemObj.has("estimate")) {
164
					if (allSame) {
165
						allSame = maxEstimate == -2 || maxEstimate == itemObj.getInt("estimate");
166
					}
167
					if (itemObj.getInt("estimate") > maxEstimate) {
168
						maxEstimate = itemObj.getInt("estimate");
169
					}
21378 kshitij.so 170
				}
23360 amit.gupta 171
				itemObj.put("imageUrl", pp.getImageUrl());
172
				itemObj.put("title", pp.getTitle());
173
			} catch (Throwable t) {
174
				Item item = itemRepository.selectById(itemObj.getInt("itemId"));
175
				itemObj.put("imageUrl", "");
176
				itemObj.put("title", item.getBrand() + " " + item.getModelName() + "" + item.getModelNumber());
177
			}
21378 kshitij.so 178
		}
179
 
24199 amit.gupta 180
		ArrayList<JSONObject> listdata = new ArrayList<JSONObject>();
181
		if (arr != null) {
182
			for (int i = 0; i < arr.length(); i++) {
21378 kshitij.so 183
				JSONArray itemMessages = arr.getJSONObject(i).optJSONArray(("cartItemMessages"));
24199 amit.gupta 184
				if (itemMessages != null && itemMessages.length() > 0) {
185
					listdata.add(0, arr.getJSONObject(i));
21378 kshitij.so 186
				} else {
187
					listdata.add(arr.getJSONObject(i));
188
				}
24199 amit.gupta 189
			}
21378 kshitij.so 190
		}
191
		arr = new JSONArray();
24199 amit.gupta 192
		for (int i = 0; i < listdata.size(); i++) {
21378 kshitij.so 193
			arr.put(listdata.get(i));
194
		}
195
		cartObj.put("cartItems", arr);
196
		JSONArray cartMessagesArray = new JSONArray();
24199 amit.gupta 197
		for (String message : Arrays.asList("cartMessageOOS", "cartMessageUndeliverable", "cartMessageChanged",
198
				"cartMessagesMerged")) {
21378 kshitij.so 199
			int count = cartObj.getInt(message);
24199 amit.gupta 200
			if (count > 0) {
201
				String type = "danger";
21378 kshitij.so 202
				if (message.equals("cartMessagesMerged")) {
203
					type = "info";
24199 amit.gupta 204
					if (count == 1) {
205
						cartMessage.put("messageText", "1 item is added from earlier cart");
206
					} else {
207
						cartMessage.put("messageText", "Few items are added from earlier cart");
21378 kshitij.so 208
					}
209
				} else if (message.equals("cartMessageOOS")) {
24199 amit.gupta 210
					if (count == 1) {
211
						cartMessage.put("messageText", "One item is currently Out of Stock");
212
					} else {
213
						cartMessage.put("messageText", "Few items are currently Out of Stock");
21378 kshitij.so 214
					}
215
				} else if (message.equals("cartMessageUndeliverable")) {
24199 amit.gupta 216
					if (count == 1) {
217
						cartMessage.put("messageText", "One item is undeliverable");
218
					} else {
219
						cartMessage.put("messageText", "Few items are underiverable");
21378 kshitij.so 220
					}
221
				} else {
24199 amit.gupta 222
					if (count == 1) {
223
						cartMessage.put("messageText", "One item qty has changed");
224
					} else {
225
						cartMessage.put("messageText", "Few items qty have changed");
21378 kshitij.so 226
					}
227
				}
24199 amit.gupta 228
				cartMessage.put("type", type);
21378 kshitij.so 229
				cartMessagesArray.put(cartMessage);
230
			}
231
		}
232
		cartObj.put("cartMessages", cartMessagesArray);
233
 
24199 amit.gupta 234
		if (maxEstimate == -1) {
21378 kshitij.so 235
			cartObj.put("estimateString", "Can't ship here");
24199 amit.gupta 236
		} else if (maxEstimate == -2) {
21378 kshitij.so 237
			cartObj.put("estimateString", "Out of Stock");
238
		} else {
239
			try {
21452 amit.gupta 240
				cartObj.put("cod", cartObj.getBoolean("codAllowed"));
24199 amit.gupta 241
				cartObj.put("estimateString", LogisticsService.getDeliveryDateString(maxEstimate, DeliveryType.COD));
21378 kshitij.so 242
			} catch (NumberFormatException | JSONException | TException e) {
243
				// TODO Auto-generated catch block
244
				e.printStackTrace();
24199 amit.gupta 245
				vc = new ValidateCartResponse(null, "Error", "Problem occurred while getting delivery estimates");
23021 ashik.ali 246
				return responseSender.internalServerError(vc);
21378 kshitij.so 247
			}
24199 amit.gupta 248
 
21378 kshitij.so 249
		}
250
		cartObj.put("maxEstimate", maxEstimate);
251
		CartResponse cartResponse = new Gson().fromJson(cartObj.toString(), CartResponse.class);
24199 amit.gupta 252
		vc = new ValidateCartResponse(cartResponse, "Success", "Items added to cart successfully");
23021 ashik.ali 253
		return responseSender.ok(vc);
21378 kshitij.so 254
	}
21393 amit.gupta 255
 
24199 amit.gupta 256
	@RequestMapping(value = ProfitMandiConstants.URL_CART_CHANGE_ADDRESS, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
21393 amit.gupta 257
	@ApiImplicitParams({
24199 amit.gupta 258
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
259
 
21393 amit.gupta 260
	@ApiOperation(value = "Change address")
24199 amit.gupta 261
	public ResponseEntity<?> changeAddress(HttpServletRequest request,
262
			@RequestParam(value = "addressId") long addressId) throws Throwable {
263
		UserCart uc = userAccountRepository.getUserCart((int) request.getAttribute("userId"));
264
		UserContextService.Client userClient = new UserClient().getClient();
265
		userClient.addAddressToCart(uc.getCartId(), addressId);
266
		return responseSender.ok("Address Changed successfully");
267
	}
21378 kshitij.so 268
}