Subversion Repositories SmartDukaan

Rev

Rev 27048 | Rev 27056 | 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,
27049 tejbeer 514
			@RequestParam(name = "offset") int offset, @RequestParam(name = "limit") int limit) throws Exception {
26855 tejbeer 515
		List<CustomerOrderDetail> customerOrderDetails = new ArrayList<>();
27049 tejbeer 516
		List<Integer> catalogIds = new ArrayList<>();
26855 tejbeer 517
		List<PendingOrder> pendingOrders = pendingOrderRepository.selectByCustomerId(id, offset, limit);
518
		if (!pendingOrders.isEmpty()) {
519
			for (PendingOrder po : pendingOrders) {
520
				List<PendingOrderItem> pois = pendingOrderItemRepository.selectByOrderId(po.getId());
27049 tejbeer 521
				for (PendingOrderItem pendingOrderItem : pois) {
522
					Item item = itemRepository.selectById(pendingOrderItem.getItemId());
523
					pendingOrderItem.setItemName(item.getItemDescription());
524
					catalogIds.add(item.getCatalogItemId());
525
				}
526
 
527
				Map<Integer, JSONObject> contentMap = commonSolrService.getContentByCatalogIds(catalogIds);
528
 
26855 tejbeer 529
				for (PendingOrderItem poi : pois) {
530
 
531
					CustomerOrderDetail customerOrderDetail = new CustomerOrderDetail();
532
 
533
					Item item = itemRepository.selectById(poi.getItemId());
27049 tejbeer 534
					JSONObject jsonObj = contentMap.get(item.getCatalogItemId());
535
					customerOrderDetail.setImageUrl(jsonObj.getString("imageUrl_s"));
26855 tejbeer 536
					customerOrderDetail.setBrand(item.getBrand());
537
					customerOrderDetail.setColor(item.getColor());
538
					customerOrderDetail.setId(poi.getOrderId());
539
					customerOrderDetail.setItemId(poi.getItemId());
540
					customerOrderDetail.setModelName(item.getModelName());
541
					customerOrderDetail.setModelNumber(item.getModelNumber());
542
					customerOrderDetail.setQuantity(poi.getQuantity());
27045 tejbeer 543
					customerOrderDetail.setBilledTimestamp(poi.getBilledTimestamp());
544
					customerOrderDetail.setStatus(poi.getStatus());
26855 tejbeer 545
					customerOrderDetail.setTotalPrice(poi.getSellingPrice());
546
					customerOrderDetail.setPayMethod(po.getPayMethod());
26861 tejbeer 547
					customerOrderDetail.setCreatedTimeStamp(po.getCreateTimestamp());
26855 tejbeer 548
					customerOrderDetails.add(customerOrderDetail);
549
				}
550
			}
551
		}
552
 
553
		return responseSender.ok(customerOrderDetails);
554
	}
555
 
26745 amit.gupta 556
	@RequestMapping(value = "/store/listing", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
557
	@Cacheable(value = "storelisting.all", cacheManager = "thirtyMinsTimeOutCacheManager")
26774 amit.gupta 558
	public ResponseEntity<?> getStoresListing(HttpServletRequest request) throws Exception {
26745 amit.gupta 559
		List<WebListing> webListings = webListingRepository.selectAllWebListing(Optional.of(true));
560
		for (WebListing webListing : webListings) {
26909 amit.gupta 561
			UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
562
			Integer storeId = userInfo.getRetailerId();
26923 amit.gupta 563
 
26745 amit.gupta 564
			List<Integer> webProducts = webProductListingRepository.selectAllByWebListingId(webListing.getId()).stream()
565
					.filter(x -> x.getRank() > 0).map(x -> x.getEntityId()).collect(Collectors.toList());
566
 
567
			RestClient rc = new RestClient();
568
			Map<String, String> params = new HashMap<>();
569
			List<String> mandatoryQ = new ArrayList<>();
570
			mandatoryQ.add(String.format(
571
					"+{!parent which=\"catalogId_i:" + StringUtils.join(webProducts, " ") + "\"} tagId_i:(%s)",
572
					StringUtils.join(TAG_IDS, " ")));
573
			params.put("q", StringUtils.join(mandatoryQ, " "));
574
			params.put("fl", "*, [child parentFilter=id:catalog*]");
575
			// params.put("sort", "create_s desc");
576
			params.put("start", String.valueOf(0));
577
			params.put("rows", String.valueOf(30));
578
			params.put("wt", "json");
579
			String response = null;
580
			try {
581
				response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
582
			} catch (HttpHostConnectException e) {
583
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
584
			}
585
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
586
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
587
			final Ordering<Integer> colorOrdering = Ordering.explicit(webProducts);
26909 amit.gupta 588
			List<FofoCatalogResponse> dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId()).stream()
26745 amit.gupta 589
					.sorted(new Comparator<FofoCatalogResponse>() {
590
						@Override
591
						public int compare(FofoCatalogResponse o1, FofoCatalogResponse o2) {
592
							return colorOrdering.compare(o1.getCatalogId(), o2.getCatalogId());
593
						}
594
					}).collect(Collectors.toList());
595
			webListing.setFofoCatalogResponses(dealResponse);
596
		}
597
		return responseSender.ok(webListings);
598
	}
