Subversion Repositories SmartDukaan

Rev

Rev 26654 | Rev 26659 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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