Subversion Repositories SmartDukaan

Rev

Rev 27045 | Rev 27049 | 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;
26607 amit.gupta 56
import com.spice.profitmandi.common.model.ProfitMandiConstants;
57
import com.spice.profitmandi.common.model.UserInfo;
58
import com.spice.profitmandi.common.solr.SolrService;
59
import com.spice.profitmandi.common.web.client.RestClient;
60
import com.spice.profitmandi.common.web.util.ResponseSender;
61
import com.spice.profitmandi.dao.entity.catalog.Item;
62
import com.spice.profitmandi.dao.entity.catalog.TagListing;
26745 amit.gupta 63
import com.spice.profitmandi.dao.entity.dtr.WebListing;
26774 amit.gupta 64
import com.spice.profitmandi.dao.entity.fofo.Customer;
26857 amit.gupta 65
import com.spice.profitmandi.dao.entity.fofo.CustomerAddress;
26855 tejbeer 66
import com.spice.profitmandi.dao.entity.fofo.PendingOrder;
67
import com.spice.profitmandi.dao.entity.fofo.PendingOrderItem;
26715 amit.gupta 68
import com.spice.profitmandi.dao.entity.fofo.PincodePartner;
26630 amit.gupta 69
import com.spice.profitmandi.dao.enumuration.dtr.OtpType;
27045 tejbeer 70
import com.spice.profitmandi.dao.enumuration.transaction.OrderStatus;
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;
27045 tejbeer 75
import com.spice.profitmandi.dao.model.CustomerOrderDetail;
27030 amit.gupta 76
import com.spice.profitmandi.dao.model.UserCart;
26607 amit.gupta 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;
27030 amit.gupta 80
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
26745 amit.gupta 81
import com.spice.profitmandi.dao.repository.dtr.WebListingRepository;
82
import com.spice.profitmandi.dao.repository.dtr.WebProductListingRepository;
26607 amit.gupta 83
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
26788 amit.gupta 84
import com.spice.profitmandi.dao.repository.fofo.CustomerAddressRepository;
26774 amit.gupta 85
import com.spice.profitmandi.dao.repository.fofo.CustomerRepository;
26855 tejbeer 86
import com.spice.profitmandi.dao.repository.fofo.PendingOrderItemRepository;
87
import com.spice.profitmandi.dao.repository.fofo.PendingOrderRepository;
26648 amit.gupta 88
import com.spice.profitmandi.dao.repository.fofo.PendingOrderService;
26715 amit.gupta 89
import com.spice.profitmandi.dao.repository.fofo.PincodePartnerRepository;
26607 amit.gupta 90
import com.spice.profitmandi.dao.repository.inventory.ItemAvailabilityCacheRepository;
26784 amit.gupta 91
import com.spice.profitmandi.service.CustomerService;
26607 amit.gupta 92
import com.spice.profitmandi.service.authentication.RoleManager;
26923 amit.gupta 93
import com.spice.profitmandi.service.inventory.AvailabilityModel;
26607 amit.gupta 94
import com.spice.profitmandi.service.inventory.FofoAvailabilityInfo;
95
import com.spice.profitmandi.service.inventory.FofoCatalogResponse;
26923 amit.gupta 96
import com.spice.profitmandi.service.inventory.InventoryService;
26909 amit.gupta 97
import com.spice.profitmandi.service.inventory.SaholicInventoryService;
26683 amit.gupta 98
import com.spice.profitmandi.service.scheme.SchemeService;
26651 amit.gupta 99
import com.spice.profitmandi.service.user.RetailerService;
26630 amit.gupta 100
import com.spice.profitmandi.web.processor.OtpProcessor;
26607 amit.gupta 101
import com.spice.profitmandi.web.res.DealBrands;
102
import com.spice.profitmandi.web.res.DealObjectResponse;
103
import com.spice.profitmandi.web.res.DealsResponse;
104
import com.spice.profitmandi.web.res.ValidateCartResponse;
105
 
106
import io.swagger.annotations.ApiImplicitParam;
107
import io.swagger.annotations.ApiImplicitParams;
108
import io.swagger.annotations.ApiOperation;
109
 
