Subversion Repositories SmartDukaan

Rev

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