Subversion Repositories SmartDukaan

Rev

Rev 26660 | Rev 26666 | 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;
26662 amit.gupta 27
import org.springframework.web.bind.annotation.PathVariable;
26607 amit.gupta 28
import org.springframework.web.bind.annotation.RequestBody;
29
import org.springframework.web.bind.annotation.RequestMapping;
30
import org.springframework.web.bind.annotation.RequestMethod;
31
import org.springframework.web.bind.annotation.RequestParam;
32
 
33
import com.eclipsesource.json.JsonObject;
34
import com.google.gson.Gson;
35
import com.google.gson.reflect.TypeToken;
36
import com.spice.profitmandi.common.enumuration.SchemeType;
37
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
26648 amit.gupta 38
import com.spice.profitmandi.common.model.CreatePendingOrderRequest;
26651 amit.gupta 39
import com.spice.profitmandi.common.model.CustomRetailer;
26607 amit.gupta 40
import com.spice.profitmandi.common.model.ProfitMandiConstants;
41
import com.spice.profitmandi.common.model.UserInfo;
42
import com.spice.profitmandi.common.solr.SolrService;
43
import com.spice.profitmandi.common.web.client.RestClient;
44
import com.spice.profitmandi.common.web.util.ResponseSender;
45
import com.spice.profitmandi.dao.entity.catalog.Item;
46
import com.spice.profitmandi.dao.entity.catalog.TagListing;
47
import com.spice.profitmandi.dao.entity.fofo.CurrentInventorySnapshot;
48
import com.spice.profitmandi.dao.entity.inventory.ItemAvailabilityCache;
26630 amit.gupta 49
import com.spice.profitmandi.dao.enumuration.dtr.OtpType;
26607 amit.gupta 50
import com.spice.profitmandi.dao.model.AddCartRequest;
51
import com.spice.profitmandi.dao.model.CartItem;
52
import com.spice.profitmandi.dao.model.CartItemResponseModel;
53
import com.spice.profitmandi.dao.model.CartResponse;
54
import com.spice.profitmandi.dao.repository.catalog.CategoryRepository;
55
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
56
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
57
import com.spice.profitmandi.dao.repository.dtr.Mongo;
58
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
59
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
26648 amit.gupta 60
import com.spice.profitmandi.dao.repository.fofo.PendingOrderService;
26607 amit.gupta 61
import com.spice.profitmandi.dao.repository.inventory.ItemAvailabilityCacheRepository;
62
import com.spice.profitmandi.service.authentication.RoleManager;
63
import com.spice.profitmandi.service.inventory.FofoAvailabilityInfo;
64
import com.spice.profitmandi.service.inventory.FofoCatalogResponse;
65
import com.spice.profitmandi.service.pricing.PricingService;
26651 amit.gupta 66
import com.spice.profitmandi.service.user.RetailerService;
26630 amit.gupta 67
import com.spice.profitmandi.web.processor.OtpProcessor;
26607 amit.gupta 68
import com.spice.profitmandi.web.res.DealBrands;
69
import com.spice.profitmandi.web.res.DealObjectResponse;
70
import com.spice.profitmandi.web.res.DealsResponse;
71
import com.spice.profitmandi.web.res.ValidateCartResponse;
72
 
73
import io.swagger.annotations.ApiImplicitParam;
74
import io.swagger.annotations.ApiImplicitParams;
75
import io.swagger.annotations.ApiOperation;
76
 
