Subversion Repositories SmartDukaan

Rev

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