599
 
26652 amit.gupta 600
	@RequestMapping(value = "/store/cart", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
601
	@ApiImplicitParams({
26651 amit.gupta 602
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
26652 amit.gupta 603
	@ApiOperation(value = "Get brand list and count for category")
604
	public ResponseEntity<?> cart(HttpServletRequest request, @RequestBody AddCartRequest cartRequest)
605
			throws Exception {
26923 amit.gupta 606
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
607
		Integer storeId = userInfo.getRetailerId();
608
		ValidateCartResponse vc = new ValidateCartResponse(this.validateCart(storeId, cartRequest.getCartItems()),
609
				"Success", "Items added to cart successfully");
610
		return responseSender.ok(vc);
611
	}
612
 
613
	// Validate Cart for B2C Customers
614
	private CartResponse validateCart(int storeId, List<CartItem> cartItems) throws Exception {
615
		cartItems = cartItems.stream().filter(x -> x.getQuantity() > 0).collect(Collectors.toList());
616
		List<Integer> itemIds = cartItems.stream().map(x -> x.getItemId()).collect(Collectors.toList());
617
		Map<Integer, AvailabilityModel> inventoryItemAvailabilityMap = inventoryService.getStoreAndOurStock(storeId,
618
				itemIds);
26607 amit.gupta 619
		CartResponse cartResponse = new CartResponse();
26612 amit.gupta 620
		List<CartItemResponseModel> cartItemResponseModels = new ArrayList<>();
621
		cartResponse.setCartItems(cartItemResponseModels);
26607 amit.gupta 622
		Set<Integer> itemsIdsSet = new HashSet<>(itemIds);
26668 amit.gupta 623
		logger.info("Store Id {}, Item Ids {}", storeId, itemsIdsSet);
26607 amit.gupta 624
 
625
		Map<Integer, Item> itemsMap = itemRepository.selectByIds(itemsIdsSet).stream()
626
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
627
 
26923 amit.gupta 628
		Map<Integer, TagListing> tagListingMap = tagListingRepository
26607 amit.gupta 629
				.selectByItemIdsAndTagIds(new HashSet<>(itemIds), new HashSet<>(Arrays.asList(4))).stream()
630
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
631
 
632
		List<Integer> catalogIds = itemsMap.values().stream().map(x -> x.getCatalogItemId())
633
				.collect(Collectors.toList());
634
 
635
		Map<Integer, JSONObject> contentMap = commonSolrService.getContentByCatalogIds(catalogIds);
636
 
637
		// cartResponse.getCartItems()
26923 amit.gupta 638
		int cartMessageChanged = 0;
639
		int cartMessageOOS = 0;
640
		int totalAmount = 0;
641
		int totalQty = 0;
642
		for (CartItem cartItem : cartItems) {
26607 amit.gupta 643
			Item item = itemsMap.get(cartItem.getItemId());
26923 amit.gupta 644
			TagListing tagListing = tagListingMap.get(cartItem.getItemId());
645
			Float cashback = schemeService.getItemSchemeCashBack().get(cartItem.getItemId());
646
			cashback = cashback == null ? 0 : cashback;
647
			float itemSellingPrice = tagListing.getMop() - cashback;
26607 amit.gupta 648
			CartItemResponseModel cartItemResponseModel = new CartItemResponseModel();
26923 amit.gupta 649
			cartItemResponseModel.setSellingPrice(cartItem.getSellingPrice());
650
			if (itemSellingPrice != cartItem.getSellingPrice()) {
651
				cartItemResponseModel.setSellingPrice(itemSellingPrice);
652
				cartMessageChanged++;
653
			}
26628 amit.gupta 654
			int estimate = -2;
27025 tejbeer 655
			LocalDateTime promiseDeliveryTime = LocalDateTime.now();
26923 amit.gupta 656
			int qtyRequired = (int) cartItem.getQuantity();
657
			AvailabilityModel availabilityModel = inventoryItemAvailabilityMap.get(cartItem.getItemId());
658
			cartItemResponseModel.setMaxQuantity(availabilityModel.getMaxAvailability());
659
			if (availabilityModel.getStoreAvailability() >= qtyRequired) {
660
				estimate = 0;
661
			} else if (availabilityModel.getWarehouseAvailability() >= qtyRequired) {
26628 amit.gupta 662
				estimate = 2;
26923 amit.gupta 663
			} else if (availabilityModel.getStoreAvailability() > 0) {
664
				estimate = 0;
665
				qtyRequired = availabilityModel.getStoreAvailability();
666
				cartMessageChanged++;
667
			} else if (availabilityModel.getWarehouseAvailability() > 0) {
668
				qtyRequired = availabilityModel.getWarehouseAvailability();
669
				estimate = 2;
670
				cartMessageChanged++;
26620 amit.gupta 671
			} else {
26923 amit.gupta 672
				qtyRequired = 0;
26926 amit.gupta 673
				cartMessageChanged++;
26607 amit.gupta 674
			}
26923 amit.gupta 675
			cartItemResponseModel.setQuantity(qtyRequired);
26630 amit.gupta 676
			if (estimate >= 0 && LocalTime.now().isAfter(CUTOFF_TIME)) {
26628 amit.gupta 677
				estimate = estimate + 1;
27025 tejbeer 678
				promiseDeliveryTime = promiseDeliveryTime.plusDays(3);
26628 amit.gupta 679
			}
26923 amit.gupta 680
			totalQty += qtyRequired;
681
			totalAmount += qtyRequired * itemSellingPrice;
26628 amit.gupta 682
			cartItemResponseModel.setEstimate(estimate);
26616 amit.gupta 683
			cartItemResponseModel.setTitle(item.getItemDescriptionNoColor());
26614 amit.gupta 684
			cartItemResponseModel.setItemId(cartItem.getItemId());
26615 amit.gupta 685
			cartItemResponseModel.setMinBuyQuantity(1);
26923 amit.gupta 686
			cartItemResponseModel.setQuantity(qtyRequired);
26621 amit.gupta 687
			cartItemResponseModel.setQuantityStep(1);
27025 tejbeer 688
			cartItemResponseModel.setPromiseDelivery(promiseDeliveryTime);
26923 amit.gupta 689
			cartItemResponseModel.setMaxQuantity(availabilityModel.getMaxAvailability());
26607 amit.gupta 690
			cartItemResponseModel.setCatalogItemId(item.getCatalogItemId());
691
			cartItemResponseModel.setImageUrl(contentMap.get(item.getCatalogItemId()).getString("imageUrl_s"));
692
			cartItemResponseModel.setColor(item.getColor());
26620 amit.gupta 693
			cartItemResponseModels.add(cartItemResponseModel);
26607 amit.gupta 694
		}
26923 amit.gupta 695
		cartResponse.setCartItems(cartItemResponseModels);
696
		cartResponse.setCartMessageChanged(cartMessageChanged);
697
		cartResponse.setCartMessageOOS(cartMessageOOS);
698
		int maxEstimate = cartItemResponseModels.stream().mapToInt(x -> x.getEstimate()).max().getAsInt();
699
		cartResponse.setMaxEstimate(maxEstimate);
700
		cartResponse.setTotalAmount(totalAmount);
701
		cartResponse.setTotalQty(totalQty);
26652 amit.gupta 702
 
26923 amit.gupta 703
		return cartResponse;
704
 
26648 amit.gupta 705
	}
26607 amit.gupta 706
 
27030 amit.gupta 707
	@RequestMapping(value = "/store/partnerStock", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
708
	public ResponseEntity<?> partnerStock(HttpServletRequest request,
709
			@RequestParam(value = "categoryId", required = false, defaultValue = "3") String categoryId,
710
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
711
			@RequestParam(value = "sort", required = false) String sort,
712
			@RequestParam(value = "brand", required = false) String brand,
713
			@RequestParam(value = "subCategoryId", required = false) int subCategoryId,
714
			@RequestParam(value = "q", required = false) String queryTerm,
715
			@RequestParam(value = " ", required = false, defaultValue = "true") boolean partnerStockOnly)
716
			throws Throwable {
717
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
718
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
27045 tejbeer 719
		dealResponse = this.getCatalogResponse(
720
				solrService.getSolrDocs(queryTerm, categoryId, offset, limit, sort, brand, subCategoryId, false), false,
721
				userInfo.getRetailerId());
27030 amit.gupta 722
		return responseSender.ok(dealResponse);
723
	}
724
 
26909 amit.gupta 725
	private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal, int fofoId)
26607 amit.gupta 726
			throws ProfitMandiBusinessException {
26909 amit.gupta 727
		Map<Integer, Integer> ourItemAvailabilityMap = null;
728
		Map<Integer, Integer> partnerStockAvailabilityMap = null;
26607 amit.gupta 729
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
730
		List<Integer> tagIds = Arrays.asList(4);
731
		if (docs.length() > 0) {
732
			HashSet<Integer> itemsSet = new HashSet<>();
733
			for (int i = 0; i < docs.length(); i++) {
734
				JSONObject doc = docs.getJSONObject(i);
735
				if (doc.has("_childDocuments_")) {
736
					for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
737
						JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
738
						int itemId = childItem.getInt("itemId_i");
739
						itemsSet.add(itemId);
740
					}
741
				}
742
			}
743
			if (itemsSet.size() == 0) {
744
				return dealResponse;
745
			}
26909 amit.gupta 746
			if (hotDeal) {
747
				ourItemAvailabilityMap = saholicInventoryService
748
						.getTotalAvailabilityByItemIds(new ArrayList<>(itemsSet));
749
			} else if (fofoId > 0) {
750
				partnerStockAvailabilityMap = currentInventorySnapshotRepository.selectItemsStock(fofoId).stream()
751
						.collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
752
				ourItemAvailabilityMap = saholicInventoryService
753
						.getTotalAvailabilityByItemIds(new ArrayList<>(itemsSet));
754
			}
26607 amit.gupta 755
		}
756
 
757
		for (int i = 0; i < docs.length(); i++) {
758
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
759
			JSONObject doc = docs.getJSONObject(i);
760
			FofoCatalogResponse ffdr = new FofoCatalogResponse();
761
			ffdr.setCatalogId(doc.getInt("catalogId_i"));
762
			ffdr.setImageUrl(doc.getString("imageUrl_s"));
763
			ffdr.setTitle(doc.getString("title_s"));
764
			try {
765
				ffdr.setFeature(doc.getString("feature_s"));
766
			} catch (Exception e) {
767
				ffdr.setFeature(null);
768
				logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
769
			}
770
			ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
771
			if (doc.has("_childDocuments_")) {
772
				for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
773
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
774
					int itemId = childItem.getInt("itemId_i");
775
					float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
776
					if (fofoAvailabilityInfoMap.containsKey(itemId)) {
777
						if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
778
							fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
779
							fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
780
						}
781
					} else {
782
						FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
26909 amit.gupta 783
						fdi.setSellingPrice(sellingPrice);
784
						fdi.setActive(childItem.getBoolean("active_b"));
785
						fdi.setMrp(childItem.getDouble("mrp_f"));
26607 amit.gupta 786
						fdi.setMop((float) childItem.getDouble("mop_f"));
787
						fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
788
						fdi.setTagId(childItem.getInt("tagId_i"));
789
						fdi.setItem_id(itemId);
26909 amit.gupta 790
						Float cashBack = schemeService.getItemSchemeCashBack().get(itemId);
791
						cashBack = cashBack == null ? 0 : cashBack;
792
						fdi.setCashback(cashBack);
26673 amit.gupta 793
						fdi.setMinBuyQuantity(1);
26909 amit.gupta 794
						if (hotDeal) {
26607 amit.gupta 795
							try {
26909 amit.gupta 796
								int totalAvailability = ourItemAvailabilityMap.get(itemId);
797
								if (totalAvailability <= 0) {
798
									continue;
799
								}
800
								fdi.setAvailability(ourItemAvailabilityMap.get(itemId));
26607 amit.gupta 801
							} catch (Exception e) {
802
								continue;
803
							}
26909 amit.gupta 804
						} else if (fofoId == 0) {
805
							// For accessories item availability should at be ordered for Rs.1000
806
							fdi.setAvailability(100);
807
							Item item = itemRepository.selectById(itemId);
808
							// In case its tampered glass moq should be 5
809
							if (item.getCategoryId() == 10020) {
810
								fdi.setMinBuyQuantity(5);
26607 amit.gupta 811
							}
812
						} else {
26909 amit.gupta 813
							int ourStockAvailability = ourItemAvailabilityMap.get(itemId) == null ? 0
814
									: ourItemAvailabilityMap.get(itemId);
815
							int partnerAvailability = partnerStockAvailabilityMap.get(itemId) == null ? 0
816
									: partnerStockAvailabilityMap.get(itemId);
817
							fdi.setAvailability(ourStockAvailability + partnerAvailability);
26607 amit.gupta 818
						}
819
						fdi.setQuantityStep(1);
26909 amit.gupta 820
						fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
26607 amit.gupta 821
						fofoAvailabilityInfoMap.put(itemId, fdi);
822
					}
823
				}
824
			}
825
			if (fofoAvailabilityInfoMap.values().size() > 0) {
26909 amit.gupta 826
				ffdr.setItems(fofoAvailabilityInfoMap.values().stream()
26923 amit.gupta 827
						.sorted((x, y) -> y.getAvailability() - x.getAvailability()).collect(Collectors.toList()));
26607 amit.gupta 828
				dealResponse.add(ffdr);
829
			}
830
		}
831
		return dealResponse;
26909 amit.gupta 832
 
26607 amit.gupta 833
	}
