Subversion Repositories SmartDukaan

Rev

Rev 36256 | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.dao.service;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.util.Utils;
import com.spice.profitmandi.common.web.client.RestClient;
import com.spice.profitmandi.dao.entity.dtr.Otp;
import com.spice.profitmandi.dao.entity.onBoarding.LoiForm;
import com.spice.profitmandi.dao.enumuration.dtr.OtpType;
import com.spice.profitmandi.dao.repository.dtr.OtpRepository;
import com.spice.profitmandi.dao.repository.user.LoiFormRepository;
import com.spice.profitmandi.service.mail.MailOutboxService;
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.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Component
public class OtpProcessor {

    public static final String SELF_CANCELLED_TEMPLATE = "Order Cancelled PO%s: Dear Customer, your order with SmartDukaan of %s has been cancelled on %s as per your request. Team SmartDukaan";
    public static final String SELF_CANCELLED_TEMPLATE_ID = "1507161943392646481";
    public static final String TEMPLATE_ORDER_CREATED = "Order Placed PO%d: Dear Customer, your order with SmartDukaan of %s worth Rs.%.0f has been placed successfully. Our team will get in touch with you soon. Team SmartDukaan";
    public static final String TEMPLATE_ORDER_CREATED_ID = "1507162021138742118";
    private static final Logger LOGGER = LogManager.getLogger(OtpProcessor.class);
    private static final String SMS_GATEWAY = "http://sms.speqtrainnov.com/api/v4/?api_key=A7897cd4627a8781e176fd31710b057a9";
    private static final int len = 5;
    private static final String SENDER = "SMTDKN";
    private static final String numbers = "0123456789";
    private static final String OTP_TEMPLATE = "Dear Customer, %s is the OTP that you have requested to login into SmartDukaan. Don't share your OTP with anyone";
    private static final String OTP_TEMPLATE_ID = "1507161889822750240";
    //LOI OTP
    public static final String LOI_ACCEPTANCE_OTP_TEMPLATE_ID = "1707171687739961361";
    public static final String DLT_PRINCIPLE_ENTITY_ID = "1501589330000013091";
    public static final String LOI_ACCEPTANCE_OTP_TEMPLATE = "Dear %s,\nThank you for showing your interest in the SmartDukaan franchise.\n%s is the OTP for your LOI acceptance.\nPlease read the LOI and provide your consent by sharing OTP with the SmartDukaan team.\nBest Regards,\nSmartDukaan Team.";
    private static final String USER = "devkinandan.lal";
    private static final String PASS = "smartdukaan@123";
    private static final String SPECTRA_TELEMARKETER = "1502472910000014692";
    //private static String NEXG_API_ENDPOINT = "https://api2.nexgplatforms.com/sms/1/text/query";
    private static String NEXG_API_ENDPOINT = "https://automate.nexgplatforms.com/api/v1/sentsms";

    @Autowired
    OtpRepository otpRepository;

    @Autowired
    JavaMailSender gmailRelaySender;
    @Autowired
    MailOutboxService mailOutboxService;
    @Autowired
    RestClient restClient;
    @Autowired
    LoiFormRepository loiFormRepository;
    @Value("${prod}")
    private boolean prodEnv;

    private String getOtp() {
        Random rndm_method = new Random();
        char[] otp = new char[len];

        for (int i = 0; i < len; i++) {
            otp[i] = numbers.charAt(rndm_method.nextInt(numbers.length()));
        }
        return String.valueOf(otp);
    }

    public OTPResponse generateOtp(String mobile, OtpType otpType) throws Exception, ProfitMandiBusinessException {
        LOGGER.info("Try generating otp for mobile -- {}", mobile);
        OTPResponse otpResponse = new OTPResponse();
        List<Otp> otps = otpRepository.selectAllByMobileWithTime(mobile);
        String otpCode = null;
        LOGGER.info("Try to size of otps -- {}", otps.size());
        if (otps.size() >= 5) {
            otpResponse.setReference_id(0);
            otpResponse.setResult(false);
            otpResponse.setMessage("Maximum limit reached for the day");
            return otpResponse;
        }
        LOGGER.info("Try to check otps isEmpty", otps.isEmpty());
        if (!otps.isEmpty()) {
            if (otps.get(0).getCreatedOn().isAfter(LocalDateTime.now().minusMinutes(2))) {
                otpResponse.setMessage("OTP generated less than 2 minutes ago");
                otpResponse.setReference_id(otps.get(0).getId());
                otpResponse.setResult(true);
                otpResponse.setOtp(otps.get(0).getOtp());
                return otpResponse;
            } else if (otps.get(0).getCreatedOn().isAfter(LocalDateTime.now().minusMinutes(10))) {
                otpCode = otps.get(0).getOtp();
            } else {
                ;
            }
        }
        LOGGER.info("Try to check otp null-- {}", otpCode == null);
        if (otpCode == null || otpCode.isEmpty()) {
            otpCode = getOtp();
        }

        Otp otp = new Otp();
        otp.setMobile(mobile);
        otp.setOtp(otpCode);
        otp.setOtpType(otpType);
        otp.setCreatedOn(LocalDateTime.now());
        otp.setExpiryTimestamp(LocalDateTime.now().plusMinutes(10));
        otpRepository.persist(otp);
        //sendOtp(otp);
        if (otpType.equals(OtpType.REGISTRATION)) {
            sendOtp(otp);
        } else if (otpType.equals(OtpType.LOI_ACCEPTANCE)) {
            sendOtpForLoiAcceptance(otp);
        } else {
            otpResponse.setOtp(otp.getOtp());

        }


        otpResponse.setReference_id(otp.getId());
        otpResponse.setMessage("OTP generated successfully");
        otpResponse.setResult(true);
        return otpResponse;
    }

