Subversion Repositories SmartDukaan

Rev

Rev 34568 | Rev 34575 | Go to most recent revision | 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.NotificationService;
import com.spice.profitmandi.service.user.RetailerService;
import com.spice.profitmandi.service.whatsapp.WhatsappMessageType;
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;

@Component
public class BidServiceImpl implements BidService {
    private static final Logger LOGGER = LogManager.getLogger(BidServiceImpl.class);
    @Autowired
    AuthRepository authRepository;
    @Autowired
    AuthService authService;
    @Autowired
    JavaMailSender mailSender;
    @Autowired
    UserRepository userRepository;
    @Autowired
    CsService csService;
    @Autowired
    BidRepository bidRepository;
    @Autowired
    LiquidationRepository liquidationRepository;
    @Autowired
    NotificationService notificationService;
    @Autowired
    private UserAccountRepository userAccountRepository;
    @Autowired
    private FofoStoreRepository fofoStoreRepository;
    @Autowired
    private RetailerService retailerService;

    @Override
    public void 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 = new String[] { authUser.getEmailId() };
        //String[] emailTo = new String[] { "vjangra856@gmail.com" };

        String[] ccTo = {user.getEmailId()};
        String subject = "Dispatch On Hold(Bidding)";
        String message = String.format(
                "Dear Team,\n\n"
                        + "This is to inform you that the material for %s, valued at Rs.%s, "
                        + "is on hold until the payment against the stock is received. Kindly "
                        + "top up your wallet with an amount of Rs.%s to proceed with the dispatch.",
                user.getName(), totalPayableAmount, (totalPayableAmount - netAmountInHand)
        );

        Utils.sendMailWithAttachments(mailSender, emailTo, ccTo, subject, message);
    }

    @Override
    public 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", "vikas.jangra@smartdukaan.com"};

            String[] ccTo = authService.getAllManagers(userId).stream().map(AuthUser::getEmailId).toArray(String[]::new);
            String subject = "Liquidation Report";
            String message = "Dear Team,\n\n"
                    + "Liquidation has been completed. Here is the summary:\n\n"
                    + content;

            Utils.sendMailWithAttachments(mailSender, emailTo, ccTo, subject, message);
        }
    }

    @Override
    public void notifyPartner(int fofoId, Bid bid, ProfitMandiConstants.BID_ENUM status) throws Exception {
        User user = userRepository.selectById(fofoId);
        List<Bid> topBid = bidRepository.selectBidByLiquidationId(bid.getLiquidationId());
        String message = this.generateWhatsAppBidMessage(user.getName(), bid, topBid.get(0).getBiddingAmount(), status);
        this.sendPushNotification(message, "Bid Update!", Arrays.asList(fofoId));
        //String mobile = user.getMobileNumber();
        //notificationService.sendWhatsappMessage(message, "Bid Update!", mobile);
    }

    @Override
    public 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);
        }
    }

    @Override
    public void sendPushNotification(String message, String title, List<Integer> fofoIds) throws Exception {
        SendNotificationModel sendNotificationModel = new SendNotificationModel();
        sendNotificationModel.setCampaignName(title);
        sendNotificationModel.setMessage(message);
        sendNotificationModel.setType("url");
        sendNotificationModel.setTitle(title);
        sendNotificationModel.setUrl("https://app.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);
        }

        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 void cancelYesterdayProcessBid(Bid bid) throws Exception {
        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);
    }

    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: ₹%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;
    }

}