Subversion Repositories SmartDukaan

Rev

Rev 22931 | Rev 23273 | 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
 
9
import org.apache.thrift.TException;
10
import org.json.JSONArray;
11
import org.json.JSONException;
12
import org.json.JSONObject;
13
import org.slf4j.Logger;
14
import org.slf4j.LoggerFactory;
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;
26
import com.spice.profitmandi.common.model.ProfitMandiConstants;
21741 ashik.ali 27
import com.spice.profitmandi.common.web.util.ResponseSender;
21735 ashik.ali 28
import com.spice.profitmandi.dao.entity.dtr.UserAccounts;
29
import com.spice.profitmandi.dao.enumuration.dtr.AccountType;
21378 kshitij.so 30
import com.spice.profitmandi.dao.model.ProductPojo;
21738 amit.gupta 31
import com.spice.profitmandi.dao.model.UserCart;
21735 ashik.ali 32
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
21643 ashik.ali 33
import com.spice.profitmandi.dao.util.ContentPojoPopulator;
34
import com.spice.profitmandi.dao.util.LogisticsService;
21378 kshitij.so 35
import com.spice.profitmandi.thrift.clients.UserClient;
36
import com.spice.profitmandi.web.req.AddCartRequest;
37
import com.spice.profitmandi.web.req.CartItems;
38
import com.spice.profitmandi.web.res.CartResponse;
39
import com.spice.profitmandi.web.res.ValidateCartResponse;
40
 
41
import in.shop2020.logistics.DeliveryType;
42
import in.shop2020.model.v1.user.ItemQuantity;
21393 amit.gupta 43
import in.shop2020.model.v1.user.UserContextService;
21378 kshitij.so 44
import in.shop2020.model.v1.user.UserContextService.Client;
45
import io.swagger.annotations.ApiImplicitParam;
46
import io.swagger.annotations.ApiImplicitParams;
47
import io.swagger.annotations.ApiOperation;
48
 
