Subversion Repositories SmartDukaan

Rev

Rev 24464 | Rev 25962 | 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 {
24502 amit.gupta 74
		//MIN_BRAND_QTY_LIMIT.put("Realme", 10);
24464 amit.gupta 75
		MIN_BRAND_QTY_LIMIT.put("Reliance", 5);
24422 amit.gupta 76
	}
77
 
24199 amit.gupta 78
	@RequestMapping(value = ProfitMandiConstants.URL_CART, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
21378 kshitij.so 79
	@ApiImplicitParams({
24199 amit.gupta 80
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21378 kshitij.so 81
	@ApiOperation(value = "Add items to cart")
24199 amit.gupta 82
	public ResponseEntity<?> validateCart(HttpServletRequest request, @RequestBody AddCartRequest cartRequest,
83
			@RequestParam(value = "pincode", defaultValue = "110001") String pincode) throws Throwable {
23273 ashik.ali 84
		UserAccount userAccount = null;
21378 kshitij.so 85
		ValidateCartResponse vc = null;
24199 amit.gupta 86
		int userId = (int) request.getAttribute("userId");
87
 
23273 ashik.ali 88
		userAccount = userAccountRepository.selectByUserIdType(userId, AccountType.cartId);
24199 amit.gupta 89
		logger.info("UserAccount................." + userAccount);
24422 amit.gupta 90
		Map<String, Integer> brandQtyMap = new HashMap<>();
21378 kshitij.so 91
		List<ItemQuantity> itemQuantities = new ArrayList<ItemQuantity>();
92
		CartItems[] cartItems = cartRequest.getCartItems();
93
		List<Integer> itemsList = new ArrayList<Integer>();
24424 amit.gupta 94
		// Only Keep Non Billable Stock if partner adds both
24199 amit.gupta 95
		boolean nogst = false;
24422 amit.gupta 96
 
97
 
24199 amit.gupta 98
		for (CartItems ci : cartItems) {
24424 amit.gupta 99
			if (ci.getQuantity() > 0 && itemRepository.selectById(ci.getItemId()).getHsnCode().equals("NOGST")) {
24199 amit.gupta 100
				nogst = true;
24153 amit.gupta 101
			}
102
		}
24199 amit.gupta 103
 
104
		JSONObject cartMessage = null;
105
		for (CartItems ci : cartItems) {
106
			if (nogst && !itemRepository.selectById(ci.getItemId()).getHsnCode().equals("NOGST")) {
107
				if (cartMessage == null) {
24198 amit.gupta 108
					cartMessage = new JSONObject();
109
					cartMessage.put("messageText", "Billable items can't be billed along with non Billable items");
110
				}
111
				continue;
24199 amit.gupta 112
 
24153 amit.gupta 113
			}
21378 kshitij.so 114
			itemsList.add(ci.getItemId());
115
			ItemQuantity iq = new ItemQuantity(ci.getItemId(), ci.getQuantity());
116
			itemQuantities.add(iq);
117
		}
24199 amit.gupta 118
		if (cartMessage == null)
119
		{
24198 amit.gupta 120
			cartMessage = new JSONObject();
121
		}
122
 
21378 kshitij.so 123
		Client userClient = null;
124
		try {
125
			userClient = new UserClient().getClient();
23273 ashik.ali 126
			userClient.addItemsToCart(Integer.valueOf(userAccount.getAccountKey()), itemQuantities, null);
21383 kshitij.so 127
		} catch (Exception e) {
24199 amit.gupta 128
			vc = new ValidateCartResponse(null, "Error", "Problem occurred while updating cart");
23021 ashik.ali 129
			return responseSender.internalServerError(vc);
21378 kshitij.so 130
		}
24199 amit.gupta 131
		String cartString = null;
132
		// Use source id temporarily for purpose of tag id as it is just one lets
133
		// hardcode the tag id
22568 amit.gupta 134
		int source = -1;
23273 ashik.ali 135
		cartString = userClient.validateCartNew(Integer.valueOf(userAccount.getAccountKey()), pincode, source);
21378 kshitij.so 136
		JSONObject cartObj = new JSONObject(cartString);
137
		JSONArray arr = cartObj.getJSONArray("cartItems");
24199 amit.gupta 138
		int maxEstimate = -2;
139
		boolean allSame = true;
21378 kshitij.so 140
		int removedCount = 0;
141
		cartObj.put("cartMessagesMerged", 0);
24422 amit.gupta 142
 
24199 amit.gupta 143
		for (int j = 0; j < arr.length(); j++) {
144
			JSONObject itemObj = arr.getJSONObject(j - removedCount);
145
			if (!itemsList.contains(itemObj.getInt("itemId"))) {
146
				if (itemObj.getInt("quantity") == 0) {
147
					arr.remove(j - removedCount);
21378 kshitij.so 148
					removedCount++;
24199 amit.gupta 149
					if (itemObj.has("estimate") && itemObj.getInt("estimate") == -1) {
21378 kshitij.so 150
						cartObj.put("cartMessageUndeliverable", cartObj.getInt("cartMessageUndeliverable") - 1);
151
					} else {
152
						cartObj.put("cartMessageOOS", cartObj.getInt("cartMessageOOS") - 1);
153
					}
154
					continue;
155
				} else {
156
					JSONArray messagesArray = new JSONArray();
157
					itemObj.put("cartItemMessages", messagesArray);
24199 amit.gupta 158
					if (itemsList.size() > 0) {
159
						JSONObject message = new JSONObject();
160
						message.put("type", "info");
161
						message.put("messageText", "Added from earlier cart");
21378 kshitij.so 162
						messagesArray.put(message);
163
						cartObj.put("cartMessagesMerged", cartObj.getInt("cartMessagesMerged") + 1);
164
					}
165
				}
166
			}
24422 amit.gupta 167
			Item item = itemRepository.selectById(itemObj.getInt("itemId"));
168
			if(!brandQtyMap.containsKey(item.getBrand())) {
169
				brandQtyMap.put(item.getBrand(), 0);
170
			}
171
			brandQtyMap.put(item.getBrand(), brandQtyMap.get(item.getBrand()) + itemObj.getInt("quantity"));
23360 amit.gupta 172
			try {
24199 amit.gupta 173
				ProductPojo pp = contentPojoPopulator.getShortContent(itemObj.getLong("catalogItemId"));
21378 kshitij.so 174
 
24199 amit.gupta 175
				if (itemObj.has("estimate")) {
176
					if (allSame) {
177
						allSame = maxEstimate == -2 || maxEstimate == itemObj.getInt("estimate");
178
					}
179
					if (itemObj.getInt("estimate") > maxEstimate) {
180
						maxEstimate = itemObj.getInt("estimate");
181
					}
21378 kshitij.so 182
				}
23360 amit.gupta 183
				itemObj.put("imageUrl", pp.getImageUrl());
184
				itemObj.put("title", pp.getTitle());
185
			} catch (Throwable t) {
186
				itemObj.put("imageUrl", "");
187
				itemObj.put("title", item.getBrand() + " " + item.getModelName() + "" + item.getModelNumber());
188
			}
21378 kshitij.so 189
		}
190
 
24199 amit.gupta 191
		ArrayList<JSONObject> listdata = new ArrayList<JSONObject>();
192
		if (arr != null) {
193
			for (int i = 0; i < arr.length(); i++) {
21378 kshitij.so 194
				JSONArray itemMessages = arr.getJSONObject(i).optJSONArray(("cartItemMessages"));
24199 amit.gupta 195
				if (itemMessages != null && itemMessages.length() > 0) {
196
					listdata.add(0, arr.getJSONObject(i));
21378 kshitij.so 197
				} else {
198
					listdata.add(arr.getJSONObject(i));
199
				}
24199 amit.gupta 200
			}
21378 kshitij.so 201
		}
202
		arr = new JSONArray();
24199 amit.gupta 203
		for (int i = 0; i < listdata.size(); i++) {
21378 kshitij.so 204
			arr.put(listdata.get(i));
205
		}
24426 amit.gupta 206
 
207
		cartObj.put("cartItems", arr);
208
		JSONArray cartMessagesArray = new JSONArray();
24422 amit.gupta 209
		for(Map.Entry<String, Integer> minBrandQtyLimit : MIN_BRAND_QTY_LIMIT.entrySet()) {
210
			if(brandQtyMap.containsKey(minBrandQtyLimit.getKey())) {
211
				if(brandQtyMap.get(minBrandQtyLimit.getKey()) < minBrandQtyLimit.getValue()) {
24426 amit.gupta 212
					cartMessagesArray.put(new JSONObject()
213
					.put("messageText", String.format("Minimum qty for %s brand should be %d", minBrandQtyLimit.getKey(), minBrandQtyLimit.getValue()))
214
					.put("type", "warn"));
24422 amit.gupta 215
				}
216
			}
217
		}
24426 amit.gupta 218
 
24199 amit.gupta 219
		for (String message : Arrays.asList("cartMessageOOS", "cartMessageUndeliverable", "cartMessageChanged",
220
				"cartMessagesMerged")) {
21378 kshitij.so 221
			int count = cartObj.getInt(message);
24199 amit.gupta 222
			if (count > 0) {
223
				String type = "danger";
21378 kshitij.so 224
				if (message.equals("cartMessagesMerged")) {
225
					type = "info";
24199 amit.gupta 226
					if (count == 1) {
227
						cartMessage.put("messageText", "1 item is added from earlier cart");
228
					} else {
229
						cartMessage.put("messageText", "Few items are added from earlier cart");
21378 kshitij.so 230
					}
231
				} else if (message.equals("cartMessageOOS")) {
24199 amit.gupta 232
					if (count == 1) {
233
						cartMessage.put("messageText", "One item is currently Out of Stock");
234
					} else {
235
						cartMessage.put("messageText", "Few items are currently Out of Stock");
21378 kshitij.so 236
					}
237
				} else if (message.equals("cartMessageUndeliverable")) {
24199 amit.gupta 238
					if (count == 1) {
239
						cartMessage.put("messageText", "One item is undeliverable");
240
					} else {
241
						cartMessage.put("messageText", "Few items are underiverable");
21378 kshitij.so 242
					}
24426 amit.gupta 243
				} else if(message.equals("cartMessageChanged")){
24199 amit.gupta 244
					if (count == 1) {
245
						cartMessage.put("messageText", "One item qty has changed");
246
					} else {
247
						cartMessage.put("messageText", "Few items qty have changed");
21378 kshitij.so 248
					}
249
				}
24199 amit.gupta 250
				cartMessage.put("type", type);
21378 kshitij.so 251
				cartMessagesArray.put(cartMessage);
252
			}
253
		}
254
		cartObj.put("cartMessages", cartMessagesArray);
24422 amit.gupta 255
		//Hardcode maxEstimate to -3 for managing brands quantity
24199 amit.gupta 256
		if (maxEstimate == -1) {
21378 kshitij.so 257
			cartObj.put("estimateString", "Can't ship here");
24199 amit.gupta 258
		} else if (maxEstimate == -2) {
21378 kshitij.so 259
			cartObj.put("estimateString", "Out of Stock");
260
		} else {
261
			try {
21452 amit.gupta 262
				cartObj.put("cod", cartObj.getBoolean("codAllowed"));
24199 amit.gupta 263
				cartObj.put("estimateString", LogisticsService.getDeliveryDateString(maxEstimate, DeliveryType.COD));
21378 kshitij.so 264
			} catch (NumberFormatException | JSONException | TException e) {
265
				// TODO Auto-generated catch block
266
				e.printStackTrace();
24199 amit.gupta 267
				vc = new ValidateCartResponse(null, "Error", "Problem occurred while getting delivery estimates");
23021 ashik.ali 268
				return responseSender.internalServerError(vc);
21378 kshitij.so 269
			}
24199 amit.gupta 270
 
21378 kshitij.so 271
		}
272
		cartObj.put("maxEstimate", maxEstimate);
273
		CartResponse cartResponse = new Gson().fromJson(cartObj.toString(), CartResponse.class);
24199 amit.gupta 274
		vc = new ValidateCartResponse(cartResponse, "Success", "Items added to cart successfully");
23021 ashik.ali 275
		return responseSender.ok(vc);
21378 kshitij.so 276
	}
21393 amit.gupta 277
 
24199 amit.gupta 278
	@RequestMapping(value = ProfitMandiConstants.URL_CART_CHANGE_ADDRESS, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
21393 amit.gupta 279
	@ApiImplicitParams({
24199 amit.gupta 280
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
281
 
21393 amit.gupta 282
	@ApiOperation(value = "Change address")
24199 amit.gupta 283
	public ResponseEntity<?> changeAddress(HttpServletRequest request,
284
			@RequestParam(value = "addressId") long addressId) throws Throwable {
285
		UserCart uc = userAccountRepository.getUserCart((int) request.getAttribute("userId"));
286
		UserContextService.Client userClient = new UserClient().getClient();
287
		userClient.addAddressToCart(uc.getCartId(), addressId);
288
		return responseSender.ok("Address Changed successfully");
289
	}
21378 kshitij.so 290
}