Subversion Repositories SmartDukaan

Rev

Rev 28375 | Blame | Last modification | View Log | RSS feed

package com.spice.profitmandi.web.processor;

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

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 com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.ImmutableMap;
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.web.client.RestClient;
import com.spice.profitmandi.dao.entity.dtr.Otp;
import com.spice.profitmandi.dao.enumuration.dtr.OtpType;
import com.spice.profitmandi.dao.repository.dtr.OtpRepository;
import com.spice.profitmandi.service.scheme.SchemeServiceImpl;
import com.spice.profitmandi.web.res.OTPResponse;

@Component
public class OtpProcessor {

    private static final Logger LOGGER = LogManager.getLogger(SchemeServiceImpl.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";
    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";

    @Autowired
    OtpRepository otpRepository;

    @Autowired
    JavaMailSender mailSender;

    @Value("${prod}")
    private boolean prodEnv;

    @Autowired
    RestClient restClient;

    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;
        if (otps.size() >= 5) {
            otpResponse.setReference_id(0);
            otpResponse.setResult(false);
            otpResponse.setMessage("Maximum limit reached for the day");
            return otpResponse;
        }
        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 {
                ;
            }
        }
        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 (prodEnv) {
            sendOtp(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 {
        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);
            return otpResponse;
        }
        if (otp.isExpired() || otp.isVerified() || otp.getExpiryTimestamp().isBefore(LocalDateTime.now())) {
            otpResponse.setMessage("OTP expired");
            otpResponse.setResult(false);
            return otpResponse;
        }
        if (otp.getTryCount() > 5) {
            otpResponse.setMessage("Maximum try count reached");
            otpResponse.setResult(false);
            return otpResponse;
        }
        otp.setExpired(true);
        otp.setVerified(true);
        otpRepository.persist(otp);
        otpResponse.setMessage("OTP validated successfully");
        otpResponse.setResult(true);
        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();
        }

    }

    public void sendSms(String dltTemplateId, String message, String mobileNumber) throws Exception {
        Map<String, String> queryParams = new HashMap<>();
        queryParams.put("sender", SENDER);
        queryParams.put("method", "sms");
        queryParams.put("to", "91" + mobileNumber);
        queryParams.put("message", message);
        queryParams.put("format", "json");
        //OTP Message Template

        String response = restClient.post(SMS_GATEWAY, queryParams, new HashMap<>(), new HashMap<>());
        LOGGER.info(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;

        public String getNumber() {
            return number;
        }

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

        private Map<String, String> text;

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

    }

}