Subversion Repositories SmartDukaan

Rev

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