49
@Controller
22037 amit.gupta 50
@Transactional(rollbackFor=Throwable.class)
21378 kshitij.so 51
public class CartController {
52
 
53
	private static final Logger logger=LoggerFactory.getLogger(CartController.class);
21440 ashik.ali 54
 
55
	@Autowired
22931 ashik.ali 56
	private ResponseSender<?> responseSender;
21378 kshitij.so 57
 
58
	@Autowired
22931 ashik.ali 59
	private UserAccountRepository userAccountRepository;
22173 amit.gupta 60
 
61
	@Autowired
22931 ashik.ali 62
	private ContentPojoPopulator contentPojoPopulator;
22568 amit.gupta 63
 
21378 kshitij.so 64
 
65
	@RequestMapping(value = ProfitMandiConstants.URL_CART, method=RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
66
	@ApiImplicitParams({
67
		@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", 
68
				required = true, dataType = "string", paramType = "header")
69
	})
70
	@ApiOperation(value = "Add items to cart")
21681 amit.gupta 71
	public ResponseEntity<?> validateCart(HttpServletRequest request,@RequestBody AddCartRequest cartRequest, @RequestParam(value="pincode", defaultValue="110001") String pincode) throws Throwable{
21378 kshitij.so 72
		UserAccounts userAccount = null;
73
		ValidateCartResponse vc = null;
21458 kshitij.so 74
		int userId = (int)request.getAttribute("userId");
21681 amit.gupta 75
 
76
		userAccount = userAccountRepository.getUserAccountByType(userId, AccountType.cartId);
77
		logger.info("UserAccount "+userAccount);
21378 kshitij.so 78
 
79
		List<ItemQuantity> itemQuantities = new ArrayList<ItemQuantity>();
80
		CartItems[] cartItems = cartRequest.getCartItems();
81
		List<Integer> itemsList = new ArrayList<Integer>();
82
		for (CartItems ci: cartItems){
83
			itemsList.add(ci.getItemId());
84
			ItemQuantity iq = new ItemQuantity(ci.getItemId(), ci.getQuantity());
85
			itemQuantities.add(iq);
86
		}
87
		Client userClient = null;
88
		try {
89
			userClient = new UserClient().getClient();
90
			userClient.addItemsToCart(Integer.valueOf(userAccount.getAccount_key()), itemQuantities, null);
21383 kshitij.so 91
		} catch (Exception e) {
21378 kshitij.so 92
			vc = new ValidateCartResponse(null, "Error","Problem occurred while updating cart");
23021 ashik.ali 93
			return responseSender.internalServerError(vc);
21378 kshitij.so 94
		}
95
		String cartString=null;
22568 amit.gupta 96
		//Use source id temporarily for purpose of tag id as it is just one lets hardcode the tag id
97
		int source = -1;
98
		cartString = userClient.validateCartNew(Integer.valueOf(userAccount.getAccount_key()), pincode, source);
21378 kshitij.so 99
		JSONObject cartObj = new JSONObject(cartString);
100
		JSONArray arr = cartObj.getJSONArray("cartItems");
101
		int maxEstimate=-2;
102
		boolean allSame=true;
103
		int removedCount = 0;
104
		cartObj.put("cartMessagesMerged", 0);
105
		for (int j=0; j<arr.length(); j++){
106
			JSONObject itemObj = arr.getJSONObject(j-removedCount);
107
			if(!itemsList.contains(itemObj.getInt("itemId"))){
108
				if(itemObj.getInt("quantity")==0){
109
					arr.remove(j-removedCount);
110
					removedCount++;
111
					if (itemObj.has("estimate") && itemObj.getInt("estimate")==-1){
112
						cartObj.put("cartMessageUndeliverable", cartObj.getInt("cartMessageUndeliverable") - 1);
113
					} else {
114
						cartObj.put("cartMessageOOS", cartObj.getInt("cartMessageOOS") - 1);
115
					}
116
					continue;
117
				} else {
118
					JSONArray messagesArray = new JSONArray();
119
					itemObj.put("cartItemMessages", messagesArray);
120
					if(itemsList.size()>0){
121
						JSONObject message=new JSONObject();
122
						message.put("type","info");
123
						message.put("messageText","Added from earlier cart");
124
						messagesArray.put(message);
125
						cartObj.put("cartMessagesMerged", cartObj.getInt("cartMessagesMerged") + 1);
126
					}
127
				}
128
			}
22173 amit.gupta 129
			ProductPojo pp = contentPojoPopulator.getShortContent(itemObj.getLong("catalogItemId"));
21389 kshitij.so 130
//			String productProperties = ContentServingService.getSnippet(Utils.PRODUCT_PROPERTIES_SNIPPET, pp.getId() +"", -1);
131
//			JSONObject productPropertiesInJson = new JSONObject(productProperties);
132
//			pp.setCategoryName(productPropertiesInJson.getString("categoryName"));
21378 kshitij.so 133
 
134
			if(itemObj.has("estimate")){
135
				if(allSame){
136
					allSame = maxEstimate==-2 || maxEstimate==itemObj.getInt("estimate");
137
				}
138
				if(itemObj.getInt("estimate") > maxEstimate){
139
					maxEstimate = itemObj.getInt("estimate");
140
				}
141
			}
142
			itemObj.put("imageUrl", pp.getImageUrl());
143
			itemObj.put("title", pp.getTitle());
144
		}
145
 
146
		ArrayList<JSONObject> listdata = new ArrayList<JSONObject>();     
147
		if (arr != null) { 
148
			for (int i=0;i<arr.length();i++){
149
				JSONArray itemMessages = arr.getJSONObject(i).optJSONArray(("cartItemMessages"));
150
				if(itemMessages!=null && itemMessages.length()>0){
151
					listdata.add(0,arr.getJSONObject(i));
152
				} else {
153
					listdata.add(arr.getJSONObject(i));
154
				}
155
			} 
156
		}
157
		arr = new JSONArray();
158
		for(int i=0;i<listdata.size();i++){
159
			arr.put(listdata.get(i));
160
		}
161
		cartObj.put("cartItems", arr);
162
		JSONArray cartMessagesArray = new JSONArray();
163
		for (String message :Arrays.asList("cartMessageOOS", "cartMessageUndeliverable", "cartMessageChanged","cartMessagesMerged")){
164
			int count = cartObj.getInt(message);
165
			if (count>0) {
166
				String type="danger";
167
				JSONObject cartMessage=new JSONObject();
168
				if (message.equals("cartMessagesMerged")) {
169
					type = "info";
170
					if (count==1){
171
						cartMessage.put("messageText","1 item is added from earlier cart");
172
					}else {
173
						cartMessage.put("messageText","Few items are added from earlier cart");
174
					}
175
				} else if (message.equals("cartMessageOOS")) {
176
					if (count==1){
177
						cartMessage.put("messageText","One item is currently Out of Stock");
178
					}else {
179
						cartMessage.put("messageText","Few items are currently Out of Stock");
180
					}
181
				} else if (message.equals("cartMessageUndeliverable")) {
182
					if (count==1){
183
						cartMessage.put("messageText","One item is undeliverable");
184
					}else {
185
						cartMessage.put("messageText","Few items are underiverable");
186
					}
187
				} else {
188
					if (count==1){
189
						cartMessage.put("messageText","One item qty has changed");
190
					}else {
191
						cartMessage.put("messageText","Few items qty have changed");
192
					}
193
				}
194
				cartMessage.put("type",type);
195
				cartMessagesArray.put(cartMessage);
196
			}
197
		}
198
		cartObj.put("cartMessages", cartMessagesArray);
199
 
200
		if (maxEstimate==-1){
201
			cartObj.put("estimateString", "Can't ship here");
202
		}
203
		else if(maxEstimate==-2){
204
			cartObj.put("estimateString", "Out of Stock");
205
		} else {
206
			try {
21452 amit.gupta 207
				cartObj.put("cod", cartObj.getBoolean("codAllowed"));
21378 kshitij.so 208
				cartObj.put("estimateString", LogisticsService.getDeliveryDateString(maxEstimate,DeliveryType.COD));
209
			} catch (NumberFormatException | JSONException | TException e) {
210
				// TODO Auto-generated catch block
211
				e.printStackTrace();
212
				vc = new ValidateCartResponse(null, "Error","Problem occurred while getting delivery estimates");
23021 ashik.ali 213
				return responseSender.internalServerError(vc);
21378 kshitij.so 214
			}
215
 
216
		}
217
		cartObj.put("maxEstimate", maxEstimate);
218
		CartResponse cartResponse = new Gson().fromJson(cartObj.toString(), CartResponse.class);
219
		vc = new ValidateCartResponse(cartResponse, "Success","Items added to cart successfully");
23021 ashik.ali 220
		return responseSender.ok(vc);
21378 kshitij.so 221
	}
21393 amit.gupta 222
 
21407 kshitij.so 223
	@RequestMapping(value = ProfitMandiConstants.URL_CART_CHANGE_ADDRESS, method=RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
21393 amit.gupta 224
	@ApiImplicitParams({
225
		@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", 
226
				required = true, dataType = "string", paramType = "header")
227
	})
228
 
229
	@ApiOperation(value = "Change address")
21738 amit.gupta 230
	public ResponseEntity<?> changeAddress(HttpServletRequest request, @RequestParam(value="addressId") long addressId) throws Throwable{
231
		UserCart uc = userAccountRepository.getUserCart((int)request.getAttribute("userId"));
21666 amit.gupta 232
    	UserContextService.Client userClient = new UserClient().getClient();
21738 amit.gupta 233
    	userClient.addAddressToCart(uc.getCartId(), addressId);
21666 amit.gupta 234
    	return responseSender.ok("Address Changed successfully");
21393 amit.gupta 235
    }
21378 kshitij.so 236
}