Subversion Repositories SmartDukaan

Rev

Rev 26607 | Rev 26609 | 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.Iterator;
8
import java.util.List;
9
import java.util.Map;
10
import java.util.Set;
11
import java.util.concurrent.atomic.AtomicInteger;
12
import java.util.stream.Collectors;
13
 
14
import javax.servlet.http.HttpServletRequest;
15
 
16
import org.apache.commons.lang3.StringUtils;
17
import org.apache.http.conn.HttpHostConnectException;
18
import org.apache.logging.log4j.LogManager;
19
import org.apache.logging.log4j.Logger;
20
import org.json.JSONArray;
21
import org.json.JSONObject;
22
import org.springframework.beans.factory.annotation.Autowired;
23
import org.springframework.beans.factory.annotation.Value;
24
import org.springframework.http.HttpStatus;
25
import org.springframework.http.MediaType;
26
import org.springframework.http.ResponseEntity;
27
import org.springframework.stereotype.Controller;
28
import org.springframework.transaction.annotation.Transactional;
29
import org.springframework.web.bind.annotation.PathVariable;
30
import org.springframework.web.bind.annotation.RequestBody;
31
import org.springframework.web.bind.annotation.RequestMapping;
32
import org.springframework.web.bind.annotation.RequestMethod;
33
import org.springframework.web.bind.annotation.RequestParam;
34
 
35
import com.eclipsesource.json.Json;
36
import com.eclipsesource.json.JsonArray;
37
import com.eclipsesource.json.JsonObject;
38
import com.eclipsesource.json.JsonValue;
39
import com.google.gson.Gson;
40
import com.google.gson.reflect.TypeToken;
41
import com.mongodb.BasicDBObject;
42
import com.mongodb.DBObject;
43
import com.spice.profitmandi.common.enumuration.SchemeType;
44
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
45
import com.spice.profitmandi.common.model.ProfitMandiConstants;
46
import com.spice.profitmandi.common.model.UserInfo;
47
import com.spice.profitmandi.common.solr.SolrService;
48
import com.spice.profitmandi.common.web.client.RestClient;
49
import com.spice.profitmandi.common.web.util.ResponseSender;
50
import com.spice.profitmandi.dao.entity.catalog.Category;
51
import com.spice.profitmandi.dao.entity.catalog.Item;
52
import com.spice.profitmandi.dao.entity.catalog.TagListing;
53
import com.spice.profitmandi.dao.entity.fofo.CurrentInventorySnapshot;
54
import com.spice.profitmandi.dao.entity.inventory.ItemAvailabilityCache;
55
import com.spice.profitmandi.dao.model.AddCartRequest;
56
import com.spice.profitmandi.dao.model.CartItem;
57
import com.spice.profitmandi.dao.model.CartItemResponseModel;
58
import com.spice.profitmandi.dao.model.CartResponse;
59
import com.spice.profitmandi.dao.model.UserCart;
60
import com.spice.profitmandi.dao.repository.catalog.CategoryRepository;
61
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
62
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
63
import com.spice.profitmandi.dao.repository.dtr.Mongo;
64
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
65
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
66
import com.spice.profitmandi.dao.repository.inventory.ItemAvailabilityCacheRepository;
67
import com.spice.profitmandi.service.authentication.RoleManager;
68
import com.spice.profitmandi.service.inventory.AvailabilityInfo;
69
import com.spice.profitmandi.service.inventory.FofoAvailabilityInfo;
70
import com.spice.profitmandi.service.inventory.FofoCatalogResponse;
71
import com.spice.profitmandi.service.pricing.PricingService;
72
import com.spice.profitmandi.web.res.DealBrands;
73
import com.spice.profitmandi.web.res.DealObjectResponse;
74
import com.spice.profitmandi.web.res.DealsResponse;
75
import com.spice.profitmandi.web.res.ValidateCartResponse;
76
 
77
import io.swagger.annotations.ApiImplicitParam;
78
import io.swagger.annotations.ApiImplicitParams;
79
import io.swagger.annotations.ApiOperation;
80
 
