Subversion Repositories SmartDukaan

Rev

Rev 23959 | Rev 24153 | 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.util.ArrayList;
4
import java.util.Arrays;
5
import java.util.List;
6
 
7
import javax.servlet.http.HttpServletRequest;
8
 
23959 amit.gupta 9
import org.apache.logging.log4j.LogManager;
10
import org.apache.logging.log4j.Logger;
21378 kshitij.so 11
import org.apache.thrift.TException;
12
import org.json.JSONArray;
13
import org.json.JSONException;
14
import org.json.JSONObject;
15
import org.springframework.beans.factory.annotation.Autowired;
16
import org.springframework.http.MediaType;
17
import org.springframework.http.ResponseEntity;
18
import org.springframework.stereotype.Controller;
21707 amit.gupta 19
import org.springframework.transaction.annotation.Transactional;
21378 kshitij.so 20
import org.springframework.web.bind.annotation.RequestBody;
21
import org.springframework.web.bind.annotation.RequestMapping;
22
import org.springframework.web.bind.annotation.RequestMethod;
21393 amit.gupta 23
import org.springframework.web.bind.annotation.RequestParam;
21378 kshitij.so 24
 
25
import com.google.gson.Gson;
26
import com.spice.profitmandi.common.model.ProfitMandiConstants;
21741 ashik.ali 27
import com.spice.profitmandi.common.web.util.ResponseSender;
23360 amit.gupta 28
import com.spice.profitmandi.dao.entity.catalog.Item;
23273 ashik.ali 29
import com.spice.profitmandi.dao.entity.dtr.UserAccount;
21735 ashik.ali 30
import com.spice.profitmandi.dao.enumuration.dtr.AccountType;
21378 kshitij.so 31
import com.spice.profitmandi.dao.model.ProductPojo;
21738 amit.gupta 32
import com.spice.profitmandi.dao.model.UserCart;
23360 amit.gupta 33
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
21735 ashik.ali 34
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
21643 ashik.ali 35
import com.spice.profitmandi.dao.util.ContentPojoPopulator;
36
import com.spice.profitmandi.dao.util.LogisticsService;
21378 kshitij.so 37
import com.spice.profitmandi.thrift.clients.UserClient;
38
import com.spice.profitmandi.web.req.AddCartRequest;
23965 amit.gupta 39
import com.spice.profitmandi.web.req.CartItems;
21378 kshitij.so 40
import com.spice.profitmandi.web.res.CartResponse;
41
import com.spice.profitmandi.web.res.ValidateCartResponse;
42
 
