Subversion Repositories SmartDukaan

Rev

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