Subversion Repositories SmartDukaan

Rev

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