Subversion Repositories SmartDukaan

Rev

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