Subversion Repositories SmartDukaan

Rev

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