Subversion Repositories SmartDukaan

Rev

Rev 26817 | Rev 26835 | 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());
391
		return responseSender.ok(customerService.addCustomer(customer));
392
	}
393
 
26648 amit.gupta 394
	@RequestMapping(value = "/store/confirmOrder", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
26652 amit.gupta 395
	public ResponseEntity<?> confirmCart(HttpServletRequest request,
396
			@RequestBody CreatePendingOrderRequest createPendingOrderRequest) throws Exception {
26648 amit.gupta 397
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
398
		Integer storeId = userInfo.getRetailerId();
399
		createPendingOrderRequest.setFofoId(storeId);
26652 amit.gupta 400
		this.pendingOrderService.createPendingOrder(createPendingOrderRequest);
26648 amit.gupta 401
		return responseSender.ok(true);
26652 amit.gupta 402
 
26648 amit.gupta 403
	}
26630 amit.gupta 404
 
26651 amit.gupta 405
	@RequestMapping(value = "/store/address", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
26607 amit.gupta 406
	@ApiImplicitParams({
407
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
408
	@ApiOperation(value = "Get brand list and count for category")
26654 amit.gupta 409
	public ResponseEntity<?> getAddress(HttpServletRequest request) throws Exception {
26651 amit.gupta 410
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
411
		Integer storeId = userInfo.getRetailerId();
412
		CustomRetailer customRetailer = retailerService.getFofoRetailer(storeId);
26652 amit.gupta 413
 
26651 amit.gupta 414
		return responseSender.ok(customRetailer.getAddress());
26652 amit.gupta 415
 
26651 amit.gupta 416
	}
26745 amit.gupta 417
 
26715 amit.gupta 418
	@RequestMapping(value = "/store/address/{pincode}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
419
	@ApiImplicitParams({
26745 amit.gupta 420
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
26715 amit.gupta 421
	@ApiOperation(value = "Get brand list and count for category")
26745 amit.gupta 422
	public ResponseEntity<?> getStoresByPincode(HttpServletRequest request, @PathVariable String pincode)
423
			throws Exception {
26715 amit.gupta 424
		List<PincodePartner> pincodePartners = pincodePartnerRepository.selectPartnersByPincode(pincode);
425
		int fofoId = DEFAULT_STORE;
26745 amit.gupta 426
		if (pincodePartners.size() > 0) {
26715 amit.gupta 427
			fofoId = pincodePartners.get(0).getFofoId();
428
		}
26718 amit.gupta 429
		return responseSender.ok(fofoStoreRepository.selectByRetailerId(fofoId).getCode());
26715 amit.gupta 430
	}
26652 amit.gupta 431
 
26745 amit.gupta 432
	@RequestMapping(value = "/store/listing", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
433
	@Cacheable(value = "storelisting.all", cacheManager = "thirtyMinsTimeOutCacheManager")
26774 amit.gupta 434
	public ResponseEntity<?> getStoresListing(HttpServletRequest request) throws Exception {
26745 amit.gupta 435
		List<WebListing> webListings = webListingRepository.selectAllWebListing(Optional.of(true));
436
		for (WebListing webListing : webListings) {
437
			List<Integer> webProducts = webProductListingRepository.selectAllByWebListingId(webListing.getId()).stream()
438
					.filter(x -> x.getRank() > 0).map(x -> x.getEntityId()).collect(Collectors.toList());
439
 
440
			RestClient rc = new RestClient();
441
			Map<String, String> params = new HashMap<>();
442
			List<String> mandatoryQ = new ArrayList<>();
443
			mandatoryQ.add(String.format(
444
					"+{!parent which=\"catalogId_i:" + StringUtils.join(webProducts, " ") + "\"} tagId_i:(%s)",
445
					StringUtils.join(TAG_IDS, " ")));
446
			params.put("q", StringUtils.join(mandatoryQ, " "));
447
			params.put("fl", "*, [child parentFilter=id:catalog*]");
448
			// params.put("sort", "create_s desc");
449
			params.put("start", String.valueOf(0));
450
			params.put("rows", String.valueOf(30));
451
			params.put("wt", "json");
452
			String response = null;
453
			try {
454
				response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
455
			} catch (HttpHostConnectException e) {
456
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
457
			}
458
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
459
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
460
			final Ordering<Integer> colorOrdering = Ordering.explicit(webProducts);
461
			List<FofoCatalogResponse> dealResponse = getCatalogResponse(docs, false).stream()
462
					.sorted(new Comparator<FofoCatalogResponse>() {
463
						@Override
464
						public int compare(FofoCatalogResponse o1, FofoCatalogResponse o2) {
465
							return colorOrdering.compare(o1.getCatalogId(), o2.getCatalogId());
466
						}
467
					}).collect(Collectors.toList());
468
			webListing.setFofoCatalogResponses(dealResponse);
469
		}
470
		return responseSender.ok(webListings);
471
	}
472
 
26652 amit.gupta 473
	@RequestMapping(value = "/store/cart", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
474
	@ApiImplicitParams({
26651 amit.gupta 475
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
26652 amit.gupta 476
	@ApiOperation(value = "Get brand list and count for category")
477
	public ResponseEntity<?> cart(HttpServletRequest request, @RequestBody AddCartRequest cartRequest)
478
			throws Exception {
26607 amit.gupta 479
		CartResponse cartResponse = new CartResponse();
26612 amit.gupta 480
		List<CartItemResponseModel> cartItemResponseModels = new ArrayList<>();
481
		cartResponse.setCartItems(cartItemResponseModels);
26620 amit.gupta 482
 
26607 amit.gupta 483
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
484
		Integer storeId = userInfo.getRetailerId();
485
		List<Integer> itemIds = cartRequest.getCartItems().stream().map(x -> x.getItemId())
486
				.collect(Collectors.toList());
487
		Set<Integer> itemsIdsSet = new HashSet<>(itemIds);
26668 amit.gupta 488
		logger.info("Store Id {}, Item Ids {}", storeId, itemsIdsSet);
26607 amit.gupta 489
		List<CurrentInventorySnapshot> currentInventorySnapshot = currentInventorySnapshotRepository
490
				.selectByFofoItemIds(storeId, itemsIdsSet);
491
		Map<Integer, Integer> storeItemAvailabilityMap = currentInventorySnapshot.stream()
26620 amit.gupta 492
				.filter(x -> x.getAvailability() > 0)
26607 amit.gupta 493
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
494
 
495
		Map<Integer, Item> itemsMap = itemRepository.selectByIds(itemsIdsSet).stream()
496
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
497
 
498
		Map<Integer, TagListing> sdItemAvailabilityMap = tagListingRepository
499
				.selectByItemIdsAndTagIds(new HashSet<>(itemIds), new HashSet<>(Arrays.asList(4))).stream()
500
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
501
 
502
		List<Integer> catalogIds = itemsMap.values().stream().map(x -> x.getCatalogItemId())
503
				.collect(Collectors.toList());
504
 
505
		Map<Integer, JSONObject> contentMap = commonSolrService.getContentByCatalogIds(catalogIds);
506
 
507
		// cartResponse.getCartItems()
508
		for (CartItem cartItem : cartRequest.getCartItems()) {
26620 amit.gupta 509
			if (cartItem.getQuantity() == 0) {
26617 amit.gupta 510
				continue;
511
			}
26607 amit.gupta 512
			Item item = itemsMap.get(cartItem.getItemId());
513
			TagListing tagListing = sdItemAvailabilityMap.get(cartItem.getItemId());
514
			CartItemResponseModel cartItemResponseModel = new CartItemResponseModel();
26628 amit.gupta 515
			int estimate = -2;
26607 amit.gupta 516
			if (storeItemAvailabilityMap.containsKey(cartItem.getItemId())) {
517
				if (storeItemAvailabilityMap.get(cartItem.getItemId()) >= cartItem.getQuantity()) {
26628 amit.gupta 518
					estimate = 0;
26607 amit.gupta 519
				} else if (tagListing.isActive()) {
26628 amit.gupta 520
					estimate = 2;
26607 amit.gupta 521
				} else {
26628 amit.gupta 522
					estimate = -2;
26607 amit.gupta 523
				}
26620 amit.gupta 524
			} else if (tagListing.isActive()) {
26628 amit.gupta 525
				estimate = 2;
26620 amit.gupta 526
			} else {
26628 amit.gupta 527
				estimate = -2;
26607 amit.gupta 528
			}
26630 amit.gupta 529
			if (estimate >= 0 && LocalTime.now().isAfter(CUTOFF_TIME)) {
26628 amit.gupta 530
				estimate = estimate + 1;
531
			}
532
			cartItemResponseModel.setEstimate(estimate);
26616 amit.gupta 533
			cartItemResponseModel.setTitle(item.getItemDescriptionNoColor());
26614 amit.gupta 534
			cartItemResponseModel.setItemId(cartItem.getItemId());
26615 amit.gupta 535
			cartItemResponseModel.setMinBuyQuantity(1);
536
			cartItemResponseModel.setQuantity(cartItem.getQuantity());
26621 amit.gupta 537
			cartItemResponseModel.setQuantityStep(1);
26698 amit.gupta 538
			Float cashback = schemeService.getItemSchemeCashBack().get(cartItem.getItemId());
26701 amit.gupta 539
			cashback = cashback == null ? 0 : cashback;
26698 amit.gupta 540
			cartItemResponseModel.setSellingPrice(tagListing.getMop() - cashback);
26673 amit.gupta 541
			cartItemResponseModel.setMaxQuantity(2);
26607 amit.gupta 542
			cartItemResponseModel.setCatalogItemId(item.getCatalogItemId());
543
			cartItemResponseModel.setImageUrl(contentMap.get(item.getCatalogItemId()).getString("imageUrl_s"));
544
			cartItemResponseModel.setColor(item.getColor());
26620 amit.gupta 545
			cartItemResponseModels.add(cartItemResponseModel);
26607 amit.gupta 546
		}
547
		ValidateCartResponse vc = new ValidateCartResponse(cartResponse, "Success", "Items added to cart successfully");
548
		return responseSender.ok(vc);
549
	}
26652 amit.gupta 550
 
26648 amit.gupta 551
	private boolean validateCart(int storeId, List<CartItem> cartItems) {
552
		return false;
553
	}
26607 amit.gupta 554
 
555
	private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal)
556
			throws ProfitMandiBusinessException {
26683 amit.gupta 557
		Map<Integer, Float> itemCashbackMap = schemeService.getItemSchemeCashBack();
26607 amit.gupta 558
		Map<Integer, TagListing> itemTagListingMap = null;
559
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
560
		List<Integer> tagIds = Arrays.asList(4);
561
		if (docs.length() > 0) {
562
			HashSet<Integer> itemsSet = new HashSet<>();
563
			for (int i = 0; i < docs.length(); i++) {
564
				JSONObject doc = docs.getJSONObject(i);
565
				if (doc.has("_childDocuments_")) {
566
					for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
567
						JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
568
						int itemId = childItem.getInt("itemId_i");
569
						itemsSet.add(itemId);
570
					}
571
				}
572
			}
573
			if (itemsSet.size() == 0) {
574
				return dealResponse;
575
			}
576
			itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemsSet, new HashSet<>(tagIds)).stream()
577
					.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
578
		}
579
 
580
		for (int i = 0; i < docs.length(); i++) {
581
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
582
			JSONObject doc = docs.getJSONObject(i);
583
			FofoCatalogResponse ffdr = new FofoCatalogResponse();
584
			ffdr.setCatalogId(doc.getInt("catalogId_i"));
585
			ffdr.setImageUrl(doc.getString("imageUrl_s"));
586
			ffdr.setTitle(doc.getString("title_s"));
587
			try {
588
				ffdr.setFeature(doc.getString("feature_s"));
589
			} catch (Exception e) {
590
				ffdr.setFeature(null);
591
				logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
592
			}
593
			ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
594
			if (doc.has("_childDocuments_")) {
595
				for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
596
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
597
					int itemId = childItem.getInt("itemId_i");
598
					TagListing tl = itemTagListingMap.get(itemId);
599
					if (tl == null) {
600
						logger.warn("Could not find item id {}", itemId);
601
						continue;
602
					}
603
					if (hotDeal) {
604
						if (!tl.isHotDeals()) {
605
							continue;
606
						}
607
					}
608
					float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
609
					if (fofoAvailabilityInfoMap.containsKey(itemId)) {
610
						if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
611
							fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
612
							fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
613
						}
614
					} else {
615
						FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
26701 amit.gupta 616
						fdi.setCashback(itemCashbackMap.get(itemId) == null ? 0 : itemCashbackMap.get(itemId));
26607 amit.gupta 617
						fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
618
						fdi.setMop((float) childItem.getDouble("mop_f"));
619
						fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
620
						fdi.setTagId(childItem.getInt("tagId_i"));
621
						fdi.setItem_id(itemId);
26700 amit.gupta 622
						fdi.setMrp(tl.getMrp());
26607 amit.gupta 623
						// In case its tampered glass moq should be 5
26673 amit.gupta 624
						fdi.setMinBuyQuantity(1);
26607 amit.gupta 625
						if (hotDeal || !tl.isActive()) {
626
 
627
							int totalAvailability = 0; // Using item availability
628
							// cache for now but can be
629
							// changed to
630
							// use caching later.
631
							try {
632
								ItemAvailabilityCache iac = itemAvailabilityCacheRepository.selectByItemId(itemId);
633
								totalAvailability = iac.getTotalAvailability();
634
								fdi.setAvailability(totalAvailability);
635
							} catch (Exception e) {
636
								continue;
637
							}
638
							if (totalAvailability <= 0) {
639
								continue;
640
							}
641
						} else {
642
							// For accessories item availability should at be ordered for Rs.1000
26673 amit.gupta 643
							fdi.setAvailability(2);
26607 amit.gupta 644
						}
645
						fdi.setQuantityStep(1);
26673 amit.gupta 646
						fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 2));
26607 amit.gupta 647
						fofoAvailabilityInfoMap.put(itemId, fdi);
648
					}
649
				}
650
			}
651
			if (fofoAvailabilityInfoMap.values().size() > 0) {
652
				ffdr.setItems(new ArrayList<FofoAvailabilityInfo>(fofoAvailabilityInfoMap.values()));
653
				dealResponse.add(ffdr);
654
			}
655
		}
656
		return dealResponse;
657
	}
658
 
26833 amit.gupta 659
	@RequestMapping(value = "/store/addresses/{customerId}", method = RequestMethod.GET)
660
	public ResponseEntity<?> getAll(HttpServletRequest request, @PathVariable int customerId) throws Throwable {
26788 amit.gupta 661
		return responseSender.ok(customerAddressRepository.selectByCustomerId(customerId));
662
	}
26833 amit.gupta 663
 
664
	@RequestMapping(value = "/store/address", method = RequestMethod.POST)
665
	public ResponseEntity<?> addAddress(HttpServletRequest request, @RequestBody CustomerAddress customerAddress)
666
			throws Throwable {
26817 amit.gupta 667
		customerAddressRepository.persist(customerAddress);
668
		return responseSender.ok(customerAddress);
669
	}
26788 amit.gupta 670
 
26774 amit.gupta 671
}
672
 
26784 amit.gupta 673
class UserModel {
26833 amit.gupta 674
	@JsonProperty(required = true)
26784 amit.gupta 675
	private String mobile;
26833 amit.gupta 676
	@JsonProperty(required = true)
26784 amit.gupta 677
	private String password;
26833 amit.gupta 678
	@JsonProperty(required = false)
679
	private String firstName;
680
	@JsonProperty(required = false)
681
	private String lastName;
682
	@JsonProperty(required = false)
683
	private String email;
684
 
26784 amit.gupta 685
	@Override
686
	public String toString() {
687
		return "UserModel [mobile=" + mobile + ", password=" + password + "]";
688
	}
26833 amit.gupta 689
 
26784 amit.gupta 690
	public String getMobile() {
691
		return mobile;
692
	}
26833 amit.gupta 693
 
26784 amit.gupta 694
	public void setMobile(String mobile) {
695
		this.mobile = mobile;
696
	}
26833 amit.gupta 697
 
26784 amit.gupta 698
	public String getPassword() {
699
		return password;
700
	}
26833 amit.gupta 701
 
26784 amit.gupta 702
	public void setPassword(String password) {
703
		this.password = password;
704
	}
26833 amit.gupta 705
 
706
	public String getFirstName() {
707
		return firstName;
708
	}
709
 
710
	public void setFirstName(String firstName) {
711
		this.firstName = firstName;
712
	}
713
 
714
	public String getLastName() {
715
		return lastName;
716
	}
717
 
718
	public void setLastName(String lastName) {
719
		this.lastName = lastName;
720
	}
721
 
722
	public String getEmail() {
723
		return email;
724
	}
725
 
726
	public void setEmail(String email) {
727
		this.email = email;
728
	}
729
 
26784 amit.gupta 730
}
731
 
26774 amit.gupta 732
class CustomerModel {
26783 amit.gupta 733
 
26774 amit.gupta 734
	@JsonProperty(required = false)
735
	private Customer customer;
736
	@JsonProperty(required = true)
737
	private boolean exists;
738
 
739
	public CustomerModel(boolean exists, Customer customer) {
740
		super();
741
		this.customer = customer;
742
		this.exists = exists;
743
	}
744
 
745
	@Override
746
	public String toString() {
747
		return "CustomerModel [customer=" + customer + ", exists=" + exists + "]";
748
	}
749
 
750
	public Customer getCustomer() {
751
		return customer;
752
	}
753
 
754
	public void setCustomer(Customer customer) {
755
		this.customer = customer;
756
	}
757
 
758
	public boolean isExists() {
759
		return exists;
760
	}
761
 
762
	public void setExists(boolean exists) {
763
		this.exists = exists;
764
	}
26607 amit.gupta 765
}