Subversion Repositories SmartDukaan

Rev

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