Subversion Repositories SmartDukaan

Rev

Rev 23965 | Rev 24166 | 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>();
24153 amit.gupta 87
		boolean hasJio = false;
21378 kshitij.so 88
		for (CartItems ci: cartItems){
24153 amit.gupta 89
			if(itemRepository.selectById(ci.getItemId()).getBrand().equalsIgnoreCase("reliance")) {
90
				hasJio = true;
91
				continue;
92
			}
93
		}
94
		for (CartItems ci: cartItems){
95
			if(hasJio && itemRepository.selectById(ci.getItemId()).getBrand().equalsIgnoreCase("reliance")) {
96
				continue;
97
			}
21378 kshitij.so 98
			itemsList.add(ci.getItemId());
99
			ItemQuantity iq = new ItemQuantity(ci.getItemId(), ci.getQuantity());
100
			itemQuantities.add(iq);
101
		}
102
		Client userClient = null;
103
		try {
104
			userClient = new UserClient().getClient();
23273 ashik.ali 105
			userClient.addItemsToCart(Integer.valueOf(userAccount.getAccountKey()), itemQuantities, null);
21383 kshitij.so 106
		} catch (Exception e) {
21378 kshitij.so 107
			vc = new ValidateCartResponse(null, "Error","Problem occurred while updating cart");
23021 ashik.ali 108
			return responseSender.internalServerError(vc);
21378 kshitij.so 109
		}
110
		String cartString=null;
22568 amit.gupta 111
		//Use source id temporarily for purpose of tag id as it is just one lets hardcode the tag id
112
		int source = -1;
23273 ashik.ali 113
		cartString = userClient.validateCartNew(Integer.valueOf(userAccount.getAccountKey()), pincode, source);
21378 kshitij.so 114
		JSONObject cartObj = new JSONObject(cartString);
115
		JSONArray arr = cartObj.getJSONArray("cartItems");
116
		int maxEstimate=-2;
117
		boolean allSame=true;
118
		int removedCount = 0;
119
		cartObj.put("cartMessagesMerged", 0);
120
		for (int j=0; j<arr.length(); j++){
121
			JSONObject itemObj = arr.getJSONObject(j-removedCount);
122
			if(!itemsList.contains(itemObj.getInt("itemId"))){
123
				if(itemObj.getInt("quantity")==0){
124
					arr.remove(j-removedCount);
125
					removedCount++;
126
					if (itemObj.has("estimate") && itemObj.getInt("estimate")==-1){
127
						cartObj.put("cartMessageUndeliverable", cartObj.getInt("cartMessageUndeliverable") - 1);
128
					} else {
129
						cartObj.put("cartMessageOOS", cartObj.getInt("cartMessageOOS") - 1);
130
					}
131
					continue;
132
				} else {
133
					JSONArray messagesArray = new JSONArray();
134
					itemObj.put("cartItemMessages", messagesArray);
135
					if(itemsList.size()>0){
136
						JSONObject message=new JSONObject();
137
						message.put("type","info");
138
						message.put("messageText","Added from earlier cart");
139
						messagesArray.put(message);
140
						cartObj.put("cartMessagesMerged", cartObj.getInt("cartMessagesMerged") + 1);
141
					}
142
				}
143
			}
23360 amit.gupta 144
			try {
22173 amit.gupta 145
			ProductPojo pp = contentPojoPopulator.getShortContent(itemObj.getLong("catalogItemId"));
21389 kshitij.so 146
//			String productProperties = ContentServingService.getSnippet(Utils.PRODUCT_PROPERTIES_SNIPPET, pp.getId() +"", -1);
147
//			JSONObject productPropertiesInJson = new JSONObject(productProperties);
148
//			pp.setCategoryName(productPropertiesInJson.getString("categoryName"));
21378 kshitij.so 149
 
150
			if(itemObj.has("estimate")){
151
				if(allSame){
152
					allSame = maxEstimate==-2 || maxEstimate==itemObj.getInt("estimate");
153
				}
154
				if(itemObj.getInt("estimate") > maxEstimate){
155
					maxEstimate = itemObj.getInt("estimate");
156
				}
157
			}
23360 amit.gupta 158
				itemObj.put("imageUrl", pp.getImageUrl());
159
				itemObj.put("title", pp.getTitle());
160
			} catch (Throwable t) {
161
				Item item = itemRepository.selectById(itemObj.getInt("itemId"));
162
				itemObj.put("imageUrl", "");
163
				itemObj.put("title", item.getBrand() + " " + item.getModelName() + "" + item.getModelNumber());
164
			}
21378 kshitij.so 165
		}
