Subversion Repositories SmartDukaan

Rev

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