Rev 35963 | Blame | Compare with Previous | Last modification | View Log | RSS feed
package com.spice.profitmandi.dao.service;import com.spice.profitmandi.common.enumuration.MessageType;import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;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.util.StringUtils;import com.spice.profitmandi.common.util.Utils;import com.spice.profitmandi.dao.entity.auth.AuthUser;import com.spice.profitmandi.dao.entity.catalog.Bid;import com.spice.profitmandi.dao.entity.catalog.Liquidation;import com.spice.profitmandi.dao.entity.user.User;import com.spice.profitmandi.dao.enumuration.cs.EscalationType;import com.spice.profitmandi.dao.repository.auth.AuthRepository;import com.spice.profitmandi.dao.repository.catalog.BidRepository;import com.spice.profitmandi.dao.repository.catalog.LiquidationRepository;import com.spice.profitmandi.dao.repository.cs.CsService;import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;import com.spice.profitmandi.dao.repository.user.UserRepository;import com.spice.profitmandi.service.AuthService;import com.spice.profitmandi.service.mail.MailOutboxService;import com.spice.profitmandi.service.NotificationService;import com.spice.profitmandi.service.user.RetailerService;import com.spice.profitmandi.service.wallet.WalletService;import com.spice.profitmandi.service.whatsapp.WhatsappMessageType;import in.shop2020.model.v1.order.WalletReferenceType;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.stereotype.Component;import java.time.LocalDateTime;import java.util.Arrays;import java.util.Collections;import java.util.List;import java.util.Map;import static java.util.stream.Collectors.toList;@Componentpublic class BidServiceImpl implements BidService {private static final Logger LOGGER = LogManager.getLogger(BidServiceImpl.class);@AutowiredAuthRepository authRepository;@AutowiredAuthService authService;@AutowiredJavaMailSender gmailRelaySender;@AutowiredMailOutboxService mailOutboxService;@AutowiredUserRepository userRepository;@AutowiredCsService csService;@AutowiredBidRepository bidRepository;@AutowiredLiquidationRepository liquidationRepository;@AutowiredNotificationService notificationService;@Autowiredprivate UserAccountRepository userAccountRepository;@Autowiredprivate FofoStoreRepository fofoStoreRepository;@Autowiredprivate RetailerService retailerService;@Autowiredprivate WalletService walletService;@Overridepublic ProfitMandiConstants.BID_ENUM sendMailToRBM(double netAmountInHand, double totalPayableAmount, int fofoId) throws Exception {User user = userRepository.selectById(fofoId);int rbmId = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L1, fofoId);AuthUser authUser = authRepository.selectById(rbmId);String[] emailTo;String[] ccTo;if (authUser == null){emailTo = new String[] { "sdtech@smartdukaan.com", "mohit.gulati@smartdukaan.com", "manish.gupta1@smartdukaan.com", "sourcing@smartdukaan.com" };ccTo = new String[]{};} else {emailTo = new String[] { user.getEmailId(), "sdtech@smartdukaan.com", "sourcing@smartdukaan.com" };ccTo = new String[]{authUser.getEmailId()};}String subject = "Dispatch On Hold(Bidding)";String message = String.format("Dear %s,<br>"+ "This is to inform you that the material for %s, valued at Rs.%s, <br>"+ "is on hold until the payment against the stock is received. Kindly <br>"+ "top up your wallet with an amount of Rs.%s to proceed with the dispatch.",user.getName(), user.getName(), totalPayableAmount, (totalPayableAmount - netAmountInHand));mailOutboxService.queueMail(emailTo, ccTo, subject, message, "BidServiceImpl.sendMailToRBM");return ProfitMandiConstants.BID_ENUM.PROCESSING;}@Overridepublic void sendSummaryMailToUserAndManagers(int userId, List<Bid> bids, Liquidation liquidation) throws Exception {if (bids.size() > 0) {String content = this.generateContent(bids, liquidation, ProfitMandiConstants.BID_ENUM.CLOSED);AuthUser authUser = authRepository.selectById(userId);String[] emailTo = {authUser.getEmailId(), "sourcing@smartdukaan.com", "sdtech@smartdukaan.com"};String[] ccTo = authService.getAllManagers(userId).stream().map(AuthUser::getEmailId).toArray(String[]::new);String subject = "Liquidation Report";String message = "Dear Team,<br><br>"+ "Liquidation has been completed. Here is the summary:<br><br>"+ content;mailOutboxService.queueMail(emailTo, ccTo, subject, message, "BidServiceImpl.sendSummaryMailToUserAndManagers");}}@Overridepublic void notifyPartner(int fofoId, Bid bid, ProfitMandiConstants.BID_ENUM status) throws Exception {User user = userRepository.selectById(fofoId);LOGGER.info("user: {}",user);List<Bid> topBid = bidRepository.selectBidByLiquidationId(bid.getLiquidationId());String message = this.generateWhatsAppBidMessage(user.getName(), bid, topBid.get(0).getBiddingAmount(), status);LOGGER.info("sendPushNotification: {}",topBid.get(0));this.sendPushNotification(message, "Bid Update!", Arrays.asList(fofoId));//String mobile = user.getMobileNumber();//notificationService.sendWhatsappMessage(message, "Bid Update!", mobile);}@Overridepublic void biddingLiveNotification(String message, String mediaURL) throws Exception {this.sendPushNotification(message, "Bidding Live Now!", Collections.emptyList());//List<String> mobiles = Arrays.asList("7619985051","8529003611","7082253510","7903840919","9667014826");if (mediaURL == null){notificationService.sendWhatsappMessage(message,null, "8529003611");} else {notificationService.sendWhatsappMediaMessage(message,"8529003611", mediaURL,"whatsapp.jpeg", WhatsappMessageType.IMAGE);}}@Overridepublic void sendPushNotification(String message, String title, List<Integer> fofoIds) throws Exception {LOGGER.info("fofoIds stating: {}",fofoIds);SendNotificationModel sendNotificationModel = new SendNotificationModel();sendNotificationModel.setCampaignName(title);sendNotificationModel.setMessage(message);sendNotificationModel.setType("url");sendNotificationModel.setTitle(title);sendNotificationModel.setUrl("https://smartdukaan.com/pages/home/clearance");sendNotificationModel.setExpiresat(LocalDateTime.now().plusHours(6));sendNotificationModel.setMessageType(MessageType.notification);List<Integer> userIds;if (fofoIds.size() > 0) {userIds = userAccountRepository.selectUserIdsByRetailerIds(fofoIds); //Arrays.asList(171912487)} else {fofoIds = fofoStoreRepository.selectActiveStores().stream().map(x->x.getId()).collect(toList());userIds = userAccountRepository.selectUserIdsByRetailerIds(fofoIds);}LOGGER.info("fofoIds: {}",fofoIds);sendNotificationModel.setUserIds(userIds);notificationService.sendNotification(sendNotificationModel);notificationService.sendNotificationToSystemUsers(sendNotificationModel);}private String generateContent(List<Bid> bids, Liquidation liquidation, ProfitMandiConstants.BID_ENUM status) throws ProfitMandiBusinessException {Map<Integer, CustomRetailer> retailers = retailerService.getAllFofoRetailers();StringBuilder sb = new StringBuilder();sb.append("<h4>Bidding Summary</h3>");sb.append("<p><strong>Liquidation ID:</strong> ").append(liquidation.getId()).append("</p>");sb.append("<p><strong>Catalog ID:</strong> ").append(liquidation.getCatalogId()).append("</p>");sb.append("<p><strong>Total Quantity Available:</strong> ").append(liquidation.getQuantity()).append("</p>");sb.append("<p><strong>End Date:</strong> ").append(liquidation.getEndDate()).append("</p>");sb.append("<table border='1' cellpadding='5' cellspacing='0' style='border-collapse: collapse;'>");sb.append("<thead>");sb.append("<tr>").append("<th>Bidder</th>").append("<th>Item Name</th>").append("<th>Bid Amount</th>").append("<th>Quantity</th>").append("<th>Status</th>").append("<th>Bid Time</th>").append("</tr>");sb.append("</thead>");sb.append("<tbody>");for (Bid bid : bids) {sb.append("<tr>").append("<td>").append(retailers.get(bid.getFofoId()).getDisplayName()).append("</td>").append("<td>").append(bid.getItemName() != null ? bid.getItemName() : "-").append("</td>").append("<td>").append(bid.getBiddingAmount()).append("</td>").append("<td>").append(bid.getQuantity()).append("</td>").append("<td>").append(bid.getStatus().name()).append("</td>").append("<td>").append(bid.getCreatedAt()).append("</td>").append("</tr>");}sb.append("</tbody>");sb.append("</table>");return sb.toString();}public ProfitMandiConstants.BID_ENUM cancelYesterdayProcessBid(Bid bid) throws Exception {LOGGER.info("Cancelling the bid of: {}",bid);bid.setStatus(ProfitMandiConstants.BID_ENUM.CANCELLED);Liquidation liquidation = liquidationRepository.selectLiquidationById(bid.getLiquidationId());List<Bid> bids = bidRepository.selectBidByLiquidationId(bid.getLiquidationId());this.sendSummaryMailToUserAndManagers(liquidation.getCreatedBy(), bids, liquidation);this.notifyPartner(bid.getFofoId(), bid, ProfitMandiConstants.BID_ENUM.CANCELLED);return bid.getStatus();}private String generateWhatsAppBidMessage(String fofoName, Bid bidData, double topBidAmount, ProfitMandiConstants.BID_ENUM status) {String bidTime = StringUtils.toLocalDateTime(String.valueOf(bidData.getCreatedAt()));String bidAmount = String.format("%.2f", bidData.getBiddingAmount());String message = "";if (status.equals(ProfitMandiConstants.BID_ENUM.CLOSED)) {message = "Congratulations! %s,\n"+"\n"+"Your bid for %s has been confirmed!\n"+"\n"+"Bid Details:\n"+"Bid Amount: Rs. %s\n"+"Quantity: %s\n"+"Bid Time: %s\n"+"\n"+"Thank you for participating. We'll dispatch your order soon.";message = String.format(message, fofoName, bidData.getItemName(), bidAmount, bidData.getQuantity(), bidTime);}else if (status.equals(ProfitMandiConstants.BID_ENUM.CANCELLED)) {message = "Hi %s,\n"+"\n"+"We regret to inform you that your bid for %s was not selected this time.\n"+"\n"+"Bid Details:\n"+"Bid Amount: Rs. %s\n"+"Quantity: %s\n"+"Bid Time: %s\n"+"\n"+"Qualified Bid Amount: Rs. %s\n"+"Thank you for your participation. Stay tuned for more opportunities!";message = String.format(message, fofoName, bidData.getItemName(), bidAmount, bidData.getQuantity(), bidTime, String.format("%.2f", topBidAmount));}else if (status.equals(ProfitMandiConstants.BID_ENUM.PENDING)) {message = "Hi %s,\n"+"\n"+"Your bid for %s has been placed successfully.\n"+"\n"+"Bid Details:\n"+"Bid Amount: Rs. %s\n"+"Quantity: %s\n"+"Time: %s\n"+"\n"+"We will keep you updated. You will be notified once the bidding period ends.";message = String.format(message, fofoName.trim(), bidData.getItemName().trim(), bidAmount, bidData.getQuantity(), bidTime);}else if (status.equals(ProfitMandiConstants.BID_ENUM.UPDATE)) {message = "Hi %s,\n"+"A higher bid has been placed for %s. Don't miss your chance!\n"+"\n"+"Your Bid Details:\n"+"Bid Amount: Rs. %s\n"+"Quantity: %s\n"+"Bid Time: %s\n"+"\n"+"Another user has placed a higher bid of %s.\n"+"Update your bid before the bidding ends to stay ahead in the race!";message = String.format(message, fofoName, bidData.getItemName(), bidAmount, bidData.getQuantity(), bidTime, String.format("%.2f", topBidAmount));}return message;}public void sendLiquidationReport(List<Map<String, Object>> liquidations) throws Exception {Map<Integer, CustomRetailer> retailers = retailerService.getAllFofoRetailers();StringBuilder sb = new StringBuilder();sb.append("<h4>Bidding Summary</h3>");sb.append("<table border='1' cellpadding='5' cellspacing='0' style='border-collapse: collapse;'>");sb.append("<thead>");for (Map<String, Object> liquidation : liquidations) {sb.append("<tr style='background-color: red; color: white;'>").append("<th>Liquidation ID</th>").append("<th>Item Name</th>").append("<th>Bidding Price</th>").append("<th>Stock Qty</th>").append("<th>End Time</th>").append("</tr>");sb.append("<tr>").append("<td>").append(liquidation.get("id")).append("</td>").append("<td>").append(liquidation.get("catalog")).append("</td>").append("<td>").append(liquidation.get("basePrice")).append("</td>").append("<td>").append(liquidation.get("openingStock")).append("/").append(liquidation.get("closingStock")).append("</td>").append("<td>").append(liquidation.get("endDate")).append("</td>").append("</tr>");sb.append("<tr style='background-color: black; color: white;'>").append("<th>Bidder</th>").append("<th>Bid Amount</th>").append("<th>Quantity</th>").append("<th>Status</th>").append("<th>Bid Time</th>").append("</tr>");sb.append("</thead>");sb.append("<tbody>");@SuppressWarnings("unchecked")List<Bid> bids = (List<Bid>) liquidation.get("bids");if (bids.size() > 0) {for (Bid bid : bids) {sb.append("<tr>").append("<td>").append(retailers.get(bid.getFofoId()).getDisplayName()).append("</td>").append("<td>").append(bid.getBiddingAmount()).append("</td>").append("<td>").append(bid.getQuantity()).append("</td>").append("<td>").append(bid.getStatus().name()).append("</td>").append("<td>").append(StringUtils.toLocalDateTime(String.valueOf(bid.getCreatedAt()))).append("</td>").append("</tr>");}} else {sb.append("<tr>").append("<td colspan='5' style='text-align: center;'>No Bids</td>");}sb.append("</tbody>");}sb.append("</table>");String[] emailTo = {"sdtech@smartdukaan.com", "sourcing@smartdukaan.com", "tarun.verma@smartdukaan.com"};String subject = "Liquidation Report";String message = "Dear Team,<br><br>"+ "<h3>Liquidation has been completed. Here is the summary:</h3><br><br>"+ sb.toString();mailOutboxService.queueMail(emailTo, null, subject, message, "BidServiceImpl.sendLiquidationReport");}public void refundBidAmountToWallet(Bid bid, ProfitMandiConstants.BID_ENUM finalBidStatus) throws ProfitMandiBusinessException {if (finalBidStatus.equals(ProfitMandiConstants.BID_ENUM.CLOSED) || finalBidStatus.equals(ProfitMandiConstants.BID_ENUM.CANCELLED)){String reason = "Amount refunded advance security for "+bid.getItemName()+" bid";walletService.addAmountToWallet(bid.getFofoId(),bid.getId(), WalletReferenceType.ADVANCE_REVERSAL,reason,ProfitMandiConstants.BID_CHARGES,LocalDateTime.now());}}}