Subversion Repositories SmartDukaan

Rev

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