43
import in.shop2020.logistics.DeliveryType;
44
import in.shop2020.model.v1.user.ItemQuantity;
21393 amit.gupta 45
import in.shop2020.model.v1.user.UserContextService;
21378 kshitij.so 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
22037 amit.gupta 52
@Transactional(rollbackFor=Throwable.class)
21378 kshitij.so 53
public class CartController {
54
 
23568 govind 55
	private static final Logger logger=LogManager.getLogger(CartController.class);
21440 ashik.ali 56
 
57
	@Autowired
22931 ashik.ali 58
	private ResponseSender<?> responseSender;
21378 kshitij.so 59
 
60
	@Autowired
22931 ashik.ali 61
	private UserAccountRepository userAccountRepository;
22173 amit.gupta 62
 
63
	@Autowired
22931 ashik.ali 64
	private ContentPojoPopulator contentPojoPopulator;
22568 amit.gupta 65
 
23360 amit.gupta 66
	@Autowired
67
	private ItemRepository itemRepository;
68
 
21378 kshitij.so 69
 
70
	@RequestMapping(value = ProfitMandiConstants.URL_CART, method=RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
71
	@ApiImplicitParams({
72
		@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", 
73
				required = true, dataType = "string", paramType = "header")
74
	})
75
	@ApiOperation(value = "Add items to cart")
21681 amit.gupta 76
	public ResponseEntity<?> validateCart(HttpServletRequest request,@RequestBody AddCartRequest cartRequest, @RequestParam(value="pincode", defaultValue="110001") String pincode) throws Throwable{
23273 ashik.ali 77
		UserAccount userAccount = null;
21378 kshitij.so 78
		ValidateCartResponse vc = null;
21458 kshitij.so 79
		int userId = (int)request.getAttribute("userId");
21681 amit.gupta 80
 
23273 ashik.ali 81
		userAccount = userAccountRepository.selectByUserIdType(userId, AccountType.cartId);
23568 govind 82
		logger.info("UserAccount................."+userAccount);
21378 kshitij.so 83
 
84
		List<ItemQuantity> itemQuantities = new ArrayList<ItemQuantity>();
85
		CartItems[] cartItems = cartRequest.getCartItems();
86
		List<Integer> itemsList = new ArrayList<Integer>();
87
		for (CartItems ci: cartItems){
88
			itemsList.add(ci.getItemId());
89
			ItemQuantity iq = new ItemQuantity(ci.getItemId(), ci.getQuantity());
90
			itemQuantities.add(iq);
91
		}
92
		Client userClient = null;
93
		try {
94
			userClient = new UserClient().getClient();
23273 ashik.ali 95
			userClient.addItemsToCart(Integer.valueOf(userAccount.getAccountKey()), itemQuantities, null);
21383 kshitij.so 96
		} catch (Exception e) {
21378 kshitij.so 97
			vc = new ValidateCartResponse(null, "Error","Problem occurred while updating cart");
23021 ashik.ali 98
			return responseSender.internalServerError(vc);
21378 kshitij.so 99
		}
100
		String cartString=null;
22568 amit.gupta 101
		//Use source id temporarily for purpose of tag id as it is just one lets hardcode the tag id
102
		int source = -1;
23273 ashik.ali 103
		cartString = userClient.validateCartNew(Integer.valueOf(userAccount.getAccountKey()), pincode, source);
21378 kshitij.so 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
			}
23360 amit.gupta 134
			try {
22173 amit.gupta 135
			ProductPojo pp = contentPojoPopulator.getShortContent(itemObj.getLong("catalogItemId"));
21389 kshitij.so 136
//			String productProperties = ContentServingService.getSnippet(Utils.PRODUCT_PROPERTIES_SNIPPET, pp.getId() +"", -1);
137
//			JSONObject productPropertiesInJson = new JSONObject(productProperties);
138
//			pp.setCategoryName(productPropertiesInJson.getString("categoryName"));
21378 kshitij.so 139
 
140
			if(itemObj.has("estimate")){
141
				if(allSame){
142
					allSame = maxEstimate==-2 || maxEstimate==itemObj.getInt("estimate");
143
				}
144
				if(itemObj.getInt("estimate") > maxEstimate){
145
					maxEstimate = itemObj.getInt("estimate");
146
				}
147
			}
23360 amit.gupta 148
				itemObj.put("imageUrl", pp.getImageUrl());
149
				itemObj.put("title", pp.getTitle());
150
			} catch (Throwable t) {
151
				Item item = itemRepository.selectById(itemObj.getInt("itemId"));
152
				itemObj.put("imageUrl", "");
153
				itemObj.put("title", item.getBrand() + " " + item.getModelName() + "" + item.getModelNumber());
154
			}
21378 kshitij.so 155
		}
156
 
157
		ArrayList<JSONObject> listdata = new ArrayList<JSONObject>();     
158
		if (arr != null) { 
159
			for (int i=0;i<arr.length();i++){
160
				JSONArray itemMessages = arr.getJSONObject(i).optJSONArray(("cartItemMessages"));
161
				if(itemMessages!=null && itemMessages.length()>0){
162
					listdata.add(0,arr.getJSONObject(i));
163
				} else {
164
					listdata.add(arr.getJSONObject(i));
165
				}
166
			} 
167
		}
168
		arr = new JSONArray();
