Subversion Repositories SmartDukaan

Rev

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