Subversion Repositories SmartDukaan

Rev

Rev 21383 | Rev 21389 | 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;
21
import org.springframework.web.bind.annotation.RequestBody;
22
import org.springframework.web.bind.annotation.RequestMapping;
23
import org.springframework.web.bind.annotation.RequestMethod;
24
 
25
import com.google.gson.Gson;
26
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
27
import com.spice.profitmandi.common.model.ProfitMandiConstants;
28
import com.spice.profitmandi.common.services.ContentPojoPopulator;
29
import com.spice.profitmandi.common.services.ContentServingService;
30
import com.spice.profitmandi.common.services.LogisticsService;
31
import com.spice.profitmandi.common.util.Utils;
32
import com.spice.profitmandi.dao.entity.UserAccounts;
21383 kshitij.so 33
import com.spice.profitmandi.dao.enumuration.AccountType;
21378 kshitij.so 34
import com.spice.profitmandi.dao.model.ProductPojo;
35
import com.spice.profitmandi.dao.repository.UserAccountRepository;
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;
43
 
44
import in.shop2020.logistics.DeliveryType;
45
import in.shop2020.model.v1.user.ItemQuantity;
46
import in.shop2020.model.v1.user.UserContextService.Client;
47
import io.swagger.annotations.ApiImplicitParam;
48
import io.swagger.annotations.ApiImplicitParams;
49
import io.swagger.annotations.ApiOperation;
50
 
51
@Controller
52
public class CartController {
53
 
54
	private static final Logger logger=LoggerFactory.getLogger(CartController.class);
55
 
56
	@Autowired
57
	UserAccountRepository userAccountRepository;
58
 
59
	@RequestMapping(value = ProfitMandiConstants.URL_CART, method=RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
60
	@ApiImplicitParams({
61
		@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", 
62
				required = true, dataType = "string", paramType = "header")
63
	})
64
	@ApiOperation(value = "Add items to cart")
65
	public ResponseEntity<?> validateCart(HttpServletRequest request,@RequestBody AddCartRequest cartRequest){
66
		UserAccounts userAccount = null;
67
		ValidateCartResponse vc = null;
68
		try {
69
			userAccount = userAccountRepository.getUserAccountByType(47, AccountType.cartId);
70
			logger.info("UserAccount "+userAccount);
71
		} catch (ProfitMandiBusinessException e1) {
72
			vc = new ValidateCartResponse(null, "Error","Error while getting cart information");
73
			final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.INTERNAL_SERVER_ERROR.toString(), HttpStatus.INTERNAL_SERVER_ERROR, ResponseStatus.FAILURE, vc);
74
			return new ResponseEntity<>(profitMandiResponse,HttpStatus.INTERNAL_SERVER_ERROR);
75
		}
76
 
77
		List<ItemQuantity> itemQuantities = new ArrayList<ItemQuantity>();
78
		CartItems[] cartItems = cartRequest.getCartItems();
79
		List<Integer> itemsList = new ArrayList<Integer>();
80
		for (CartItems ci: cartItems){
81
			itemsList.add(ci.getItemId());
82
			ItemQuantity iq = new ItemQuantity(ci.getItemId(), ci.getQuantity());
83
			itemQuantities.add(iq);
84
		}
85
		Client userClient = null;
86
		try {
87
			userClient = new UserClient().getClient();
88
			userClient.addItemsToCart(Integer.valueOf(userAccount.getAccount_key()), itemQuantities, null);
21383 kshitij.so 89
		} catch (Exception e) {
21378 kshitij.so 90
			vc = new ValidateCartResponse(null, "Error","Problem occurred while updating cart");
91
			final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.INTERNAL_SERVER_ERROR.toString(), HttpStatus.INTERNAL_SERVER_ERROR, ResponseStatus.FAILURE, vc);
92
			return new ResponseEntity<>(profitMandiResponse,HttpStatus.INTERNAL_SERVER_ERROR);
93
		}
94
		String cartString=null;
