Subversion Repositories SmartDukaan

Rev

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