Subversion Repositories SmartDukaan

Rev

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