Subversion Repositories SmartDukaan

Rev

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