Subversion Repositories SmartDukaan

Rev

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