Subversion Repositories SmartDukaan

Rev

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