Subversion Repositories SmartDukaan

Rev

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