26923 amit.gupta 834
 
835
	@GetMapping(value = "store/order-status/{pendingOrderId}")
27028 tejbeer 836
	public ResponseEntity<?> orderStatus(HttpServletRequest request, @PathVariable int pendingOrderId)
837
			throws Exception {
26923 amit.gupta 838
		PendingOrder pendingOrder = pendingOrderRepository.selectById(pendingOrderId);
839
		List<PendingOrderItem> pendingOrderItems = pendingOrderItemRepository.selectByOrderId(pendingOrder.getId());
840
		List<Integer> catalogIds = new ArrayList<>();
27028 tejbeer 841
		for (PendingOrderItem pendingOrderItem : pendingOrderItems) {
26923 amit.gupta 842
			Item item = itemRepository.selectById(pendingOrderItem.getItemId());
843
			pendingOrderItem.setItemName(item.getItemDescription());
844
			catalogIds.add(item.getCatalogItemId());
845
		}
846
		Map<Integer, JSONObject> contentMap = commonSolrService.getContentByCatalogIds(catalogIds);
27028 tejbeer 847
		for (PendingOrderItem pendingOrderItem : pendingOrderItems) {
26923 amit.gupta 848
			Item item = itemRepository.selectById(pendingOrderItem.getItemId());
849
			JSONObject jsonObj = contentMap.get(item.getCatalogItemId());
850
			pendingOrderItem.setImgUrl(jsonObj.getString("imageUrl_s"));
851
		}
852
		pendingOrder.setPendingOrderItems(pendingOrderItems);
853
		return responseSender.ok(pendingOrder);
854
	}
