Subversion Repositories SmartDukaan

Rev

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