Subversion Repositories SmartDukaan

Rev

Rev 26659 | Rev 26662 | 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
 
26659 amit.gupta 138
	private Set<Integer> bestSellers = new HashSet<>(
139
			Arrays.asList(1022090, 1022024, 1022346, 1022337, 1022355, 1022344, 1022343, 1022336, 1021933, 1022025,
140
					1003800, 1022322, 1022307, 1022304, 1022004, 1022004, 1021934, 1021897, 1021768));
26654 amit.gupta 141
 
26659 amit.gupta 142
	private Set<Integer> latestArrivals = new HashSet<>(Arrays.asList(1022382, 1022335, 1022381, 1022386, 1022380,
143
			1022377, 1022376, 1022375, 1022374, 1022373, 1022372, 1022371, 1022370));
26654 amit.gupta 144
 
26607 amit.gupta 145
	@ApiImplicitParams({
146
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
147
	@RequestMapping(value = "/store/fofo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
148
	public ResponseEntity<?> getFofo(HttpServletRequest request,
149
			@RequestParam(value = "categoryId", required = false, defaultValue = "(3 OR 6)") String categoryId,
150
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
151
			@RequestParam(value = "sort", required = false) String sort,
152
			@RequestParam(value = "brand", required = false) String brand,
153
			@RequestParam(value = "subCategoryId", required = false) int subCategoryId,
154
			@RequestParam(value = "q", required = false) String queryTerm,
155
			@RequestParam(value = "hotDeal", required = false) boolean hotDeal) throws Throwable {
156
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
157
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
158
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
159
			// UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
160
			List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(userInfo.getRetailerId());
161
			RestClient rc = new RestClient();
162
			Map<String, String> params = new HashMap<>();
163
			List<String> mandatoryQ = new ArrayList<>();
164
			if (queryTerm != null && !queryTerm.equals("null")) {
165
				mandatoryQ.add(String.format("+(%s)", queryTerm));
166
			} else {
167
				queryTerm = null;
168
			}
169
			if (subCategoryId != 0) {
170
				mandatoryQ
171
						.add(String.format("+(subCategoryId_i:%s) +{!parent which=\"subCategoryId_i:%s\"} tagId_i:(%s)",
172
								subCategoryId, subCategoryId, StringUtils.join(tagIds, " ")));
173
			} else if (hotDeal) {
174
				mandatoryQ.add(String.format("+{!parent which=\"hot_deals_b=true\"} tagId_i:(%s)",
175
						StringUtils.join(tagIds, " ")));
176
 
177
			} else if (StringUtils.isNotBlank(brand)) {
178
				mandatoryQ.add(
179
						String.format("+(categoryId_i:%s) +(brand_ss:%s) +{!parent which=\"brand_ss:%s\"} tagId_i:(%s)",
180
								categoryId, brand, brand, StringUtils.join(tagIds, " ")));
181
 
182
			} else {
183
				mandatoryQ.add(
184
						String.format("+{!parent which=\"id:catalog*\"} tagId_i:(%s)", StringUtils.join(tagIds, " ")));
185
			}
186
			params.put("q", StringUtils.join(mandatoryQ, " "));
187
			params.put("fl", "*, [child parentFilter=id:catalog*]");
188
			if (queryTerm == null) {
189
				params.put("sort", "create_s desc");
190
			}
191
			params.put("start", String.valueOf(offset));
192
			params.put("rows", String.valueOf(limit));
193
			params.put("wt", "json");
194
			String response = null;
195
			try {
196
				response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
197
			} catch (HttpHostConnectException e) {
198
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
199
			}
200
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
201
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
202
			dealResponse = getCatalogResponse(docs, hotDeal);
203
			/*
204
			 * if (Mongo.PARTNER_BLoCKED_BRANDS.containsKey(userInfo.getEmail())) {
205
			 * dealResponse.stream() .filter(x ->
206
			 * Mongo.PARTNER_BLoCKED_BRANDS.get(userInfo.getEmail()).contains(x.getBrand()))
207
			 * ; }
208
			 */
209
		} else {
210
			return responseSender.badRequest(
211
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
212
		}
213
		return responseSender.ok(dealResponse);
214
	}
215
 
216
	private Object toDealObject(JsonObject jsonObject) {
217
		if (jsonObject.get("dealObject") != null && jsonObject.get("dealObject").asInt() == 1) {
218
			return new Gson().fromJson(jsonObject.toString(), DealObjectResponse.class);
219
		}
220
		return new Gson().fromJson(jsonObject.toString(), DealsResponse.class);
221
	}
222
 
223
	@RequestMapping(value = "/store/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
224
	@ApiImplicitParams({
225
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
226
	@ApiOperation(value = "Get brand list and count for category")
227
	public ResponseEntity<?> getBrands(HttpServletRequest request,
228
			@RequestParam(value = "category_id") String category_id) throws ProfitMandiBusinessException {
229
		logger.info("Request " + request.getParameterMap());
230
		String response = null;
231
		// TODO: move to properties
232
		String uri = ProfitMandiConstants.URL_BRANDS;
233
		RestClient rc = new RestClient();
234
		Map<String, String> params = new HashMap<>();
235
		params.put("category_id", category_id);
236
		List<DealBrands> dealBrandsResponse = null;
237
		try {
238
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
239
		} catch (HttpHostConnectException e) {
240
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
241
		}
242
 
243
		dealBrandsResponse = new Gson().fromJson(response, new TypeToken<List<DealBrands>>() {
244
		}.getType());
245
 
246
		return responseSender.ok(dealBrandsResponse);
247
	}
248
 
26654 amit.gupta 249
	@RequestMapping(value = "/store/tag/{tag}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
26660 amit.gupta 250
	public ResponseEntity<?> bestSellers(HttpServletRequest request, @RequestParam String tag) throws Exception {
26654 amit.gupta 251
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
252
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
253
		// UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
254
		List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(userInfo.getRetailerId());
255
		RestClient rc = new RestClient();
256
		Map<String, String> params = new HashMap<>();
257
		List<String> mandatoryQ = new ArrayList<>();
258
		Set<Integer> catalogIds = this.bestSellers;
26658 amit.gupta 259
		if (tag.equalsIgnoreCase("latestArrivals")) {
26654 amit.gupta 260
			catalogIds = this.latestArrivals;
261
		}
262
		mandatoryQ.add(
263
				String.format("+{!parent which=\"catalogId_i:" + StringUtils.join(catalogIds, " ") + "\"} tagId_i:(%s)",
264
						StringUtils.join(tagIds, " ")));
265
		params.put("q", StringUtils.join(mandatoryQ, " "));
266
		params.put("fl", "*, [child parentFilter=id:catalog*]");
267
		// params.put("sort", "create_s desc");
268
		params.put("start", String.valueOf(0));
269
		params.put("rows", String.valueOf(30));
270
		params.put("wt", "json");
271
		String response = null;
272
		try {
273
			response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
274
		} catch (HttpHostConnectException e) {
275
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
276
		}
277
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
278
		JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
279
		dealResponse = getCatalogResponse(docs, false);
280
		return responseSender.ok(dealResponse);
281
	}
282
 
26632 amit.gupta 283
	@RequestMapping(value = "/store/otp/generateOTP", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
26652 amit.gupta 284
	public ResponseEntity<?> generateOtp(HttpServletRequest request, @RequestParam String email,
285
			@RequestParam String phone) throws Exception {
26630 amit.gupta 286
 
287
		return responseSender.ok(otpProcessor.generateOtp(email, phone, OtpType.PREBOOKING_ORDER));
288
 
289
	}
26652 amit.gupta 290
 
26648 amit.gupta 291
	@RequestMapping(value = "/store/confirmOrder", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
26652 amit.gupta 292
	public ResponseEntity<?> confirmCart(HttpServletRequest request,
293
			@RequestBody CreatePendingOrderRequest createPendingOrderRequest) throws Exception {
26648 amit.gupta 294
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
295
		Integer storeId = userInfo.getRetailerId();
296
		createPendingOrderRequest.setFofoId(storeId);
26652 amit.gupta 297
		this.pendingOrderService.createPendingOrder(createPendingOrderRequest);
26648 amit.gupta 298
		return responseSender.ok(true);
26652 amit.gupta 299
 
26648 amit.gupta 300
	}
26630 amit.gupta 301
 
26651 amit.gupta 302
	@RequestMapping(value = "/store/address", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
26607 amit.gupta 303
	@ApiImplicitParams({
304
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
305
	@ApiOperation(value = "Get brand list and count for category")
26654 amit.gupta 306
	public ResponseEntity<?> getAddress(HttpServletRequest request) throws Exception {
26651 amit.gupta 307
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
308
		Integer storeId = userInfo.getRetailerId();
309
		CustomRetailer customRetailer = retailerService.getFofoRetailer(storeId);
26652 amit.gupta 310
 
26651 amit.gupta 311
		return responseSender.ok(customRetailer.getAddress());
26652 amit.gupta 312
 
26651 amit.gupta 313
	}
26652 amit.gupta 314
 
315
	@RequestMapping(value = "/store/cart", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
316
	@ApiImplicitParams({
26651 amit.gupta 317
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
26652 amit.gupta 318
	@ApiOperation(value = "Get brand list and count for category")
319
	public ResponseEntity<?> cart(HttpServletRequest request, @RequestBody AddCartRequest cartRequest)
320
			throws Exception {
26607 amit.gupta 321
		CartResponse cartResponse = new CartResponse();
26612 amit.gupta 322
		List<CartItemResponseModel> cartItemResponseModels = new ArrayList<>();
323
		cartResponse.setCartItems(cartItemResponseModels);
26620 amit.gupta 324
 
26607 amit.gupta 325
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
326
		Integer storeId = userInfo.getRetailerId();
327
		List<Integer> itemIds = cartRequest.getCartItems().stream().map(x -> x.getItemId())
328
				.collect(Collectors.toList());
329
		Set<Integer> itemsIdsSet = new HashSet<>(itemIds);
330
		List<CurrentInventorySnapshot> currentInventorySnapshot = currentInventorySnapshotRepository
331
				.selectByFofoItemIds(storeId, itemsIdsSet);
332
		Map<Integer, Integer> storeItemAvailabilityMap = currentInventorySnapshot.stream()
26620 amit.gupta 333
				.filter(x -> x.getAvailability() > 0)
26607 amit.gupta 334
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
335
 
336
		Map<Integer, Item> itemsMap = itemRepository.selectByIds(itemsIdsSet).stream()
337
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
338
 
339
		Map<Integer, TagListing> sdItemAvailabilityMap = tagListingRepository
340
				.selectByItemIdsAndTagIds(new HashSet<>(itemIds), new HashSet<>(Arrays.asList(4))).stream()
341
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
342
 
343
		List<Integer> catalogIds = itemsMap.values().stream().map(x -> x.getCatalogItemId())
344
				.collect(Collectors.toList());
345
 
346
		Map<Integer, JSONObject> contentMap = commonSolrService.getContentByCatalogIds(catalogIds);
347
 
348
		// cartResponse.getCartItems()
349
		for (CartItem cartItem : cartRequest.getCartItems()) {
26620 amit.gupta 350
			if (cartItem.getQuantity() == 0) {
26617 amit.gupta 351
				continue;
352
			}
26607 amit.gupta 353
			Item item = itemsMap.get(cartItem.getItemId());
354
			TagListing tagListing = sdItemAvailabilityMap.get(cartItem.getItemId());
355
			CartItemResponseModel cartItemResponseModel = new CartItemResponseModel();
26628 amit.gupta 356
			int estimate = -2;
26607 amit.gupta 357
			if (storeItemAvailabilityMap.containsKey(cartItem.getItemId())) {
358
				if (storeItemAvailabilityMap.get(cartItem.getItemId()) >= cartItem.getQuantity()) {
26628 amit.gupta 359
					estimate = 0;
26607 amit.gupta 360
				} else if (tagListing.isActive()) {
26628 amit.gupta 361
					estimate = 2;
26607 amit.gupta 362
				} else {
26628 amit.gupta 363
					estimate = -2;
26607 amit.gupta 364
				}
26620 amit.gupta 365
			} else if (tagListing.isActive()) {
26628 amit.gupta 366
				estimate = 2;
26620 amit.gupta 367
			} else {
26628 amit.gupta 368
				estimate = -2;
26607 amit.gupta 369
			}
26630 amit.gupta 370
			if (estimate >= 0 && LocalTime.now().isAfter(CUTOFF_TIME)) {
26628 amit.gupta 371
				estimate = estimate + 1;
372
			}
373
			cartItemResponseModel.setEstimate(estimate);
26616 amit.gupta 374
			cartItemResponseModel.setTitle(item.getItemDescriptionNoColor());
26614 amit.gupta 375
			cartItemResponseModel.setItemId(cartItem.getItemId());
26615 amit.gupta 376
			cartItemResponseModel.setMinBuyQuantity(1);
377
			cartItemResponseModel.setQuantity(cartItem.getQuantity());
26621 amit.gupta 378
			cartItemResponseModel.setQuantityStep(1);
26607 amit.gupta 379
			cartItemResponseModel.setSellingPrice(tagListing.getMop());
380
			cartItemResponseModel.setMaxQuantity(10);
381
			cartItemResponseModel.setCatalogItemId(item.getCatalogItemId());
382
			cartItemResponseModel.setImageUrl(contentMap.get(item.getCatalogItemId()).getString("imageUrl_s"));
383
			cartItemResponseModel.setColor(item.getColor());
26620 amit.gupta 384
			cartItemResponseModels.add(cartItemResponseModel);
26607 amit.gupta 385
		}
386
		ValidateCartResponse vc = new ValidateCartResponse(cartResponse, "Success", "Items added to cart successfully");
387
		return responseSender.ok(vc);
388
	}
26652 amit.gupta 389
 
26648 amit.gupta 390
	private boolean validateCart(int storeId, List<CartItem> cartItems) {
391
		return false;
392
	}
26607 amit.gupta 393
 
394
	private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal)
395
			throws ProfitMandiBusinessException {
396
		Map<Integer, TagListing> itemTagListingMap = null;
397
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
398
		List<Integer> tagIds = Arrays.asList(4);
399
		if (docs.length() > 0) {
400
			HashSet<Integer> itemsSet = new HashSet<>();
401
			for (int i = 0; i < docs.length(); i++) {
402
				JSONObject doc = docs.getJSONObject(i);
403
				if (doc.has("_childDocuments_")) {
404
					for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
405
						JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
406
						int itemId = childItem.getInt("itemId_i");
407
						itemsSet.add(itemId);
408
					}
409
				}
410
			}
411
			if (itemsSet.size() == 0) {
412
				return dealResponse;
413
			}
414
			itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemsSet, new HashSet<>(tagIds)).stream()
415
					.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
416
		}
417
 
418
		for (int i = 0; i < docs.length(); i++) {
419
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
420
			JSONObject doc = docs.getJSONObject(i);
421
			FofoCatalogResponse ffdr = new FofoCatalogResponse();
422
			ffdr.setCatalogId(doc.getInt("catalogId_i"));
423
			ffdr.setImageUrl(doc.getString("imageUrl_s"));
424
			ffdr.setTitle(doc.getString("title_s"));
425
			try {
426
				ffdr.setFeature(doc.getString("feature_s"));
427
			} catch (Exception e) {
428
				ffdr.setFeature(null);
429
				logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
430
			}
431
			ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
432
			if (doc.has("_childDocuments_")) {
433
				for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
434
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
435
					int itemId = childItem.getInt("itemId_i");
436
					TagListing tl = itemTagListingMap.get(itemId);
437
					if (tl == null) {
438
						logger.warn("Could not find item id {}", itemId);
439
						continue;
440
					}
441
					if (hotDeal) {
442
						if (!tl.isHotDeals()) {
443
							continue;
444
						}
445
					}
446
					float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
447
					if (fofoAvailabilityInfoMap.containsKey(itemId)) {
448
						if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
449
							fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
450
							fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
451
						}
452
					} else {
453
						FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
454
						fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
455
						fdi.setMop((float) childItem.getDouble("mop_f"));
456
						fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
457
						fdi.setTagId(childItem.getInt("tagId_i"));
458
						fdi.setItem_id(itemId);
459
						Item item = itemRepository.selectById(itemId);
460
						// In case its tampered glass moq should be 5
461
						if (item.getCategoryId() == 10020) {
462
							fdi.setMinBuyQuantity(10);
463
						} else {
464
							fdi.setMinBuyQuantity(1);
465
						}
466
						if (hotDeal || !tl.isActive()) {
467
 
468
							int totalAvailability = 0; // Using item availability
469
							// cache for now but can be
470
							// changed to
471
							// use caching later.
472
							try {
473
								ItemAvailabilityCache iac = itemAvailabilityCacheRepository.selectByItemId(itemId);
474
								totalAvailability = iac.getTotalAvailability();
475
								fdi.setAvailability(totalAvailability);
476
							} catch (Exception e) {
477
								continue;
478
							}
479
							if (totalAvailability <= 0) {
480
								continue;
481
							}
482
						} else {
483
							// For accessories item availability should at be ordered for Rs.1000
484
							fdi.setAvailability(100);
485
						}
486
						fdi.setQuantityStep(1);
487
						fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
488
						fofoAvailabilityInfoMap.put(itemId, fdi);
489
					}
490
				}
491
			}
492
			if (fofoAvailabilityInfoMap.values().size() > 0) {
493
				ffdr.setItems(new ArrayList<FofoAvailabilityInfo>(fofoAvailabilityInfoMap.values()));
494
				dealResponse.add(ffdr);
495
			}
496
		}
497
		return dealResponse;
498
 
499
	}
500
 
501
}