Subversion Repositories SmartDukaan

Rev

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