Subversion Repositories SmartDukaan

Rev

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