Subversion Repositories SmartDukaan

Rev

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