169
		for(int i=0;i<listdata.size();i++){
170
			arr.put(listdata.get(i));
171
		}
172
		cartObj.put("cartItems", arr);
173
		JSONArray cartMessagesArray = new JSONArray();
174
		for (String message :Arrays.asList("cartMessageOOS", "cartMessageUndeliverable", "cartMessageChanged","cartMessagesMerged")){
175
			int count = cartObj.getInt(message);
176
			if (count>0) {
177
				String type="danger";
178
				JSONObject cartMessage=new JSONObject();
179
				if (message.equals("cartMessagesMerged")) {
180
					type = "info";
181
					if (count==1){
182
						cartMessage.put("messageText","1 item is added from earlier cart");
183
					}else {
184
						cartMessage.put("messageText","Few items are added from earlier cart");
185
					}
186
				} else if (message.equals("cartMessageOOS")) {
187
					if (count==1){
188
						cartMessage.put("messageText","One item is currently Out of Stock");
189
					}else {
190
						cartMessage.put("messageText","Few items are currently Out of Stock");
191
					}
192
				} else if (message.equals("cartMessageUndeliverable")) {
193
					if (count==1){
194
						cartMessage.put("messageText","One item is undeliverable");
195
					}else {
196
						cartMessage.put("messageText","Few items are underiverable");
197
					}
198
				} else {
199
					if (count==1){
200
						cartMessage.put("messageText","One item qty has changed");
201
					}else {
202
						cartMessage.put("messageText","Few items qty have changed");
203
					}
204
				}
205
				cartMessage.put("type",type);
206
				cartMessagesArray.put(cartMessage);
207
			}
208
		}
209
		cartObj.put("cartMessages", cartMessagesArray);
210
 
211
		if (maxEstimate==-1){
212
			cartObj.put("estimateString", "Can't ship here");
213
		}
214
		else if(maxEstimate==-2){
215
			cartObj.put("estimateString", "Out of Stock");
216
		} else {
217
			try {
21452 amit.gupta 218
				cartObj.put("cod", cartObj.getBoolean("codAllowed"));
21378 kshitij.so 219
				cartObj.put("estimateString", LogisticsService.getDeliveryDateString(maxEstimate,DeliveryType.COD));
220
			} catch (NumberFormatException | JSONException | TException e) {
221
				// TODO Auto-generated catch block
222
				e.printStackTrace();
223
				vc = new ValidateCartResponse(null, "Error","Problem occurred while getting delivery estimates");
23021 ashik.ali 224
				return responseSender.internalServerError(vc);
21378 kshitij.so 225
			}
226
 
227
		}
228
		cartObj.put("maxEstimate", maxEstimate);
229
		CartResponse cartResponse = new Gson().fromJson(cartObj.toString(), CartResponse.class);
230
		vc = new ValidateCartResponse(cartResponse, "Success","Items added to cart successfully");
23021 ashik.ali 231
		return responseSender.ok(vc);
21378 kshitij.so 232
	}
21393 amit.gupta 233
 
21407 kshitij.so 234
	@RequestMapping(value = ProfitMandiConstants.URL_CART_CHANGE_ADDRESS, method=RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
21393 amit.gupta 235
	@ApiImplicitParams({
236
		@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", 
237
				required = true, dataType = "string", paramType = "header")
238
	})
239
 
240
	@ApiOperation(value = "Change address")
21738 amit.gupta 241
	public ResponseEntity<?> changeAddress(HttpServletRequest request, @RequestParam(value="addressId") long addressId) throws Throwable{
242
		UserCart uc = userAccountRepository.getUserCart((int)request.getAttribute("userId"));
21666 amit.gupta 243
    	UserContextService.Client userClient = new UserClient().getClient();
21738 amit.gupta 244
    	userClient.addAddressToCart(uc.getCartId(), addressId);
21666 amit.gupta 245
    	return responseSender.ok("Address Changed successfully");
21393 amit.gupta 246
    }
21378 kshitij.so 247
}