Subversion Repositories SmartDukaan

Rev

Rev 27028 | Rev 27045 | 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
 
27028 tejbeer 3
import java.io.StringWriter;
27025 tejbeer 4
import java.time.LocalDateTime;
26628 amit.gupta 5
import java.time.LocalTime;
26607 amit.gupta 6
import java.util.ArrayList;
7
import java.util.Arrays;
26745 amit.gupta 8
import java.util.Comparator;
26607 amit.gupta 9
import java.util.HashMap;
10
import java.util.HashSet;
11
import java.util.List;
12
import java.util.Map;
26745 amit.gupta 13
import java.util.Optional;
26607 amit.gupta 14
import java.util.Set;
15
import java.util.stream.Collectors;
16
 
27028 tejbeer 17
import javax.mail.internet.InternetAddress;
18
import javax.mail.internet.MimeMessage;
26607 amit.gupta 19
import javax.servlet.http.HttpServletRequest;
20
 
21
import org.apache.commons.lang3.StringUtils;
22
import org.apache.http.conn.HttpHostConnectException;
23
import org.apache.logging.log4j.LogManager;
24
import org.apache.logging.log4j.Logger;
27028 tejbeer 25
import org.apache.velocity.Template;
26
import org.apache.velocity.VelocityContext;
27
import org.apache.velocity.app.VelocityEngine;
26607 amit.gupta 28
import org.json.JSONArray;
29
import org.json.JSONObject;
30
import org.springframework.beans.factory.annotation.Autowired;
31
import org.springframework.beans.factory.annotation.Value;
26745 amit.gupta 32
import org.springframework.cache.annotation.Cacheable;
26607 amit.gupta 33
import org.springframework.http.MediaType;
34
import org.springframework.http.ResponseEntity;
27028 tejbeer 35
import org.springframework.mail.javamail.JavaMailSender;
36
import org.springframework.mail.javamail.MimeMessageHelper;
26607 amit.gupta 37
import org.springframework.stereotype.Controller;
38
import org.springframework.transaction.annotation.Transactional;
26923 amit.gupta 39
import org.springframework.web.bind.annotation.GetMapping;
26662 amit.gupta 40
import org.springframework.web.bind.annotation.PathVariable;
26607 amit.gupta 41
import org.springframework.web.bind.annotation.RequestBody;
42
import org.springframework.web.bind.annotation.RequestMapping;
43
import org.springframework.web.bind.annotation.RequestMethod;
44
import org.springframework.web.bind.annotation.RequestParam;
45
 
46
import com.eclipsesource.json.JsonObject;
26774 amit.gupta 47
import com.fasterxml.jackson.annotation.JsonProperty;
26745 amit.gupta 48
import com.google.common.collect.Ordering;
26607 amit.gupta 49
import com.google.gson.Gson;
50
import com.google.gson.reflect.TypeToken;
51
import com.spice.profitmandi.common.enumuration.SchemeType;
52
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
26923 amit.gupta 53
import com.spice.profitmandi.common.model.CreatePendingOrderItem;
26648 amit.gupta 54
import com.spice.profitmandi.common.model.CreatePendingOrderRequest;
26651 amit.gupta 55
import com.spice.profitmandi.common.model.CustomRetailer;
26855 tejbeer 56
import com.spice.profitmandi.common.model.CustomerOrderDetail;
26607 amit.gupta 57
import com.spice.profitmandi.common.model.ProfitMandiConstants;
58
import com.spice.profitmandi.common.model.UserInfo;
59
import com.spice.profitmandi.common.solr.SolrService;
60
import com.spice.profitmandi.common.web.client.RestClient;
61
import com.spice.profitmandi.common.web.util.ResponseSender;
62
import com.spice.profitmandi.dao.entity.catalog.Item;
63
import com.spice.profitmandi.dao.entity.catalog.TagListing;
26745 amit.gupta 64
import com.spice.profitmandi.dao.entity.dtr.WebListing;
26774 amit.gupta 65
import com.spice.profitmandi.dao.entity.fofo.Customer;
26857 amit.gupta 66
import com.spice.profitmandi.dao.entity.fofo.CustomerAddress;
26855 tejbeer 67
import com.spice.profitmandi.dao.entity.fofo.PendingOrder;
68
import com.spice.profitmandi.dao.entity.fofo.PendingOrderItem;
26715 amit.gupta 69
import com.spice.profitmandi.dao.entity.fofo.PincodePartner;
26630 amit.gupta 70
import com.spice.profitmandi.dao.enumuration.dtr.OtpType;
26607 amit.gupta 71
import com.spice.profitmandi.dao.model.AddCartRequest;
72
import com.spice.profitmandi.dao.model.CartItem;
73
import com.spice.profitmandi.dao.model.CartItemResponseModel;
74
import com.spice.profitmandi.dao.model.CartResponse;
27030 amit.gupta 75
import com.spice.profitmandi.dao.model.UserCart;
26607 amit.gupta 76
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
77
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
26718 amit.gupta 78
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
27030 amit.gupta 79
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
26745 amit.gupta 80
import com.spice.profitmandi.dao.repository.dtr.WebListingRepository;
81
import com.spice.profitmandi.dao.repository.dtr.WebProductListingRepository;
26607 amit.gupta 82
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
26788 amit.gupta 83
import com.spice.profitmandi.dao.repository.fofo.CustomerAddressRepository;
26774 amit.gupta 84
import com.spice.profitmandi.dao.repository.fofo.CustomerRepository;
26855 tejbeer 85
import com.spice.profitmandi.dao.repository.fofo.PendingOrderItemRepository;
86
import com.spice.profitmandi.dao.repository.fofo.PendingOrderRepository;
26648 amit.gupta 87
import com.spice.profitmandi.dao.repository.fofo.PendingOrderService;
26715 amit.gupta 88
import com.spice.profitmandi.dao.repository.fofo.PincodePartnerRepository;
26607 amit.gupta 89
import com.spice.profitmandi.dao.repository.inventory.ItemAvailabilityCacheRepository;
26784 amit.gupta 90
import com.spice.profitmandi.service.CustomerService;
26607 amit.gupta 91
import com.spice.profitmandi.service.authentication.RoleManager;
26923 amit.gupta 92
import com.spice.profitmandi.service.inventory.AvailabilityModel;
26607 amit.gupta 93
import com.spice.profitmandi.service.inventory.FofoAvailabilityInfo;
94
import com.spice.profitmandi.service.inventory.FofoCatalogResponse;
26923 amit.gupta 95
import com.spice.profitmandi.service.inventory.InventoryService;
26909 amit.gupta 96
import com.spice.profitmandi.service.inventory.SaholicInventoryService;
26683 amit.gupta 97
import com.spice.profitmandi.service.scheme.SchemeService;
26651 amit.gupta 98
import com.spice.profitmandi.service.user.RetailerService;
26630 amit.gupta 99
import com.spice.profitmandi.web.processor.OtpProcessor;
26607 amit.gupta 100
import com.spice.profitmandi.web.res.DealBrands;
101
import com.spice.profitmandi.web.res.DealObjectResponse;
102
import com.spice.profitmandi.web.res.DealsResponse;
103
import com.spice.profitmandi.web.res.ValidateCartResponse;
104
 
