Subversion Repositories SmartDukaan

Rev

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