Subversion Repositories SmartDukaan

Rev

Rev 26615 | Rev 26617 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
26607 amit.gupta 1
package com.spice.profitmandi.web.controller;
2
 
3
import java.util.ArrayList;
4
import java.util.Arrays;
5
import java.util.HashMap;
6
import java.util.HashSet;
7
import java.util.List;
8
import java.util.Map;
9
import java.util.Set;
10
import java.util.stream.Collectors;
11
 
12
import javax.servlet.http.HttpServletRequest;
13
 
14
import org.apache.commons.lang3.StringUtils;
15
import org.apache.http.conn.HttpHostConnectException;
16
import org.apache.logging.log4j.LogManager;
17
import org.apache.logging.log4j.Logger;
18
import org.json.JSONArray;
19
import org.json.JSONObject;
20
import org.springframework.beans.factory.annotation.Autowired;
21
import org.springframework.beans.factory.annotation.Value;
22
import org.springframework.http.MediaType;
23
import org.springframework.http.ResponseEntity;
24
import org.springframework.stereotype.Controller;
25
import org.springframework.transaction.annotation.Transactional;
26
import org.springframework.web.bind.annotation.RequestBody;
27
import org.springframework.web.bind.annotation.RequestMapping;
28
import org.springframework.web.bind.annotation.RequestMethod;
29
import org.springframework.web.bind.annotation.RequestParam;
30
 
31
import com.eclipsesource.json.JsonObject;
32
import com.google.gson.Gson;
33
import com.google.gson.reflect.TypeToken;
34
import com.spice.profitmandi.common.enumuration.SchemeType;
35
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
36
import com.spice.profitmandi.common.model.ProfitMandiConstants;
37
import com.spice.profitmandi.common.model.UserInfo;
38
import com.spice.profitmandi.common.solr.SolrService;
39
import com.spice.profitmandi.common.web.client.RestClient;
40
import com.spice.profitmandi.common.web.util.ResponseSender;
41
import com.spice.profitmandi.dao.entity.catalog.Item;
42
import com.spice.profitmandi.dao.entity.catalog.TagListing;
43
import com.spice.profitmandi.dao.entity.fofo.CurrentInventorySnapshot;
44
import com.spice.profitmandi.dao.entity.inventory.ItemAvailabilityCache;
45
import com.spice.profitmandi.dao.model.AddCartRequest;
46
import com.spice.profitmandi.dao.model.CartItem;
47
import com.spice.profitmandi.dao.model.CartItemResponseModel;
48
import com.spice.profitmandi.dao.model.CartResponse;
49
import com.spice.profitmandi.dao.repository.catalog.CategoryRepository;
50
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
51
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
52
import com.spice.profitmandi.dao.repository.dtr.Mongo;
53
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
54
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
55
import com.spice.profitmandi.dao.repository.inventory.ItemAvailabilityCacheRepository;
56
import com.spice.profitmandi.service.authentication.RoleManager;
57
import com.spice.profitmandi.service.inventory.FofoAvailabilityInfo;
58
import com.spice.profitmandi.service.inventory.FofoCatalogResponse;
59
import com.spice.profitmandi.service.pricing.PricingService;
60
import com.spice.profitmandi.web.res.DealBrands;
61
import com.spice.profitmandi.web.res.DealObjectResponse;
62
import com.spice.profitmandi.web.res.DealsResponse;
63
import com.spice.profitmandi.web.res.ValidateCartResponse;
64
 
65
import io.swagger.annotations.ApiImplicitParam;
66
import io.swagger.annotations.ApiImplicitParams;
67
import io.swagger.annotations.ApiOperation;
68
 
