Subversion Repositories SmartDukaan

Rev

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