Subversion Repositories SmartDukaan

Rev

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