Subversion Repositories SmartDukaan

Rev

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