Subversion Repositories SmartDukaan

Rev

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