Subversion Repositories SmartDukaan

Rev

Rev 34470 | Rev 34545 | 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.model.ProfitMandiConstants;
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.user.UserRepository;
import com.spice.profitmandi.service.AuthService;
import com.spice.profitmandi.service.NotificationService;
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.util.ArrayList;
import java.util.List;

@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;

    @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 {
        String content = this.generateContent(bids, liquidation, ProfitMandiConstants.BID_ENUM.CLOSED);
        AuthUser authUser = authRepository.selectById(userId);
        //String[] emailTo = {"vikas.jangra@smartdukaan.com"};
        String[] emailTo = {authUser.getEmailId(), "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;

        LOGGER.info("mailMessage: {}",message);
        Utils.sendMailWithAttachments(mailSender, emailTo, ccTo, subject, message);
    }

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

    private String generateContent(List<Bid> bids, Liquidation liquidation, ProfitMandiConstants.BID_ENUM status){
        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 ID (Fofo)</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(bid.getFofoId()).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: ₹%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: ₹%s\n" +
                    "* Quantity: %s\n" +
                    "* Bid Time: %s\n" +
                    "* Qualified Bid Amount: ₹%s\n" +
                    "\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: ₹%s\n" +
                    "* Quantity: %s\n" +
                    "* Bid Time: %s\n" +
                    "\n"+
                    "We'll keep you updated. You'll be notified once the bidding period ends.";
            message = String.format(message, fofoName, bidData.getItemName(), bidAmount, bidData.getQuantity(), bidTime);
        }
        else if (status.equals(ProfitMandiConstants.BID_ENUM.UPDATE)) {
            message = "Hi %s,"+ "\n"+
                    "\n"+
                    "A higher bid has been placed for %s. Don't miss your chance!\n" +
                    "\n"+
                    "Your Bid Details:\n" +
                    "* Bid Amount: ₹%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;
    }

}