Subversion Repositories SmartDukaan

Rev

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