Subversion Repositories SmartDukaan

Rev

Rev 28269 | Rev 28287 | 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,
28269 amit.gupta 714
			@RequestParam(required = false, defaultValue = "true") boolean partnerStockOnly)
27030 amit.gupta 715
			throws Throwable {
716
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
717
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
28269 amit.gupta 718
		FofoStore fs = fofoStoreRepository.selectByRetailerId(userInfo.getRetailerId());
719
		sort = "w" + fs.getWarehouseId() + "_i desc";
27045 tejbeer 720
		dealResponse = this.getCatalogResponse(
721
				solrService.getSolrDocs(queryTerm, categoryId, offset, limit, sort, brand, subCategoryId, false), false,
722
				userInfo.getRetailerId());
27030 amit.gupta 723
		return responseSender.ok(dealResponse);
724
	}
725
 
26909 amit.gupta 726
	private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal, int fofoId)
26607 amit.gupta 727
			throws ProfitMandiBusinessException {
26909 amit.gupta 728
		Map<Integer, Integer> ourItemAvailabilityMap = null;
729
		Map<Integer, Integer> partnerStockAvailabilityMap = null;
26607 amit.gupta 730
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
731
		List<Integer> tagIds = Arrays.asList(4);
732
		if (docs.length() > 0) {
733
			HashSet<Integer> itemsSet = new HashSet<>();
734
			for (int i = 0; i < docs.length(); i++) {
735
				JSONObject doc = docs.getJSONObject(i);
736
				if (doc.has("_childDocuments_")) {
737
					for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
738
						JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
739
						int itemId = childItem.getInt("itemId_i");
740
						itemsSet.add(itemId);
741
					}
742
				}
743
			}
744
			if (itemsSet.size() == 0) {
745
				return dealResponse;
746
			}
28269 amit.gupta 747
			if (fofoId > 0) {
26909 amit.gupta 748
				partnerStockAvailabilityMap = currentInventorySnapshotRepository.selectItemsStock(fofoId).stream()
749
						.collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
750
			}
28269 amit.gupta 751
			ourItemAvailabilityMap = saholicInventoryService
752
					.getTotalAvailabilityByItemIds(new ArrayList<>(itemsSet));
26607 amit.gupta 753
		}
754
 
755
		for (int i = 0; i < docs.length(); i++) {
756
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
757
			JSONObject doc = docs.getJSONObject(i);
758
			FofoCatalogResponse ffdr = new FofoCatalogResponse();
759
			ffdr.setCatalogId(doc.getInt("catalogId_i"));
760
			ffdr.setImageUrl(doc.getString("imageUrl_s"));
761
			ffdr.setTitle(doc.getString("title_s"));
762
			try {
763
				ffdr.setFeature(doc.getString("feature_s"));
764
			} catch (Exception e) {
765
				ffdr.setFeature(null);
766
				logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
767
			}
768
			ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
769
			if (doc.has("_childDocuments_")) {
770
				for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
771
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
772
					int itemId = childItem.getInt("itemId_i");
773
					float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
774
					if (fofoAvailabilityInfoMap.containsKey(itemId)) {
775
						if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
776
							fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
777
							fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
778
						}
779
					} else {
780
						FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
26909 amit.gupta 781
						fdi.setSellingPrice(sellingPrice);
782
						fdi.setActive(childItem.getBoolean("active_b"));
783
						fdi.setMrp(childItem.getDouble("mrp_f"));
26607 amit.gupta 784
						fdi.setMop((float) childItem.getDouble("mop_f"));
785
						fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
786
						fdi.setTagId(childItem.getInt("tagId_i"));
787
						fdi.setItem_id(itemId);
26909 amit.gupta 788
						Float cashBack = schemeService.getItemSchemeCashBack().get(itemId);
789
						cashBack = cashBack == null ? 0 : cashBack;
790
						fdi.setCashback(cashBack);
26673 amit.gupta 791
						fdi.setMinBuyQuantity(1);
28271 amit.gupta 792
						int ourStockAvailability = ourItemAvailabilityMap.get(itemId) == null ? 0 : Math.max(0,ourItemAvailabilityMap.get(itemId));
28269 amit.gupta 793
						int partnerAvailability = partnerStockAvailabilityMap.get(itemId) == null ? 0
794
								: partnerStockAvailabilityMap.get(itemId);
795
						fdi.setAvailability(Math.min(5,ourStockAvailability + partnerAvailability));
26607 amit.gupta 796
						fdi.setQuantityStep(1);
28269 amit.gupta 797
						fdi.setMaxQuantity(fdi.getAvailability());
26607 amit.gupta 798
						fofoAvailabilityInfoMap.put(itemId, fdi);
799
					}
800
				}
801
			}
802
			if (fofoAvailabilityInfoMap.values().size() > 0) {
26909 amit.gupta 803
				ffdr.setItems(fofoAvailabilityInfoMap.values().stream()
26923 amit.gupta 804
						.sorted((x, y) -> y.getAvailability() - x.getAvailability()).collect(Collectors.toList()));
26607 amit.gupta 805
				dealResponse.add(ffdr);
806
			}
