Subversion Repositories SmartDukaan

Rev

Rev 24425 | Rev 24442 | 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 {
24425 amit.gupta 74
		MIN_BRAND_QTY_LIMIT.put("Realme", 10);
24422 amit.gupta 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>();
24424 amit.gupta 93
		// Only Keep Non Billable Stock if partner adds both
24199 amit.gupta 94
		boolean nogst = false;
24422 amit.gupta 95
 
96
 
24199 amit.gupta 97
		for (CartItems ci : cartItems) {
24424 amit.gupta 98
			if (ci.getQuantity() > 0 && 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
		}
24426 amit.gupta 205
 
206
		cartObj.put("cartItems", arr);
207
		JSONArray cartMessagesArray = new JSONArray();
24422 amit.gupta 208
		for(Map.Entry<String, Integer> minBrandQtyLimit : MIN_BRAND_QTY_LIMIT.entrySet()) {
209
			if(brandQtyMap.containsKey(minBrandQtyLimit.getKey())) {
210
				if(brandQtyMap.get(minBrandQtyLimit.getKey()) < minBrandQtyLimit.getValue()) {
24426 amit.gupta 211
					cartMessagesArray.put(new JSONObject()
212
					.put("messageText", String.format("Minimum qty for %s brand should be %d", minBrandQtyLimit.getKey(), minBrandQtyLimit.getValue()))
213
					.put("type", "warn"));
24422 amit.gupta 214
				}
215
			}
216
		}
24426 amit.gupta 217
 
24199 amit.gupta 218
		for (String message : Arrays.asList("cartMessageOOS", "cartMessageUndeliverable", "cartMessageChanged",
219
				"cartMessagesMerged")) {
21378 kshitij.so 220
			int count = cartObj.getInt(message);
24199 amit.gupta 221
			if (count > 0) {
222
				String type = "danger";
21378 kshitij.so 223
				if (message.equals("cartMessagesMerged")) {
224
					type = "info";
24199 amit.gupta 225
					if (count == 1) {
226
						cartMessage.put("messageText", "1 item is added from earlier cart");
227
					} else {
228
						cartMessage.put("messageText", "Few items are added from earlier cart");
21378 kshitij.so 229
					}
230
				} else if (message.equals("cartMessageOOS")) {
24199 amit.gupta 231
					if (count == 1) {
232
						cartMessage.put("messageText", "One item is currently Out of Stock");
233
					} else {
234
						cartMessage.put("messageText", "Few items are currently Out of Stock");
21378 kshitij.so 235
					}
236
				} else if (message.equals("cartMessageUndeliverable")) {
24199 amit.gupta 237
					if (count == 1) {
238
						cartMessage.put("messageText", "One item is undeliverable");
239
					} else {
240
						cartMessage.put("messageText", "Few items are underiverable");
21378 kshitij.so 241
					}
24426 amit.gupta 242
				} else if(message.equals("cartMessageChanged")){
24199 amit.gupta 243
					if (count == 1) {
244
						cartMessage.put("messageText", "One item qty has changed");
245
					} else {
246
						cartMessage.put("messageText", "Few items qty have changed");
21378 kshitij.so 247
					}
248
				}
24199 amit.gupta 249
				cartMessage.put("type", type);
21378 kshitij.so 250
				cartMessagesArray.put(cartMessage);
251
			}
252
		}
253
		cartObj.put("cartMessages", cartMessagesArray);
24422 amit.gupta 254
		//Hardcode maxEstimate to -3 for managing brands quantity
24199 amit.gupta 255
		if (maxEstimate == -1) {
21378 kshitij.so 256
			cartObj.put("estimateString", "Can't ship here");
24199 amit.gupta 257
		} else if (maxEstimate == -2) {
21378 kshitij.so 258
			cartObj.put("estimateString", "Out of Stock");
259
		} else {
260
			try {
21452 amit.gupta 261
				cartObj.put("cod", cartObj.getBoolean("codAllowed"));
24199 amit.gupta 262
				cartObj.put("estimateString", LogisticsService.getDeliveryDateString(maxEstimate, DeliveryType.COD));
21378 kshitij.so 263
			} catch (NumberFormatException | JSONException | TException e) {
264
				// TODO Auto-generated catch block
265
				e.printStackTrace();
24199 amit.gupta 266
				vc = new ValidateCartResponse(null, "Error", "Problem occurred while getting delivery estimates");
23021 ashik.ali 267
				return responseSender.internalServerError(vc);
21378 kshitij.so 268
			}
24199 amit.gupta 269
 
21378 kshitij.so 270
		}
271
		cartObj.put("maxEstimate", maxEstimate);
272
		CartResponse cartResponse = new Gson().fromJson(cartObj.toString(), CartResponse.class);
24199 amit.gupta 273
		vc = new ValidateCartResponse(cartResponse, "Success", "Items added to cart successfully");
23021 ashik.ali 274
		return responseSender.ok(vc);
21378 kshitij.so 275
	}
21393 amit.gupta 276
 
24199 amit.gupta 277
	@RequestMapping(value = ProfitMandiConstants.URL_CART_CHANGE_ADDRESS, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
21393 amit.gupta 278
	@ApiImplicitParams({
24199 amit.gupta 279
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
280
 
21393 amit.gupta 281
	@ApiOperation(value = "Change address")
24199 amit.gupta 282
	public ResponseEntity<?> changeAddress(HttpServletRequest request,
283
			@RequestParam(value = "addressId") long addressId) throws Throwable {
284
		UserCart uc = userAccountRepository.getUserCart((int) request.getAttribute("userId"));
285
		UserContextService.Client userClient = new UserClient().getClient();
286
		userClient.addAddressToCart(uc.getCartId(), addressId);
287
		return responseSender.ok("Address Changed successfully");
288
	}
21378 kshitij.so 289
}