Subversion Repositories SmartDukaan

Rev

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