Subversion Repositories SmartDukaan

Rev

Rev 24199 | Rev 24203 | 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
		{
24198 amit.gupta 110
			cartMessage = new JSONObject();
111
		}
112
 
21378 kshitij.so 113
		Client userClient = null;
114
		try {
115
			userClient = new UserClient().getClient();
23273 ashik.ali 116
			userClient.addItemsToCart(Integer.valueOf(userAccount.getAccountKey()), itemQuantities, null);
21383 kshitij.so 117
		} catch (Exception e) {
24199 amit.gupta 118
			vc = new ValidateCartResponse(null, "Error", "Problem occurred while updating cart");
23021 ashik.ali 119
			return responseSender.internalServerError(vc);
21378 kshitij.so 120
		}
24199 amit.gupta 121
		String cartString = null;
122
		// Use source id temporarily for purpose of tag id as it is just one lets
123
		// hardcode the tag id
22568 amit.gupta 124
		int source = -1;
23273 ashik.ali 125
		cartString = userClient.validateCartNew(Integer.valueOf(userAccount.getAccountKey()), pincode, source);
21378 kshitij.so 126
		JSONObject cartObj = new JSONObject(cartString);
127
		JSONArray arr = cartObj.getJSONArray("cartItems");
24199 amit.gupta 128
		int maxEstimate = -2;
129
		boolean allSame = true;
21378 kshitij.so 130
		int removedCount = 0;
131
		cartObj.put("cartMessagesMerged", 0);
24199 amit.gupta 132
		for (int j = 0; j < arr.length(); j++) {
133
			JSONObject itemObj = arr.getJSONObject(j - removedCount);
134
			if (!itemsList.contains(itemObj.getInt("itemId"))) {
135
				if (itemObj.getInt("quantity") == 0) {
136
					arr.remove(j - removedCount);
21378 kshitij.so 137
					removedCount++;
24199 amit.gupta 138
					if (itemObj.has("estimate") && itemObj.getInt("estimate") == -1) {
21378 kshitij.so 139
						cartObj.put("cartMessageUndeliverable", cartObj.getInt("cartMessageUndeliverable") - 1);
140
					} else {
141
						cartObj.put("cartMessageOOS", cartObj.getInt("cartMessageOOS") - 1);
142
					}
143
					continue;
144
				} else {
145
					JSONArray messagesArray = new JSONArray();
146
					itemObj.put("cartItemMessages", messagesArray);
24199 amit.gupta 147
					if (itemsList.size() > 0) {
148
						JSONObject message = new JSONObject();
149
						message.put("type", "info");
150
						message.put("messageText", "Added from earlier cart");
21378 kshitij.so 151
						messagesArray.put(message);
152
						cartObj.put("cartMessagesMerged", cartObj.getInt("cartMessagesMerged") + 1);
153
					}
154
				}
155
			}
23360 amit.gupta 156
			try {
24199 amit.gupta 157
				ProductPojo pp = contentPojoPopulator.getShortContent(itemObj.getLong("catalogItemId"));
21389 kshitij.so 158
//			String productProperties = ContentServingService.getSnippet(Utils.PRODUCT_PROPERTIES_SNIPPET, pp.getId() +"", -1);
159
//			JSONObject productPropertiesInJson = new JSONObject(productProperties);
160
//			pp.setCategoryName(productPropertiesInJson.getString("categoryName"));
21378 kshitij.so 161
 
24199 amit.gupta 162
				if (itemObj.has("estimate")) {
163
					if (allSame) {
164
						allSame = maxEstimate == -2 || maxEstimate == itemObj.getInt("estimate");
165
					}
166
					if (itemObj.getInt("estimate") > maxEstimate) {
167
						maxEstimate = itemObj.getInt("estimate");
168
					}
21378 kshitij.so 169
				}
23360 amit.gupta 170
				itemObj.put("imageUrl", pp.getImageUrl());
171
				itemObj.put("title", pp.getTitle());
172
			} catch (Throwable t) {
173
				Item item = itemRepository.selectById(itemObj.getInt("itemId"));
174
				itemObj.put("imageUrl", "");
175
				itemObj.put("title", item.getBrand() + " " + item.getModelName() + "" + item.getModelNumber());
176
			}
21378 kshitij.so 177
		}
178
 
24199 amit.gupta 179
		ArrayList<JSONObject> listdata = new ArrayList<JSONObject>();
180
		if (arr != null) {
181
			for (int i = 0; i < arr.length(); i++) {
21378 kshitij.so 182
				JSONArray itemMessages = arr.getJSONObject(i).optJSONArray(("cartItemMessages"));
24199 amit.gupta 183
				if (itemMessages != null && itemMessages.length() > 0) {
184
					listdata.add(0, arr.getJSONObject(i));
21378 kshitij.so 185
				} else {
186
					listdata.add(arr.getJSONObject(i));
187
				}
24199 amit.gupta 188
			}
21378 kshitij.so 189
		}
