Subversion Repositories SmartDukaan

Rev

Rev 37051 | Rev 37409 | Go to most recent revision | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.service;

import com.google.gson.Gson;
import com.spice.profitmandi.common.enumuration.MessageType;
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.ProfitMandiConstants;
import com.spice.profitmandi.common.model.SendNotificationModel;
import com.spice.profitmandi.dao.entity.auth.AuthUser;
import com.spice.profitmandi.dao.entity.dtr.*;
import com.spice.profitmandi.dao.entity.fofo.Customer;
import com.spice.profitmandi.dao.entity.user.Device;
import com.spice.profitmandi.dao.entity.whatsapp.WhatsappMessage;
import com.spice.profitmandi.dao.model.SimpleCampaign;
import com.spice.profitmandi.dao.model.SimpleCampaignParams;
import com.spice.profitmandi.dao.repository.catalog.DeviceRepository;
import com.spice.profitmandi.dao.repository.cs.CsService;
import com.spice.profitmandi.dao.repository.cs.PartnerRegionRepository;
import com.spice.profitmandi.dao.repository.dtr.*;
import com.spice.profitmandi.dao.repository.fofo.CustomerRepository;
import com.spice.profitmandi.dao.repository.whatsapp.WhatsappMessageRepository;
import com.spice.profitmandi.service.user.RetailerService;
import com.spice.profitmandi.service.whatsapp.WhatsappFlow;
import com.spice.profitmandi.service.whatsapp.WhatsappMessageService;
import com.spice.profitmandi.service.whatsapp.WhatsappMessageType;
import com.spice.profitmandi.service.whatsapp.WhatsappNumbers;
import com.spice.profitmandi.service.whatsapp.WhatsappProviderResolver;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class NotificationServiceImpl implements NotificationService {

    private static final Logger LOGGER = LogManager.getLogger(NotificationServiceImpl.class);

    // Region id that represents "all partners". Schemes meant for everyone are tagged to this region;
    // partner_region is not populated for it, so it must be expanded to all partners here.
    private static final int ALL_PARTNERS_REGION = 5;

    @Autowired
    UserCampaignRepository userCampaignRepository;
    @Autowired
    UserRepository dtrUserRepository;
    @Autowired
    UserAccountRepository userAccountRepository;
    @Autowired
    NotificationCampaignRepository notificationCampaignRepository;
    @Autowired
    DeviceRepository deviceRepository;

    @Autowired
    PartnerRegionRepository partnerRegionRepository;


    @Autowired
    FofoStoreRepository fofoStoreRepository;
    @Autowired
    CsService csService;
    @Autowired
    RetailerService retailerService;
    @Autowired
    CustomerRepository customerRepository;
    @Autowired
    PushNotificationRepository pushNotificationRepository;
    @Autowired
    private Gson gson;
    @Value("${prod}")
    private boolean isProd;

    @Autowired
    private WhatsappMessageRepository whatsappMessageRepository;

    @Autowired
    private WhatsappMessageService whatsappMessageService;

    @Autowired
    private WhatsappProviderResolver whatsappProviders;

    @Override
    public void sendNotification(SendNotificationModel sendNotificationModel) throws ProfitMandiBusinessException {

        SimpleCampaignParams scp = new SimpleCampaignParams();
        scp.setMessage(sendNotificationModel.getMessage());
        scp.setTitle(sendNotificationModel.getTitle());
        scp.setImageUrl(sendNotificationModel.getImageUrl());
        scp.setType(sendNotificationModel.getType());
        scp.setUrl(sendNotificationModel.getUrl());
        scp.setShowImage(sendNotificationModel.getShowImage());
        scp.setExpireTimestamp(sendNotificationModel.getExpiresat());
        SimpleCampaign sc = new SimpleCampaign(scp);
        sc.setSimpleCampaignParams(scp);

        NotificationCampaign nc = new NotificationCampaign();
        nc.setName(sendNotificationModel.getCampaignName());
        nc.setImplementationType("SimpleCampaign");
        nc.setImplementationParams(gson.toJson(scp));
        nc.setMessageType(sendNotificationModel.getMessageType());
        nc.setDocumentId(sendNotificationModel.getDocumentId());
        nc.setCreatedTimestamp(LocalDateTime.now());
        notificationCampaignRepository.persist(nc);

        Set<Integer> userIds = new HashSet<>();
        if (sendNotificationModel.getUserIds() != null && sendNotificationModel.getUserIds().size() > 0) {
            userIds.addAll(sendNotificationModel.getUserIds());
        }

        if (sendNotificationModel.getStateIds() != null && sendNotificationModel.getStateIds().size() > 0) {
            List<Integer> fofoIds = fofoStoreRepository.selectByWarehouseIds(sendNotificationModel.getStateIds()).stream()
                    .map(x -> x.getId()).collect(Collectors.toList());
            if (fofoIds.size() > 0) {
                userIds.addAll(userAccountRepository.selectUserIdsByRetailerIds(fofoIds));
            }

        }
        if(sendNotificationModel.getRegionIds() != null && sendNotificationModel.getRegionIds().size() > 0) {
            if (sendNotificationModel.getRegionIds().contains(ALL_PARTNERS_REGION)) {
                // "ALL partners" region: partner_region only holds a sentinel, so expand to every partner.
                userIds.addAll(fofoStoreRepository.selectAllDtrUserIds());
            } else {
                List<Integer> fofoIds = partnerRegionRepository.selectAllByRegionIds(sendNotificationModel.getRegionIds()).stream().map(x->x.getFofoId()).collect(Collectors.toList());
                if(fofoIds.size()>0) {
                    userIds.addAll(userAccountRepository.selectUserIdsByRetailerIds(fofoIds));
                }
            }
        }

        if (userIds.size() > 0) {
            for (Integer userId : userIds) {
                UserCampaign uc = new UserCampaign();
                uc.setCampaignId(nc.getId());
                uc.setUserId(userId);
                uc.setPushTimestamp(LocalDateTime.now());
                userCampaignRepository.persist(uc);
            }
            List<Device> devices = deviceRepository.selectByUserIdAndModifiedTimestamp(new ArrayList<>(userIds),
                    LocalDateTime.now().minusMonths(1), LocalDateTime.now());
            pushNotification(nc.getId(), devices);
        } else {
            LOGGER.info("Failed to send notification to any retailer with this model - {}", sendNotificationModel);
        }

    }

    @Override
    public void sendNotificationToAll(SendNotificationModel sendNotificationModel) throws ProfitMandiBusinessException {
        sendNotificationModel.setUserIds(fofoStoreRepository.selectAllDtrUserIds());
        Set<AuthUser> authUsers = new HashSet<>(
                csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_RBM));
        authUsers.addAll(csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_CATEGORY));
        authUsers.addAll(csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_SALES));
        authUsers.addAll(csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_ABM));
        List<String> emailIds = authUsers.stream().map(x -> x.getEmailId()).collect(Collectors.toList());
        emailIds.add("devkinandan.lal@smartdukaan.com");
        List<User> systemUsers = dtrUserRepository.selectAllByEmailIds(emailIds);
        sendNotificationModel.getUserIds()
                .addAll(systemUsers.stream().map(x -> x.getId()).collect(Collectors.toList()));
        this.sendNotification(sendNotificationModel);
    }

    @Override
    public void sendNotificationToSystemUsers(SendNotificationModel sendNotificationModel) throws ProfitMandiBusinessException {
        Set<AuthUser> authUsers = new HashSet<>(csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_RBM));
        authUsers.addAll(csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_CATEGORY));
        authUsers.addAll(csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_SALES));
        authUsers.addAll(csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_ABM));
        List<String> emailIds = authUsers.stream().map(x -> x.getEmailId()).collect(Collectors.toList());
        emailIds.add("devkinandan.lal@smartdukaan.com");
        List<User> systemUsers = dtrUserRepository.selectAllByEmailIds(emailIds);
        sendNotificationModel.setUserIds(systemUsers.stream().map(x -> x.getId()).collect(Collectors.toList()));
        this.sendNotification(sendNotificationModel);
    }

    @Override
    public void sendNotification(int fofoId, String campaignName, MessageType messageType, String title, String message)
            throws ProfitMandiBusinessException {
        SendNotificationModel sendNotificationModel = this.getDefaultNotificationModel();
        sendNotificationModel.setCampaignName(campaignName);
        sendNotificationModel.setMessageType(messageType);
        sendNotificationModel.setTitle(title);
        sendNotificationModel.setMessage(message);
        int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
        sendNotificationModel.setUserIds(Arrays.asList(userId));
        sendNotificationModel.setMessageType(MessageType.wallet);
        this.sendNotification(sendNotificationModel);
    }

    public SendNotificationModel getDefaultNotificationModel() {
        SendNotificationModel sendNotificationModel = new SendNotificationModel();
        sendNotificationModel.setType("url");
        sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
        sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
        sendNotificationModel.setMessageType(MessageType.notification);
        return sendNotificationModel;
    }

    public void pushNotification(int cid, List<Device> devices) {

        for (Device device : devices) {
            PushNotifications pn = new PushNotifications();
            pn.setNotificationCampaignid(cid);
            pn.setDeviceId(device.getId());
            pn.setUserId(device.getUser_id());
            pushNotificationRepository.persist(pn);
        }

    }

    @Override
    public void sendNotification(int fofoId, String campaignName, MessageType messageType, String title, String message, String url) throws ProfitMandiBusinessException {
        SendNotificationModel sendNotificationModel = this.getDefaultNotificationModel();
        sendNotificationModel.setCampaignName(campaignName);
        sendNotificationModel.setMessageType(messageType);
        sendNotificationModel.setTitle(title);
        sendNotificationModel.setMessage(message);
        int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
        sendNotificationModel.setUserIds(Arrays.asList(userId));
        sendNotificationModel.setMessageType(messageType);
        sendNotificationModel.setUrl(url);
        this.sendNotification(sendNotificationModel);
    }

    @Override
    public boolean sendWhatsappMessage(String message, String title, String mobile) throws Exception {
        boolean isSend=false;
        LOGGER.info("Is Prod - {}", isProd);
        if (isProd) {
            isSend=this.sendWhatsappMessage(WhatsappFlow.GENERIC, WhatsappMessageType.TEXT, message, title, mobile, null, null);
        }
        return isSend;
    }

    @Override
    public void sendADLDWhatsappMessage(String mobile) throws Exception {
        LOGGER.info("Is Prod - {}", isProd);
        if (isProd) {
            String message = "क्या आपने SmartDukaan Protect Plus Plan लिया है?\n\n" +
                    "सिर्फ ₹199 से शुरू, पाएं अपने मोबाइल के लिए 1 साल की स्मार्ट सुरक्षा —\n" +
                    "Liquid Damage Protection\n" +
                    "Accidental Damage Protection\n" +
                    "अपने फोन को महंगे रिपेयर खर्च से बचाएं।\n" +
                    "अभी जानकारी लें और अपने फोन को सुरक्षित बनाएं!";
            String title = "SmartDukaan से खरीदारी करने के लिए धन्यवाद!";

            this.sendWhatsappMessage(WhatsappFlow.ADLD, WhatsappMessageType.TEXT, message, title, mobile, null, null);
        }
    }

    @Override
    public boolean sendWhatsappInvoice(int customerId, int fofoId, String invoiceNumber, String whatsAppNo) throws Exception {
        boolean shouldSend = shouldSendWhatsappMessage(whatsAppNo);
        if (!shouldSend) return false;

        Customer customer = customerRepository.selectById(customerId);
        String mobileNumber = (whatsAppNo != null && !whatsAppNo.isEmpty()) ? whatsAppNo : customer.getMobileNumber();

        String message = "*SmartDukaan's One-Time Offer Unlocked!*\n" +
                "Thank you for your purchase.\n" +
                "\n" +
                "Abhi-abhi naya phone liya hai...\n" +
                "Par kya aapne uski poori suraksha li hai?\n" +
                "SmartDukaan par sabse kam daam mein plans available hain:\n" +
                "\n" +
                "*Complete Protection Plan* (Accidental & Liquid Damage) - Starting ₹199\n" +
                "\n" +
                "*Extended 1 Year Warranty* - ₹199 se shuru\n" +
                "\n" +
                "Abhi store par iski jaankari lein.\n" +
                "\n" +
                "*Ye offer phone ki kharidari ke sirf 24 hours tak hi valid hai!*";

        String mediaUrl = "https://partners.smartdukaan.com/wa-invoice-send/"
                + Base64.getMimeEncoder().encodeToString(invoiceNumber.getBytes(StandardCharsets.UTF_8)) + ".pdf";
        String fileName = "INV-" + invoiceNumber.replace("/", "-") + ".pdf";

        LOGGER.info("sendWhatsappInvoice: mobile={} mediaUrl={}", mobileNumber, mediaUrl);
        // Goes straight to the provider rather than through sendWhatsappMediaMessage so the INVOICE flow
        // is named: a template-first provider needs it to pick the approved invoice template.
        return this.sendWhatsappMessage(WhatsappFlow.INVOICE, WhatsappMessageType.DOCUMENT, message, null,
                mobileNumber, mediaUrl, fileName);
    }

    @Override
    public boolean sendWhatsappMediaMessage(String message, String mobile, String mediaUrl, String fileName, WhatsappMessageType whatsappMessageType) throws Exception {
        boolean isSend=false;
//        if (isProd) {
//            isSend=this.sendWhatsappMessage(whatsappMessageType, message, null, mobile, mediaUrl, fileName);
//        }
        isSend = this.sendWhatsappMessage(WhatsappFlow.GENERIC, whatsappMessageType, message, null, mobile, mediaUrl, fileName);
        return isSend;
    }

    /**
     * Kept on this interface because cron calls it directly; it delegates to the active provider and is
     * a no-op for providers with no opt-in concept.
     */
    @Override
    public void optIn(String phoneNumber) throws Exception {
        whatsappProviders.active().optIn(phoneNumber);
    }

    private boolean sendWhatsappMessage(WhatsappFlow flow, WhatsappMessageType whatsappMessageType, String message,
                                        String title, String mobile, String mediaUrl, String fileName)
            throws Exception {
        return whatsappProviders.active()
                .sendBasic(flow, whatsappMessageType, message, title, mobile, mediaUrl, fileName);
    }

    @Override
    public boolean shouldSendWhatsappMessage(String mobile) {
        // Normalised rather than concatenated: cpass and BotPenguin store the normalised MSISDN, so for
        // anything that is not already a bare ten digits the old "91" + mobile key could never match a
        // stored row and the throttle quietly never fired. Identical result for clean input.
        String destAddr = WhatsappNumbers.toMsisdn(mobile);
        if (destAddr == null) {
            return true;
        }
        boolean shouldSend = true;
        List<WhatsappMessage> whatsappMessages = whatsappMessageRepository.selectByDestAddr(destAddr, LocalDate.now());
        if (!whatsappMessages.isEmpty()) {
            long failedCount = whatsappMessages.stream().filter(x -> x.getFailed() != null && x.getFailed().equals("FAILED")).collect(Collectors.counting());
            if (failedCount >= 2) {
                shouldSend = false;
            }
        }
        return shouldSend;
    }


    @Override
    public void sendPaymentWhatsappMessage(String mobile, String message) throws Exception {
        whatsappProviders.active().sendText(WhatsappFlow.PAYMENT_LINK, mobile, message);
    }

}