77
@Controller
78
@Transactional(rollbackFor = Throwable.class)
79
public class StoreController {
80
 
81
	private static final Logger logger = LogManager.getLogger(StoreController.class);
26630 amit.gupta 82
 
26628 amit.gupta 83
	private static final LocalTime CUTOFF_TIME = LocalTime.of(15, 0);
26607 amit.gupta 84
 
85
	@Value("${python.api.host}")
86
	private String host;
87
 
88
	@Value("${python.api.port}")
89
	private int port;
90
 
91
	// This is now unused as we are not supporting multiple companies.
92
	@Value("${gadgetCops.invoice.cc}")
93
	private String[] ccGadgetCopInvoiceTo;
94
 
95
	@Autowired
96
	private PricingService pricingService;
97
 
98
	@Autowired
26651 amit.gupta 99
	private RetailerService retailerService;
26652 amit.gupta 100
 
26651 amit.gupta 101
	@Autowired
26652 amit.gupta 102
	private PendingOrderService pendingOrderService;
26648 amit.gupta 103
 
104
	@Autowired
26607 amit.gupta 105
	private CategoryRepository categoryRepository;
106
 
107
	@Autowired
108
	private SolrService commonSolrService;
109
 
110
	@Autowired
111
	private Mongo mongoClient;
112
 
113
	@Autowired
26630 amit.gupta 114
	private OtpProcessor otpProcessor;
115
 
116
	@Autowired
26607 amit.gupta 117
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
118
 
26609 amit.gupta 119
	@Autowired
26607 amit.gupta 120
	private UserAccountRepository userAccountRepository;
121
 
122
	@Autowired
123
	private ResponseSender<?> responseSender;
124
 
125
	@Autowired
126
	private TagListingRepository tagListingRepository;
127
 
128
	@Autowired
129
	private ItemRepository itemRepository;
130
 
131
	@Autowired
132
	private ItemAvailabilityCacheRepository itemAvailabilityCacheRepository;
133
 
134
	@Autowired
135
	private RoleManager roleManagerService;
136
 
137
	List<String> filterableParams = Arrays.asList("brand");
138
 
26659 amit.gupta 139
	private Set<Integer> bestSellers = new HashSet<>(
140
			Arrays.asList(1022090, 1022024, 1022346, 1022337, 1022355, 1022344, 1022343, 1022336, 1021933, 1022025,
141
					1003800, 1022322, 1022307, 1022304, 1022004, 1022004, 1021934, 1021897, 1021768));
26654 amit.gupta 142
 
26659 amit.gupta 143
	private Set<Integer> latestArrivals = new HashSet<>(Arrays.asList(1022382, 1022335, 1022381, 1022386, 1022380,
144
			1022377, 1022376, 1022375, 1022374, 1022373, 1022372, 1022371, 1022370));
26654 amit.gupta 145
 
26607 amit.gupta 146
	@ApiImplicitParams({
147
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
148
	@RequestMapping(value = "/store/fofo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
149
	public ResponseEntity<?> getFofo(HttpServletRequest request,
150
			@RequestParam(value = "categoryId", required = false, defaultValue = "(3 OR 6)") String categoryId,
151
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
152
			@RequestParam(value = "sort", required = false) String sort,
153
			@RequestParam(value = "brand", required = false) String brand,
154
			@RequestParam(value = "subCategoryId", required = false) int subCategoryId,
155
			@RequestParam(value = "q", required = false) String queryTerm,
156
			@RequestParam(value = "hotDeal", required = false) boolean hotDeal) throws Throwable {
157
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
158
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
159
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
160
			// UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
161
			List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(userInfo.getRetailerId());
162
			RestClient rc = new RestClient();
163
			Map<String, String> params = new HashMap<>();
164
			List<String> mandatoryQ = new ArrayList<>();
165
			if (queryTerm != null && !queryTerm.equals("null")) {
166
				mandatoryQ.add(String.format("+(%s)", queryTerm));
167
			} else {
168
				queryTerm = null;
169
			}
170
			if (subCategoryId != 0) {
171
				mandatoryQ
172
						.add(String.format("+(subCategoryId_i:%s) +{!parent which=\"subCategoryId_i:%s\"} tagId_i:(%s)",
173
								subCategoryId, subCategoryId, StringUtils.join(tagIds, " ")));
174
			} else if (hotDeal) {
175
				mandatoryQ.add(String.format("+{!parent which=\"hot_deals_b=true\"} tagId_i:(%s)",
176
						StringUtils.join(tagIds, " ")));
177
 
178
			} else if (StringUtils.isNotBlank(brand)) {
179
				mandatoryQ.add(
180
						String.format("+(categoryId_i:%s) +(brand_ss:%s) +{!parent which=\"brand_ss:%s\"} tagId_i:(%s)",
181
								categoryId, brand, brand, StringUtils.join(tagIds, " ")));
182
 
183
			} else {
184
				mandatoryQ.add(
185
						String.format("+{!parent which=\"id:catalog*\"} tagId_i:(%s)", StringUtils.join(tagIds, " ")));
186
			}
187
			params.put("q", StringUtils.join(mandatoryQ, " "));
188
			params.put("fl", "*, [child parentFilter=id:catalog*]");
189
			if (queryTerm == null) {
190
				params.put("sort", "create_s desc");
191
			}
192
			params.put("start", String.valueOf(offset));
193
			params.put("rows", String.valueOf(limit));
194
			params.put("wt", "json");
195
			String response = null;
196
			try {
197
				response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
198
			} catch (HttpHostConnectException e) {
199
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
200
			}
201
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
202
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
203
			dealResponse = getCatalogResponse(docs, hotDeal);
204
			/*
205
			 * if (Mongo.PARTNER_BLoCKED_BRANDS.containsKey(userInfo.getEmail())) {
206
			 * dealResponse.stream() .filter(x ->
207
			 * Mongo.PARTNER_BLoCKED_BRANDS.get(userInfo.getEmail()).contains(x.getBrand()))
208
			 * ; }
209
			 */
210
		} else {
211
			return responseSender.badRequest(
212
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
213
		}
214
		return responseSender.ok(dealResponse);
215
	}
216
 
217
	private Object toDealObject(JsonObject jsonObject) {
218
		if (jsonObject.get("dealObject") != null && jsonObject.get("dealObject").asInt() == 1) {
219
			return new Gson().fromJson(jsonObject.toString(), DealObjectResponse.class);
220
		}
221
		return new Gson().fromJson(jsonObject.toString(), DealsResponse.class);
222
	}
223
 
224
	@RequestMapping(value = "/store/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
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<?> getBrands(HttpServletRequest request,
229
			@RequestParam(value = "category_id") String category_id) throws ProfitMandiBusinessException {
230
		logger.info("Request " + request.getParameterMap());
231
		String response = null;
232
		// TODO: move to properties
233
		String uri = ProfitMandiConstants.URL_BRANDS;
234
		RestClient rc = new RestClient();
235
		Map<String, String> params = new HashMap<>();
236
		params.put("category_id", category_id);
237
		List<DealBrands> dealBrandsResponse = null;
238
		try {
239
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
240
		} catch (HttpHostConnectException e) {
241
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
242
		}
243
 
244
		dealBrandsResponse = new Gson().fromJson(response, new TypeToken<List<DealBrands>>() {
245
		}.getType());
246
 
247
		return responseSender.ok(dealBrandsResponse);
248
	}
249
 
26654 amit.gupta 250
	@RequestMapping(value = "/store/tag/{tag}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
26662 amit.gupta 251
	public ResponseEntity<?> bestSellers(HttpServletRequest request, @PathVariable String tag) throws Exception {
26654 amit.gupta 252
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
253
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
254
		// UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
255
		List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(userInfo.getRetailerId());
256
		RestClient rc = new RestClient();
257
		Map<String, String> params = new HashMap<>();
258
		List<String> mandatoryQ = new ArrayList<>();
259
		Set<Integer> catalogIds = this.bestSellers;
26658 amit.gupta 260
		if (tag.equalsIgnoreCase("latestArrivals")) {
26654 amit.gupta 261
			catalogIds = this.latestArrivals;
262
		}
263
		mandatoryQ.add(
264
				String.format("+{!parent which=\"catalogId_i:" + StringUtils.join(catalogIds, " ") + "\"} tagId_i:(%s)",
265
						StringUtils.join(tagIds, " ")));
266
		params.put("q", StringUtils.join(mandatoryQ, " "));
267
		params.put("fl", "*, [child parentFilter=id:catalog*]");
268
		// params.put("sort", "create_s desc");
269
		params.put("start", String.valueOf(0));
270
		params.put("rows", String.valueOf(30));
271
		params.put("wt", "json");
272
		String response = null;
273
		try {
274
			response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
275
		} catch (HttpHostConnectException e) {
276
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
277
		}
278
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
279
		JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
280
		dealResponse = getCatalogResponse(docs, false);
281
		return responseSender.ok(dealResponse);
282
	}
283
 
26632 amit.gupta 284
	@RequestMapping(value = "/store/otp/generateOTP", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
26652 amit.gupta 285
	public ResponseEntity<?> generateOtp(HttpServletRequest request, @RequestParam String email,
286
			@RequestParam String phone) throws Exception {
26630 amit.gupta 287
 
288
		return responseSender.ok(otpProcessor.generateOtp(email, phone, OtpType.PREBOOKING_ORDER));
289
 
290
	}
26652 amit.gupta 291
 
26648 amit.gupta 292
	@RequestMapping(value = "/store/confirmOrder", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
26652 amit.gupta 293
	public ResponseEntity<?> confirmCart(HttpServletRequest request,
294
			@RequestBody CreatePendingOrderRequest createPendingOrderRequest) throws Exception {
26648 amit.gupta 295
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
296
		Integer storeId = userInfo.getRetailerId();
297
		createPendingOrderRequest.setFofoId(storeId);
26652 amit.gupta 298
		this.pendingOrderService.createPendingOrder(createPendingOrderRequest);
26648 amit.gupta 299
		return responseSender.ok(true);
26652 amit.gupta 300
 
26648 amit.gupta 301
	}
26630 amit.gupta 302
 
26651 amit.gupta 303
	@RequestMapping(value = "/store/address", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
26607 amit.gupta 304
	@ApiImplicitParams({
305
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
306
	@ApiOperation(value = "Get brand list and count for category")
26654 amit.gupta 307
	public ResponseEntity<?> getAddress(HttpServletRequest request) throws Exception {
26651 amit.gupta 308
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
309
		Integer storeId = userInfo.getRetailerId();
310
		CustomRetailer customRetailer = retailerService.getFofoRetailer(storeId);
26652 amit.gupta 311
 
26651 amit.gupta 312
		return responseSender.ok(customRetailer.getAddress());
26652 amit.gupta 313
 
26651 amit.gupta 314
	}
26652 amit.gupta 315
 
316
	@RequestMapping(value = "/store/cart", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
317
	@ApiImplicitParams({
26651 amit.gupta 318
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
26652 amit.gupta 319
	@ApiOperation(value = "Get brand list and count for category")
320
	public ResponseEntity<?> cart(HttpServletRequest request, @RequestBody AddCartRequest cartRequest)
321
			throws Exception {
26607 amit.gupta 322
		CartResponse cartResponse = new CartResponse();
26612 amit.gupta 323
		List<CartItemResponseModel> cartItemResponseModels = new ArrayList<>();
324
		cartResponse.setCartItems(cartItemResponseModels);
26620 amit.gupta 325
 
26607 amit.gupta 326
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
327
		Integer storeId = userInfo.getRetailerId();
328
		List<Integer> itemIds = cartRequest.getCartItems().stream().map(x -> x.getItemId())
329
				.collect(Collectors.toList());
330
		Set<Integer> itemsIdsSet = new HashSet<>(itemIds);
331
		List<CurrentInventorySnapshot> currentInventorySnapshot = currentInventorySnapshotRepository
332
				.selectByFofoItemIds(storeId, itemsIdsSet);
333
		Map<Integer, Integer> storeItemAvailabilityMap = currentInventorySnapshot.stream()
26620 amit.gupta 334
				.filter(x -> x.getAvailability() > 0)
26607 amit.gupta 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()) {
26620 amit.gupta 351
			if (cartItem.getQuantity() == 0) {
26617 amit.gupta 352
				continue;
353
			}
26607 amit.gupta 354
			Item item = itemsMap.get(cartItem.getItemId());
355
			TagListing tagListing = sdItemAvailabilityMap.get(cartItem.getItemId());
356
			CartItemResponseModel cartItemResponseModel = new CartItemResponseModel();
26628 amit.gupta 357
			int estimate = -2;
26607 amit.gupta 358
			if (storeItemAvailabilityMap.containsKey(cartItem.getItemId())) {
359
				if (storeItemAvailabilityMap.get(cartItem.getItemId()) >= cartItem.getQuantity()) {
26628 amit.gupta 360
					estimate = 0;
26607 amit.gupta 361
				} else if (tagListing.isActive()) {
26628 amit.gupta 362
					estimate = 2;
26607 amit.gupta 363
				} else {
26628 amit.gupta 364
					estimate = -2;
26607 amit.gupta 365
				}
26620 amit.gupta 366
			} else if (tagListing.isActive()) {
26628 amit.gupta 367
				estimate = 2;
26620 amit.gupta 368
			} else {
26628 amit.gupta 369
				estimate = -2;
26607 amit.gupta 370
			}
26630 amit.gupta 371
			if (estimate >= 0 && LocalTime.now().isAfter(CUTOFF_TIME)) {
26628 amit.gupta 372
				estimate = estimate + 1;
373
			}
374
			cartItemResponseModel.setEstimate(estimate);
26616 amit.gupta 375
			cartItemResponseModel.setTitle(item.getItemDescriptionNoColor());
26614 amit.gupta 376
			cartItemResponseModel.setItemId(cartItem.getItemId());
26615 amit.gupta 377
			cartItemResponseModel.setMinBuyQuantity(1);
378
			cartItemResponseModel.setQuantity(cartItem.getQuantity());
26621 amit.gupta 379
			cartItemResponseModel.setQuantityStep(1);
26607 amit.gupta 380
			cartItemResponseModel.setSellingPrice(tagListing.getMop());
381
			cartItemResponseModel.setMaxQuantity(10);
382
			cartItemResponseModel.setCatalogItemId(item.getCatalogItemId());
383
			cartItemResponseModel.setImageUrl(contentMap.get(item.getCatalogItemId()).getString("imageUrl_s"));
384
			cartItemResponseModel.setColor(item.getColor());
26620 amit.gupta 385
			cartItemResponseModels.add(cartItemResponseModel);
26607 amit.gupta 386
		}
387
		ValidateCartResponse vc = new ValidateCartResponse(cartResponse, "Success", "Items added to cart successfully");
388
		return responseSender.ok(vc);
389
	}
26652 amit.gupta 390
 
26648 amit.gupta 391
	private boolean validateCart(int storeId, List<CartItem> cartItems) {
392
		return false;
393
	}
26607 amit.gupta 394
 
395
	private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal)
396
			throws ProfitMandiBusinessException {
397
		Map<Integer, TagListing> itemTagListingMap = null;
398
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
399
		List<Integer> tagIds = Arrays.asList(4);
400
		if (docs.length() > 0) {
401
			HashSet<Integer> itemsSet = new HashSet<>();
402
			for (int i = 0; i < docs.length(); i++) {
403
				JSONObject doc = docs.getJSONObject(i);
404
				if (doc.has("_childDocuments_")) {
405
					for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
406
						JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
407
						int itemId = childItem.getInt("itemId_i");
408
						itemsSet.add(itemId);
409
					}
410
				}
411
			}
412
			if (itemsSet.size() == 0) {
413
				return dealResponse;
414
			}
415
			itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemsSet, new HashSet<>(tagIds)).stream()
416
					.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
417
		}
418
 
419
		for (int i = 0; i < docs.length(); i++) {
420
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
421
			JSONObject doc = docs.getJSONObject(i);
422
			FofoCatalogResponse ffdr = new FofoCatalogResponse();
423
			ffdr.setCatalogId(doc.getInt("catalogId_i"));
424
			ffdr.setImageUrl(doc.getString("imageUrl_s"));
425
			ffdr.setTitle(doc.getString("title_s"));
426
			try {
427
				ffdr.setFeature(doc.getString("feature_s"));
428
			} catch (Exception e) {
429
				ffdr.setFeature(null);
430
				logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
431
			}
432
			ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
433
			if (doc.has("_childDocuments_")) {
434
				for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
435
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
436
					int itemId = childItem.getInt("itemId_i");
437
					TagListing tl = itemTagListingMap.get(itemId);
438
					if (tl == null) {
439
						logger.warn("Could not find item id {}", itemId);
440
						continue;
441
					}
442
					if (hotDeal) {
443
						if (!tl.isHotDeals()) {
444
							continue;
445
						}
446
					}
447
					float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
448
					if (fofoAvailabilityInfoMap.containsKey(itemId)) {
449
						if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
450
							fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
451
							fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
452
						}
453
					} else {
454
						FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
455
						fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
456
						fdi.setMop((float) childItem.getDouble("mop_f"));
457
						fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
458
						fdi.setTagId(childItem.getInt("tagId_i"));
459
						fdi.setItem_id(itemId);
460
						Item item = itemRepository.selectById(itemId);
461
						// In case its tampered glass moq should be 5
462
						if (item.getCategoryId() == 10020) {
463
							fdi.setMinBuyQuantity(10);
464
						} else {
465
							fdi.setMinBuyQuantity(1);
466
						}
467
						if (hotDeal || !tl.isActive()) {
468
 
469
							int totalAvailability = 0; // Using item availability
470
							// cache for now but can be
471
							// changed to
472
							// use caching later.
473
							try {
474
								ItemAvailabilityCache iac = itemAvailabilityCacheRepository.selectByItemId(itemId);
475
								totalAvailability = iac.getTotalAvailability();
476
								fdi.setAvailability(totalAvailability);
477
							} catch (Exception e) {
478
								continue;
479
							}
480
							if (totalAvailability <= 0) {
481
								continue;
482
							}
483
						} else {
484
							// For accessories item availability should at be ordered for Rs.1000
485
							fdi.setAvailability(100);
486
						}
487
						fdi.setQuantityStep(1);
488
						fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
489
						fofoAvailabilityInfoMap.put(itemId, fdi);
490
					}
491
				}
492
			}
493
			if (fofoAvailabilityInfoMap.values().size() > 0) {
494
				ffdr.setItems(new ArrayList<FofoAvailabilityInfo>(fofoAvailabilityInfoMap.values()));
495
				dealResponse.add(ffdr);
496
			}
497
		}
498
		return dealResponse;
499
 
500
	}
501
 
502
}