855
 
26833 amit.gupta 856
	@RequestMapping(value = "/store/addresses/{customerId}", method = RequestMethod.GET)
857
	public ResponseEntity<?> getAll(HttpServletRequest request, @PathVariable int customerId) throws Throwable {
27045 tejbeer 858
		return responseSender.ok(customerAddressRepository.selectByActiveCustomerId(customerId));
26788 amit.gupta 859
	}
26833 amit.gupta 860
 
26857 amit.gupta 861
	@RequestMapping(value = "/store/address", method = RequestMethod.POST)
862
	public ResponseEntity<?> addAddress(HttpServletRequest request, @RequestBody CustomerAddress customerAddress)
863
			throws Throwable {
864
		customerAddressRepository.persist(customerAddress);
865
		return responseSender.ok(customerAddress);
866
	}
867
 
27045 tejbeer 868
	@RequestMapping(value = "/store/deactivateCustomerAddress", method = RequestMethod.POST)
869
	public ResponseEntity<?> deactivateAddresss(HttpServletRequest request, @RequestParam int id) throws Throwable {
870
		CustomerAddress cust = customerAddressRepository.selectById(id);
871
		cust.setActive(false);
872
		return responseSender.ok(cust);
873
	}
874
 
26861 tejbeer 875
	@RequestMapping(value = "/store/updateCustomer", method = RequestMethod.POST)
