Subversion Repositories SmartDukaan

Rev

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