95
		try {
96
			cartString = userClient.validateCartNew(Integer.valueOf(userAccount.getAccount_key()), "110002", -1);
21383 kshitij.so 97
		} catch (Exception e) {
21378 kshitij.so 98
			// TODO Auto-generated catch block
99
			e.printStackTrace();
100
			vc = new ValidateCartResponse(null, "Error","Problem occurred while validating cart");
101
			final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.INTERNAL_SERVER_ERROR.toString(), HttpStatus.INTERNAL_SERVER_ERROR, ResponseStatus.FAILURE, vc);
102
			return new ResponseEntity<>(profitMandiResponse,HttpStatus.INTERNAL_SERVER_ERROR);
103
		}
104
		JSONObject cartObj = new JSONObject(cartString);
105
		JSONArray arr = cartObj.getJSONArray("cartItems");
106
		int maxEstimate=-2;
107
		boolean allSame=true;
108
		int removedCount = 0;
109
		cartObj.put("cartMessagesMerged", 0);
110
		for (int j=0; j<arr.length(); j++){
111
			JSONObject itemObj = arr.getJSONObject(j-removedCount);
112
			if(!itemsList.contains(itemObj.getInt("itemId"))){
113
				if(itemObj.getInt("quantity")==0){
114
					arr.remove(j-removedCount);
115
					removedCount++;
116
					if (itemObj.has("estimate") && itemObj.getInt("estimate")==-1){
117
						cartObj.put("cartMessageUndeliverable", cartObj.getInt("cartMessageUndeliverable") - 1);
118
					} else {
119
						cartObj.put("cartMessageOOS", cartObj.getInt("cartMessageOOS") - 1);
120
					}
121
					continue;
122
				} else {
123
					JSONArray messagesArray = new JSONArray();
124
					itemObj.put("cartItemMessages", messagesArray);
125
					if(itemsList.size()>0){
126
						JSONObject message=new JSONObject();
127
						message.put("type","info");
128
						message.put("messageText","Added from earlier cart");
129
						messagesArray.put(message);
130
						cartObj.put("cartMessagesMerged", cartObj.getInt("cartMessagesMerged") + 1);
131
					}
132
				}
133
			}
134
			ProductPojo pp = ContentPojoPopulator.getShortContent(itemObj.getLong("catalogItemId"));
21386 kshitij.so 135
			logger.info("ProductPojo "+pp);
21378 kshitij.so 136
			String productProperties = ContentServingService.getSnippet(Utils.PRODUCT_PROPERTIES_SNIPPET, pp.getId() +"", -1);
21386 kshitij.so 137
			logger.info("productProperties "+productProperties);
21378 kshitij.so 138
			JSONObject productPropertiesInJson = new JSONObject(productProperties);
139
			pp.setCategoryName(productPropertiesInJson.getString("categoryName"));
140
 
141
			if(itemObj.has("estimate")){
142
				if(allSame){
143
					allSame = maxEstimate==-2 || maxEstimate==itemObj.getInt("estimate");
144
				}
145
				if(itemObj.getInt("estimate") > maxEstimate){
146
					maxEstimate = itemObj.getInt("estimate");
147
				}
148
			}
149
			itemObj.put("imageUrl", pp.getImageUrl());
150
			itemObj.put("categoryName", pp.getCategoryName());
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");
221
				final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.INTERNAL_SERVER_ERROR.toString(), HttpStatus.INTERNAL_SERVER_ERROR, ResponseStatus.FAILURE, vc);
222
				return new ResponseEntity<>(profitMandiResponse,HttpStatus.INTERNAL_SERVER_ERROR);
223
			}
224
 
225
		}
226
		cartObj.put("maxEstimate", maxEstimate);
227
		CartResponse cartResponse = new Gson().fromJson(cartObj.toString(), CartResponse.class);
228
		vc = new ValidateCartResponse(cartResponse, "Success","Items added to cart successfully");
229
		final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.OK.toString(), HttpStatus.OK, ResponseStatus.SUCCESS, vc);
230
		return new ResponseEntity<>(profitMandiResponse,HttpStatus.OK);
231
	}
232
}