Subversion Repositories SmartDukaan

Rev

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