Subversion Repositories SmartDukaan

Rev

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