69
@Controller
70
@Transactional(rollbackFor = Throwable.class)
71
public class StoreController {
72
 
73
	private static final Logger logger = LogManager.getLogger(StoreController.class);
74
 
75
	@Value("${python.api.host}")
76
	private String host;
77
 
78
	@Value("${python.api.port}")
79
	private int port;
80
 
81
	// This is now unused as we are not supporting multiple companies.
82
	@Value("${gadgetCops.invoice.cc}")
83
	private String[] ccGadgetCopInvoiceTo;
84
 
85
	@Autowired
86
	private PricingService pricingService;
87
 
88
	@Autowired
89
	private CategoryRepository categoryRepository;
90
 
91
	@Autowired
92
	private SolrService commonSolrService;
93
 
94
	@Autowired
95
	private Mongo mongoClient;
96
 
97
	@Autowired
98
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
99
 
26609 amit.gupta 100
	@Autowired
26607 amit.gupta 101
	private UserAccountRepository userAccountRepository;
102
 
103
	@Autowired
104
	private ResponseSender<?> responseSender;
105
 
106
	@Autowired
107
	private TagListingRepository tagListingRepository;
108
 
109
	@Autowired
110
	private ItemRepository itemRepository;
111
 
112
	@Autowired
113
	private ItemAvailabilityCacheRepository itemAvailabilityCacheRepository;
114
 
115
	@Autowired
116
	private RoleManager roleManagerService;
117
 
118
	List<String> filterableParams = Arrays.asList("brand");
119
 
120
	@ApiImplicitParams({
121
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
122
	@RequestMapping(value = "/store/fofo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
123
	public ResponseEntity<?> getFofo(HttpServletRequest request,
124
			@RequestParam(value = "categoryId", required = false, defaultValue = "(3 OR 6)") String categoryId,
125
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
126
			@RequestParam(value = "sort", required = false) String sort,
127
			@RequestParam(value = "brand", required = false) String brand,
128
			@RequestParam(value = "subCategoryId", required = false) int subCategoryId,
129
			@RequestParam(value = "q", required = false) String queryTerm,
130
			@RequestParam(value = "hotDeal", required = false) boolean hotDeal) throws Throwable {
131
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
132
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
133
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
134
			// UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
135
			List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(userInfo.getRetailerId());
136
			RestClient rc = new RestClient();
137
			Map<String, String> params = new HashMap<>();
138
			List<String> mandatoryQ = new ArrayList<>();
139
			if (queryTerm != null && !queryTerm.equals("null")) {
140
				mandatoryQ.add(String.format("+(%s)", queryTerm));
141
			} else {
142
				queryTerm = null;
143
			}
144
			if (subCategoryId != 0) {
145
				mandatoryQ
146
						.add(String.format("+(subCategoryId_i:%s) +{!parent which=\"subCategoryId_i:%s\"} tagId_i:(%s)",
147
								subCategoryId, subCategoryId, StringUtils.join(tagIds, " ")));
148
			} else if (hotDeal) {
149
				mandatoryQ.add(String.format("+{!parent which=\"hot_deals_b=true\"} tagId_i:(%s)",
150
						StringUtils.join(tagIds, " ")));
151
 
152
			} else if (StringUtils.isNotBlank(brand)) {
153
				mandatoryQ.add(
154
						String.format("+(categoryId_i:%s) +(brand_ss:%s) +{!parent which=\"brand_ss:%s\"} tagId_i:(%s)",
155
								categoryId, brand, brand, StringUtils.join(tagIds, " ")));
156
 
157
			} else {
158
				mandatoryQ.add(
159
						String.format("+{!parent which=\"id:catalog*\"} tagId_i:(%s)", StringUtils.join(tagIds, " ")));
160
			}
161
			params.put("q", StringUtils.join(mandatoryQ, " "));
162
			params.put("fl", "*, [child parentFilter=id:catalog*]");
163
			if (queryTerm == null) {
164
				params.put("sort", "create_s desc");
165
			}
166
			params.put("start", String.valueOf(offset));
167
			params.put("rows", String.valueOf(limit));
168
			params.put("wt", "json");
169
			String response = null;
170
			try {
171
				response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
172
			} catch (HttpHostConnectException e) {
173
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
174
			}
175
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
176
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
177
			dealResponse = getCatalogResponse(docs, hotDeal);
178
			/*
179
			 * if (Mongo.PARTNER_BLoCKED_BRANDS.containsKey(userInfo.getEmail())) {
180
			 * dealResponse.stream() .filter(x ->
181
			 * Mongo.PARTNER_BLoCKED_BRANDS.get(userInfo.getEmail()).contains(x.getBrand()))
182
			 * ; }
183
			 */
184
		} else {
185
			return responseSender.badRequest(
186
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
187
		}
188
		return responseSender.ok(dealResponse);
189
	}
190
 
191
	private Object toDealObject(JsonObject jsonObject) {
192
		if (jsonObject.get("dealObject") != null && jsonObject.get("dealObject").asInt() == 1) {
193
			return new Gson().fromJson(jsonObject.toString(), DealObjectResponse.class);
194
		}
195
		return new Gson().fromJson(jsonObject.toString(), DealsResponse.class);
196
	}
197
 
198
	@RequestMapping(value = "/store/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
199
	@ApiImplicitParams({
200
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
201
	@ApiOperation(value = "Get brand list and count for category")
202
	public ResponseEntity<?> getBrands(HttpServletRequest request,
203
			@RequestParam(value = "category_id") String category_id) throws ProfitMandiBusinessException {
204
		logger.info("Request " + request.getParameterMap());
205
		String response = null;
206
		// TODO: move to properties
207
		String uri = ProfitMandiConstants.URL_BRANDS;
208
		RestClient rc = new RestClient();
209
		Map<String, String> params = new HashMap<>();
210
		params.put("category_id", category_id);
211
		List<DealBrands> dealBrandsResponse = null;
212
		try {
213
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
214
		} catch (HttpHostConnectException e) {
215
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
216
		}
217
 
218
		dealBrandsResponse = new Gson().fromJson(response, new TypeToken<List<DealBrands>>() {
219
		}.getType());
220
 
221
		return responseSender.ok(dealBrandsResponse);
222
	}
223
 
26610 amit.gupta 224
	@RequestMapping(value = "/store/cart", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
26607 amit.gupta 225
	@ApiImplicitParams({
226
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
227
	@ApiOperation(value = "Get brand list and count for category")
228
	public ResponseEntity<?> cart(HttpServletRequest request, @RequestBody AddCartRequest cartRequest)
229
			throws Exception {
230
		CartResponse cartResponse = new CartResponse();
26612 amit.gupta 231
		List<CartItemResponseModel> cartItemResponseModels = new ArrayList<>();
232
		cartResponse.setCartItems(cartItemResponseModels);
233
 
26607 amit.gupta 234
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
235
		Integer storeId = userInfo.getRetailerId();
236
		List<Integer> itemIds = cartRequest.getCartItems().stream().map(x -> x.getItemId())
237
				.collect(Collectors.toList());
238
		Set<Integer> itemsIdsSet = new HashSet<>(itemIds);
239
		List<CurrentInventorySnapshot> currentInventorySnapshot = currentInventorySnapshotRepository
240
				.selectByFofoItemIds(storeId, itemsIdsSet);
241
		Map<Integer, Integer> storeItemAvailabilityMap = currentInventorySnapshot.stream()
242
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
243
 
244
		Map<Integer, Item> itemsMap = itemRepository.selectByIds(itemsIdsSet).stream()
245
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
246
 
247
		Map<Integer, TagListing> sdItemAvailabilityMap = tagListingRepository
248
				.selectByItemIdsAndTagIds(new HashSet<>(itemIds), new HashSet<>(Arrays.asList(4))).stream()
249
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
250
 
251
		List<Integer> catalogIds = itemsMap.values().stream().map(x -> x.getCatalogItemId())
252
				.collect(Collectors.toList());
253
 
254
		Map<Integer, JSONObject> contentMap = commonSolrService.getContentByCatalogIds(catalogIds);
255
 
256
		// cartResponse.getCartItems()
257
		for (CartItem cartItem : cartRequest.getCartItems()) {
258
			Item item = itemsMap.get(cartItem.getItemId());
259
			TagListing tagListing = sdItemAvailabilityMap.get(cartItem.getItemId());
260
			CartItemResponseModel cartItemResponseModel = new CartItemResponseModel();
261
			if (storeItemAvailabilityMap.containsKey(cartItem.getItemId())) {
262
				if (storeItemAvailabilityMap.get(cartItem.getItemId()) >= cartItem.getQuantity()) {
263
					cartItemResponseModel.setEstimate(1);
264
				} else if (tagListing.isActive()) {
265
					cartItemResponseModel.setEstimate(3);
266
				} else {
267
					cartItemResponseModel.setEstimate(-1);
268
				}
269
			}
26616 amit.gupta 270
			cartItemResponseModel.setTitle(item.getItemDescriptionNoColor());
26614 amit.gupta 271
			cartItemResponseModel.setItemId(cartItem.getItemId());
26615 amit.gupta 272
			cartItemResponseModel.setMinBuyQuantity(1);
273
			cartItemResponseModel.setQuantity(cartItem.getQuantity());
26607 amit.gupta 274
			cartItemResponseModel.setSellingPrice(tagListing.getMop());
275
			cartItemResponseModel.setMaxQuantity(10);
276
			cartItemResponseModel.setCatalogItemId(item.getCatalogItemId());
277
			cartItemResponseModel.setImageUrl(contentMap.get(item.getCatalogItemId()).getString("imageUrl_s"));
278
			cartItemResponseModel.setColor(item.getColor());
26614 amit.gupta 279
			cartItemResponseModels.add(cartItemResponseModel); 
26607 amit.gupta 280
		}
281
		ValidateCartResponse vc = new ValidateCartResponse(cartResponse, "Success", "Items added to cart successfully");
282
		return responseSender.ok(vc);
283
	}
284
 
285
	private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal)
286
			throws ProfitMandiBusinessException {
287
		Map<Integer, TagListing> itemTagListingMap = null;
288
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
289
		List<Integer> tagIds = Arrays.asList(4);
290
		if (docs.length() > 0) {
291
			HashSet<Integer> itemsSet = new HashSet<>();
292
			for (int i = 0; i < docs.length(); i++) {
293
				JSONObject doc = docs.getJSONObject(i);
294
				if (doc.has("_childDocuments_")) {
295
					for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
296
						JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
297
						int itemId = childItem.getInt("itemId_i");
298
						itemsSet.add(itemId);
299
					}
300
				}
301
			}
302
			if (itemsSet.size() == 0) {
303
				return dealResponse;
304
			}
305
			itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemsSet, new HashSet<>(tagIds)).stream()
306
					.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
307
		}
308
 
309
		for (int i = 0; i < docs.length(); i++) {
310
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
311
			JSONObject doc = docs.getJSONObject(i);
312
			FofoCatalogResponse ffdr = new FofoCatalogResponse();
313
			ffdr.setCatalogId(doc.getInt("catalogId_i"));
314
			ffdr.setImageUrl(doc.getString("imageUrl_s"));
315
			ffdr.setTitle(doc.getString("title_s"));
316
			try {
317
				ffdr.setFeature(doc.getString("feature_s"));
318
			} catch (Exception e) {
319
				ffdr.setFeature(null);
320
				logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
321
			}
322
			ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
323
			if (doc.has("_childDocuments_")) {
324
				for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
325
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
326
					int itemId = childItem.getInt("itemId_i");
327
					TagListing tl = itemTagListingMap.get(itemId);
328
					if (tl == null) {
329
						logger.warn("Could not find item id {}", itemId);
330
						continue;
331
					}
332
					if (hotDeal) {
333
						if (!tl.isHotDeals()) {
334
							continue;
335
						}
336
					}
337
					float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
338
					if (fofoAvailabilityInfoMap.containsKey(itemId)) {
339
						if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
340
							fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
341
							fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
342
						}
343
					} else {
344
						FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
345
						fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
346
						fdi.setMop((float) childItem.getDouble("mop_f"));
347
						fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
348
						fdi.setTagId(childItem.getInt("tagId_i"));
349
						fdi.setItem_id(itemId);
350
						Item item = itemRepository.selectById(itemId);
351
						// In case its tampered glass moq should be 5
352
						if (item.getCategoryId() == 10020) {
353
							fdi.setMinBuyQuantity(10);
354
						} else {
355
							fdi.setMinBuyQuantity(1);
356
						}
357
						if (hotDeal || !tl.isActive()) {
358
 
359
							int totalAvailability = 0; // Using item availability
360
							// cache for now but can be
361
							// changed to
362
							// use caching later.
363
							try {
364
								ItemAvailabilityCache iac = itemAvailabilityCacheRepository.selectByItemId(itemId);
365
								totalAvailability = iac.getTotalAvailability();
366
								fdi.setAvailability(totalAvailability);
367
							} catch (Exception e) {
368
								continue;
369
							}
370
							if (totalAvailability <= 0) {
371
								continue;
372
							}
373
						} else {
374
							// For accessories item availability should at be ordered for Rs.1000
375
							fdi.setAvailability(100);
376
						}
377
						fdi.setQuantityStep(1);
378
						fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
379
						fofoAvailabilityInfoMap.put(itemId, fdi);
380
					}
381
				}
382
			}
383
			if (fofoAvailabilityInfoMap.values().size() > 0) {
384
				ffdr.setItems(new ArrayList<FofoAvailabilityInfo>(fofoAvailabilityInfoMap.values()));
385
				dealResponse.add(ffdr);
386
			}
387
		}
388
		return dealResponse;
389
 
390
	}
391
 
392
}