Subversion Repositories SmartDukaan

Rev

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