876
	public ResponseEntity<?> updateCustomerProfile(HttpServletRequest request, @RequestBody Customer customer)
877
			throws Throwable {
878
		Customer cust = customerRepository.selectById(customer.getId());
879
		cust.setGender(customer.getGender());
26867 tejbeer 880
		cust.setProfileImageId(customer.getProfileImageId());
26861 tejbeer 881
		cust.setDob(customer.getDob());
882
		return responseSender.ok(cust);
883
	}
884
 
27048 tejbeer 885
	@RequestMapping(value = "/cancelPendingOrderItem", method = RequestMethod.POST)
886
	public ResponseEntity<?> cancelPendingOrderItem(HttpServletRequest request, @RequestParam int id,
27045 tejbeer 887
 
27048 tejbeer 888
			@RequestParam String statusDescription) throws Exception {
889
 
890
		PendingOrderItem pendingOrderItem = pendingOrderItemRepository.selectById(id);
891
 
892
		PendingOrder pendingOrder = pendingOrderRepository.selectById(pendingOrderItem.getId());
893
		if (pendingOrderItem.getBilledTimestamp() == null) {
894
			pendingOrderItem.setStatus(OrderStatus.CANCELLED);
895
			pendingOrderItem.setStatusDescription(statusDescription);
896
			List<OrderStatus> status = pendingOrderItemRepository.selectByOrderId(pendingOrderItem.getOrderId())
897
					.stream().map(x -> x.getStatus()).collect(Collectors.toList());
898
 
899
			if (!status.contains(OrderStatus.PENDING)) {
900
				pendingOrder.setStatus(OrderStatus.CLOSED);
901
			}
902
 
903
			pendingOrderItemRepository.persist(pendingOrderItem);
904
		}
905
 
906
		return responseSender.ok(true);
907
 
908
	}
