Subversion Repositories SmartDukaan

Rev

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