Subversion Repositories SmartDukaan

Rev

Rev 26620 | Rev 26628 | 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);
26620 amit.gupta 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()
26620 amit.gupta 242
				.filter(x -> x.getAvailability() > 0)
26607 amit.gupta 243
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
244
 
245
		Map<Integer, Item> itemsMap = itemRepository.selectByIds(itemsIdsSet).stream()
246
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
247
 
248
		Map<Integer, TagListing> sdItemAvailabilityMap = tagListingRepository
249
				.selectByItemIdsAndTagIds(new HashSet<>(itemIds), new HashSet<>(Arrays.asList(4))).stream()
250
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
251
 
252
		List<Integer> catalogIds = itemsMap.values().stream().map(x -> x.getCatalogItemId())
253
				.collect(Collectors.toList());
254
 
255
		Map<Integer, JSONObject> contentMap = commonSolrService.getContentByCatalogIds(catalogIds);
256
 
257
		// cartResponse.getCartItems()
258
		for (CartItem cartItem : cartRequest.getCartItems()) {
26620 amit.gupta 259
			if (cartItem.getQuantity() == 0) {
26617 amit.gupta 260
				continue;
261
			}
26607 amit.gupta 262
			Item item = itemsMap.get(cartItem.getItemId());
263
			TagListing tagListing = sdItemAvailabilityMap.get(cartItem.getItemId());
264
			CartItemResponseModel cartItemResponseModel = new CartItemResponseModel();
265
			if (storeItemAvailabilityMap.containsKey(cartItem.getItemId())) {
266
				if (storeItemAvailabilityMap.get(cartItem.getItemId()) >= cartItem.getQuantity()) {
267
					cartItemResponseModel.setEstimate(1);
268
				} else if (tagListing.isActive()) {
269
					cartItemResponseModel.setEstimate(3);
270
				} else {
271
					cartItemResponseModel.setEstimate(-1);
272
				}
26620 amit.gupta 273
			} else if (tagListing.isActive()) {
274
				cartItemResponseModel.setEstimate(3);
275
			} else {
276
				cartItemResponseModel.setEstimate(-1);
26607 amit.gupta 277
			}
26620 amit.gupta 278
 
26616 amit.gupta 279
			cartItemResponseModel.setTitle(item.getItemDescriptionNoColor());
26614 amit.gupta 280
			cartItemResponseModel.setItemId(cartItem.getItemId());
26615 amit.gupta 281
			cartItemResponseModel.setMinBuyQuantity(1);
282
			cartItemResponseModel.setQuantity(cartItem.getQuantity());
26621 amit.gupta 283
			cartItemResponseModel.setQuantityStep(1);
26607 amit.gupta 284
			cartItemResponseModel.setSellingPrice(tagListing.getMop());
285
			cartItemResponseModel.setMaxQuantity(10);
286
			cartItemResponseModel.setCatalogItemId(item.getCatalogItemId());
287
			cartItemResponseModel.setImageUrl(contentMap.get(item.getCatalogItemId()).getString("imageUrl_s"));
288
			cartItemResponseModel.setColor(item.getColor());
26620 amit.gupta 289
			cartItemResponseModels.add(cartItemResponseModel);
26607 amit.gupta 290
		}
291
		ValidateCartResponse vc = new ValidateCartResponse(cartResponse, "Success", "Items added to cart successfully");
292
		return responseSender.ok(vc);
293
	}
294
 
295
	private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal)
296
			throws ProfitMandiBusinessException {
297
		Map<Integer, TagListing> itemTagListingMap = null;
298
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
299
		List<Integer> tagIds = Arrays.asList(4);
300
		if (docs.length() > 0) {
301
			HashSet<Integer> itemsSet = new HashSet<>();
302
			for (int i = 0; i < docs.length(); i++) {
303
				JSONObject doc = docs.getJSONObject(i);
304
				if (doc.has("_childDocuments_")) {
305
					for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
306
						JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
307
						int itemId = childItem.getInt("itemId_i");
308
						itemsSet.add(itemId);
309
					}
310
				}
311
			}
312
			if (itemsSet.size() == 0) {
313
				return dealResponse;
314
			}
315
			itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemsSet, new HashSet<>(tagIds)).stream()
316
					.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
317
		}
318
 
319
		for (int i = 0; i < docs.length(); i++) {
320
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
321
			JSONObject doc = docs.getJSONObject(i);
322
			FofoCatalogResponse ffdr = new FofoCatalogResponse();
323
			ffdr.setCatalogId(doc.getInt("catalogId_i"));
324
			ffdr.setImageUrl(doc.getString("imageUrl_s"));
325
			ffdr.setTitle(doc.getString("title_s"));
326
			try {
327
				ffdr.setFeature(doc.getString("feature_s"));
328
			} catch (Exception e) {
329
				ffdr.setFeature(null);
330
				logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
331
			}
332
			ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
333
			if (doc.has("_childDocuments_")) {
334
				for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
335
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
336
					int itemId = childItem.getInt("itemId_i");
337
					TagListing tl = itemTagListingMap.get(itemId);
338
					if (tl == null) {
339
						logger.warn("Could not find item id {}", itemId);
340
						continue;
341
					}
342
					if (hotDeal) {
343
						if (!tl.isHotDeals()) {
344
							continue;
345
						}
346
					}
347
					float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
348
					if (fofoAvailabilityInfoMap.containsKey(itemId)) {
349
						if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
350
							fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
351
							fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
352
						}
353
					} else {
354
						FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
355
						fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
356
						fdi.setMop((float) childItem.getDouble("mop_f"));
357
						fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
358
						fdi.setTagId(childItem.getInt("tagId_i"));
359
						fdi.setItem_id(itemId);
360
						Item item = itemRepository.selectById(itemId);
361
						// In case its tampered glass moq should be 5
362
						if (item.getCategoryId() == 10020) {
363
							fdi.setMinBuyQuantity(10);
364
						} else {
365
							fdi.setMinBuyQuantity(1);
366
						}
367
						if (hotDeal || !tl.isActive()) {
368
 
369
							int totalAvailability = 0; // Using item availability
370
							// cache for now but can be
371
							// changed to
372
							// use caching later.
373
							try {
374
								ItemAvailabilityCache iac = itemAvailabilityCacheRepository.selectByItemId(itemId);
375
								totalAvailability = iac.getTotalAvailability();
376
								fdi.setAvailability(totalAvailability);
377
							} catch (Exception e) {
378
								continue;
379
							}
380
							if (totalAvailability <= 0) {
381
								continue;
382
							}
383
						} else {
384
							// For accessories item availability should at be ordered for Rs.1000
385
							fdi.setAvailability(100);
386
						}
387
						fdi.setQuantityStep(1);
388
						fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
389
						fofoAvailabilityInfoMap.put(itemId, fdi);
390
					}
391
				}
392
			}
393
			if (fofoAvailabilityInfoMap.values().size() > 0) {
394
				ffdr.setItems(new ArrayList<FofoAvailabilityInfo>(fofoAvailabilityInfoMap.values()));
395
				dealResponse.add(ffdr);
396
			}
397
		}
398
		return dealResponse;
399
 
400
	}
401
 
402
}