909
 
26774 amit.gupta 910
}
911
 
26784 amit.gupta 912
class UserModel {
26857 amit.gupta 913
	@JsonProperty(required = true)
26784 amit.gupta 914
	private String mobile;
26857 amit.gupta 915
	@JsonProperty(required = true)
26784 amit.gupta 916
	private String password;
26857 amit.gupta 917
	@JsonProperty(required = false)
918
	private String firstName;
919
	@JsonProperty(required = false)
920
	private String lastName;
921
	@JsonProperty(required = false)
922
	private String email;
26833 amit.gupta 923
 
26784 amit.gupta 924
	@Override
925
	public String toString() {
926
		return "UserModel [mobile=" + mobile + ", password=" + password + "]";
927
	}
26833 amit.gupta 928
 
26784 amit.gupta 929
	public String getMobile() {
930
		return mobile;
931
	}
26833 amit.gupta 932
 
26784 amit.gupta 933
	public void setMobile(String mobile) {
934
		this.mobile = mobile;
935
	}
26833 amit.gupta 936
 
26784 amit.gupta 937
	public String getPassword() {
938
		return password;
939
	}
26833 amit.gupta 940
 
26784 amit.gupta 941
	public void setPassword(String password) {
942
		this.password = password;
943
	}
26857 amit.gupta 944
 
945
	public String getFirstName() {
946
		return firstName;
947
	}
948
 
949
	public void setFirstName(String firstName) {
950
		this.firstName = firstName;
951
	}
952
 
953
	public String getLastName() {
954
		return lastName;
955
	}
956
 
957
	public void setLastName(String lastName) {
958
		this.lastName = lastName;
959
	}
960
 
961
	public String getEmail() {
962
		return email;
963
	}
964
 
965
	public void setEmail(String email) {
966
		this.email = email;
967
	}
968
 
26784 amit.gupta 969
}
970
 
26774 amit.gupta 971
class CustomerModel {
26783 amit.gupta 972
 
26774 amit.gupta 973
	@JsonProperty(required = false)
974
	private Customer customer;
975
	@JsonProperty(required = true)
976
	private boolean exists;
977
 
978
	public CustomerModel(boolean exists, Customer customer) {
979
		super();
980
		this.customer = customer;
981
		this.exists = exists;
982
	}
983
 
984
	@Override
985
	public String toString() {
986
		return "CustomerModel [customer=" + customer + ", exists=" + exists + "]";
987
	}
988
 
989
	public Customer getCustomer() {
990
		return customer;
991
	}
992
 
993
	public void setCustomer(Customer customer) {
994
		this.customer = customer;
995
	}
996
 
997
	public boolean isExists() {
998
		return exists;
999
	}
1000
 
1001
	public void setExists(boolean exists) {
1002
		this.exists = exists;
1003
	}
26607 amit.gupta 1004
}