Rev 35435 | Blame | Compare with Previous | Last modification | View Log | RSS feed
package com.spice.profitmandi.web.controller;import java.time.LocalDateTime;import java.util.ArrayList;import java.util.Arrays;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Set;import java.util.stream.Collectors;import javax.servlet.http.HttpServletRequest;import com.spice.profitmandi.common.enumuration.SchemeType;import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;import com.spice.profitmandi.common.model.UserInfo;import com.spice.profitmandi.common.web.client.RestClient;import com.spice.profitmandi.dao.model.*;import com.spice.profitmandi.dao.repository.fofo.FofoOpeningStockRepository;import com.spice.profitmandi.service.inventory.*;import org.apache.commons.lang3.StringUtils;import org.apache.http.conn.HttpHostConnectException;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import org.json.JSONArray;import org.json.JSONObject;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.MediaType;import org.springframework.http.ResponseEntity;import org.springframework.stereotype.Controller;import org.springframework.transaction.annotation.Transactional;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.*;import com.spice.profitmandi.common.enumuration.MessageType;import com.spice.profitmandi.common.model.CustomRetailer;import com.spice.profitmandi.common.model.ProfitMandiConstants;import com.spice.profitmandi.common.model.SendNotificationModel;import com.spice.profitmandi.common.services.mandii.MandiiService;import com.spice.profitmandi.common.web.util.ResponseSender;import com.spice.profitmandi.dao.cart.CartService;import com.spice.profitmandi.dao.entity.auth.AuthUser;import com.spice.profitmandi.dao.entity.catalog.FocusedModelByPassRequest;import com.spice.profitmandi.dao.entity.cs.Position;import com.spice.profitmandi.dao.entity.dtr.User;import com.spice.profitmandi.dao.entity.dtr.UserAccount;import com.spice.profitmandi.dao.entity.fofo.FofoPayment;import com.spice.profitmandi.dao.entity.fofo.PartnerDailyInvestment;import com.spice.profitmandi.dao.entity.transaction.UserWalletHistory;import com.spice.profitmandi.dao.enumuration.catalog.ByPassRequestStatus;import com.spice.profitmandi.dao.enumuration.cs.EscalationType;import com.spice.profitmandi.dao.enumuration.dtr.AccountType;import com.spice.profitmandi.dao.enumuration.fofo.PaymentStatus;import com.spice.profitmandi.dao.repository.auth.AuthRepository;import com.spice.profitmandi.dao.repository.catalog.FocusedModelByPassRepository;import com.spice.profitmandi.dao.repository.catalog.FocusedModelRepository;import com.spice.profitmandi.dao.repository.catalog.ItemRepository;import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;import com.spice.profitmandi.dao.repository.cs.CsService;import com.spice.profitmandi.dao.repository.cs.PartnerRegionRepository;import com.spice.profitmandi.dao.repository.cs.PositionRepository;import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;import com.spice.profitmandi.dao.repository.dtr.RetailerBlockBrandsRepository;import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;import com.spice.profitmandi.dao.repository.dtr.UserRepository;import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;import com.spice.profitmandi.dao.repository.fofo.FofoPaymentRepository;import com.spice.profitmandi.dao.repository.transaction.OrderRepository;import com.spice.profitmandi.dao.repository.transaction.UserWalletHistoryRepository;import com.spice.profitmandi.dao.util.ContentPojoPopulator;import com.spice.profitmandi.service.FofoUser;import com.spice.profitmandi.service.NotificationService;import com.spice.profitmandi.service.PartnerInvestmentService;import com.spice.profitmandi.service.transaction.TransactionService;import com.spice.profitmandi.service.user.RetailerService;import com.spice.profitmandi.service.wallet.WalletService;import com.spice.profitmandi.web.res.ValidateCartResponse;import in.shop2020.model.v1.order.WalletReferenceType;import io.swagger.annotations.ApiImplicitParam;import io.swagger.annotations.ApiImplicitParams;import io.swagger.annotations.ApiOperation;@Controller@Transactional(rollbackFor = Throwable.class)public class CartController {private static final Logger logger = LogManager.getLogger(CartController.class);@Autowiredprivate ResponseSender<?> responseSender;@Autowiredprivate UserAccountRepository userAccountRepository;@Autowiredprivate ItemBucketService itemBucketService;@AutowiredCartService cartService;@Autowiredprivate ContentPojoPopulator contentPojoPopulator;@Autowiredprivate ItemRepository itemRepository;@Autowiredprivate UserRepository userRepository;@Autowiredprivate AuthRepository authRepository;@Autowiredprivate CsService csService;@Autowiredprivate PositionRepository positionRepository;@Autowiredprivate FocusedModelByPassRepository focusedModelByPassRepository;@Autowiredprivate FofoPaymentRepository fofoPaymentRepository;@Autowiredprivate RetailerService retailerService;@Autowiredprivate PartnerInvestmentService partnerInvestmentService;@Autowiredprivate FofoUser fofoUser;@Autowiredprivate FocusedModelRepository focusedModelRepository;@Autowiredprivate PartnerRegionRepository partnerRegionRepository;@Autowiredprivate SaholicInventoryService saholicInventoryService;@Autowiredprivate TransactionService transactionService;@Autowiredprivate FofoStoreRepository fofoStoreRepository;@Autowiredprivate RetailerBlockBrandsRepository retailerBlockBrandRepository;@Autowiredprivate OrderRepository orderRepository;@Autowiredprivate TagListingRepository tagListingRepository;@Autowiredprivate NotificationService notificationService;@Autowiredprivate FofoOpeningStockRepository fofoOpeningStockRepository;@Autowiredprivate CurrentInventorySnapshotRepository currentInventorySnapshotRepository;public static final Map<String, Integer> MIN_BRAND_QTY_LIMIT = new HashMap<>();private static final Logger log = LogManager.getLogger(CartController.class);List<EscalationType> esclationType = Arrays.asList(EscalationType.L3, EscalationType.L4, EscalationType.L2);List<String> emails = Arrays.asList("kamini.sharma@smartdukaan.com", "tarun.verma@smartdukaan.com","niranjan.kala@smartdukaan.com", "sm@smartdukaan.com");static {// MIN_BRAND_QTY_LIMIT.put("Realme", 10);MIN_BRAND_QTY_LIMIT.put("Reliance", 5);}@RequestMapping(value = ProfitMandiConstants.URL_CART, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)@ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })@ApiOperation(value = "Add items to cart")public ResponseEntity<?> validateCart(HttpServletRequest request,@RequestParam(value = "pincode", defaultValue = "110001") String pincode, @RequestParam int bucketId)throws Throwable {AddCartRequest cartRequest = new AddCartRequest();List<CartItem> ci = new ArrayList<>();itemBucketService.getBucketDetails(bucketId).stream().forEach(x -> {ci.add(new CartItem(x.getQuantity(), x.getItemId()));});cartRequest.setCartItems(ci);return this.validateCart(request, cartRequest, "110001");}@RequestMapping(value = ProfitMandiConstants.URL_CART, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)@ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })@ApiOperation(value = "Add items to cart")public ResponseEntity<?> validateCart(HttpServletRequest request, @RequestBody AddCartRequest cartRequest,@RequestParam(value = "pincode", defaultValue = "110001") String pincode) throws Throwable {UserAccount userAccount = null;ValidateCartResponse vc = null;int userId = (int) request.getAttribute("userId");int cartId = userAccountRepository.selectByUserIdType(userId, AccountType.cartId).getAccountKey();List<CartItem> cartItems = cartRequest.getCartItems();cartService.addItemsToCart(cartId, cartItems);CartResponse cartValidationResponse = cartService.getCartValidation(cartId);for (CartItemResponseModel cartItem : cartValidationResponse.getCartItems()) {ProductPojo pp = contentPojoPopulator.getShortContent(cartItem.getCatalogItemId());log.info("pp {}", pp);if (pp != null) {cartItem.setImageUrl(pp.getImageUrl()); // cartItem.setTitle(pp.getTitle());}}vc = new ValidateCartResponse(cartValidationResponse, "Success", "Items added to cart successfully");return responseSender.ok(vc);}@RequestMapping(value = ProfitMandiConstants.URL_CART_CHANGE_ADDRESS, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)@ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })@ApiOperation(value = "Change address")public ResponseEntity<?> changeAddress(HttpServletRequest request,@RequestParam(value = "addressId") long addressId) throws Throwable {UserCart uc = userAccountRepository.getUserCart((int) request.getAttribute("userId"));cartService.addAddressToCart(uc.getCartId(), addressId);return responseSender.ok("Address Changed successfully");}@RequestMapping(value = "/byPassRequests", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)@ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })@ApiOperation(value = "byPassRequests")public ResponseEntity<?> byPassRequests(HttpServletRequest request, Model model) throws Exception {int userId = (int) request.getAttribute("userId");User user = userRepository.selectById(userId);AuthUser authUser = authRepository.selectByEmailOrMobile(user.getEmailId());List<FocusedModelByPassRequest> byPassRequests = null;Set<Integer> authfofoIds = null;boolean actionAccess = false;logger.info("authUser" + authUser);List<Position> positions = positionRepository.selectPositionByAuthId(authUser.getId()).stream().filter(x -> (x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES|| x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_RBM)).collect(Collectors.toList());Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();if (emails.contains(authUser.getEmailId())) {byPassRequests = focusedModelByPassRepository.selectByStatus(ByPassRequestStatus.PENDING);actionAccess = true;} else {if (!positions.isEmpty()) {for (Position ps : positions) {if (ProfitMandiConstants.TICKET_CATEGORY_RBM == ps.getCategoryId()) {authfofoIds = storeGuyMap.get(user.getEmailId());logger.info("authfofoIdsw" + authfofoIds);actionAccess = true;break;} else if (ProfitMandiConstants.TICKET_CATEGORY_SALES == ps.getCategoryId()) {authfofoIds = storeGuyMap.get(user.getEmailId());logger.info("authfofoIdsw" + authfofoIds);actionAccess = false;break;}}}}logger.info("authfofoIds" + authfofoIds);if (authfofoIds != null) {byPassRequests = focusedModelByPassRepository.selectByStatusAndFofoIds(new ArrayList<>(authfofoIds),ByPassRequestStatus.PENDING);}Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();List<ByPassRequestModel> byPassList = new ArrayList<>();for (FocusedModelByPassRequest byPassRequest : byPassRequests) {List<FocusedShortageModel> fsms = cartService.focusedModelShortageValidation(byPassRequest.getFofoId(),new HashMap<>());Map<String, Object> investments = fofoUser.getInvestments(byPassRequest.getFofoId());ByPassRequestModel bp = new ByPassRequestModel();bp.setPartnerName(customRetailerMap.get(byPassRequest.getFofoId()).getBusinessName());bp.setCity(customRetailerMap.get(byPassRequest.getFofoId()).getAddress().getCity());bp.setState(customRetailerMap.get(byPassRequest.getFofoId()).getAddress().getState());bp.setCode(customRetailerMap.get(byPassRequest.getFofoId()).getCode());bp.setStatus(byPassRequest.getStatus());bp.setFofoId(byPassRequest.getFofoId());bp.setByPassRequestId(byPassRequest.getId());bp.setInvestmentOkDays((Long) investments.get("okDays"));bp.setInvestmentShort((PartnerDailyInvestment) investments.get("investment"));bp.setMobileNumber(customRetailerMap.get(byPassRequest.getFofoId()).getMobileNumber());bp.setActionAccess(actionAccess);bp.setCreateTimestamp(byPassRequest.getCreatedTimeStamp());bp.setUpdateTimestamp(byPassRequest.getUpdatedTimestamp());bp.setFsms(fsms);byPassList.add(bp);}return responseSender.ok(byPassList);}@RequestMapping(value = "/byPassRequestAction", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)@ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })@ApiOperation(value = "Add items to cart")public ResponseEntity<?> addAmountToWalletRequestRejected(HttpServletRequest request,@RequestParam(name = "id", defaultValue = "0") int id, @RequestParam ByPassRequestStatus status,@RequestParam String reason, Model model) throws Exception {int userId = (int) request.getAttribute("userId");User user = userRepository.selectById(userId);AuthUser authUser = authRepository.selectByEmailOrMobile(user.getEmailId());FocusedModelByPassRequest byPassRequest = focusedModelByPassRepository.selectById(id);if (status.equals(ByPassRequestStatus.APPROVED)) {byPassRequest.setByPass(true);byPassRequest.setAuthId(authUser.getId());byPassRequest.setStatus(ByPassRequestStatus.APPROVED);byPassRequest.setUpdatedTimestamp(LocalDateTime.now());byPassRequest.setReason(reason);} else if (status.equals(ByPassRequestStatus.REJECTED)) {byPassRequest.setByPass(false);byPassRequest.setAuthId(authUser.getId());byPassRequest.setStatus(ByPassRequestStatus.REJECTED);byPassRequest.setUpdatedTimestamp(LocalDateTime.now());byPassRequest.setReason(reason);}String title = "Billing Request";String message = String.format("Your Billing Request is " + status+ ". Please ensure to order the missing focus models as soon as possible.");SendNotificationModel sendNotificationModel = new SendNotificationModel();sendNotificationModel.setCampaignName("Billing Request");sendNotificationModel.setTitle(title);sendNotificationModel.setMessage(message);sendNotificationModel.setType("url");sendNotificationModel.setUrl("https://smartdukaan.com/pages/home/notifications");sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));sendNotificationModel.setMessageType(MessageType.notification);sendNotificationModel.setUserIds(Arrays.asList(userAccountRepository.selectUserIdByRetailerId(byPassRequest.getFofoId())));notificationService.sendNotification(sendNotificationModel);return responseSender.ok(true);}@AutowiredWalletService walletService;@AutowiredMandiiService mandiiService;@AutowiredUserWalletHistoryRepository userWalletHistoryRepository;@RequestMapping(value = "/cart/payment", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)public ResponseEntity<?> validateCartPayment(HttpServletRequest request,@RequestParam(defaultValue = "0") int paymentId, Model model) throws Exception {int userId = (int) request.getAttribute("userId");UserCart uc = userAccountRepository.getUserCart(userId);FofoPayment fofoPayment = fofoPaymentRepository.selectById(paymentId);if (fofoPayment == null || fofoPayment.getFofoId() != uc.getUserId()) {return responseSender.ok(false);}String gatewayReference = fofoPayment.getGatewayReference();List<UserWalletHistory> historyList = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(paymentId, WalletReferenceType.PAYMENT_GATEWAY);if (fofoPayment.getStatus().equals(PaymentStatus.INIT) && historyList.size() == 0) {String jsonString = mandiiService.getOrderStatus(gatewayReference);JSONObject jsonOrder = new JSONObject(jsonString);double orderAmount = jsonOrder.getDouble("order_amount");double capturedAmount = jsonOrder.getDouble("captured_amount");int merchantOrderId = jsonOrder.getInt("merchant_order_number");String status = jsonOrder.getString("status");if (merchantOrderId == paymentId && status.equals("SUCCESS") || status.equals("CAPTURED")) {if (orderAmount == fofoPayment.getAmount()) {fofoPayment.setStatus(PaymentStatus.SUCCESS);fofoPayment.setAmount(capturedAmount);walletService.addAmountToWallet(uc.getUserId(), paymentId, WalletReferenceType.PAYMENT_GATEWAY,"Amount added to wallet via SD Credit via Mandii", (float) fofoPayment.getAmount(),LocalDateTime.now());if (orderAmount == capturedAmount) {return responseSender.ok(true);}}}}return responseSender.ok(false);}@RequestMapping(value = "/partner/hidAllocation", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)@ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})public ResponseEntity<?> getItemHidAllocation(HttpServletRequest request) throwsException {List<HidAllocationModel> hidAllocationModels = new ArrayList<>();int userId = (int) request.getAttribute(ProfitMandiConstants.USER_ID);int retailerId = userAccountRepository.selectRetailerIdByUserId(userId);hidAllocationModels = fofoOpeningStockRepository.getPartnerHidAllocation(retailerId);return responseSender.ok(hidAllocationModels);}}