105
import io.swagger.annotations.ApiImplicitParam;
106
import io.swagger.annotations.ApiImplicitParams;
107
import io.swagger.annotations.ApiOperation;
108
 
109
@Controller
110
@Transactional(rollbackFor = Throwable.class)
111
public class StoreController {
112
 
113
	private static final Logger logger = LogManager.getLogger(StoreController.class);
26630 amit.gupta 114
 
26628 amit.gupta 115
	private static final LocalTime CUTOFF_TIME = LocalTime.of(15, 0);
26745 amit.gupta 116
 
117
	private static final List<Integer> TAG_IDS = Arrays.asList(4);
118
 
26717 amit.gupta 119
	private static final int DEFAULT_STORE = 171912487;
26833 amit.gupta 120
 
26788 amit.gupta 121
	@Autowired
122
	CustomerAddressRepository customerAddressRepository;
26607 amit.gupta 123
 
26923 amit.gupta 124
	@Autowired
27030 amit.gupta 125
	SolrService solrService;
126
 
127
	@Autowired
26923 amit.gupta 128
	InventoryService inventoryService;
27030 amit.gupta 129
 
130
	@Autowired
131
	UserAccountRepository userAccountRepository;
26923 amit.gupta 132
 
26607 amit.gupta 133
	@Value("${python.api.host}")
134
	private String host;
26833 amit.gupta 135
 
26784 amit.gupta 136
	@Autowired
137
	CustomerService customerService;
26607 amit.gupta 138
 
139
	@Value("${python.api.port}")
140
	private int port;
26923 amit.gupta 141
 
26909 amit.gupta 142
	@Autowired
143
	private SaholicInventoryService saholicInventoryService;
26607 amit.gupta 144
 
145
	// This is now unused as we are not supporting multiple companies.
146
	@Value("${gadgetCops.invoice.cc}")
147
	private String[] ccGadgetCopInvoiceTo;
148
 
149
	@Autowired
26715 amit.gupta 150
	private PincodePartnerRepository pincodePartnerRepository;
151
 
152
	@Autowired
26718 amit.gupta 153
	private FofoStoreRepository fofoStoreRepository;
26745 amit.gupta 154
 
26718 amit.gupta 155
	@Autowired
26651 amit.gupta 156
	private RetailerService retailerService;
26861 tejbeer 157
 
26857 amit.gupta 158
	@Autowired
159
	private PendingOrderRepository pendingOrderRepository;
26861 tejbeer 160
 
26857 amit.gupta 161
	@Autowired
162
	private PendingOrderItemRepository pendingOrderItemRepository;
26652 amit.gupta 163
 
26651 amit.gupta 164
	@Autowired
26652 amit.gupta 165
	private PendingOrderService pendingOrderService;
26648 amit.gupta 166
 
167
	@Autowired
26774 amit.gupta 168
	private CustomerRepository customerRepository;
169
 
170
	@Autowired
26607 amit.gupta 171
	private SolrService commonSolrService;
172
 
173
	@Autowired
26630 amit.gupta 174
	private OtpProcessor otpProcessor;
175
 
176
	@Autowired
26607 amit.gupta 177
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
178
 
26609 amit.gupta 179
	@Autowired
26607 amit.gupta 180
	private ResponseSender<?> responseSender;
181
 
182
	@Autowired
183
	private TagListingRepository tagListingRepository;
184
 
185
	@Autowired
186
	private ItemRepository itemRepository;
26701 amit.gupta 187
 
26683 amit.gupta 188
	@Autowired
189
	private SchemeService schemeService;
26607 amit.gupta 190
 
191
	@Autowired
192
	private ItemAvailabilityCacheRepository itemAvailabilityCacheRepository;
193
 
194
	@Autowired
26745 amit.gupta 195
	private WebListingRepository webListingRepository;
196
 
197
	@Autowired
198
	private WebProductListingRepository webProductListingRepository;
199
 
200
	@Autowired
26607 amit.gupta 201
	private RoleManager roleManagerService;
202
 
27028 tejbeer 203
	@Autowired
204
	private VelocityEngine velocityEngine;
205
 
206
	@Autowired
207
	JavaMailSender mailSender;
208
 
26607 amit.gupta 209
	List<String> filterableParams = Arrays.asList("brand");
210
 
27030 amit.gupta 211
	/*@ApiImplicitParams({
26607 amit.gupta 212
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
213
	@RequestMapping(value = "/store/fofo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
214
	public ResponseEntity<?> getFofo(HttpServletRequest request,
215
			@RequestParam(value = "categoryId", required = false, defaultValue = "(3 OR 6)") String categoryId,
216
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
217
			@RequestParam(value = "sort", required = false) String sort,
218
			@RequestParam(value = "brand", required = false) String brand,
219
			@RequestParam(value = "subCategoryId", required = false) int subCategoryId,
220
			@RequestParam(value = "q", required = false) String queryTerm,
221
			@RequestParam(value = "hotDeal", required = false) boolean hotDeal) throws Throwable {
222
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
223
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
224
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
225
			// UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
226
			RestClient rc = new RestClient();
227
			Map<String, String> params = new HashMap<>();
228
			List<String> mandatoryQ = new ArrayList<>();
229
			if (queryTerm != null && !queryTerm.equals("null")) {
230
				mandatoryQ.add(String.format("+(%s)", queryTerm));
231
			} else {
232
				queryTerm = null;
233
			}
234
			if (subCategoryId != 0) {
235
				mandatoryQ
236
						.add(String.format("+(subCategoryId_i:%s) +{!parent which=\"subCategoryId_i:%s\"} tagId_i:(%s)",
26745 amit.gupta 237
								subCategoryId, subCategoryId, StringUtils.join(TAG_IDS, " ")));
26607 amit.gupta 238
			} else if (hotDeal) {
239
				mandatoryQ.add(String.format("+{!parent which=\"hot_deals_b=true\"} tagId_i:(%s)",
26745 amit.gupta 240
						StringUtils.join(TAG_IDS, " ")));
26607 amit.gupta 241
 
242
			} else if (StringUtils.isNotBlank(brand)) {
243
				mandatoryQ.add(
244
						String.format("+(categoryId_i:%s) +(brand_ss:%s) +{!parent which=\"brand_ss:%s\"} tagId_i:(%s)",
26745 amit.gupta 245
								categoryId, brand, brand, StringUtils.join(TAG_IDS, " ")));
26607 amit.gupta 246
 
247
			} else {
248
				mandatoryQ.add(
26745 amit.gupta 249
						String.format("+{!parent which=\"id:catalog*\"} tagId_i:(%s)", StringUtils.join(TAG_IDS, " ")));
26607 amit.gupta 250
			}
251
			params.put("q", StringUtils.join(mandatoryQ, " "));
252
			params.put("fl", "*, [child parentFilter=id:catalog*]");
253
			if (queryTerm == null) {
254
				params.put("sort", "create_s desc");
255
			}
256
			params.put("start", String.valueOf(offset));
257
			params.put("rows", String.valueOf(limit));
258
			params.put("wt", "json");
259
			String response = null;
260
			try {
261
				response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
262
			} catch (HttpHostConnectException e) {
263
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
264
			}
265
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
266
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
26909 amit.gupta 267
			dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId());
27030 amit.gupta 268
 
26607 amit.gupta 269
			 * if (Mongo.PARTNER_BLoCKED_BRANDS.containsKey(userInfo.getEmail())) {
270
			 * dealResponse.stream() .filter(x ->
271
			 * Mongo.PARTNER_BLoCKED_BRANDS.get(userInfo.getEmail()).contains(x.getBrand()))
272
			 * ; }
27030 amit.gupta 273
 
26607 amit.gupta 274
		} else {
275
			return responseSender.badRequest(
276
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
277
		}
278
		return responseSender.ok(dealResponse);
27030 amit.gupta 279
	}*/
26701 amit.gupta 280
 
26668 amit.gupta 281
	@RequestMapping(value = "/store/entity/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
282
	@ApiImplicitParams({
283
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
284
	@ApiOperation(value = "Get unit deal object")
285
	public ResponseEntity<?> getUnitFocoDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
286
			throws ProfitMandiBusinessException {
287
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
288
		List<Integer> tagIds = Arrays.asList(4);
289
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
290
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
291
			String categoryId = "(3 OR 6)";
26745 amit.gupta 292
 
26668 amit.gupta 293
			RestClient rc = new RestClient();
294
			Map<String, String> params = new HashMap<>();
295
			List<String> mandatoryQ = new ArrayList<>();
296
			String catalogString = "catalog" + id;
26607 amit.gupta 297
 
26668 amit.gupta 298
			mandatoryQ.add(String.format("+(categoryId_i:%s) +(id:%s) +{!parent which=\"id:%s\"} tagId_i:(%s)",
299
					categoryId, catalogString, catalogString, StringUtils.join(tagIds, " ")));
300
 
301
			params.put("q", StringUtils.join(mandatoryQ, " "));
302
			params.put("fl", "*, [child parentFilter=id:catalog*]");
303
			params.put("sort", "rank_i asc, create_s desc");
304
			params.put("wt", "json");
305
			String response = null;
306
			try {
307
				response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
308
			} catch (HttpHostConnectException e) {
309
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
310
			}
311
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
312
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
26909 amit.gupta 313
			dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId());
26668 amit.gupta 314
		} else {
315
			return responseSender.badRequest(
316
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
317
		}
318
		return responseSender.ok(dealResponse.get(0));
319
	}
320
 
26607 amit.gupta 321
	private Object toDealObject(JsonObject jsonObject) {
322
		if (jsonObject.get("dealObject") != null && jsonObject.get("dealObject").asInt() == 1) {
323
			return new Gson().fromJson(jsonObject.toString(), DealObjectResponse.class);
324
		}
325
		return new Gson().fromJson(jsonObject.toString(), DealsResponse.class);
326
	}
327
 
328
	@RequestMapping(value = "/store/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
329
	@ApiImplicitParams({
330
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
331
	@ApiOperation(value = "Get brand list and count for category")
332
	public ResponseEntity<?> getBrands(HttpServletRequest request,
333
			@RequestParam(value = "category_id") String category_id) throws ProfitMandiBusinessException {
334
		logger.info("Request " + request.getParameterMap());
335
		String response = null;
336
		// TODO: move to properties
337
		String uri = ProfitMandiConstants.URL_BRANDS;
338
		RestClient rc = new RestClient();
339
		Map<String, String> params = new HashMap<>();
340
		params.put("category_id", category_id);
341
		List<DealBrands> dealBrandsResponse = null;
342
		try {
343
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
344
		} catch (HttpHostConnectException e) {
345
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
346
		}
347
 
348
		dealBrandsResponse = new Gson().fromJson(response, new TypeToken<List<DealBrands>>() {
349
		}.getType());
350
 
351
		return responseSender.ok(dealBrandsResponse);
352
	}
353
 
26745 amit.gupta 354
	@RequestMapping(value = "/store/listing/{listingUrl}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
355
	public ResponseEntity<?> bestSellers(HttpServletRequest request, @PathVariable String listingUrl) throws Exception {
26654 amit.gupta 356
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
26909 amit.gupta 357
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
26666 amit.gupta 358
		List<Integer> tagIds = Arrays.asList(4);
26745 amit.gupta 359
 
360
		WebListing webListing = webListingRepository.selectByUrl("url");
361
		if (webListing == null) {
362
			throw new ProfitMandiBusinessException("Url", listingUrl, "Could not find the Url");
363
		}
364
		List<Integer> webProducts = webProductListingRepository.selectAllByWebListingId(webListing.getId()).stream()
365
				.filter(x -> x.getRank() > 0).map(x -> x.getEntityId()).collect(Collectors.toList());
366
 
26654 amit.gupta 367
		RestClient rc = new RestClient();
368
		Map<String, String> params = new HashMap<>();
369
		List<String> mandatoryQ = new ArrayList<>();
26745 amit.gupta 370
		mandatoryQ.add(String.format(
371
				"+{!parent which=\"catalogId_i:" + StringUtils.join(webProducts, " ") + "\"} tagId_i:(%s)",
372
				StringUtils.join(tagIds, " ")));
26654 amit.gupta 373
		params.put("q", StringUtils.join(mandatoryQ, " "));
374
		params.put("fl", "*, [child parentFilter=id:catalog*]");
375
		// params.put("sort", "create_s desc");
376
		params.put("start", String.valueOf(0));
377
		params.put("rows", String.valueOf(30));
378
		params.put("wt", "json");
379
		String response = null;
380
		try {
381
			response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
382
		} catch (HttpHostConnectException e) {
383
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
384
		}
385
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
386
		JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
26745 amit.gupta 387
		final Ordering<Integer> rankOrdering = Ordering.explicit(webProducts);
26923 amit.gupta 388
		dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId()).stream()
389
				.sorted(new Comparator<FofoCatalogResponse>() {
390
					@Override
391
					public int compare(FofoCatalogResponse o1, FofoCatalogResponse o2) {
392
						return rankOrdering.compare(o1.getCatalogId(), o2.getCatalogId());
393
					}
394
				}).collect(Collectors.toList());
26745 amit.gupta 395
		webListing.setFofoCatalogResponses(dealResponse);
396
		return responseSender.ok(webListing);
26654 amit.gupta 397
	}
398
 
26632 amit.gupta 399
	@RequestMapping(value = "/store/otp/generateOTP", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
26783 amit.gupta 400
	public ResponseEntity<?> generateOtp(HttpServletRequest request, @RequestParam String mobile) throws Exception {
26630 amit.gupta 401
 
26857 amit.gupta 402
		return responseSender.ok(otpProcessor.generateOtp(mobile, OtpType.REGISTRATION));
26630 amit.gupta 403
 
404
	}
26652 amit.gupta 405
 
26784 amit.gupta 406
	@RequestMapping(value = "/store/checkmobile/{mobile}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
26833 amit.gupta 407
	public ResponseEntity<?> checkRegistrationUsingMobile(HttpServletRequest request, @PathVariable String mobile)
408
			throws Exception {
26774 amit.gupta 409
		try {
410
			Customer customer = customerRepository.selectByMobileNumber(mobile);
26777 amit.gupta 411
			customer.setPasswordExist(StringUtils.isNotEmpty(customer.getPassword()));
26774 amit.gupta 412
			return responseSender.ok(new CustomerModel(true, customer));
413
		} catch (Exception e) {
414
			return responseSender.ok(new CustomerModel(false, null));
415
		}
416
	}
26833 amit.gupta 417
 
26784 amit.gupta 418
	@RequestMapping(value = "/store/signin", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
419
	public ResponseEntity<?> signIn(HttpServletRequest request, @RequestBody UserModel userModel) throws Exception {
26833 amit.gupta 420
		if (customerService.authenticate(userModel.getMobile(), userModel.getPassword())) {
26784 amit.gupta 421
			return responseSender.ok(true);
422
		} else {
423
			return responseSender.ok(false);
424
		}
425
	}
26923 amit.gupta 426
 
26841 amit.gupta 427
	@RequestMapping(value = "/store/resetPassword", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
26923 amit.gupta 428
	public ResponseEntity<?> resetPassword(HttpServletRequest request, @RequestBody UserModel userModel)
429
			throws Exception {
26843 amit.gupta 430
		customerService.changePassword(userModel.getMobile(), userModel.getPassword());
26841 amit.gupta 431
		return responseSender.ok(true);
432
	}
26774 amit.gupta 433
 
26857 amit.gupta 434
	@RequestMapping(value = "/store/register", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
435
	public ResponseEntity<?> register(HttpServletRequest request, @RequestBody UserModel userModel) throws Exception {
436
		Customer customer = new Customer();
437
		customer.setPassword(userModel.getPassword());
438
		customer.setEmailId(userModel.getEmail());
439
		customer.setFirstName(userModel.getFirstName());
440
		customer.setLastName(userModel.getLastName());
441
		customer.setMobileNumber(userModel.getMobile());
442
		return responseSender.ok(customerService.addCustomer(customer));
443
	}
444
 
26648 amit.gupta 445
	@RequestMapping(value = "/store/confirmOrder", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
26857 amit.gupta 446
	public ResponseEntity<?> confirmOrder(HttpServletRequest request,
26652 amit.gupta 447
			@RequestBody CreatePendingOrderRequest createPendingOrderRequest) throws Exception {
26648 amit.gupta 448
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
449
		Integer storeId = userInfo.getRetailerId();
450
		createPendingOrderRequest.setFofoId(storeId);
26923 amit.gupta 451
		List<CreatePendingOrderItem> pendingOrderItems = createPendingOrderRequest.getCreatePendingOrderItem();
452
		List<CartItem> cartItems = new ArrayList<>();
453
		pendingOrderItems.stream().forEach(x -> {
454
			CartItem ci = new CartItem();
455
			ci.setItemId(x.getItemId());
456
			ci.setQuantity(x.getQuantity());
457
			ci.setSellingPrice(x.getSellingPrice());
458
			cartItems.add(ci);
459
		});
460
		CartResponse cr = this.validateCart(storeId, cartItems);
461
		if (cr.getCartMessageChanged() > 0 || cr.getTotalAmount() != createPendingOrderRequest.getTotalAmount()) {
462
			return responseSender.badRequest("Invalid request");
463
		}
26652 amit.gupta 464
 
27028 tejbeer 465
		Map<String, String> returnMap = this.pendingOrderService.createPendingOrder(createPendingOrderRequest, cr);
466
		Customer customer = customerRepository.selectById(createPendingOrderRequest.getCustomerId());
467
		Template t = velocityEngine.getTemplate("sms.vm");
468
		VelocityContext context = new VelocityContext();
469
 
470
		context.put("customer", customer.getFirstName());
471
		context.put("invoiceNumber", returnMap.get("poid"));
472
		StringWriter writer = new StringWriter();
473
		t.merge(context, writer);
474
		sendMailWithAttachments("Order Confirmation", writer.toString());
475
		return responseSender.ok(returnMap);
476
 
26648 amit.gupta 477
	}
26630 amit.gupta 478
 
27028 tejbeer 479
	private void sendMailWithAttachments(String subject, String messageText) throws Exception {
480
		MimeMessage message = mailSender.createMimeMessage();
481
		MimeMessageHelper helper = new MimeMessageHelper(message, true);
482
		String[] email = { "tejbeer.kaur@shop2020.in" };
483
		helper.setSubject(subject);
484
		helper.setText(messageText, true);
485
		helper.setTo(email);
486
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
487
		helper.setFrom(senderAddress);
488
		mailSender.send(message);
489
 
490
	}
491
 
26857 amit.gupta 492
	@RequestMapping(value = "/store/address", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
493
	@ApiImplicitParams({
494
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
495
	@ApiOperation(value = "Get brand list and count for category")
496
	public ResponseEntity<?> getAddress(HttpServletRequest request) throws Exception {
497
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
498
		Integer storeId = userInfo.getRetailerId();
499
		CustomRetailer customRetailer = retailerService.getFofoRetailer(storeId);
500
 
501
		return responseSender.ok(customRetailer.getAddress());
502
 
503
	}
504
 
505
	@RequestMapping(value = "/store/address/{pincode}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
506
	@ApiImplicitParams({
507
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
508
	@ApiOperation(value = "Get brand list and count for category")
509
	public ResponseEntity<?> getStoresByPincode(HttpServletRequest request, @PathVariable String pincode)
510
			throws Exception {
511
		List<PincodePartner> pincodePartners = pincodePartnerRepository.selectPartnersByPincode(pincode);
512
		int fofoId = DEFAULT_STORE;
513
		if (pincodePartners.size() > 0) {
514
			fofoId = pincodePartners.get(0).getFofoId();
515
		}
516
		return responseSender.ok(fofoStoreRepository.selectByRetailerId(fofoId).getCode());
517
	}
26923 amit.gupta 518
 
26855 tejbeer 519
	@RequestMapping(value = "/store/order", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
520
	public ResponseEntity<?> getOrderDetail(HttpServletRequest request, @RequestParam(value = "id") int id,
521
			@RequestParam(name = "offset") int offset, @RequestParam(name = "limit") int limit)
522
			throws ProfitMandiBusinessException {
523
		List<CustomerOrderDetail> customerOrderDetails = new ArrayList<>();
524
 
525
		List<PendingOrder> pendingOrders = pendingOrderRepository.selectByCustomerId(id, offset, limit);
526
		if (!pendingOrders.isEmpty()) {
527
			for (PendingOrder po : pendingOrders) {
528
				List<PendingOrderItem> pois = pendingOrderItemRepository.selectByOrderId(po.getId());
529
				for (PendingOrderItem poi : pois) {
530
 
531
					CustomerOrderDetail customerOrderDetail = new CustomerOrderDetail();
532
 
533
					Item item = itemRepository.selectById(poi.getItemId());
534
					customerOrderDetail.setBrand(item.getBrand());
535
					customerOrderDetail.setColor(item.getColor());
536
					customerOrderDetail.setId(poi.getOrderId());
537
					customerOrderDetail.setItemId(poi.getItemId());
538
					customerOrderDetail.setModelName(item.getModelName());
539
					customerOrderDetail.setModelNumber(item.getModelNumber());
540
					customerOrderDetail.setQuantity(poi.getQuantity());
26923 amit.gupta 541
					customerOrderDetail.setStatus(po.getStatus());
26855 tejbeer 542
					customerOrderDetail.setTotalPrice(poi.getSellingPrice());
543
					customerOrderDetail.setPayMethod(po.getPayMethod());
26861 tejbeer 544
					customerOrderDetail.setCreatedTimeStamp(po.getCreateTimestamp());
26855 tejbeer 545
					customerOrderDetails.add(customerOrderDetail);
546
				}
547
			}
548
		}
549
 
550
		return responseSender.ok(customerOrderDetails);
551
	}
552
 
26745 amit.gupta 553
	@RequestMapping(value = "/store/listing", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
554
	@Cacheable(value = "storelisting.all", cacheManager = "thirtyMinsTimeOutCacheManager")
26774 amit.gupta 555
	public ResponseEntity<?> getStoresListing(HttpServletRequest request) throws Exception {
26745 amit.gupta 556
		List<WebListing> webListings = webListingRepository.selectAllWebListing(Optional.of(true));
557
		for (WebListing webListing : webListings) {
26909 amit.gupta 558
			UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
559
			Integer storeId = userInfo.getRetailerId();
26923 amit.gupta 560
 
26745 amit.gupta 561
			List<Integer> webProducts = webProductListingRepository.selectAllByWebListingId(webListing.getId()).stream()
562
					.filter(x -> x.getRank() > 0).map(x -> x.getEntityId()).collect(Collectors.toList());
563
 
564
			RestClient rc = new RestClient();
565
			Map<String, String> params = new HashMap<>();
566
			List<String> mandatoryQ = new ArrayList<>();
567
			mandatoryQ.add(String.format(
568
					"+{!parent which=\"catalogId_i:" + StringUtils.join(webProducts, " ") + "\"} tagId_i:(%s)",
569
					StringUtils.join(TAG_IDS, " ")));
570
			params.put("q", StringUtils.join(mandatoryQ, " "));
571
			params.put("fl", "*, [child parentFilter=id:catalog*]");
572
			// params.put("sort", "create_s desc");
573
			params.put("start", String.valueOf(0));
574
			params.put("rows", String.valueOf(30));
575
			params.put("wt", "json");
576
			String response = null;
577
			try {
578
				response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
579
			} catch (HttpHostConnectException e) {
580
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
581
			}
582
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
583
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
584
			final Ordering<Integer> colorOrdering = Ordering.explicit(webProducts);
26909 amit.gupta 585
			List<FofoCatalogResponse> dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId()).stream()
26745 amit.gupta 586
					.sorted(new Comparator<FofoCatalogResponse>() {
587
						@Override
588
						public int compare(FofoCatalogResponse o1, FofoCatalogResponse o2) {
589
							return colorOrdering.compare(o1.getCatalogId(), o2.getCatalogId());
590
						}
591
					}).collect(Collectors.toList());
592
			webListing.setFofoCatalogResponses(dealResponse);
593
		}
594
		return responseSender.ok(webListings);
595
	}
596
 
26652 amit.gupta 597
	@RequestMapping(value = "/store/cart", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
598
	@ApiImplicitParams({
26651 amit.gupta 599
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
26652 amit.gupta 600
	@ApiOperation(value = "Get brand list and count for category")
601
	public ResponseEntity<?> cart(HttpServletRequest request, @RequestBody AddCartRequest cartRequest)
602
			throws Exception {
26923 amit.gupta 603
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
604
		Integer storeId = userInfo.getRetailerId();
605
		ValidateCartResponse vc = new ValidateCartResponse(this.validateCart(storeId, cartRequest.getCartItems()),
606
				"Success", "Items added to cart successfully");
607
		return responseSender.ok(vc);
608
	}
609
 
610
	// Validate Cart for B2C Customers
611
	private CartResponse validateCart(int storeId, List<CartItem> cartItems) throws Exception {
612
		cartItems = cartItems.stream().filter(x -> x.getQuantity() > 0).collect(Collectors.toList());
613
		List<Integer> itemIds = cartItems.stream().map(x -> x.getItemId()).collect(Collectors.toList());
614
		Map<Integer, AvailabilityModel> inventoryItemAvailabilityMap = inventoryService.getStoreAndOurStock(storeId,
615
				itemIds);
26607 amit.gupta 616
		CartResponse cartResponse = new CartResponse();
26612 amit.gupta 617
		List<CartItemResponseModel> cartItemResponseModels = new ArrayList<>();
618
		cartResponse.setCartItems(cartItemResponseModels);
26607 amit.gupta 619
		Set<Integer> itemsIdsSet = new HashSet<>(itemIds);
26668 amit.gupta 620
		logger.info("Store Id {}, Item Ids {}", storeId, itemsIdsSet);
26607 amit.gupta 621
 
622
		Map<Integer, Item> itemsMap = itemRepository.selectByIds(itemsIdsSet).stream()
623
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
624
 
26923 amit.gupta 625
		Map<Integer, TagListing> tagListingMap = tagListingRepository
26607 amit.gupta 626
				.selectByItemIdsAndTagIds(new HashSet<>(itemIds), new HashSet<>(Arrays.asList(4))).stream()
627
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
628
 
629
		List<Integer> catalogIds = itemsMap.values().stream().map(x -> x.getCatalogItemId())
630
				.collect(Collectors.toList());
631
 
632
		Map<Integer, JSONObject> contentMap = commonSolrService.getContentByCatalogIds(catalogIds);
633
 
634
		// cartResponse.getCartItems()
26923 amit.gupta 635
		int cartMessageChanged = 0;
636
		int cartMessageOOS = 0;
637
		int totalAmount = 0;
638
		int totalQty = 0;
639
		for (CartItem cartItem : cartItems) {
26607 amit.gupta 640
			Item item = itemsMap.get(cartItem.getItemId());
26923 amit.gupta 641
			TagListing tagListing = tagListingMap.get(cartItem.getItemId());
642
			Float cashback = schemeService.getItemSchemeCashBack().get(cartItem.getItemId());
643
			cashback = cashback == null ? 0 : cashback;
644
			float itemSellingPrice = tagListing.getMop() - cashback;
26607 amit.gupta 645
			CartItemResponseModel cartItemResponseModel = new CartItemResponseModel();
26923 amit.gupta 646
			cartItemResponseModel.setSellingPrice(cartItem.getSellingPrice());
647
			if (itemSellingPrice != cartItem.getSellingPrice()) {
648
				cartItemResponseModel.setSellingPrice(itemSellingPrice);
649
				cartMessageChanged++;
650
			}
26628 amit.gupta 651
			int estimate = -2;
27025 tejbeer 652
			LocalDateTime promiseDeliveryTime = LocalDateTime.now();
26923 amit.gupta 653
			int qtyRequired = (int) cartItem.getQuantity();
654
			AvailabilityModel availabilityModel = inventoryItemAvailabilityMap.get(cartItem.getItemId());
655
			cartItemResponseModel.setMaxQuantity(availabilityModel.getMaxAvailability());
656
			if (availabilityModel.getStoreAvailability() >= qtyRequired) {
657
				estimate = 0;
658
			} else if (availabilityModel.getWarehouseAvailability() >= qtyRequired) {
26628 amit.gupta 659
				estimate = 2;
26923 amit.gupta 660
			} else if (availabilityModel.getStoreAvailability() > 0) {
661
				estimate = 0;
662
				qtyRequired = availabilityModel.getStoreAvailability();
663
				cartMessageChanged++;
664
			} else if (availabilityModel.getWarehouseAvailability() > 0) {
665
				qtyRequired = availabilityModel.getWarehouseAvailability();
666
				estimate = 2;
667
				cartMessageChanged++;
26620 amit.gupta 668
			} else {
26923 amit.gupta 669
				qtyRequired = 0;
26926 amit.gupta 670
				cartMessageChanged++;
26607 amit.gupta 671
			}
26923 amit.gupta 672
			cartItemResponseModel.setQuantity(qtyRequired);
26630 amit.gupta 673
			if (estimate >= 0 && LocalTime.now().isAfter(CUTOFF_TIME)) {
26628 amit.gupta 674
				estimate = estimate + 1;
27025 tejbeer 675
				promiseDeliveryTime = promiseDeliveryTime.plusDays(3);
26628 amit.gupta 676
			}
26923 amit.gupta 677
			totalQty += qtyRequired;
678
			totalAmount += qtyRequired * itemSellingPrice;
26628 amit.gupta 679
			cartItemResponseModel.setEstimate(estimate);
26616 amit.gupta 680
			cartItemResponseModel.setTitle(item.getItemDescriptionNoColor());
26614 amit.gupta 681
			cartItemResponseModel.setItemId(cartItem.getItemId());
26615 amit.gupta 682
			cartItemResponseModel.setMinBuyQuantity(1);
26923 amit.gupta 683
			cartItemResponseModel.setQuantity(qtyRequired);
26621 amit.gupta 684
			cartItemResponseModel.setQuantityStep(1);
27025 tejbeer 685
			cartItemResponseModel.setPromiseDelivery(promiseDeliveryTime);
26923 amit.gupta 686
			cartItemResponseModel.setMaxQuantity(availabilityModel.getMaxAvailability());
26607 amit.gupta 687
			cartItemResponseModel.setCatalogItemId(item.getCatalogItemId());
688
			cartItemResponseModel.setImageUrl(contentMap.get(item.getCatalogItemId()).getString("imageUrl_s"));
689
			cartItemResponseModel.setColor(item.getColor());
26620 amit.gupta 690
			cartItemResponseModels.add(cartItemResponseModel);
26607 amit.gupta 691
		}
26923 amit.gupta 692
		cartResponse.setCartItems(cartItemResponseModels);
693
		cartResponse.setCartMessageChanged(cartMessageChanged);
694
		cartResponse.setCartMessageOOS(cartMessageOOS);
695
		int maxEstimate = cartItemResponseModels.stream().mapToInt(x -> x.getEstimate()).max().getAsInt();
696
		cartResponse.setMaxEstimate(maxEstimate);
697
		cartResponse.setTotalAmount(totalAmount);
698
		cartResponse.setTotalQty(totalQty);
26652 amit.gupta 699
 
26923 amit.gupta 700
		return cartResponse;
701
 
26648 amit.gupta 702
	}
26607 amit.gupta 703
 
27030 amit.gupta 704
	@RequestMapping(value = "/store/partnerStock", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
705
	public ResponseEntity<?> partnerStock(HttpServletRequest request,
706
			@RequestParam(value = "categoryId", required = false, defaultValue = "3") String categoryId,
707
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
708
			@RequestParam(value = "sort", required = false) String sort,
709
			@RequestParam(value = "brand", required = false) String brand,
710
			@RequestParam(value = "subCategoryId", required = false) int subCategoryId,
711
			@RequestParam(value = "q", required = false) String queryTerm,
712
			@RequestParam(value = " ", required = false, defaultValue = "true") boolean partnerStockOnly)
713
			throws Throwable {
714
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
715
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
716
		dealResponse = this.getCatalogResponse(solrService.getSolrDocs(queryTerm, categoryId, offset, limit,
717
				sort, brand, subCategoryId, false), false, userInfo.getRetailerId());
718
		return responseSender.ok(dealResponse);
719
	}
720
 
26909 amit.gupta 721
	private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal, int fofoId)
26607 amit.gupta 722
			throws ProfitMandiBusinessException {
26909 amit.gupta 723
		Map<Integer, Integer> ourItemAvailabilityMap = null;
724
		Map<Integer, Integer> partnerStockAvailabilityMap = null;
26607 amit.gupta 725
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
726
		List<Integer> tagIds = Arrays.asList(4);
727
		if (docs.length() > 0) {
728
			HashSet<Integer> itemsSet = new HashSet<>();
729
			for (int i = 0; i < docs.length(); i++) {
730
				JSONObject doc = docs.getJSONObject(i);
731
				if (doc.has("_childDocuments_")) {
732
					for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
733
						JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
734
						int itemId = childItem.getInt("itemId_i");
735
						itemsSet.add(itemId);
736
					}
737
				}
738
			}
739
			if (itemsSet.size() == 0) {
740
				return dealResponse;
741
			}
26909 amit.gupta 742
			if (hotDeal) {
743
				ourItemAvailabilityMap = saholicInventoryService
744
						.getTotalAvailabilityByItemIds(new ArrayList<>(itemsSet));
745
			} else if (fofoId > 0) {
746
				partnerStockAvailabilityMap = currentInventorySnapshotRepository.selectItemsStock(fofoId).stream()
747
						.collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
748
				ourItemAvailabilityMap = saholicInventoryService
749
						.getTotalAvailabilityByItemIds(new ArrayList<>(itemsSet));
750
			}
26607 amit.gupta 751
		}
752
 
753
		for (int i = 0; i < docs.length(); i++) {
754
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
755
			JSONObject doc = docs.getJSONObject(i);
756
			FofoCatalogResponse ffdr = new FofoCatalogResponse();
757
			ffdr.setCatalogId(doc.getInt("catalogId_i"));
758
			ffdr.setImageUrl(doc.getString("imageUrl_s"));
759
			ffdr.setTitle(doc.getString("title_s"));
760
			try {
761
				ffdr.setFeature(doc.getString("feature_s"));
762
			} catch (Exception e) {
763
				ffdr.setFeature(null);
764
				logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
765
			}
766
			ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
767
			if (doc.has("_childDocuments_")) {
768
				for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
769
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
770
					int itemId = childItem.getInt("itemId_i");
771
					float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
772
					if (fofoAvailabilityInfoMap.containsKey(itemId)) {
773
						if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
774
							fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
775
							fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
776
						}
777
					} else {
778
						FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
26909 amit.gupta 779
						fdi.setSellingPrice(sellingPrice);
780
						fdi.setActive(childItem.getBoolean("active_b"));
781
						fdi.setMrp(childItem.getDouble("mrp_f"));
26607 amit.gupta 782
						fdi.setMop((float) childItem.getDouble("mop_f"));
783
						fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
784
						fdi.setTagId(childItem.getInt("tagId_i"));
785
						fdi.setItem_id(itemId);
26909 amit.gupta 786
						Float cashBack = schemeService.getItemSchemeCashBack().get(itemId);
787
						cashBack = cashBack == null ? 0 : cashBack;
788
						fdi.setCashback(cashBack);
26673 amit.gupta 789
						fdi.setMinBuyQuantity(1);
26909 amit.gupta 790
						if (hotDeal) {
26607 amit.gupta 791
							try {
26909 amit.gupta 792
								int totalAvailability = ourItemAvailabilityMap.get(itemId);
793
								if (totalAvailability <= 0) {
794
									continue;
795
								}
796
								fdi.setAvailability(ourItemAvailabilityMap.get(itemId));
26607 amit.gupta 797
							} catch (Exception e) {
798
								continue;
799
							}
26909 amit.gupta 800
						} else if (fofoId == 0) {
801
							// For accessories item availability should at be ordered for Rs.1000
802
							fdi.setAvailability(100);
803
							Item item = itemRepository.selectById(itemId);
804
							// In case its tampered glass moq should be 5
805
							if (item.getCategoryId() == 10020) {
806
								fdi.setMinBuyQuantity(5);
26607 amit.gupta 807
							}
808
						} else {
26909 amit.gupta 809
							int ourStockAvailability = ourItemAvailabilityMap.get(itemId) == null ? 0
810
									: ourItemAvailabilityMap.get(itemId);
811
							int partnerAvailability = partnerStockAvailabilityMap.get(itemId) == null ? 0
812
									: partnerStockAvailabilityMap.get(itemId);
813
							fdi.setAvailability(ourStockAvailability + partnerAvailability);
26607 amit.gupta 814
						}
815
						fdi.setQuantityStep(1);
26909 amit.gupta 816
						fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
26607 amit.gupta 817
						fofoAvailabilityInfoMap.put(itemId, fdi);
818
					}
819
				}
820
			}
821
			if (fofoAvailabilityInfoMap.values().size() > 0) {
26909 amit.gupta 822
				ffdr.setItems(fofoAvailabilityInfoMap.values().stream()
26923 amit.gupta 823
						.sorted((x, y) -> y.getAvailability() - x.getAvailability()).collect(Collectors.toList()));
26607 amit.gupta 824
				dealResponse.add(ffdr);
825
			}
826
		}
827
		return dealResponse;
26909 amit.gupta 828
 
26607 amit.gupta 829
	}
26923 amit.gupta 830
 
831
	@GetMapping(value = "store/order-status/{pendingOrderId}")
27028 tejbeer 832
	public ResponseEntity<?> orderStatus(HttpServletRequest request, @PathVariable int pendingOrderId)
833
			throws Exception {
26923 amit.gupta 834
		PendingOrder pendingOrder = pendingOrderRepository.selectById(pendingOrderId);
835
		List<PendingOrderItem> pendingOrderItems = pendingOrderItemRepository.selectByOrderId(pendingOrder.getId());
836
		List<Integer> catalogIds = new ArrayList<>();
27028 tejbeer 837
		for (PendingOrderItem pendingOrderItem : pendingOrderItems) {
26923 amit.gupta 838
			Item item = itemRepository.selectById(pendingOrderItem.getItemId());
839
			pendingOrderItem.setItemName(item.getItemDescription());
840
			catalogIds.add(item.getCatalogItemId());
841
		}
842
		Map<Integer, JSONObject> contentMap = commonSolrService.getContentByCatalogIds(catalogIds);
27028 tejbeer 843
		for (PendingOrderItem pendingOrderItem : pendingOrderItems) {
26923 amit.gupta 844
			Item item = itemRepository.selectById(pendingOrderItem.getItemId());
845
			JSONObject jsonObj = contentMap.get(item.getCatalogItemId());
846
			pendingOrderItem.setImgUrl(jsonObj.getString("imageUrl_s"));
847
		}
848
		pendingOrder.setPendingOrderItems(pendingOrderItems);
849
		return responseSender.ok(pendingOrder);
850
	}
851
 
26833 amit.gupta 852
	@RequestMapping(value = "/store/addresses/{customerId}", method = RequestMethod.GET)
853
	public ResponseEntity<?> getAll(HttpServletRequest request, @PathVariable int customerId) throws Throwable {
26788 amit.gupta 854
		return responseSender.ok(customerAddressRepository.selectByCustomerId(customerId));
855
	}
26833 amit.gupta 856
 
26857 amit.gupta 857
	@RequestMapping(value = "/store/address", method = RequestMethod.POST)
858
	public ResponseEntity<?> addAddress(HttpServletRequest request, @RequestBody CustomerAddress customerAddress)
859
			throws Throwable {
860
		customerAddressRepository.persist(customerAddress);
861
		return responseSender.ok(customerAddress);
862
	}
863
 
26861 tejbeer 864
	@RequestMapping(value = "/store/updateCustomer", method = RequestMethod.POST)
865
	public ResponseEntity<?> updateCustomerProfile(HttpServletRequest request, @RequestBody Customer customer)
866
			throws Throwable {
867
		Customer cust = customerRepository.selectById(customer.getId());
868
		cust.setGender(customer.getGender());
26867 tejbeer 869
		cust.setProfileImageId(customer.getProfileImageId());
26861 tejbeer 870
		cust.setDob(customer.getDob());
871
		return responseSender.ok(cust);
872
	}
873
 
26774 amit.gupta 874
}
875
 
26784 amit.gupta 876
class UserModel {
26857 amit.gupta 877
	@JsonProperty(required = true)
26784 amit.gupta 878
	private String mobile;
26857 amit.gupta 879
	@JsonProperty(required = true)
26784 amit.gupta 880
	private String password;
26857 amit.gupta 881
	@JsonProperty(required = false)
882
	private String firstName;
883
	@JsonProperty(required = false)
884
	private String lastName;
885
	@JsonProperty(required = false)
886
	private String email;
26833 amit.gupta 887
 
26784 amit.gupta 888
	@Override
889
	public String toString() {
890
		return "UserModel [mobile=" + mobile + ", password=" + password + "]";
891
	}
26833 amit.gupta 892
 
26784 amit.gupta 893
	public String getMobile() {
894
		return mobile;
895
	}
26833 amit.gupta 896
 
26784 amit.gupta 897
	public void setMobile(String mobile) {
898
		this.mobile = mobile;
899
	}
26833 amit.gupta 900
 
26784 amit.gupta 901
	public String getPassword() {
902
		return password;
903
	}
26833 amit.gupta 904
 
26784 amit.gupta 905
	public void setPassword(String password) {
906
		this.password = password;
907
	}
26857 amit.gupta 908
 
909
	public String getFirstName() {
910
		return firstName;
911
	}
912
 
913
	public void setFirstName(String firstName) {
914
		this.firstName = firstName;
915
	}
916
 
917
	public String getLastName() {
918
		return lastName;
919
	}
920
 
921
	public void setLastName(String lastName) {
922
		this.lastName = lastName;
923
	}
924
 
925
	public String getEmail() {
926
		return email;
927
	}
928
 
929
	public void setEmail(String email) {
930
		this.email = email;
931
	}
932
 
26784 amit.gupta 933
}
934
 
26774 amit.gupta 935
class CustomerModel {
26783 amit.gupta 936
 
26774 amit.gupta 937
	@JsonProperty(required = false)
938
	private Customer customer;
939
	@JsonProperty(required = true)
940
	private boolean exists;
941
 
942
	public CustomerModel(boolean exists, Customer customer) {
943
		super();
944
		this.customer = customer;
945
		this.exists = exists;
946
	}
947
 
948
	@Override
949
	public String toString() {
950
		return "CustomerModel [customer=" + customer + ", exists=" + exists + "]";
951
	}
952
 
953
	public Customer getCustomer() {
954
		return customer;
955
	}
956
 
957
	public void setCustomer(Customer customer) {
958
		this.customer = customer;
959
	}
960
 
961
	public boolean isExists() {
962
		return exists;
963
	}
964
 
965
	public void setExists(boolean exists) {
966
		this.exists = exists;
967
	}
26607 amit.gupta 968
}