Subversion Repositories SmartDukaan

Rev

Rev 21666 | Rev 21707 | 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")
21681 amit.gupta 70
	public ResponseEntity<?> validateCart(HttpServletRequest request,@RequestBody AddCartRequest cartRequest, @RequestParam(value="pincode", defaultValue="110001") String pincode) throws Throwable{
21378 kshitij.so 71
		UserAccounts userAccount = null;
72
		ValidateCartResponse vc = null;
21458 kshitij.so 73
		int userId = (int)request.getAttribute("userId");
21681 amit.gupta 74
 
75
		userAccount = userAccountRepository.getUserAccountByType(userId, AccountType.cartId);
76
		logger.info("UserAccount "+userAccount);
21378 kshitij.so 77
 
78
		List<ItemQuantity> itemQuantities = new ArrayList<ItemQuantity>();
79
		CartItems[] cartItems = cartRequest.getCartItems();
80
		List<Integer> itemsList = new ArrayList<Integer>();
81
		for (CartItems ci: cartItems){
82
			itemsList.add(ci.getItemId());
83
			ItemQuantity iq = new ItemQuantity(ci.getItemId(), ci.getQuantity());
84
			itemQuantities.add(iq);
85
		}
86
		Client userClient = null;
87
		try {
88
			userClient = new UserClient().getClient();
89
			userClient.addItemsToCart(Integer.valueOf(userAccount.getAccount_key()), itemQuantities, null);
21383 kshitij.so 90
		} catch (Exception e) {
21378 kshitij.so 91
			vc = new ValidateCartResponse(null, "Error","Problem occurred while updating cart");
92
			final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.INTERNAL_SERVER_ERROR.toString(), HttpStatus.INTERNAL_SERVER_ERROR, ResponseStatus.FAILURE, vc);
93
			return new ResponseEntity<>(profitMandiResponse,HttpStatus.INTERNAL_SERVER_ERROR);
94
		}
95
		String cartString=null;
21681 amit.gupta 96
		cartString = userClient.validateCartNew(Integer.valueOf(userAccount.getAccount_key()), pincode, -1);
21378 kshitij.so 97
		JSONObject cartObj = new JSONObject(cartString);
98
		JSONArray arr = cartObj.getJSONArray("cartItems");
99
		int maxEstimate=-2;
100
		boolean allSame=true;
101
		int removedCount = 0;
102
		cartObj.put("cartMessagesMerged", 0);
103
		for (int j=0; j<arr.length(); j++){
104
			JSONObject itemObj = arr.getJSONObject(j-removedCount);
105
			if(!itemsList.contains(itemObj.getInt("itemId"))){
106
				if(itemObj.getInt("quantity")==0){
107
					arr.remove(j-removedCount);
108
					removedCount++;
109
					if (itemObj.has("estimate") && itemObj.getInt("estimate")==-1){
110
						cartObj.put("cartMessageUndeliverable", cartObj.getInt("cartMessageUndeliverable") - 1);
111
					} else {
112
						cartObj.put("cartMessageOOS", cartObj.getInt("cartMessageOOS") - 1);
113
					}
114
					continue;
115
				} else {
116
					JSONArray messagesArray = new JSONArray();
117
					itemObj.put("cartItemMessages", messagesArray);
118
					if(itemsList.size()>0){
119
						JSONObject message=new JSONObject();
120
						message.put("type","info");
121
						message.put("messageText","Added from earlier cart");
122
						messagesArray.put(message);
123
						cartObj.put("cartMessagesMerged", cartObj.getInt("cartMessagesMerged") + 1);
124
					}
125
				}
126
			}
127
			ProductPojo pp = ContentPojoPopulator.getShortContent(itemObj.getLong("catalogItemId"));
21389 kshitij.so 128
//			String productProperties = ContentServingService.getSnippet(Utils.PRODUCT_PROPERTIES_SNIPPET, pp.getId() +"", -1);
129
//			JSONObject productPropertiesInJson = new JSONObject(productProperties);
130
//			pp.setCategoryName(productPropertiesInJson.getString("categoryName"));
21378 kshitij.so 131
 
132
			if(itemObj.has("estimate")){
133
				if(allSame){
134
					allSame = maxEstimate==-2 || maxEstimate==itemObj.getInt("estimate");
135
				}
136
				if(itemObj.getInt("estimate") > maxEstimate){
137
					maxEstimate = itemObj.getInt("estimate");
138
				}
139
			}
140
			itemObj.put("imageUrl", pp.getImageUrl());
141
			itemObj.put("title", pp.getTitle());
142
		}