807
		}
28240 amit.gupta 808
		return dealResponse.stream().sorted((x,y)-> {
28237 amit.gupta 809
			return Math.min(y.getItems().get(0).getAvailability(),1) - Math.min(x.getItems().get(0).getAvailability(),1);
810
		}).collect(Collectors.toList());
26909 amit.gupta 811
 
26607 amit.gupta 812
	}
26923 amit.gupta 813
 
814
	@GetMapping(value = "store/order-status/{pendingOrderId}")
27028 tejbeer 815
	public ResponseEntity<?> orderStatus(HttpServletRequest request, @PathVariable int pendingOrderId)
816
			throws Exception {
26923 amit.gupta 817
		PendingOrder pendingOrder = pendingOrderRepository.selectById(pendingOrderId);
818
		List<PendingOrderItem> pendingOrderItems = pendingOrderItemRepository.selectByOrderId(pendingOrder.getId());
819
		List<Integer> catalogIds = new ArrayList<>();
27028 tejbeer 820
		for (PendingOrderItem pendingOrderItem : pendingOrderItems) {
26923 amit.gupta 821
			Item item = itemRepository.selectById(pendingOrderItem.getItemId());
822
			pendingOrderItem.setItemName(item.getItemDescription());
823
			catalogIds.add(item.getCatalogItemId());
824
		}
825
		Map<Integer, JSONObject> contentMap = commonSolrService.getContentByCatalogIds(catalogIds);
27028 tejbeer 826
		for (PendingOrderItem pendingOrderItem : pendingOrderItems) {
26923 amit.gupta 827
			Item item = itemRepository.selectById(pendingOrderItem.getItemId());
828
			JSONObject jsonObj = contentMap.get(item.getCatalogItemId());
829
			pendingOrderItem.setImgUrl(jsonObj.getString("imageUrl_s"));
830
		}
831
		pendingOrder.setPendingOrderItems(pendingOrderItems);
27069 tejbeer 832
 
833
		CustomerAddress customerAddress = customerAddressRepository.selectById(pendingOrder.getCustomerAddressId());
834
 
835
		DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy H:m");
836
		Template t = velocityEngine.getTemplate("sms.vm");
837
		VelocityContext context = new VelocityContext();
838
 
839
		context.put("customer", customerAddress);
840
		context.put("pendingOrder", pendingOrder);
841
		context.put("date", dateTimeFormatter);
842
		StringWriter writer = new StringWriter();
843
		t.merge(context, writer);
844
 
845
		this.sendMailWithAttachments("Order Confirmation", writer.toString(), pendingOrder);
26923 amit.gupta 846
		return responseSender.ok(pendingOrder);
847
	}
848
 
27069 tejbeer 849
	private void sendMailWithAttachments(String subject, String messageText, PendingOrder pendingOrder)
850
			throws Exception {
851
		CustomRetailer customRetailer = retailerService.getFofoRetailer(pendingOrder.getFofoId());
852
		Customer customer = customerRepository.selectById(pendingOrder.getCustomerId());
853
		MimeMessage message = mailSender.createMimeMessage();
854
		MimeMessageHelper helper = new MimeMessageHelper(message, true);
855
		if (!customer.getEmailId().equals(null)) {
27207 tejbeer 856
			String[] email = {customer.getEmailId() };
27069 tejbeer 857
			helper.setTo(email);
858
		}
859
		String[] bccemail = { customRetailer.getEmail(), "tejbeer.kaur@shop2020.in", "tarun.verma@smartdukaan.com" };
860
		helper.setSubject(subject);
861
		helper.setBcc(bccemail);
862
		helper.setText(messageText, true);
863
 
864
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "Smartdukaan Alerts");
865
		helper.setFrom(senderAddress);
866
		mailSender.send(message);
867
 
868
	}
869
 
26833 amit.gupta 870
	@RequestMapping(value = "/store/addresses/{customerId}", method = RequestMethod.GET)
871
	public ResponseEntity<?> getAll(HttpServletRequest request, @PathVariable int customerId) throws Throwable {
27045 tejbeer 872
		return responseSender.ok(customerAddressRepository.selectByActiveCustomerId(customerId));
26788 amit.gupta 873
	}
26833 amit.gupta 874
 
26857 amit.gupta 875
	@RequestMapping(value = "/store/address", method = RequestMethod.POST)
876
	public ResponseEntity<?> addAddress(HttpServletRequest request, @RequestBody CustomerAddress customerAddress)
877
			throws Throwable {
878
		customerAddressRepository.persist(customerAddress);
879
		return responseSender.ok(customerAddress);
880
	}
881
 
27045 tejbeer 882
	@RequestMapping(value = "/store/deactivateCustomerAddress", method = RequestMethod.POST)
