Subversion Repositories SmartDukaan

Rev

Rev 34470 | 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.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.dtr.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.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.getFirstName() + " " + user.getLastName(), 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 = {authUser.getEmailId()};

        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, List<Bid> bids, Liquidation liquidation, ProfitMandiConstants.BID_ENUM status) throws Exception {
        User user = userRepository.selectById(userId);
        List<Bid> topBid = bidRepository.selectBidByLiquidationId(bids.get(0).getLiquidationId());
        String message = this.generateBidStatusMessage(user.getFirstName()+" "+user.getLastName(), bids.get(0), topBid.get(0).getBiddingAmount());
        notificationService.sendWhatsappMessage(message, "Bidding Update!", user.getMobileNumber());
    }

    private String generateContent(List<Bid> bids, Liquidation liquidation, ProfitMandiConstants.BID_ENUM status){
        StringBuilder sb = new StringBuilder();
        if (status.equals(ProfitMandiConstants.BID_ENUM.CLOSED)){
            sb.append("<h3>Congratulations your BID has ").append(status).append("</h3>");
        } else {
            sb.append("<h3>Sorry your BID has ").append(status).append("</h3>");
        }
        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(int id) throws Exception {
        Bid bid = bidRepository.selectById(id);
        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);
        List<Bid> partnerBid = new ArrayList<>();
        partnerBid.add(bid);
        this.notifyPartner(bid.getFofoId(), partnerBid, liquidation, ProfitMandiConstants.BID_ENUM.CANCELLED);
    }

    private String generateBidStatusMessage(String fofoName, Bid bidData, double topBidAmount) {
        StringBuilder message = new StringBuilder();
        message.append("Hi ").append(fofoName).append(",👋\n\n");

        switch (bidData.getStatus()) {
            case CLOSED:
                message.append("Your bid for ").append(bidData.getItemName()).append(" has been confirmed!🎉\n\n")
                    .append("🧾Bid Details:\n")
                    .append("* Bid Amount: ₹").append(String.format("%.2f", bidData.getBiddingAmount())).append("\n")
                    .append("* Quantity: ").append(bidData.getQuantity()).append("\n")
                    .append("* Confirmation Date: ").append(bidData.getCreatedAt()).append("\n\n")
                    .append("Thank you for participating. We'll dispatch your order soon.");
                break;

            case CANCELLED:
                message.append("We regret to inform you that your bid for ").append(bidData.getItemName()).append(" was not selected this time.\n\n")
                    .append("🧾Bid Details:\n")
                    .append("* Bid Amount: ₹").append(String.format("%.2f", bidData.getBiddingAmount())).append("\n")
                    .append("* Quantity: ").append(bidData.getQuantity()).append("\n")
                    .append("* Bid Date: ").append(bidData.getCreatedAt()).append("\n")
                        .append("Qualified Bid Amount: ").append(topBidAmount).append("\n\n")
                    .append("Thank you for your participation. Stay tuned for more opportunities!");
                break;

            case PENDING:
                message.append("Your bid for ").append(bidData.getItemName()).append(" is currently pending.⏳\n\n")
                    .append("Bid Details:\n")
                    .append("* Bid Amount: ₹").append(String.format("%.2f", bidData.getBiddingAmount())).append("\n")
                    .append("* Quantity: ").append(bidData.getQuantity()).append("\n")
                    .append("* Bid Date: ").append(bidData.getCreatedAt()).append("\n\n")
                    .append("We'll notify you once the bidding period ends.");
                break;
        }

        return message.toString();
    }
}