Subversion Repositories SmartDukaan

Rev

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