883
	public ResponseEntity<?> deactivateAddresss(HttpServletRequest request, @RequestParam int id) throws Throwable {
884
		CustomerAddress cust = customerAddressRepository.selectById(id);
885
		cust.setActive(false);
886
		return responseSender.ok(cust);
887
	}
888
 
26861 tejbeer 889
	@RequestMapping(value = "/store/updateCustomer", method = RequestMethod.POST)
890
	public ResponseEntity<?> updateCustomerProfile(HttpServletRequest request, @RequestBody Customer customer)
891
			throws Throwable {
892
		Customer cust = customerRepository.selectById(customer.getId());
893
		cust.setGender(customer.getGender());
26867 tejbeer 894
		cust.setProfileImageId(customer.getProfileImageId());
26861 tejbeer 895
		cust.setDob(customer.getDob());
896
		return responseSender.ok(cust);
897
	}
898
 
27048 tejbeer 899
	@RequestMapping(value = "/cancelPendingOrderItem", method = RequestMethod.POST)
900
	public ResponseEntity<?> cancelPendingOrderItem(HttpServletRequest request, @RequestParam int id,
27045 tejbeer 901
 
27048 tejbeer 902
			@RequestParam String statusDescription) throws Exception {
903
 
904
		PendingOrderItem pendingOrderItem = pendingOrderItemRepository.selectById(id);
905
 
27057 tejbeer 906
		PendingOrder pendingOrder = pendingOrderRepository.selectById(pendingOrderItem.getOrderId());
27048 tejbeer 907
		if (pendingOrderItem.getBilledTimestamp() == null) {
908
			pendingOrderItem.setStatus(OrderStatus.CANCELLED);
909
			pendingOrderItem.setStatusDescription(statusDescription);
910
			List<OrderStatus> status = pendingOrderItemRepository.selectByOrderId(pendingOrderItem.getOrderId())
911
					.stream().map(x -> x.getStatus()).collect(Collectors.toList());
912
 
913
			if (!status.contains(OrderStatus.PENDING)) {
914
				pendingOrder.setStatus(OrderStatus.CLOSED);
915
			}
916
 
917
			pendingOrderItemRepository.persist(pendingOrderItem);
918
		}
919
 
920
		return responseSender.ok(true);
921
 
922
	}
923
 
26774 amit.gupta 924
}
925
 
26784 amit.gupta 926
class UserModel {
26857 amit.gupta 927
	@JsonProperty(required = true)
26784 amit.gupta 928
	private String mobile;
26857 amit.gupta 929
	@JsonProperty(required = true)
26784 amit.gupta 930
	private String password;
26857 amit.gupta 931
	@JsonProperty(required = false)
932
	private String firstName;
933
	@JsonProperty(required = false)
934
	private String lastName;
935
	@JsonProperty(required = false)
936
	private String email;
26833 amit.gupta 937
 
26784 amit.gupta 938
	@Override
939
	public String toString() {
940
		return "UserModel [mobile=" + mobile + ", password=" + password + "]";
941
	}
26833 amit.gupta 942
 
26784 amit.gupta 943
	public String getMobile() {
944
		return mobile;
945
	}
26833 amit.gupta 946
 
26784 amit.gupta 947
	public void setMobile(String mobile) {
948
		this.mobile = mobile;
949
	}
26833 amit.gupta 950
 
26784 amit.gupta 951
	public String getPassword() {
952
		return password;
953
	}
26833 amit.gupta 954
 
26784 amit.gupta 955
	public void setPassword(String password) {
956
		this.password = password;
957
	}
26857 amit.gupta 958
 
959
	public String getFirstName() {
960
		return firstName;
961
	}
962
 
963
	public void setFirstName(String firstName) {
964
		this.firstName = firstName;
965
	}
966
 
967
	public String getLastName() {
968
		return lastName;
969
	}
970
 
971
	public void setLastName(String lastName) {
972
		this.lastName = lastName;
973
	}
974
 
975
	public String getEmail() {
976
		return email;
977
	}
978
 
979
	public void setEmail(String email) {
980
		this.email = email;
981
	}
982
 
26784 amit.gupta 983
}
984
 
26774 amit.gupta 985
class CustomerModel {
26783 amit.gupta 986
 
26774 amit.gupta 987
	@JsonProperty(required = false)
988
	private Customer customer;
989
	@JsonProperty(required = true)
990
	private boolean exists;
991
 
992
	public CustomerModel(boolean exists, Customer customer) {
993
		super();
994
		this.customer = customer;
995
		this.exists = exists;
996
	}
997
 
998
	@Override
999
	public String toString() {
1000
		return "CustomerModel [customer=" + customer + ", exists=" + exists + "]";
1001
	}
1002
 
1003
	public Customer getCustomer() {
1004
		return customer;
1005
	}
1006
 
1007
	public void setCustomer(Customer customer) {
1008
		this.customer = customer;
1009
	}
1010
 
1011
	public boolean isExists() {
1012
		return exists;
1013
	}
1014
 
1015
	public void setExists(boolean exists) {
1016
		this.exists = exists;
1017
	}
26607 amit.gupta 1018
}