Subversion Repositories SmartDukaan

Rev

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