190
		arr = new JSONArray();
24199 amit.gupta 191
		for (int i = 0; i < listdata.size(); i++) {
21378 kshitij.so 192
			arr.put(listdata.get(i));
193
		}
194
		cartObj.put("cartItems", arr);
195
		JSONArray cartMessagesArray = new JSONArray();
24199 amit.gupta 196
		for (String message : Arrays.asList("cartMessageOOS", "cartMessageUndeliverable", "cartMessageChanged",
197
				"cartMessagesMerged")) {
21378 kshitij.so 198
			int count = cartObj.getInt(message);
24199 amit.gupta 199
			if (count > 0) {
200
				String type = "danger";
21378 kshitij.so 201
				if (message.equals("cartMessagesMerged")) {
202
					type = "info";
24199 amit.gupta 203
					if (count == 1) {
204
						cartMessage.put("messageText", "1 item is added from earlier cart");
205
					} else {
206
						cartMessage.put("messageText", "Few items are added from earlier cart");
21378 kshitij.so 207
					}
208
				} else if (message.equals("cartMessageOOS")) {
24199 amit.gupta 209
					if (count == 1) {
210
						cartMessage.put("messageText", "One item is currently Out of Stock");
211
					} else {
212
						cartMessage.put("messageText", "Few items are currently Out of Stock");
21378 kshitij.so 213
					}
214
				} else if (message.equals("cartMessageUndeliverable")) {
24199 amit.gupta 215
					if (count == 1) {
216
						cartMessage.put("messageText", "One item is undeliverable");
217
					} else {
218
						cartMessage.put("messageText", "Few items are underiverable");
21378 kshitij.so 219
					}
220
				} else {
24199 amit.gupta 221
					if (count == 1) {
222
						cartMessage.put("messageText", "One item qty has changed");
223
					} else {
224
						cartMessage.put("messageText", "Few items qty have changed");
21378 kshitij.so 225
					}
226
				}
24199 amit.gupta 227
				cartMessage.put("type", type);
21378 kshitij.so 228
				cartMessagesArray.put(cartMessage);
229
			}
230
		}
231
		cartObj.put("cartMessages", cartMessagesArray);
232
 
24199 amit.gupta 233
		if (maxEstimate == -1) {
21378 kshitij.so 234
			cartObj.put("estimateString", "Can't ship here");
24199 amit.gupta 235
		} else if (maxEstimate == -2) {
21378 kshitij.so 236
			cartObj.put("estimateString", "Out of Stock");
237
		} else {
238
			try {
21452 amit.gupta 239
				cartObj.put("cod", cartObj.getBoolean("codAllowed"));
24199 amit.gupta 240
				cartObj.put("estimateString", LogisticsService.getDeliveryDateString(maxEstimate, DeliveryType.COD));
21378 kshitij.so 241
			} catch (NumberFormatException | JSONException | TException e) {
242
				// TODO Auto-generated catch block
243
				e.printStackTrace();
24199 amit.gupta 244
				vc = new ValidateCartResponse(null, "Error", "Problem occurred while getting delivery estimates");
23021 ashik.ali 245
				return responseSender.internalServerError(vc);
21378 kshitij.so 246
			}
24199 amit.gupta 247
 
21378 kshitij.so 248
		}
249
		cartObj.put("maxEstimate", maxEstimate);
250
		CartResponse cartResponse = new Gson().fromJson(cartObj.toString(), CartResponse.class);
24199 amit.gupta 251
		vc = new ValidateCartResponse(cartResponse, "Success", "Items added to cart successfully");
23021 ashik.ali 252
		return responseSender.ok(vc);
21378 kshitij.so 253
	}
21393 amit.gupta 254
 
24199 amit.gupta 255
	@RequestMapping(value = ProfitMandiConstants.URL_CART_CHANGE_ADDRESS, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
21393 amit.gupta 256
	@ApiImplicitParams({
24199 amit.gupta 257
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
258
 
21393 amit.gupta 259
	@ApiOperation(value = "Change address")
24199 amit.gupta 260
	public ResponseEntity<?> changeAddress(HttpServletRequest request,
261
			@RequestParam(value = "addressId") long addressId) throws Throwable {
262
		UserCart uc = userAccountRepository.getUserCart((int) request.getAttribute("userId"));
263
		UserContextService.Client userClient = new UserClient().getClient();
264
		userClient.addAddressToCart(uc.getCartId(), addressId);
265
		return responseSender.ok("Address Changed successfully");
266
	}
21378 kshitij.so 267
}