Subversion Repositories SmartDukaan

Rev

Rev 21386 | Rev 21393 | 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"));
21389 kshitij.so 135
//			String productProperties = ContentServingService.getSnippet(Utils.PRODUCT_PROPERTIES_SNIPPET, pp.getId() +"", -1);
136
//			JSONObject productPropertiesInJson = new JSONObject(productProperties);
137
//			pp.setCategoryName(productPropertiesInJson.getString("categoryName"));
21378 kshitij.so 138
 
139
			if(itemObj.has("estimate")){
140
				if(allSame){
141
					allSame = maxEstimate==-2 || maxEstimate==itemObj.getInt("estimate");
142
				}
143
				if(itemObj.getInt("estimate") > maxEstimate){
144
					maxEstimate = itemObj.getInt("estimate");
145
				}
146
			}
147
			itemObj.put("imageUrl", pp.getImageUrl());
148
			itemObj.put("title", pp.getTitle());
149
		}
150
 
151
		ArrayList<JSONObject> listdata = new ArrayList<JSONObject>();     
152
		if (arr != null) { 
153
			for (int i=0;i<arr.length();i++){
154
				JSONArray itemMessages = arr.getJSONObject(i).optJSONArray(("cartItemMessages"));
155
				if(itemMessages!=null && itemMessages.length()>0){
156
					listdata.add(0,arr.getJSONObject(i));
157
				} else {
158
					listdata.add(arr.getJSONObject(i));
159
				}
160
			} 
161
		}
162
		arr = new JSONArray();
163
		for(int i=0;i<listdata.size();i++){
164
			arr.put(listdata.get(i));
165
		}
166
		cartObj.put("cartItems", arr);
167
		JSONArray cartMessagesArray = new JSONArray();
168
		for (String message :Arrays.asList("cartMessageOOS", "cartMessageUndeliverable", "cartMessageChanged","cartMessagesMerged")){
169
			int count = cartObj.getInt(message);
170
			if (count>0) {
171
				String type="danger";
172
				JSONObject cartMessage=new JSONObject();
173
				if (message.equals("cartMessagesMerged")) {
174
					type = "info";
175
					if (count==1){
176
						cartMessage.put("messageText","1 item is added from earlier cart");
177
					}else {
178
						cartMessage.put("messageText","Few items are added from earlier cart");
179
					}
180
				} else if (message.equals("cartMessageOOS")) {
181
					if (count==1){
182
						cartMessage.put("messageText","One item is currently Out of Stock");
183
					}else {
184
						cartMessage.put("messageText","Few items are currently Out of Stock");
185
					}
186
				} else if (message.equals("cartMessageUndeliverable")) {
187
					if (count==1){
188
						cartMessage.put("messageText","One item is undeliverable");
189
					}else {
190
						cartMessage.put("messageText","Few items are underiverable");
191
					}
192
				} else {
193
					if (count==1){
194
						cartMessage.put("messageText","One item qty has changed");
195
					}else {
196
						cartMessage.put("messageText","Few items qty have changed");
197
					}
198
				}
199
				cartMessage.put("type",type);
200
				cartMessagesArray.put(cartMessage);
201
			}
202
		}
203
		cartObj.put("cartMessages", cartMessagesArray);
204
 
205
		if (maxEstimate==-1){
206
			cartObj.put("estimateString", "Can't ship here");
207
		}
208
		else if(maxEstimate==-2){
209
			cartObj.put("estimateString", "Out of Stock");
210
		} else {
211
			try {
212
				cartObj.put("cod", userClient.showCODOption(Integer.valueOf(userAccount.getAccount_key()), 0, "110002"));
213
				cartObj.put("estimateString", LogisticsService.getDeliveryDateString(maxEstimate,DeliveryType.COD));
214
			} catch (NumberFormatException | JSONException | TException e) {
215
				// TODO Auto-generated catch block
216
				e.printStackTrace();
217
				vc = new ValidateCartResponse(null, "Error","Problem occurred while getting delivery estimates");
218
				final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.INTERNAL_SERVER_ERROR.toString(), HttpStatus.INTERNAL_SERVER_ERROR, ResponseStatus.FAILURE, vc);
219
				return new ResponseEntity<>(profitMandiResponse,HttpStatus.INTERNAL_SERVER_ERROR);
220
			}
221
 
222
		}
223
		cartObj.put("maxEstimate", maxEstimate);
224
		CartResponse cartResponse = new Gson().fromJson(cartObj.toString(), CartResponse.class);
225
		vc = new ValidateCartResponse(cartResponse, "Success","Items added to cart successfully");
226
		final ProfitMandiResponse<?> profitMandiResponse=new ProfitMandiResponse<>(LocalDateTime.now(), request.getRequestURL().toString() , HttpStatus.OK.toString(), HttpStatus.OK, ResponseStatus.SUCCESS, vc);
227
		return new ResponseEntity<>(profitMandiResponse,HttpStatus.OK);
228
	}
229
}