    public OTPResponse validateOtp(int referenceId, String mobile, String otpCode)
            throws Exception, ProfitMandiBusinessException {
        LOGGER.info("validate_call");
        OTPResponse otpResponse = new OTPResponse();
        Otp otp = otpRepository.selectById(referenceId);
        otp.setTryCount(otp.getTryCount() + 1);
        otpResponse.setReference_id(referenceId);
        if (!otp.getMobile().equals(mobile) || !otp.getOtp().equalsIgnoreCase(otpCode)) {
            otpResponse.setMessage("Invalid otp");
            otpResponse.setResult(false);
            LOGGER.info("Invalid otp");
            return otpResponse;
        }
        if (otp.isExpired() || otp.isVerified() || otp.getExpiryTimestamp().isBefore(LocalDateTime.now())) {
            otpResponse.setMessage("OTP expired");
            otpResponse.setResult(false);
            LOGGER.info("OTP expired");
            return otpResponse;
        }
        if (otp.getTryCount() > 5) {
            otpResponse.setMessage("Maximum try count reached");
            otpResponse.setResult(false);
            LOGGER.info("Maximum try count reached");
            return otpResponse;
        }
        otp.setExpired(true);
        otp.setVerified(true);
        otpRepository.persist(otp);
        otpResponse.setMessage("OTP validated successfully");
        otpResponse.setResult(true);
        LOGGER.info("OTP validated successfully");
        return otpResponse;
    }

    public void sendOtp(Otp otp) throws Exception {
        // In case of Cant receive SMS?
        // String mailMessage = java.text.MessageFormat.format(text, otp.getOtp());
        String otpString = otp.getOtp();
        try {
            this.sendSms(OTP_TEMPLATE_ID, String.format(OTP_TEMPLATE, otpString), otp.getMobile());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //todo
    public void sendOtpForLoiAcceptance(Otp otp1) throws Exception {
        String otp = otp1.getOtp();
        LoiForm pod = loiFormRepository.selectByEmailOrMobile(otp1.getMobile());
        String ownerName = pod.getFirstName();
        String message = String.format(LOI_ACCEPTANCE_OTP_TEMPLATE, ownerName, otp);
        this.sendSms(LOI_ACCEPTANCE_OTP_TEMPLATE_ID, message, otp1.getMobile());
        String emailTo[] = {pod.getEmail()};
        try {
            mailOutboxService.queueMail(emailTo, null, "LOI ACCEPTANCE OTP", message, "OtpProcessor.sendOtpForLoiAcceptance");
        } catch (Exception e) {
            LOGGER.error("Loi OTP not send on email couse -  ", e);
        }

    }

    public String sendSms(String dltTemplateId, String message, String mobileNumber) throws Exception {
        Map<String, String> queryParams = new HashMap<>();
        queryParams.put("header", SENDER);
        queryParams.put("templateid", dltTemplateId);
        queryParams.put("entityid", DLT_PRINCIPLE_ENTITY_ID);
        queryParams.put("contactnumber", "91" + mobileNumber);
        queryParams.put("message", message);
        queryParams.put("messageType", "normal");
        queryParams.put("serviceType", "otp");
        queryParams.put("password", PASS);
        queryParams.put("username", USER);
        //OTP Message Template

        String response = restClient.get(NEXG_API_ENDPOINT, queryParams, new HashMap<>());
        LOGGER.info("LOI_ACCEPTANCE_OTP_Response - " + response);
        return response;

    }

    class SmsMessage {
        private String sender = "SMTDKN";
        @JsonProperty(value = "templateid")
        private String templateId = "54";

        private List<Message> message;

        @JsonProperty(value = "messagetype")
        private String messageType = "TXT";

        @Override
        public String toString() {
            return "SmsMessage [sender=" + sender + ", templateId=" + templateId + ", message=" + message
                    + ", messageType=" + messageType + "]";
        }

        public String getMessageType() {
            return messageType;
        }

        public void setMessageType(String messageType) {
            this.messageType = messageType;
        }

        public String getSender() {
            return sender;
        }

        public void setSender(String sender) {
            this.sender = sender;
        }

        public String getTemplateId() {
            return templateId;
        }

        public void setTemplateId(String templateId) {
            this.templateId = templateId;
        }

        public List<Message> getMessage() {
            return message;
        }

        public void setMessage(List<Message> message) {
            this.message = message;
        }

    }

    class Message {
        private String number;
        private Map<String, String> text;

        public String getNumber() {
            return number;
        }

        public void setNumber(String number) {
            this.number = number;
        }

        @Override
        public String toString() {
            return "Message [number=" + number + ", text=" + text + "]";
        }

        public Map<String, String> getText() {
            return text;
        }

        public void setText(Map<String, String> text) {
            this.text = text;
        }

    }

}