Subversion Repositories SmartDukaan

Rev

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