110
@Controller
111
@Transactional(rollbackFor = Throwable.class)
112
public class StoreController {
113
 
114
	private static final Logger logger = LogManager.getLogger(StoreController.class);
26630 amit.gupta 115
 
26628 amit.gupta 116
	private static final LocalTime CUTOFF_TIME = LocalTime.of(15, 0);
26745 amit.gupta 117
 
118
	private static final List<Integer> TAG_IDS = Arrays.asList(4);
119
 
26717 amit.gupta 120
	private static final int DEFAULT_STORE = 171912487;
26833 amit.gupta 121
 
26788 amit.gupta 122
	@Autowired
123
	CustomerAddressRepository customerAddressRepository;
26607 amit.gupta 124
 
26923 amit.gupta 125
	@Autowired
27030 amit.gupta 126
	SolrService solrService;
27045 tejbeer 127
 
27030 amit.gupta 128
	@Autowired
26923 amit.gupta 129
	InventoryService inventoryService;
27045 tejbeer 130
 
27030 amit.gupta 131
	@Autowired
132
	UserAccountRepository userAccountRepository;
26923 amit.gupta 133
 
26607 amit.gupta 134
	@Value("${python.api.host}")
135
	private String host;
26833 amit.gupta 136
 
26784 amit.gupta 137
	@Autowired
138
	CustomerService customerService;
26607 amit.gupta 139
 
140
	@Value("${python.api.port}")
141
	private int port;
26923 amit.gupta 142
 
26909 amit.gupta 143
	@Autowired
144
	private SaholicInventoryService saholicInventoryService;
26607 amit.gupta 145
 
146
	// This is now unused as we are not supporting multiple companies.
147
	@Value("${gadgetCops.invoice.cc}")
148
	private String[] ccGadgetCopInvoiceTo;
149
 
150
	@Autowired
26715 amit.gupta 151
	private PincodePartnerRepository pincodePartnerRepository;
152
 
153
	@Autowired
26718 amit.gupta 154
	private FofoStoreRepository fofoStoreRepository;
26745 amit.gupta 155
 
26718 amit.gupta 156
	@Autowired
26651 amit.gupta 157
	private RetailerService retailerService;
26861 tejbeer 158
 
26857 amit.gupta 159
	@Autowired
160
	private PendingOrderRepository pendingOrderRepository;
26861 tejbeer 161
 
26857 amit.gupta 162
	@Autowired
163
	private PendingOrderItemRepository pendingOrderItemRepository;
26652 amit.gupta 164
 
26651 amit.gupta 165
	@Autowired
26652 amit.gupta 166
	private PendingOrderService pendingOrderService;
26648 amit.gupta 167
 
168
	@Autowired
26774 amit.gupta 169
	private CustomerRepository customerRepository;
170
 
171
	@Autowired
26607 amit.gupta 172
	private SolrService commonSolrService;
173
 
174
	@Autowired
26630 amit.gupta 175
	private OtpProcessor otpProcessor;
176
 
177
	@Autowired
26607 amit.gupta 178
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
179
 
26609 amit.gupta 180
	@Autowired
26607 amit.gupta 181
	private ResponseSender<?> responseSender;
182
 
183
	@Autowired
184
	private TagListingRepository tagListingRepository;
185
 
186
	@Autowired
187
	private ItemRepository itemRepository;
26701 amit.gupta 188
 
26683 amit.gupta 189
	@Autowired
190
	private SchemeService schemeService;
26607 amit.gupta 191
 
192
	@Autowired
193
	private ItemAvailabilityCacheRepository itemAvailabilityCacheRepository;
194
 
195
	@Autowired
26745 amit.gupta 196
	private WebListingRepository webListingRepository;
197
 
198
	@Autowired
199
	private WebProductListingRepository webProductListingRepository;
200
 
201
	@Autowired
26607 amit.gupta 202
	private RoleManager roleManagerService;
203
 
27028 tejbeer 204
	@Autowired
205
	private VelocityEngine velocityEngine;
206
 
207
	@Autowired
208
	JavaMailSender mailSender;
209
 
26607 amit.gupta 210
	List<String> filterableParams = Arrays.asList("brand");
211
 
27045 tejbeer 212
	/*
213
	 * @ApiImplicitParams({
214
	 * 
215
	 * @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true,
216
	 * dataType = "string", paramType = "header") })
217
	 * 
218
	 * @RequestMapping(value = "/store/fofo", method = RequestMethod.GET, produces =
219
	 * MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<?>
220
	 * getFofo(HttpServletRequest request,
221
	 * 
222
	 * @RequestParam(value = "categoryId", required = false, defaultValue =
223
	 * "(3 OR 6)") String categoryId,
224
	 * 
225
	 * @RequestParam(value = "offset") String offset, @RequestParam(value = "limit")
226
	 * String limit,
227
	 * 
228
	 * @RequestParam(value = "sort", required = false) String sort,
229
	 * 
230
	 * @RequestParam(value = "brand", required = false) String brand,
231
	 * 
232
	 * @RequestParam(value = "subCategoryId", required = false) int subCategoryId,
233
	 * 
234
	 * @RequestParam(value = "q", required = false) String queryTerm,
235
	 * 
236
	 * @RequestParam(value = "hotDeal", required = false) boolean hotDeal) throws
237
	 * Throwable { List<FofoCatalogResponse> dealResponse = new ArrayList<>();
238
	 * UserInfo userInfo = (UserInfo) request.getAttribute("userInfo"); if
239
	 * (roleManagerService.isPartner(userInfo.getRoleIds())) { // UserCart uc =
240
	 * userAccountRepository.getUserCart(userInfo.getUserId()); RestClient rc = new
241
	 * RestClient(); Map<String, String> params = new HashMap<>(); List<String>
242
	 * mandatoryQ = new ArrayList<>(); if (queryTerm != null &&
243
	 * !queryTerm.equals("null")) { mandatoryQ.add(String.format("+(%s)",
244
	 * queryTerm)); } else { queryTerm = null; } if (subCategoryId != 0) {
245
	 * mandatoryQ .add(String.
246
	 * format("+(subCategoryId_i:%s) +{!parent which=\"subCategoryId_i:%s\"} tagId_i:(%s)"
247
	 * , subCategoryId, subCategoryId, StringUtils.join(TAG_IDS, " "))); } else if
248
	 * (hotDeal) { mandatoryQ.add(String.
249
	 * format("+{!parent which=\"hot_deals_b=true\"} tagId_i:(%s)",
250
	 * StringUtils.join(TAG_IDS, " ")));
251
	 * 
252
	 * } else if (StringUtils.isNotBlank(brand)) { mandatoryQ.add( String.
253
	 * format("+(categoryId_i:%s) +(brand_ss:%s) +{!parent which=\"brand_ss:%s\"} tagId_i:(%s)"
254
	 * , categoryId, brand, brand, StringUtils.join(TAG_IDS, " ")));
255
	 * 
256
	 * } else { mandatoryQ.add(
257
	 * String.format("+{!parent which=\"id:catalog*\"} tagId_i:(%s)",
258
	 * StringUtils.join(TAG_IDS, " "))); } params.put("q",
259
	 * StringUtils.join(mandatoryQ, " ")); params.put("fl",
260
	 * "*, [child parentFilter=id:catalog*]"); if (queryTerm == null) {
261
	 * params.put("sort", "create_s desc"); } params.put("start",
262
	 * String.valueOf(offset)); params.put("rows", String.valueOf(limit));
263
	 * params.put("wt", "json"); String response = null; try { response =
264
	 * rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params); }
265
	 * catch (HttpHostConnectException e) { throw new
266
	 * ProfitMandiBusinessException("", "", "Could not connect to host"); }
267
	 * JSONObject solrResponseJSONObj = new
268
	 * JSONObject(response).getJSONObject("response"); JSONArray docs =
269
	 * solrResponseJSONObj.getJSONArray("docs"); dealResponse =
270
	 * getCatalogResponse(docs, false, userInfo.getRetailerId());
271
	 * 
272
	 * if (Mongo.PARTNER_BLoCKED_BRANDS.containsKey(userInfo.getEmail())) {
273
	 * dealResponse.stream() .filter(x ->
274
	 * Mongo.PARTNER_BLoCKED_BRANDS.get(userInfo.getEmail()).contains(x.getBrand()))
275
	 * ; }
276
	 * 
277
	 * } else { return responseSender.badRequest( new
278
	 * ProfitMandiBusinessException("Retailer id", userInfo.getUserId(),
279
	 * "NOT_FOFO_RETAILER")); } return responseSender.ok(dealResponse); }
280
	 */
26607 amit.gupta 281
 
26668 amit.gupta 282
	@RequestMapping(value = "/store/entity/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
283
	@ApiImplicitParams({
284
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
285
	@ApiOperation(value = "Get unit deal object")
286
	public ResponseEntity<?> getUnitFocoDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
287
			throws ProfitMandiBusinessException {
288
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
289
		List<Integer> tagIds = Arrays.asList(4);
290
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
291
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
292
			String categoryId = "(3 OR 6)";
26745 amit.gupta 293
 
26668 amit.gupta 294
			RestClient rc = new RestClient();
295
			Map<String, String> params = new HashMap<>();
296
			List<String> mandatoryQ = new ArrayList<>();
297
			String catalogString = "catalog" + id;
26607 amit.gupta 298
 
26668 amit.gupta 299
			mandatoryQ.add(String.format("+(categoryId_i:%s) +(id:%s) +{!parent which=\"id:%s\"} tagId_i:(%s)",
300
					categoryId, catalogString, catalogString, StringUtils.join(tagIds, " ")));
301
 
302
			params.put("q", StringUtils.join(mandatoryQ, " "));
303
			params.put("fl", "*, [child parentFilter=id:catalog*]");
304
			params.put("sort", "rank_i asc, create_s desc");
305
			params.put("wt", "json");
306
			String response = null;
307
			try {
308
				response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
309
			} catch (HttpHostConnectException e) {
310
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
311
			}
312
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
313
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
26909 amit.gupta 314
			dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId());
26668 amit.gupta 315
		} else {
316
			return responseSender.badRequest(
317
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
318
		}
319
		return responseSender.ok(dealResponse.get(0));
320
	}
321
 
26607 amit.gupta 322
	private Object toDealObject(JsonObject jsonObject) {
323
		if (jsonObject.get("dealObject") != null && jsonObject.get("dealObject").asInt() == 1) {
324
			return new Gson().fromJson(jsonObject.toString(), DealObjectResponse.class);
325
		}
326
		return new Gson().fromJson(jsonObject.toString(), DealsResponse.class);
327
	}
328
 
329
	@RequestMapping(value = "/store/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
330
	@ApiImplicitParams({
331
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
332
	@ApiOperation(value = "Get brand list and count for category")
333
	public ResponseEntity<?> getBrands(HttpServletRequest request,
334
			@RequestParam(value = "category_id") String category_id) throws ProfitMandiBusinessException {
335
		logger.info("Request " + request.getParameterMap());
336
		String response = null;
337
		// TODO: move to properties
338
		String uri = ProfitMandiConstants.URL_BRANDS;
339
		RestClient rc = new RestClient();
340
		Map<String, String> params = new HashMap<>();
341
		params.put("category_id", category_id);
342
		List<DealBrands> dealBrandsResponse = null;
343
		try {
344
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
345
		} catch (HttpHostConnectException e) {
346
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
347
		}
348
 
349
		dealBrandsResponse = new Gson().fromJson(response, new TypeToken<List<DealBrands>>() {
350
		}.getType());
351
 
352
		return responseSender.ok(dealBrandsResponse);
353
	}
354
 
26745 amit.gupta 355
	@RequestMapping(value = "/store/listing/{listingUrl}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
356
	public ResponseEntity<?> bestSellers(HttpServletRequest request, @PathVariable String listingUrl) throws Exception {
26654 amit.gupta 357
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
26909 amit.gupta 358
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
26666 amit.gupta 359
		List<Integer> tagIds = Arrays.asList(4);
26745 amit.gupta 360
 
361
		WebListing webListing = webListingRepository.selectByUrl("url");
362
		if (webListing == null) {
363
			throw new ProfitMandiBusinessException("Url", listingUrl, "Could not find the Url");
364
		}
365
		List<Integer> webProducts = webProductListingRepository.selectAllByWebListingId(webListing.getId()).stream()
366
				.filter(x -> x.getRank() > 0).map(x -> x.getEntityId()).collect(Collectors.toList());
367
 
26654 amit.gupta 368
		RestClient rc = new RestClient();
369
		Map<String, String> params = new HashMap<>();
370
		List<String> mandatoryQ = new ArrayList<>();
26745 amit.gupta 371
		mandatoryQ.add(String.format(
372
				"+{!parent which=\"catalogId_i:" + StringUtils.join(webProducts, " ") + "\"} tagId_i:(%s)",
373
				StringUtils.join(tagIds, " ")));
26654 amit.gupta 374
		params.put("q", StringUtils.join(mandatoryQ, " "));
375
		params.put("fl", "*, [child parentFilter=id:catalog*]");
376
		// params.put("sort", "create_s desc");
377
		params.put("start", String.valueOf(0));
378
		params.put("rows", String.valueOf(30));
379
		params.put("wt", "json");
380
		String response = null;
381
		try {
382
			response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
383
		} catch (HttpHostConnectException e) {
384
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
385
		}
386
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
387
		JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
26745 amit.gupta 388
		final Ordering<Integer> rankOrdering = Ordering.explicit(webProducts);
26923 amit.gupta 389
		dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId()).stream()
390
				.sorted(new Comparator<FofoCatalogResponse>() {
391
					@Override
392
					public int compare(FofoCatalogResponse o1, FofoCatalogResponse o2) {
393
						return rankOrdering.compare(o1.getCatalogId(), o2.getCatalogId());
394
					}
395
				}).collect(Collectors.toList());
26745 amit.gupta 396
		webListing.setFofoCatalogResponses(dealResponse);
397
		return responseSender.ok(webListing);
26654 amit.gupta 398
	}
399
 
26632 amit.gupta 400
	@RequestMapping(value = "/store/otp/generateOTP", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
26783 amit.gupta 401
	public ResponseEntity<?> generateOtp(HttpServletRequest request, @RequestParam String mobile) throws Exception {
26630 amit.gupta 402
 
26857 amit.gupta 403
		return responseSender.ok(otpProcessor.generateOtp(mobile, OtpType.REGISTRATION));
26630 amit.gupta 404
 
405
	}
26652 amit.gupta 406
 
26784 amit.gupta 407
	@RequestMapping(value = "/store/checkmobile/{mobile}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
26833 amit.gupta 408
	public ResponseEntity<?> checkRegistrationUsingMobile(HttpServletRequest request, @PathVariable String mobile)
409
			throws Exception {
26774 amit.gupta 410
		try {
411
			Customer customer = customerRepository.selectByMobileNumber(mobile);
26777 amit.gupta 412
			customer.setPasswordExist(StringUtils.isNotEmpty(customer.getPassword()));
26774 amit.gupta 413
			return responseSender.ok(new CustomerModel(true, customer));
414
		} catch (Exception e) {
415
			return responseSender.ok(new CustomerModel(false, null));
416
		}
417
	}
26833 amit.gupta 418
 
26784 amit.gupta 419
	@RequestMapping(value = "/store/signin", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
420
	public ResponseEntity<?> signIn(HttpServletRequest request, @RequestBody UserModel userModel) throws Exception {
26833 amit.gupta 421
		if (customerService.authenticate(userModel.getMobile(), userModel.getPassword())) {
26784 amit.gupta 422
			return responseSender.ok(true);
423
		} else {
424
			return responseSender.ok(false);
425
		}
426
	}
26923 amit.gupta 427
 
26841 amit.gupta 428
	@RequestMapping(value = "/store/resetPassword", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
26923 amit.gupta 429
	public ResponseEntity<?> resetPassword(HttpServletRequest request, @RequestBody UserModel userModel)
430
			throws Exception {
26843 amit.gupta 431
		customerService.changePassword(userModel.getMobile(), userModel.getPassword());
26841 amit.gupta 432
		return responseSender.ok(true);
433
	}
26774 amit.gupta 434
 
26857 amit.gupta 435
	@RequestMapping(value = "/store/register", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
436
	public ResponseEntity<?> register(HttpServletRequest request, @RequestBody UserModel userModel) throws Exception {
437
		Customer customer = new Customer();
438
		customer.setPassword(userModel.getPassword());
439
		customer.setEmailId(userModel.getEmail());
440
		customer.setFirstName(userModel.getFirstName());
441
		customer.setLastName(userModel.getLastName());
442
		customer.setMobileNumber(userModel.getMobile());
443
		return responseSender.ok(customerService.addCustomer(customer));
444
	}
445
 
26648 amit.gupta 446
	@RequestMapping(value = "/store/confirmOrder", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
26857 amit.gupta 447
	public ResponseEntity<?> confirmOrder(HttpServletRequest request,
26652 amit.gupta 448
			@RequestBody CreatePendingOrderRequest createPendingOrderRequest) throws Exception {
26648 amit.gupta 449
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
450
		Integer storeId = userInfo.getRetailerId();
451
		createPendingOrderRequest.setFofoId(storeId);
26923 amit.gupta 452
		List<CreatePendingOrderItem> pendingOrderItems = createPendingOrderRequest.getCreatePendingOrderItem();
453
		List<CartItem> cartItems = new ArrayList<>();
454
		pendingOrderItems.stream().forEach(x -> {
455
			CartItem ci = new CartItem();
456
			ci.setItemId(x.getItemId());
457
			ci.setQuantity(x.getQuantity());
458
			ci.setSellingPrice(x.getSellingPrice());
459
			cartItems.add(ci);
460
		});
461
		CartResponse cr = this.validateCart(storeId, cartItems);
462
		if (cr.getCartMessageChanged() > 0 || cr.getTotalAmount() != createPendingOrderRequest.getTotalAmount()) {
463
			return responseSender.badRequest("Invalid request");
464
		}
26652 amit.gupta 465
 
27028 tejbeer 466
		Map<String, String> returnMap = this.pendingOrderService.createPendingOrder(createPendingOrderRequest, cr);
467
 
468
		return responseSender.ok(returnMap);
469
 
26648 amit.gupta 470
	}
26630 amit.gupta 471
 
27028 tejbeer 472
	private void sendMailWithAttachments(String subject, String messageText) throws Exception {
473
		MimeMessage message = mailSender.createMimeMessage();
474
		MimeMessageHelper helper = new MimeMessageHelper(message, true);
475
		String[] email = { "tejbeer.kaur@shop2020.in" };
476
		helper.setSubject(subject);
477
		helper.setText(messageText, true);
478
		helper.setTo(email);
479
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
480
		helper.setFrom(senderAddress);
481
		mailSender.send(message);
482
 
483
	}
484
 
26857 amit.gupta 485
	@RequestMapping(value = "/store/address", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
486
	@ApiImplicitParams({
487
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
488
	@ApiOperation(value = "Get brand list and count for category")
489
	public ResponseEntity<?> getAddress(HttpServletRequest request) throws Exception {
490
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
491
		Integer storeId = userInfo.getRetailerId();
492
		CustomRetailer customRetailer = retailerService.getFofoRetailer(storeId);
493
 
494
		return responseSender.ok(customRetailer.getAddress());
495
 
496
	}
497
 
498
	@RequestMapping(value = "/store/address/{pincode}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
499
	@ApiImplicitParams({
500
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
501
	@ApiOperation(value = "Get brand list and count for category")
502
	public ResponseEntity<?> getStoresByPincode(HttpServletRequest request, @PathVariable String pincode)
503
			throws Exception {
504
		List<PincodePartner> pincodePartners = pincodePartnerRepository.selectPartnersByPincode(pincode);
505
		int fofoId = DEFAULT_STORE;
506
		if (pincodePartners.size() > 0) {
507
			fofoId = pincodePartners.get(0).getFofoId();
508
		}
509
		return responseSender.ok(fofoStoreRepository.selectByRetailerId(fofoId).getCode());
510
	}
26923 amit.gupta 511
 
26855 tejbeer 512
	@RequestMapping(value = "/store/order", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
513
	public ResponseEntity<?> getOrderDetail(HttpServletRequest request, @RequestParam(value = "id") int id,
514
			@RequestParam(name = "offset") int offset, @RequestParam(name = "limit") int limit)
515
			throws ProfitMandiBusinessException {
516
		List<CustomerOrderDetail> customerOrderDetails = new ArrayList<>();
517
 
518
		List<PendingOrder> pendingOrders = pendingOrderRepository.selectByCustomerId(id, offset, limit);
519
		if (!pendingOrders.isEmpty()) {
520
			for (PendingOrder po : pendingOrders) {
521
				List<PendingOrderItem> pois = pendingOrderItemRepository.selectByOrderId(po.getId());
522
				for (PendingOrderItem poi : pois) {
523
 
524
					CustomerOrderDetail customerOrderDetail = new CustomerOrderDetail();
525
 
526
					Item item = itemRepository.selectById(poi.getItemId());
527
					customerOrderDetail.setBrand(item.getBrand());
528
					customerOrderDetail.setColor(item.getColor());
529
					customerOrderDetail.setId(poi.getOrderId());
530
					customerOrderDetail.setItemId(poi.getItemId());
531
					customerOrderDetail.setModelName(item.getModelName());
532
					customerOrderDetail.setModelNumber(item.getModelNumber());
533
					customerOrderDetail.setQuantity(poi.getQuantity());
27045 tejbeer 534
					customerOrderDetail.setBilledTimestamp(poi.getBilledTimestamp());
535
					customerOrderDetail.setStatus(poi.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
 
27030 amit.gupta 698
	@RequestMapping(value = "/store/partnerStock", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
699
	public ResponseEntity<?> partnerStock(HttpServletRequest request,
700
			@RequestParam(value = "categoryId", required = false, defaultValue = "3") String categoryId,
701
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
702
			@RequestParam(value = "sort", required = false) String sort,
703
			@RequestParam(value = "brand", required = false) String brand,
704
			@RequestParam(value = "subCategoryId", required = false) int subCategoryId,
705
			@RequestParam(value = "q", required = false) String queryTerm,
706
			@RequestParam(value = " ", required = false, defaultValue = "true") boolean partnerStockOnly)
707
			throws Throwable {
708
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
709
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
27045 tejbeer 710
		dealResponse = this.getCatalogResponse(
711
				solrService.getSolrDocs(queryTerm, categoryId, offset, limit, sort, brand, subCategoryId, false), false,
712
				userInfo.getRetailerId());
27030 amit.gupta 713
		return responseSender.ok(dealResponse);
714
	}
715
 
26909 amit.gupta 716
	private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal, int fofoId)
26607 amit.gupta 717
			throws ProfitMandiBusinessException {
26909 amit.gupta 718
		Map<Integer, Integer> ourItemAvailabilityMap = null;
719
		Map<Integer, Integer> partnerStockAvailabilityMap = null;
26607 amit.gupta 720
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
721
		List<Integer> tagIds = Arrays.asList(4);
722
		if (docs.length() > 0) {
723
			HashSet<Integer> itemsSet = new HashSet<>();
724
			for (int i = 0; i < docs.length(); i++) {
725
				JSONObject doc = docs.getJSONObject(i);
726
				if (doc.has("_childDocuments_")) {
727
					for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
728
						JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
729
						int itemId = childItem.getInt("itemId_i");
730
						itemsSet.add(itemId);
731
					}
732
				}
733
			}
734
			if (itemsSet.size() == 0) {
735
				return dealResponse;
736
			}
26909 amit.gupta 737
			if (hotDeal) {
738
				ourItemAvailabilityMap = saholicInventoryService
739
						.getTotalAvailabilityByItemIds(new ArrayList<>(itemsSet));
740
			} else if (fofoId > 0) {
741
				partnerStockAvailabilityMap = currentInventorySnapshotRepository.selectItemsStock(fofoId).stream()
742
						.collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
743
				ourItemAvailabilityMap = saholicInventoryService
744
						.getTotalAvailabilityByItemIds(new ArrayList<>(itemsSet));
745
			}
26607 amit.gupta 746
		}
747
 
748
		for (int i = 0; i < docs.length(); i++) {
749
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
750
			JSONObject doc = docs.getJSONObject(i);
751
			FofoCatalogResponse ffdr = new FofoCatalogResponse();
752
			ffdr.setCatalogId(doc.getInt("catalogId_i"));
753
			ffdr.setImageUrl(doc.getString("imageUrl_s"));
754
			ffdr.setTitle(doc.getString("title_s"));
755
			try {
756
				ffdr.setFeature(doc.getString("feature_s"));
757
			} catch (Exception e) {
758
				ffdr.setFeature(null);
759
				logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
760
			}
761
			ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
762
			if (doc.has("_childDocuments_")) {
763
				for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
764
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
765
					int itemId = childItem.getInt("itemId_i");
766
					float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
767
					if (fofoAvailabilityInfoMap.containsKey(itemId)) {
768
						if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
769
							fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
770
							fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
771
						}
772
					} else {
773
						FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
26909 amit.gupta 774
						fdi.setSellingPrice(sellingPrice);
775
						fdi.setActive(childItem.getBoolean("active_b"));
776
						fdi.setMrp(childItem.getDouble("mrp_f"));
26607 amit.gupta 777
						fdi.setMop((float) childItem.getDouble("mop_f"));
778
						fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
779
						fdi.setTagId(childItem.getInt("tagId_i"));
780
						fdi.setItem_id(itemId);
26909 amit.gupta 781
						Float cashBack = schemeService.getItemSchemeCashBack().get(itemId);
782
						cashBack = cashBack == null ? 0 : cashBack;
783
						fdi.setCashback(cashBack);
26673 amit.gupta 784
						fdi.setMinBuyQuantity(1);
26909 amit.gupta 785
						if (hotDeal) {
26607 amit.gupta 786
							try {
26909 amit.gupta 787
								int totalAvailability = ourItemAvailabilityMap.get(itemId);
788
								if (totalAvailability <= 0) {
789
									continue;
790
								}
791
								fdi.setAvailability(ourItemAvailabilityMap.get(itemId));
26607 amit.gupta 792
							} catch (Exception e) {
793
								continue;
794
							}
26909 amit.gupta 795
						} else if (fofoId == 0) {
796
							// For accessories item availability should at be ordered for Rs.1000
797
							fdi.setAvailability(100);
798
							Item item = itemRepository.selectById(itemId);
799
							// In case its tampered glass moq should be 5
800
							if (item.getCategoryId() == 10020) {
801
								fdi.setMinBuyQuantity(5);
26607 amit.gupta 802
							}
803
						} else {
26909 amit.gupta 804
							int ourStockAvailability = ourItemAvailabilityMap.get(itemId) == null ? 0
805
									: ourItemAvailabilityMap.get(itemId);
806
							int partnerAvailability = partnerStockAvailabilityMap.get(itemId) == null ? 0
807
									: partnerStockAvailabilityMap.get(itemId);
808
							fdi.setAvailability(ourStockAvailability + partnerAvailability);
26607 amit.gupta 809
						}
810
						fdi.setQuantityStep(1);
26909 amit.gupta 811
						fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
26607 amit.gupta 812
						fofoAvailabilityInfoMap.put(itemId, fdi);
813
					}
814
				}
815
			}
816
			if (fofoAvailabilityInfoMap.values().size() > 0) {
26909 amit.gupta 817
				ffdr.setItems(fofoAvailabilityInfoMap.values().stream()
26923 amit.gupta 818
						.sorted((x, y) -> y.getAvailability() - x.getAvailability()).collect(Collectors.toList()));
26607 amit.gupta 819
				dealResponse.add(ffdr);
820
			}
821
		}
822
		return dealResponse;
26909 amit.gupta 823
 
26607 amit.gupta 824
	}
26923 amit.gupta 825
 
826
	@GetMapping(value = "store/order-status/{pendingOrderId}")
27028 tejbeer 827
	public ResponseEntity<?> orderStatus(HttpServletRequest request, @PathVariable int pendingOrderId)
828
			throws Exception {
26923 amit.gupta 829
		PendingOrder pendingOrder = pendingOrderRepository.selectById(pendingOrderId);
830
		List<PendingOrderItem> pendingOrderItems = pendingOrderItemRepository.selectByOrderId(pendingOrder.getId());
831
		List<Integer> catalogIds = new ArrayList<>();
27028 tejbeer 832
		for (PendingOrderItem pendingOrderItem : pendingOrderItems) {
26923 amit.gupta 833
			Item item = itemRepository.selectById(pendingOrderItem.getItemId());
834
			pendingOrderItem.setItemName(item.getItemDescription());
835
			catalogIds.add(item.getCatalogItemId());
836
		}
837
		Map<Integer, JSONObject> contentMap = commonSolrService.getContentByCatalogIds(catalogIds);
27028 tejbeer 838
		for (PendingOrderItem pendingOrderItem : pendingOrderItems) {
26923 amit.gupta 839
			Item item = itemRepository.selectById(pendingOrderItem.getItemId());
840
			JSONObject jsonObj = contentMap.get(item.getCatalogItemId());
841
			pendingOrderItem.setImgUrl(jsonObj.getString("imageUrl_s"));
842
		}
843
		pendingOrder.setPendingOrderItems(pendingOrderItems);
844
		return responseSender.ok(pendingOrder);
845
	}
846
 
26833 amit.gupta 847
	@RequestMapping(value = "/store/addresses/{customerId}", method = RequestMethod.GET)
848
	public ResponseEntity<?> getAll(HttpServletRequest request, @PathVariable int customerId) throws Throwable {
27045 tejbeer 849
		return responseSender.ok(customerAddressRepository.selectByActiveCustomerId(customerId));
26788 amit.gupta 850
	}
26833 amit.gupta 851
 
26857 amit.gupta 852
	@RequestMapping(value = "/store/address", method = RequestMethod.POST)
853
	public ResponseEntity<?> addAddress(HttpServletRequest request, @RequestBody CustomerAddress customerAddress)
854
			throws Throwable {
855
		customerAddressRepository.persist(customerAddress);
856
		return responseSender.ok(customerAddress);
857
	}
858
 
27045 tejbeer 859
	@RequestMapping(value = "/store/deactivateCustomerAddress", method = RequestMethod.POST)
860
	public ResponseEntity<?> deactivateAddresss(HttpServletRequest request, @RequestParam int id) throws Throwable {
861
		CustomerAddress cust = customerAddressRepository.selectById(id);
862
		cust.setActive(false);
863
		return responseSender.ok(cust);
864
	}
865
 
26861 tejbeer 866
	@RequestMapping(value = "/store/updateCustomer", method = RequestMethod.POST)
867
	public ResponseEntity<?> updateCustomerProfile(HttpServletRequest request, @RequestBody Customer customer)
868
			throws Throwable {
869
		Customer cust = customerRepository.selectById(customer.getId());
870
		cust.setGender(customer.getGender());
26867 tejbeer 871
		cust.setProfileImageId(customer.getProfileImageId());
26861 tejbeer 872
		cust.setDob(customer.getDob());
873
		return responseSender.ok(cust);
874
	}
875
 
27048 tejbeer 876
	@RequestMapping(value = "/cancelPendingOrderItem", method = RequestMethod.POST)
877
	public ResponseEntity<?> cancelPendingOrderItem(HttpServletRequest request, @RequestParam int id,
27045 tejbeer 878
 
27048 tejbeer 879
			@RequestParam String statusDescription) throws Exception {
880
 
881
		PendingOrderItem pendingOrderItem = pendingOrderItemRepository.selectById(id);
882
 
883
		PendingOrder pendingOrder = pendingOrderRepository.selectById(pendingOrderItem.getId());
884
		if (pendingOrderItem.getBilledTimestamp() == null) {
885
			pendingOrderItem.setStatus(OrderStatus.CANCELLED);
886
			pendingOrderItem.setStatusDescription(statusDescription);
887
			List<OrderStatus> status = pendingOrderItemRepository.selectByOrderId(pendingOrderItem.getOrderId())
888
					.stream().map(x -> x.getStatus()).collect(Collectors.toList());
889
 
890
			if (!status.contains(OrderStatus.PENDING)) {
891
				pendingOrder.setStatus(OrderStatus.CLOSED);
892
			}
893
 
894
			pendingOrderItemRepository.persist(pendingOrderItem);
895
		}
896
 
897
		return responseSender.ok(true);
898
 
899
	}
900
 
26774 amit.gupta 901
}
902
 
26784 amit.gupta 903
class UserModel {
26857 amit.gupta 904
	@JsonProperty(required = true)
26784 amit.gupta 905
	private String mobile;
26857 amit.gupta 906
	@JsonProperty(required = true)
26784 amit.gupta 907
	private String password;
26857 amit.gupta 908
	@JsonProperty(required = false)
909
	private String firstName;
910
	@JsonProperty(required = false)
911
	private String lastName;
912
	@JsonProperty(required = false)
913
	private String email;
26833 amit.gupta 914
 
26784 amit.gupta 915
	@Override
916
	public String toString() {
917
		return "UserModel [mobile=" + mobile + ", password=" + password + "]";
918
	}
26833 amit.gupta 919
 
26784 amit.gupta 920
	public String getMobile() {
921
		return mobile;
922
	}
26833 amit.gupta 923
 
26784 amit.gupta 924
	public void setMobile(String mobile) {
925
		this.mobile = mobile;
926
	}
26833 amit.gupta 927
 
26784 amit.gupta 928
	public String getPassword() {
929
		return password;
930
	}
26833 amit.gupta 931
 
26784 amit.gupta 932
	public void setPassword(String password) {
933
		this.password = password;
934
	}
26857 amit.gupta 935
 
936
	public String getFirstName() {
937
		return firstName;
938
	}
939
 
940
	public void setFirstName(String firstName) {
941
		this.firstName = firstName;
942
	}
943
 
944
	public String getLastName() {
945
		return lastName;
946
	}
947
 
948
	public void setLastName(String lastName) {
949
		this.lastName = lastName;
950
	}
951
 
952
	public String getEmail() {
953
		return email;
954
	}
955
 
956
	public void setEmail(String email) {
957
		this.email = email;
958
	}
959
 
26784 amit.gupta 960
}
961
 
26774 amit.gupta 962
class CustomerModel {
26783 amit.gupta 963
 
26774 amit.gupta 964
	@JsonProperty(required = false)
965
	private Customer customer;
966
	@JsonProperty(required = true)
967
	private boolean exists;
968
 
969
	public CustomerModel(boolean exists, Customer customer) {
970
		super();
971
		this.customer = customer;
972
		this.exists = exists;
973
	}
974
 
975
	@Override
976
	public String toString() {
977
		return "CustomerModel [customer=" + customer + ", exists=" + exists + "]";
978
	}
979
 
980
	public Customer getCustomer() {
981
		return customer;
982
	}
983
 
984
	public void setCustomer(Customer customer) {
985
		this.customer = customer;
986
	}
987
 
988
	public boolean isExists() {
989
		return exists;
990
	}
991
 
992
	public void setExists(boolean exists) {
993
		this.exists = exists;
994
	}
26607 amit.gupta 995
}