81
@Controller
82
@Transactional(rollbackFor = Throwable.class)
83
public class StoreController {
84
 
85
	private static final Logger logger = LogManager.getLogger(StoreController.class);
86
 
87
	@Value("${python.api.host}")
88
	private String host;
89
 
90
	@Value("${python.api.port}")
91
	private int port;
92
 
93
	// This is now unused as we are not supporting multiple companies.
94
	@Value("${gadgetCops.invoice.cc}")
95
	private String[] ccGadgetCopInvoiceTo;
96
 
97
	@Autowired
98
	private PricingService pricingService;
99
 
100
	@Autowired
101
	private CategoryRepository categoryRepository;
102
 
103
	@Autowired
104
	private SolrService commonSolrService;
105
 
106
	@Autowired
107
	private Mongo mongoClient;
108
 
109
	@Autowired
110
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
111
 
26608 amit.gupta 112
		@Autowired
26607 amit.gupta 113
	private UserAccountRepository userAccountRepository;
114
 
115
	@Autowired
116
	private ResponseSender<?> responseSender;
117
 
118
	@Autowired
119
	private TagListingRepository tagListingRepository;
120
 
121
	@Autowired
122
	private ItemRepository itemRepository;
123
 
124
	@Autowired
125
	private ItemAvailabilityCacheRepository itemAvailabilityCacheRepository;
126
 
127
	@Autowired
128
	private RoleManager roleManagerService;
129
 
130
	List<String> filterableParams = Arrays.asList("brand");
131
 
132
	@ApiImplicitParams({
133
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
134
	@RequestMapping(value = "/store/fofo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
135
	public ResponseEntity<?> getFofo(HttpServletRequest request,
136
			@RequestParam(value = "categoryId", required = false, defaultValue = "(3 OR 6)") String categoryId,
137
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
138
			@RequestParam(value = "sort", required = false) String sort,
139
			@RequestParam(value = "brand", required = false) String brand,
140
			@RequestParam(value = "subCategoryId", required = false) int subCategoryId,
141
			@RequestParam(value = "q", required = false) String queryTerm,
142
			@RequestParam(value = "hotDeal", required = false) boolean hotDeal) throws Throwable {
143
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
144
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
145
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
146
			// UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
147
			List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(userInfo.getRetailerId());
148
			RestClient rc = new RestClient();
149
			Map<String, String> params = new HashMap<>();
150
			List<String> mandatoryQ = new ArrayList<>();
151
			if (queryTerm != null && !queryTerm.equals("null")) {
152
				mandatoryQ.add(String.format("+(%s)", queryTerm));
153
			} else {
154
				queryTerm = null;
155
			}
156
			if (subCategoryId != 0) {
157
				mandatoryQ
158
						.add(String.format("+(subCategoryId_i:%s) +{!parent which=\"subCategoryId_i:%s\"} tagId_i:(%s)",
159
								subCategoryId, subCategoryId, StringUtils.join(tagIds, " ")));
160
			} else if (hotDeal) {
161
				mandatoryQ.add(String.format("+{!parent which=\"hot_deals_b=true\"} tagId_i:(%s)",
162
						StringUtils.join(tagIds, " ")));
163
 
164
			} else if (StringUtils.isNotBlank(brand)) {
165
				mandatoryQ.add(
166
						String.format("+(categoryId_i:%s) +(brand_ss:%s) +{!parent which=\"brand_ss:%s\"} tagId_i:(%s)",
167
								categoryId, brand, brand, StringUtils.join(tagIds, " ")));
168
 
169
			} else {
170
				mandatoryQ.add(
171
						String.format("+{!parent which=\"id:catalog*\"} tagId_i:(%s)", StringUtils.join(tagIds, " ")));
172
			}
173
			params.put("q", StringUtils.join(mandatoryQ, " "));
174
			params.put("fl", "*, [child parentFilter=id:catalog*]");
175
			if (queryTerm == null) {
176
				params.put("sort", "create_s desc");
177
			}
178
			params.put("start", String.valueOf(offset));
179
			params.put("rows", String.valueOf(limit));
180
			params.put("wt", "json");
181
			String response = null;
182
			try {
183
				response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
184
			} catch (HttpHostConnectException e) {
185
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
186
			}
187
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
188
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
189
			dealResponse = getCatalogResponse(docs, hotDeal);
190
			/*
191
			 * if (Mongo.PARTNER_BLoCKED_BRANDS.containsKey(userInfo.getEmail())) {
192
			 * dealResponse.stream() .filter(x ->
193
			 * Mongo.PARTNER_BLoCKED_BRANDS.get(userInfo.getEmail()).contains(x.getBrand()))
194
			 * ; }
195
			 */
196
		} else {
197
			return responseSender.badRequest(
198
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
199
		}
200
		return responseSender.ok(dealResponse);
201
	}
202
 
203
	@ApiImplicitParams({
204
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
205
	@RequestMapping(value = "/partnerStock", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
206
	public ResponseEntity<?> partnerStock(HttpServletRequest request,
207
			@RequestParam(value = "categoryId", required = false, defaultValue = "(3 OR 6)") String categoryId,
208
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
209
			@RequestParam(value = "sort", required = false) String sort,
210
			@RequestParam(value = "brand", required = false) String brand,
211
			@RequestParam(value = "subCategoryId", required = false) int subCategoryId,
212
			@RequestParam(value = "q", required = false) String queryTerm,
213
			@RequestParam(value = " ", required = false, defaultValue = "true") boolean partnerStockOnly)
214
			throws Throwable {
215
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
216
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
217
		UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
218
 
219
		logger.info("Retiler Id ==> {}", uc.getUserId());
220
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
221
			if (partnerStockOnly) {
222
 
223
			}
224
			List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(userInfo.getRetailerId());
225
			RestClient rc = new RestClient();
226
			Map<String, String> params = new HashMap<>();
227
			List<String> mandatoryQ = new ArrayList<>();
228
			if (queryTerm != null && !queryTerm.equals("null")) {
229
				mandatoryQ.add(String.format("+(%s)", queryTerm));
230
			} else {
231
				queryTerm = null;
232
			}
233
			if (subCategoryId != 0) {
234
				mandatoryQ
235
						.add(String.format("+(subCategoryId_i:%s) +{!parent which=\"subCategoryId_i:%s\"} tagId_i:(%s)",
236
								subCategoryId, subCategoryId, StringUtils.join(tagIds, " ")));
237
			} else if (StringUtils.isNotBlank(brand)) {
238
				mandatoryQ.add(
239
						String.format("+(categoryId_i:%s) +(brand_ss:%s) +{!parent which=\"brand_ss:%s\"} tagId_i:(%s)",
240
								categoryId, brand, brand, StringUtils.join(tagIds, " ")));
241
 
242
			} else {
243
				mandatoryQ.add(
244
						String.format("+{!parent which=\"id:catalog*\"} tagId_i:(%s)", StringUtils.join(tagIds, " ")));
245
			}
246
			params.put("q", StringUtils.join(mandatoryQ, " "));
247
			params.put("fl", "*, [child parentFilter=id:catalog*]");
248
			if (queryTerm == null) {
249
				params.put("sort", "create_s desc");
250
			}
251
			params.put("start", String.valueOf(offset));
252
			params.put("rows", String.valueOf(limit));
253
			params.put("wt", "json");
254
			String response = null;
255
			try {
256
				response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
257
			} catch (HttpHostConnectException e) {
258
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
259
			}
260
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
261
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
262
			dealResponse = getCatalogResponse(docs, false);
263
			/*
264
			 * if (Mongo.PARTNER_BLoCKED_BRANDS.containsKey(userInfo.getEmail())) {
265
			 * dealResponse.stream() .filter(x ->
266
			 * Mongo.PARTNER_BLoCKED_BRANDS.get(userInfo.getEmail()).contains(x.getBrand()))
267
			 * ; }
268
			 */
269
		} else {
270
			return responseSender.badRequest(
271
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
272
		}
273
		return responseSender.ok(dealResponse);
274
	}
275
 
276
	private Object toDealObject(JsonObject jsonObject) {
277
		if (jsonObject.get("dealObject") != null && jsonObject.get("dealObject").asInt() == 1) {
278
			return new Gson().fromJson(jsonObject.toString(), DealObjectResponse.class);
279
		}
280
		return new Gson().fromJson(jsonObject.toString(), DealsResponse.class);
281
	}
282
 
283
	@RequestMapping(value = "/store/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
284
	@ApiImplicitParams({
285
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
286
	@ApiOperation(value = "Get brand list and count for category")
287
	public ResponseEntity<?> getBrands(HttpServletRequest request,
288
			@RequestParam(value = "category_id") String category_id) throws ProfitMandiBusinessException {
289
		logger.info("Request " + request.getParameterMap());
290
		String response = null;
291
		// TODO: move to properties
292
		String uri = ProfitMandiConstants.URL_BRANDS;
293
		RestClient rc = new RestClient();
294
		Map<String, String> params = new HashMap<>();
295
		params.put("category_id", category_id);
296
		List<DealBrands> dealBrandsResponse = null;
297
		try {
298
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
299
		} catch (HttpHostConnectException e) {
300
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
301
		}
302
 
303
		dealBrandsResponse = new Gson().fromJson(response, new TypeToken<List<DealBrands>>() {
304
		}.getType());
305
 
306
		return responseSender.ok(dealBrandsResponse);
307
	}
308
 
309
	@RequestMapping(value = "/store/cart", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
310
	@ApiImplicitParams({
311
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
312
	@ApiOperation(value = "Get brand list and count for category")
313
	public ResponseEntity<?> cart(HttpServletRequest request, @RequestBody AddCartRequest cartRequest)
314
			throws Exception {
315
		CartResponse cartResponse = new CartResponse();
316
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
317
		Integer storeId = userInfo.getRetailerId();
318
		List<Integer> itemIds = cartRequest.getCartItems().stream().map(x -> x.getItemId())
319
				.collect(Collectors.toList());
320
		Set<Integer> itemsIdsSet = new HashSet<>(itemIds);
321
		List<CurrentInventorySnapshot> currentInventorySnapshot = currentInventorySnapshotRepository
322
				.selectByFofoItemIds(storeId, itemsIdsSet);
323
		Map<Integer, Integer> storeItemAvailabilityMap = currentInventorySnapshot.stream()
324
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
325
 
326
		Map<Integer, Item> itemsMap = itemRepository.selectByIds(itemsIdsSet).stream()
327
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
328
 
329
		Map<Integer, TagListing> sdItemAvailabilityMap = tagListingRepository
330
				.selectByItemIdsAndTagIds(new HashSet<>(itemIds), new HashSet<>(Arrays.asList(4))).stream()
331
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
332
 
333
		List<Integer> catalogIds = itemsMap.values().stream().map(x -> x.getCatalogItemId())
334
				.collect(Collectors.toList());
335
 
336
		Map<Integer, JSONObject> contentMap = commonSolrService.getContentByCatalogIds(catalogIds);
337
 
338
		// cartResponse.getCartItems()
339
		for (CartItem cartItem : cartRequest.getCartItems()) {
340
			Item item = itemsMap.get(cartItem.getItemId());
341
			TagListing tagListing = sdItemAvailabilityMap.get(cartItem.getItemId());
342
			CartItemResponseModel cartItemResponseModel = new CartItemResponseModel();
343
			if (storeItemAvailabilityMap.containsKey(cartItem.getItemId())) {
344
				if (storeItemAvailabilityMap.get(cartItem.getItemId()) >= cartItem.getQuantity()) {
345
					cartItemResponseModel.setEstimate(1);
346
				} else if (tagListing.isActive()) {
347
					cartItemResponseModel.setEstimate(3);
348
				} else {
349
					cartItemResponseModel.setEstimate(-1);
350
				}
351
			}
352
			cartItemResponseModel.setSellingPrice(tagListing.getMop());
353
			cartItemResponseModel.setMaxQuantity(10);
354
			cartItemResponseModel.setCatalogItemId(item.getCatalogItemId());
355
			cartItemResponseModel.setImageUrl(contentMap.get(item.getCatalogItemId()).getString("imageUrl_s"));
356
			cartItemResponseModel.setColor(item.getColor());
357
		}
358
		ValidateCartResponse vc = new ValidateCartResponse(cartResponse, "Success", "Items added to cart successfully");
359
		return responseSender.ok(vc);
360
	}
361
 
362
	@RequestMapping(value = ProfitMandiConstants.URL_UNIT_DEAL, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
363
	@ApiImplicitParams({
364
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
365
	@ApiOperation(value = "Get unit deal object")
366
	public ResponseEntity<?> getUnitDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
367
			throws ProfitMandiBusinessException {
368
		String response = null;
369
		// TODO: move to properties
370
		String uri = "getDealById/" + id;
371
		System.out.println("Unit deal " + uri);
372
		RestClient rc = new RestClient();
373
		Map<String, String> params = new HashMap<>();
374
		DealsResponse dealsResponse = null;
375
		try {
376
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
377
		} catch (HttpHostConnectException e) {
378
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
379
		}
380
 
381
		JsonObject result_json = Json.parse(response).asObject();
382
		if (!result_json.isEmpty()) {
383
			dealsResponse = new Gson().fromJson(response, DealsResponse.class);
384
			Iterator<AvailabilityInfo> iter = dealsResponse.getAvailabilityInfo().iterator();
385
			while (iter.hasNext()) {
386
				AvailabilityInfo ai = iter.next();
387
				if (ai.getAvailability() <= 0)
388
					iter.remove();
389
			}
390
		}
391
		return responseSender.ok(dealsResponse);
392
	}
393
 
394
	@RequestMapping(value = "/partnerdeals/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
395
	@ApiImplicitParams({
396
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
397
	@ApiOperation(value = "Get unit deal object")
398
	public ResponseEntity<?> getUnitFocoDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
399
			throws ProfitMandiBusinessException {
400
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
401
		List<Integer> tagIds = Arrays.asList(4);
402
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
403
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
404
			String categoryId = "(3 OR 6)";
405
			UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
406
			RestClient rc = new RestClient();
407
			Map<String, String> params = new HashMap<>();
408
			List<String> mandatoryQ = new ArrayList<>();
409
			String catalogString = "catalog" + id;
410
 
411
			mandatoryQ.add(String.format("+(categoryId_i:%s) +(id:%s) +{!parent which=\"id:%s\"} tagId_i:(%s)",
412
					categoryId, catalogString, catalogString, StringUtils.join(tagIds, " ")));
413
 
414
			params.put("q", StringUtils.join(mandatoryQ, " "));
415
			params.put("fl", "*, [child parentFilter=id:catalog*]");
416
			params.put("sort", "rank_i asc, create_s desc");
417
			params.put("wt", "json");
418
			String response = null;
419
			try {
420
				response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
421
			} catch (HttpHostConnectException e) {
422
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
423
			}
424
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
425
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
426
			dealResponse = getCatalogResponse(docs, false);
427
		} else {
428
			return responseSender.badRequest(
429
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
430
		}
431
		return responseSender.ok(dealResponse.get(0));
432
	}
433
 
434
	@RequestMapping(value = "/fofo/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
435
	public ResponseEntity<?> getBrandsToDisplay(HttpServletRequest request,
436
			@RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {
437
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
438
		logger.info("userInfo [{}]", userInfo);
439
		List<DBObject> brandsDisplay = mongoClient.getMongoBrands(userInfo.getRetailerId(), userInfo.getEmail(),
440
				categoryId);
441
		return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
442
	}
443
 
444
	@RequestMapping(value = "/fofo/accessory/all-categories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
445
	public ResponseEntity<?> getSubCategoriesToDisplay(HttpServletRequest request) throws Exception {
446
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
447
		logger.info("userInfo [{}]", userInfo);
448
		List<DBObject> subCateogriesDisplay = this.getSubCategoriesToDisplay();
449
		return new ResponseEntity<>(subCateogriesDisplay, HttpStatus.OK);
450
	}
451
 
452
	private List<DBObject> getSubCategoriesToDisplay() throws Exception {
453
		List<DBObject> subCategories = new ArrayList<>();
454
		RestClient rc = new RestClient();
455
		Map<String, String> params = new HashMap<>();
456
		params.put("q", "categoryId_i:6");
457
		params.put("group", "true");
458
		params.put("group.field", "subCategoryId_i");
459
		params.put("wt", "json");
460
		params.put("rows", "50");
461
		params.put("fl", "subCategoryId_i");
462
		String response = null;
463
		try {
464
			response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
465
		} catch (HttpHostConnectException e) {
466
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
467
		}
468
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("grouped");
469
		JSONArray groups = solrResponseJSONObj.getJSONObject("subCategoryId_i").getJSONArray("groups");
470
		List<Integer> categoryIds = new ArrayList<>();
471
		for (int i = 0; i < groups.length(); i++) {
472
			JSONObject groupObject = groups.getJSONObject(i);
473
			int subCategoryId = groupObject.getInt("groupValue");
474
			int quantity = groupObject.getJSONObject("doclist").getInt("numFound");
475
			categoryIds.add(subCategoryId);
476
		}
477
 
478
		List<Category> categories = categoryRepository.selectByIds(categoryIds);
479
		AtomicInteger i = new AtomicInteger(0);
480
		categories.forEach(x -> {
481
			DBObject dbObject = new BasicDBObject();
482
			dbObject.put("name", x.getLabel());
483
			dbObject.put("subCategoryId", x.getId());
484
			dbObject.put("rank", i.incrementAndGet());
485
			dbObject.put("categoryId", 6);
486
			dbObject.put("url", "https://images.smartdukaan.com/uploads/campaigns/" + x.getId() + ".png");
487
			subCategories.add(dbObject);
488
		});
489
 
490
		return subCategories;
491
 
492
	}
493
 
494
	@RequestMapping(value = "/banners/{bannerType}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
495
	public ResponseEntity<?> getBanners(@PathVariable String bannerType) {
496
		return new ResponseEntity<>(mongoClient.getBannersByType(bannerType), HttpStatus.OK);
497
	}
498
 
499
	@RequestMapping(value = "/deals/subCategories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
500
	public ResponseEntity<?> getSubcategoriesToDisplay() {
501
		return new ResponseEntity<>(mongoClient.getSubcategoriesToDisplay(), HttpStatus.OK);
502
	}
503
 
504
	@ApiImplicitParams({
505
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
506
	@RequestMapping(value = "/deals/skus/{skus}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
507
	public ResponseEntity<?> getDealsBySkus(@PathVariable String skus) throws ProfitMandiBusinessException {
508
		StringBuffer sb = new StringBuffer("/getDealsForNotification/");
509
		String uri = sb.append(skus).toString();
510
		RestClient rc = new RestClient();
511
		String response;
512
		try {
513
			response = rc.get(SchemeType.HTTP, host, port, uri, new HashMap<>());
514
		} catch (HttpHostConnectException e) {
515
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
516
		}
517
		JsonArray result_json = Json.parse(response).asArray();
518
		List<Object> responseObject = new ArrayList<>();
519
		for (JsonValue j : result_json) {
520
			// logger.info("res " + j.asArray());
521
			List<Object> innerObject = new ArrayList<>();
522
			for (JsonValue jsonObject : j.asArray()) {
523
				innerObject.add(toDealObject(jsonObject.asObject()));
524
			}
525
			if (innerObject.size() > 0) {
526
				responseObject.add(innerObject);
527
			}
528
		}
529
		return responseSender.ok(responseObject);
530
	}
531
 
532
	private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal)
533
			throws ProfitMandiBusinessException {
534
		Map<Integer, TagListing> itemTagListingMap = null;
535
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
536
		List<Integer> tagIds = Arrays.asList(4);
537
		if (docs.length() > 0) {
538
			HashSet<Integer> itemsSet = new HashSet<>();
539
			for (int i = 0; i < docs.length(); i++) {
540
				JSONObject doc = docs.getJSONObject(i);
541
				if (doc.has("_childDocuments_")) {
542
					for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
543
						JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
544
						int itemId = childItem.getInt("itemId_i");
545
						itemsSet.add(itemId);
546
					}
547
				}
548
			}
549
			if (itemsSet.size() == 0) {
550
				return dealResponse;
551
			}
552
			itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemsSet, new HashSet<>(tagIds)).stream()
553
					.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
554
		}
555
 
556
		for (int i = 0; i < docs.length(); i++) {
557
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
558
			JSONObject doc = docs.getJSONObject(i);
559
			FofoCatalogResponse ffdr = new FofoCatalogResponse();
560
			ffdr.setCatalogId(doc.getInt("catalogId_i"));
561
			ffdr.setImageUrl(doc.getString("imageUrl_s"));
562
			ffdr.setTitle(doc.getString("title_s"));
563
			try {
564
				ffdr.setFeature(doc.getString("feature_s"));
565
			} catch (Exception e) {
566
				ffdr.setFeature(null);
567
				logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
568
			}
569
			ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
570
			if (doc.has("_childDocuments_")) {
571
				for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
572
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
573
					int itemId = childItem.getInt("itemId_i");
574
					TagListing tl = itemTagListingMap.get(itemId);
575
					if (tl == null) {
576
						logger.warn("Could not find item id {}", itemId);
577
						continue;
578
					}
579
					if (hotDeal) {
580
						if (!tl.isHotDeals()) {
581
							continue;
582
						}
583
					}
584
					float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
585
					if (fofoAvailabilityInfoMap.containsKey(itemId)) {
586
						if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
587
							fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
588
							fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
589
						}
590
					} else {
591
						FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
592
						fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
593
						fdi.setMop((float) childItem.getDouble("mop_f"));
594
						fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
595
						fdi.setTagId(childItem.getInt("tagId_i"));
596
						fdi.setItem_id(itemId);
597
						Item item = itemRepository.selectById(itemId);
598
						// In case its tampered glass moq should be 5
599
						if (item.getCategoryId() == 10020) {
600
							fdi.setMinBuyQuantity(10);
601
						} else {
602
							fdi.setMinBuyQuantity(1);
603
						}
604
						if (hotDeal || !tl.isActive()) {
605
 
606
							int totalAvailability = 0; // Using item availability
607
							// cache for now but can be
608
							// changed to
609
							// use caching later.
610
							try {
611
								ItemAvailabilityCache iac = itemAvailabilityCacheRepository.selectByItemId(itemId);
612
								totalAvailability = iac.getTotalAvailability();
613
								fdi.setAvailability(totalAvailability);
614
							} catch (Exception e) {
615
								continue;
616
							}
617
							if (totalAvailability <= 0) {
618
								continue;
619
							}
620
						} else {
621
							// For accessories item availability should at be ordered for Rs.1000
622
							fdi.setAvailability(100);
623
						}
624
						fdi.setQuantityStep(1);
625
						fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
626
						fofoAvailabilityInfoMap.put(itemId, fdi);
627
					}
628
				}
629
			}
630
			if (fofoAvailabilityInfoMap.values().size() > 0) {
631
				ffdr.setItems(new ArrayList<FofoAvailabilityInfo>(fofoAvailabilityInfoMap.values()));
632
				dealResponse.add(ffdr);
633
			}
634
		}
635
		return dealResponse;
636
 
637
	}
638
 
639
	private List<FofoCatalogResponse> getCatalogSingleSkuResponse(JSONArray docs, Map<Integer, Integer> itemFilter,
640
			boolean hotDeal) throws ProfitMandiBusinessException {
641
		Map<Integer, TagListing> itemTagListingMap = null;
642
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
643
		List<Integer> tagIds = Arrays.asList(4);
644
 
645
		itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemFilter.keySet(), new HashSet<>(tagIds))
646
				.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x));
647
 
648
		for (int i = 0; i < docs.length(); i++) {
649
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
650
			JSONObject doc = docs.getJSONObject(i);
651
 
652
			for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
653
				JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
654
				int itemId = childItem.getInt("itemId_i");
655
				TagListing tl = itemTagListingMap.get(itemId);
656
				if (tl == null) {
657
					continue;
658
				}
659
				if (hotDeal) {
660
					if (!tl.isHotDeals()) {
661
						continue;
662
					}
663
				}
664
				float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
665
				if (fofoAvailabilityInfoMap.containsKey(itemId)) {
666
					if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
667
						fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
668
						fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
669
					}
670
				} else {
671
					FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
672
					fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
673
					fdi.setMop((float) childItem.getDouble("mop_f"));
674
					fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
675
					fdi.setTagId(childItem.getInt("tagId_i"));
676
					fdi.setItem_id(itemId);
677
					Item item = itemRepository.selectById(itemId);
678
					// In case its tampered glass moq should be 5
679
					if (item.getCategoryId() == 10020) {
680
						fdi.setMinBuyQuantity(10);
681
					} else {
682
						fdi.setMinBuyQuantity(1);
683
					}
684
					fdi.setAvailability(itemFilter.get(itemId));
685
					fdi.setQuantityStep(1);
686
					fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
687
					fofoAvailabilityInfoMap.put(itemId, fdi);
688
				}
689
			}
690
			if (fofoAvailabilityInfoMap.values().size() > 0) {
691
				for (FofoAvailabilityInfo fofoAvailabilityInfo : fofoAvailabilityInfoMap.values()) {
692
					FofoCatalogResponse ffdr = new FofoCatalogResponse();
693
					ffdr.setCatalogId(doc.getInt("catalogId_i"));
694
					ffdr.setImageUrl(doc.getString("imageUrl_s"));
695
					ffdr.setTitle(doc.getString("title_s"));
696
					try {
697
						ffdr.setFeature(doc.getString("feature_s"));
698
					} catch (Exception e) {
699
						ffdr.setFeature(null);
700
						logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
701
					}
702
					ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
703
					ffdr.setItems(Arrays.asList(fofoAvailabilityInfo));
704
					dealResponse.add(ffdr);
705
				}
706
			}
707
		}
708
		return dealResponse;
709
 
710
	}
711
}