166
 
167
		ArrayList<JSONObject> listdata = new ArrayList<JSONObject>();     
168
		if (arr != null) { 
169
			for (int i=0;i<arr.length();i++){
170
				JSONArray itemMessages = arr.getJSONObject(i).optJSONArray(("cartItemMessages"));
171
				if(itemMessages!=null && itemMessages.length()>0){
172
					listdata.add(0,arr.getJSONObject(i));
173
				} else {
174
					listdata.add(arr.getJSONObject(i));
175
				}
176
			} 
177
		}
178
		arr = new JSONArray();
179
		for(int i=0;i<listdata.size();i++){
180
			arr.put(listdata.get(i));
181
		}
182
		cartObj.put("cartItems", arr);
183
		JSONArray cartMessagesArray = new JSONArray();
184
		for (String message :Arrays.asList("cartMessageOOS", "cartMessageUndeliverable", "cartMessageChanged","cartMessagesMerged")){
185
			int count = cartObj.getInt(message);
186
			if (count>0) {
187
				String type="danger";
188
				JSONObject cartMessage=new JSONObject();
189
				if (message.equals("cartMessagesMerged")) {
190
					type = "info";
191
					if (count==1){
192
						cartMessage.put("messageText","1 item is added from earlier cart");
193
					}else {
194
						cartMessage.put("messageText","Few items are added from earlier cart");
195
					}
196
				} else if (message.equals("cartMessageOOS")) {
197
					if (count==1){
198
						cartMessage.put("messageText","One item is currently Out of Stock");
199
					}else {
200
						cartMessage.put("messageText","Few items are currently Out of Stock");
201
					}
202
				} else if (message.equals("cartMessageUndeliverable")) {
203
					if (count==1){
204
						cartMessage.put("messageText","One item is undeliverable");
205
					}else {
206
						cartMessage.put("messageText","Few items are underiverable");
207
					}
208
				} else {
209
					if (count==1){
210
						cartMessage.put("messageText","One item qty has changed");
211
					}else {
212
						cartMessage.put("messageText","Few items qty have changed");
213
					}
214
				}
215
				cartMessage.put("type",type);
216
				cartMessagesArray.put(cartMessage);
217
			}
218
		}
219
		cartObj.put("cartMessages", cartMessagesArray);
220
 
221
		if (maxEstimate==-1){
222
			cartObj.put("estimateString", "Can't ship here");
223
		}
224
		else if(maxEstimate==-2){
225
			cartObj.put("estimateString", "Out of Stock");
226
		} else {
227
			try {
21452 amit.gupta 228
				cartObj.put("cod", cartObj.getBoolean("codAllowed"));
21378 kshitij.so 229
				cartObj.put("estimateString", LogisticsService.getDeliveryDateString(maxEstimate,DeliveryType.COD));
230
			} catch (NumberFormatException | JSONException | TException e) {
231
				// TODO Auto-generated catch block
232
				e.printStackTrace();
233
				vc = new ValidateCartResponse(null, "Error","Problem occurred while getting delivery estimates");
23021 ashik.ali 234
				return responseSender.internalServerError(vc);
21378 kshitij.so 235
			}
236
 
237
		}
238
		cartObj.put("maxEstimate", maxEstimate);
239
		CartResponse cartResponse = new Gson().fromJson(cartObj.toString(), CartResponse.class);
240
		vc = new ValidateCartResponse(cartResponse, "Success","Items added to cart successfully");
23021 ashik.ali 241
		return responseSender.ok(vc);
21378 kshitij.so 242
	}
21393 amit.gupta 243
 
21407 kshitij.so 244
	@RequestMapping(value = ProfitMandiConstants.URL_CART_CHANGE_ADDRESS, method=RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
21393 amit.gupta 245
	@ApiImplicitParams({
246
		@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", 
247
				required = true, dataType = "string", paramType = "header")
248
	})
249
 
250
	@ApiOperation(value = "Change address")
21738 amit.gupta 251
	public ResponseEntity<?> changeAddress(HttpServletRequest request, @RequestParam(value="addressId") long addressId) throws Throwable{
252
		UserCart uc = userAccountRepository.getUserCart((int)request.getAttribute("userId"));
21666 amit.gupta 253
    	UserContextService.Client userClient = new UserClient().getClient();
21738 amit.gupta 254
    	userClient.addAddressToCart(uc.getCartId(), addressId);
21666 amit.gupta 255
    	return responseSender.ok("Address Changed successfully");
21393 amit.gupta 256
    }
21378 kshitij.so 257
}