143
 
144
		ArrayList<JSONObject> listdata = new ArrayList<JSONObject>();     
145
		if (arr != null) { 
146
			for (int i=0;i<arr.length();i++){
147
				JSONArray itemMessages = arr.getJSONObject(i).optJSONArray(("cartItemMessages"));
148
				if(itemMessages!=null && itemMessages.length()>0){
149
					listdata.add(0,arr.getJSONObject(i));
150
				} else {
151
					listdata.add(arr.getJSONObject(i));
152
				}
153
			} 
154
		}
155
		arr = new JSONArray();
156
		for(int i=0;i<listdata.size();i++){
157
			arr.put(listdata.get(i));
158
		}
159
		cartObj.put("cartItems", arr);
160
		JSONArray cartMessagesArray = new JSONArray();
161
		for (String message :Arrays.asList("cartMessageOOS", "cartMessageUndeliverable", "cartMessageChanged","cartMessagesMerged")){
162
			int count = cartObj.getInt(message);
163
			if (count>0) {
164
				String type="danger";
165
				JSONObject cartMessage=new JSONObject();
166
				if (message.equals("cartMessagesMerged")) {
167
					type = "info";
168
					if (count==1){
169
						cartMessage.put("messageText","1 item is added from earlier cart");
170
					}else {
171
						cartMessage.put("messageText","Few items are added from earlier cart");
172
					}
173
				} else if (message.equals("cartMessageOOS")) {
174
					if (count==1){
175
						cartMessage.put("messageText","One item is currently Out of Stock");
176
					}else {
177
						cartMessage.put("messageText","Few items are currently Out of Stock");
178
					}
179
				} else if (message.equals("cartMessageUndeliverable")) {
180
					if (count==1){
181
						cartMessage.put("messageText","One item is undeliverable");
182
					}else {
183
						cartMessage.put("messageText","Few items are underiverable");
184
					}
185
				} else {
186
					if (count==1){
187
						cartMessage.put("messageText","One item qty has changed");
188
					}else {
189
						cartMessage.put("messageText","Few items qty have changed");
190
					}
191
				}
192
				cartMessage.put("type",type);
193
				cartMessagesArray.put(cartMessage);
194
			}
195
		}
196
		cartObj.put("cartMessages", cartMessagesArray);
197
 
198
		if (maxEstimate==-1){
199
			cartObj.put("estimateString", "Can't ship here");
200
		}
201
		else if(maxEstimate==-2){
202
			cartObj.put("estimateString", "Out of Stock");
203
		} else {
204
			try {
21452 amit.gupta 205
				cartObj.put("cod", cartObj.getBoolean("codAllowed"));
21378 kshitij.so 206
				cartObj.put("estimateString", LogisticsService.getDeliveryDateString(maxEstimate,DeliveryType.COD));
207
			} catch (NumberFormatException | JSONException | TException e) {
208
				// TODO Auto-generated catch block
209
				e.printStackTrace();
210
				vc = new ValidateCartResponse(null, "Error","Problem occurred while getting delivery estimates");
21393 amit.gupta 211
				final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , 
212
						HttpStatus.INTERNAL_SERVER_ERROR.toString(), HttpStatus.INTERNAL_SERVER_ERROR, ResponseStatus.FAILURE, vc);
21378 kshitij.so 213
				return new ResponseEntity<>(profitMandiResponse,HttpStatus.INTERNAL_SERVER_ERROR);
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");
220
		final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.OK.toString(), HttpStatus.OK, ResponseStatus.SUCCESS, vc);
221
		return new ResponseEntity<>(profitMandiResponse,HttpStatus.OK);
222
	}
21393 amit.gupta 223
 
21407 kshitij.so 224
	@RequestMapping(value = ProfitMandiConstants.URL_CART_CHANGE_ADDRESS, method=RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
21393 amit.gupta 225
	@ApiImplicitParams({
226
		@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", 
227
				required = true, dataType = "string", paramType = "header")
228
	})
229
 
230
	@ApiOperation(value = "Change address")
21666 amit.gupta 231
	public ResponseEntity<?> changeAddress(HttpServletRequest request,@PathVariable(value="cartId") long cartId, @RequestParam(value="addressId") long addressId) throws Throwable{
232
    	UserContextService.Client userClient = new UserClient().getClient();
233
    	userClient.addAddressToCart(cartId, addressId);
234
    	return responseSender.ok("Address Changed successfully");
21393 amit.gupta 235
    }
21378 kshitij.so 236
}