Subversion Repositories SmartDukaan

Rev

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