Subversion Repositories SmartDukaan

Rev

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