Subversion Repositories SmartDukaan

Rev

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