Subversion Repositories SmartDukaan

Rev

Rev 37194 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
33510 tejus.loha 1
package com.spice.profitmandi.dao.service;
21285 kshitij.so 2
 
33510 tejus.loha 3
import com.fasterxml.jackson.annotation.JsonProperty;
4
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
33577 tejus.loha 5
import com.spice.profitmandi.common.util.Utils;
33510 tejus.loha 6
import com.spice.profitmandi.common.web.client.RestClient;
7
import com.spice.profitmandi.dao.entity.dtr.Otp;
8
import com.spice.profitmandi.dao.entity.onBoarding.LoiForm;
9
import com.spice.profitmandi.dao.enumuration.dtr.OtpType;
10
import com.spice.profitmandi.dao.repository.dtr.OtpRepository;
11
import com.spice.profitmandi.dao.repository.user.LoiFormRepository;
35963 amit 12
import com.spice.profitmandi.service.mail.MailOutboxService;
26712 amit.gupta 13
import org.apache.logging.log4j.LogManager;
14
import org.apache.logging.log4j.Logger;
21285 kshitij.so 15
import org.springframework.beans.factory.annotation.Autowired;
26649 amit.gupta 16
import org.springframework.beans.factory.annotation.Value;
26657 amit.gupta 17
import org.springframework.mail.javamail.JavaMailSender;
21285 kshitij.so 18
import org.springframework.stereotype.Component;
19
 
33510 tejus.loha 20
import java.time.LocalDateTime;
21
import java.util.HashMap;
22
import java.util.List;
23
import java.util.Map;
24
import java.util.Random;
21285 kshitij.so 25
 
26
@Component
26087 tejbeer 27
public class OtpProcessor {
21285 kshitij.so 28
 
33510 tejus.loha 29
    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";
30
    public static final String SELF_CANCELLED_TEMPLATE_ID = "1507161943392646481";
31
    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";
32
    public static final String TEMPLATE_ORDER_CREATED_ID = "1507162021138742118";
33
    private static final Logger LOGGER = LogManager.getLogger(OtpProcessor.class);
31828 amit.gupta 34
    private static final String SMS_GATEWAY = "http://sms.speqtrainnov.com/api/v4/?api_key=A7897cd4627a8781e176fd31710b057a9";
35
    private static final int len = 5;
36
    private static final String SENDER = "SMTDKN";
37
    private static final String numbers = "0123456789";
38
    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";
39
    private static final String OTP_TEMPLATE_ID = "1507161889822750240";
33577 tejus.loha 40
    //LOI OTP
41
    public static final String LOI_ACCEPTANCE_OTP_TEMPLATE_ID = "1707171687739961361";
42
    public static final String DLT_PRINCIPLE_ENTITY_ID = "1501589330000013091";
43
    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.";
36240 vikas 44
    private static final String USER = "devkinandan.lal";
45
    private static final String PASS = "smartdukaan@123";
34014 amit.gupta 46
    private static final String SPECTRA_TELEMARKETER = "1502472910000014692";
36240 vikas 47
    //private static String NEXG_API_ENDPOINT = "https://api2.nexgplatforms.com/sms/1/text/query";
48
    private static String NEXG_API_ENDPOINT = "https://automate.nexgplatforms.com/api/v1/sentsms";
26711 amit.gupta 49
 
31828 amit.gupta 50
    @Autowired
51
    OtpRepository otpRepository;
26711 amit.gupta 52
 
31828 amit.gupta 53
    @Autowired
36399 amit 54
    JavaMailSender gmailRelaySender;
33510 tejus.loha 55
    @Autowired
35963 amit 56
    MailOutboxService mailOutboxService;
57
    @Autowired
33510 tejus.loha 58
    RestClient restClient;
59
    @Autowired
33867 tejus.loha 60
    LoiFormRepository loiFormRepository;
31828 amit.gupta 61
    @Value("${prod}")
62
    private boolean prodEnv;
26649 amit.gupta 63
 
31828 amit.gupta 64
    private String getOtp() {
65
        Random rndm_method = new Random();
66
        char[] otp = new char[len];
21285 kshitij.so 67
 
31828 amit.gupta 68
        for (int i = 0; i < len; i++) {
69
            otp[i] = numbers.charAt(rndm_method.nextInt(numbers.length()));
70
        }
71
        return String.valueOf(otp);
72
    }
26087 tejbeer 73
 
31828 amit.gupta 74
    public OTPResponse generateOtp(String mobile, OtpType otpType) throws Exception, ProfitMandiBusinessException {
75
        LOGGER.info("Try generating otp for mobile -- {}", mobile);
76
        OTPResponse otpResponse = new OTPResponse();
77
        List<Otp> otps = otpRepository.selectAllByMobileWithTime(mobile);
78
        String otpCode = null;
33510 tejus.loha 79
        LOGGER.info("Try to size of otps -- {}", otps.size());
31828 amit.gupta 80
        if (otps.size() >= 5) {
81
            otpResponse.setReference_id(0);
82
            otpResponse.setResult(false);
83
            otpResponse.setMessage("Maximum limit reached for the day");
84
            return otpResponse;
85
        }
33510 tejus.loha 86
        LOGGER.info("Try to check otps isEmpty", otps.isEmpty());
37632 aman 87
        // The resend throttle / code reuse only applies to an OTP that is still usable. A verified one is
88
        // spent, so handing it back ("generated less than 2 minutes ago") would leave the user with no
89
        // working OTP - e.g. an LOI re-sign straight after the signed PDF failed to save.
90
        if (!otps.isEmpty() && !otps.get(0).isVerified()) {
31828 amit.gupta 91
            if (otps.get(0).getCreatedOn().isAfter(LocalDateTime.now().minusMinutes(2))) {
92
                otpResponse.setMessage("OTP generated less than 2 minutes ago");
93
                otpResponse.setReference_id(otps.get(0).getId());
94
                otpResponse.setResult(true);
95
                otpResponse.setOtp(otps.get(0).getOtp());
96
                return otpResponse;
97
            } else if (otps.get(0).getCreatedOn().isAfter(LocalDateTime.now().minusMinutes(10))) {
98
                otpCode = otps.get(0).getOtp();
99
            } else {
100
                ;
101
            }
102
        }
33510 tejus.loha 103
        LOGGER.info("Try to check otp null-- {}", otpCode == null);
31828 amit.gupta 104
        if (otpCode == null || otpCode.isEmpty()) {
105
            otpCode = getOtp();
106
        }
26087 tejbeer 107
 
31828 amit.gupta 108
        Otp otp = new Otp();
109
        otp.setMobile(mobile);
110
        otp.setOtp(otpCode);
111
        otp.setOtpType(otpType);
112
        otp.setCreatedOn(LocalDateTime.now());
113
        otp.setExpiryTimestamp(LocalDateTime.now().plusMinutes(10));
114
        otpRepository.persist(otp);
115
        //sendOtp(otp);
33510 tejus.loha 116
        if (otpType.equals(OtpType.REGISTRATION)) {
31828 amit.gupta 117
            sendOtp(otp);
37194 aman 118
            otpResponse.setSent(true);
33510 tejus.loha 119
        } else if (otpType.equals(OtpType.LOI_ACCEPTANCE)) {
120
            sendOtpForLoiAcceptance(otp);
37194 aman 121
            otpResponse.setSent(true);
31828 amit.gupta 122
        } else {
123
            otpResponse.setOtp(otp.getOtp());
33510 tejus.loha 124
 
31828 amit.gupta 125
        }
26087 tejbeer 126
 
33510 tejus.loha 127
 
31828 amit.gupta 128
        otpResponse.setReference_id(otp.getId());
129
        otpResponse.setMessage("OTP generated successfully");
130
        otpResponse.setResult(true);
131
        return otpResponse;
132
    }
26087 tejbeer 133
 
31828 amit.gupta 134
    public OTPResponse validateOtp(int referenceId, String mobile, String otpCode)
135
            throws Exception, ProfitMandiBusinessException {
33510 tejus.loha 136
        LOGGER.info("validate_call");
31828 amit.gupta 137
        OTPResponse otpResponse = new OTPResponse();
138
        Otp otp = otpRepository.selectById(referenceId);
139
        otp.setTryCount(otp.getTryCount() + 1);
140
        otpResponse.setReference_id(referenceId);
141
        if (!otp.getMobile().equals(mobile) || !otp.getOtp().equalsIgnoreCase(otpCode)) {
142
            otpResponse.setMessage("Invalid otp");
143
            otpResponse.setResult(false);
33510 tejus.loha 144
            LOGGER.info("Invalid otp");
31828 amit.gupta 145
            return otpResponse;
146
        }
147
        if (otp.isExpired() || otp.isVerified() || otp.getExpiryTimestamp().isBefore(LocalDateTime.now())) {
148
            otpResponse.setMessage("OTP expired");
149
            otpResponse.setResult(false);
33510 tejus.loha 150
            LOGGER.info("OTP expired");
31828 amit.gupta 151
            return otpResponse;
152
        }
153
        if (otp.getTryCount() > 5) {
154
            otpResponse.setMessage("Maximum try count reached");
155
            otpResponse.setResult(false);
33510 tejus.loha 156
            LOGGER.info("Maximum try count reached");
31828 amit.gupta 157
            return otpResponse;
158
        }
159
        otp.setExpired(true);
160
        otp.setVerified(true);
161
        otpRepository.persist(otp);
162
        otpResponse.setMessage("OTP validated successfully");
163
        otpResponse.setResult(true);
33510 tejus.loha 164
        LOGGER.info("OTP validated successfully");
31828 amit.gupta 165
        return otpResponse;
166
    }
26711 amit.gupta 167
 
31828 amit.gupta 168
    public void sendOtp(Otp otp) throws Exception {
169
        // In case of Cant receive SMS?
170
        // String mailMessage = java.text.MessageFormat.format(text, otp.getOtp());
171
        String otpString = otp.getOtp();
172
        try {
173
            this.sendSms(OTP_TEMPLATE_ID, String.format(OTP_TEMPLATE, otpString), otp.getMobile());
174
        } catch (Exception e) {
175
            e.printStackTrace();
176
        }
28305 amit.gupta 177
 
31828 amit.gupta 178
    }
26711 amit.gupta 179
 
33510 tejus.loha 180
    //todo
181
    public void sendOtpForLoiAcceptance(Otp otp1) throws Exception {
182
        String otp = otp1.getOtp();
33867 tejus.loha 183
        LoiForm pod = loiFormRepository.selectByEmailOrMobile(otp1.getMobile());
33510 tejus.loha 184
        String ownerName = pod.getFirstName();
185
        String message = String.format(LOI_ACCEPTANCE_OTP_TEMPLATE, ownerName, otp);
186
        this.sendSms(LOI_ACCEPTANCE_OTP_TEMPLATE_ID, message, otp1.getMobile());
33577 tejus.loha 187
        String emailTo[] = {pod.getEmail()};
33867 tejus.loha 188
        try {
35963 amit 189
            mailOutboxService.queueMail(emailTo, null, "LOI ACCEPTANCE OTP", message, "OtpProcessor.sendOtpForLoiAcceptance");
33867 tejus.loha 190
        } catch (Exception e) {
191
            LOGGER.error("Loi OTP not send on email couse -  ", e);
192
        }
33577 tejus.loha 193
 
33510 tejus.loha 194
    }
195
 
196
    public String sendSms(String dltTemplateId, String message, String mobileNumber) throws Exception {
31828 amit.gupta 197
        Map<String, String> queryParams = new HashMap<>();
36240 vikas 198
        queryParams.put("header", SENDER);
199
        queryParams.put("templateid", dltTemplateId);
200
        queryParams.put("entityid", DLT_PRINCIPLE_ENTITY_ID);
201
        queryParams.put("contactnumber", "91" + mobileNumber);
202
        queryParams.put("message", message);
203
        queryParams.put("messageType", "normal");
204
        queryParams.put("serviceType", "otp");
33577 tejus.loha 205
        queryParams.put("password", PASS);
33510 tejus.loha 206
        queryParams.put("username", USER);
31828 amit.gupta 207
        //OTP Message Template
26783 amit.gupta 208
 
36256 vikas 209
        String response = restClient.get(NEXG_API_ENDPOINT, queryParams, new HashMap<>());
33617 tejus.loha 210
        LOGGER.info("LOI_ACCEPTANCE_OTP_Response - " + response);
33510 tejus.loha 211
        return response;
26711 amit.gupta 212
 
31828 amit.gupta 213
    }
26783 amit.gupta 214
 
31828 amit.gupta 215
    class SmsMessage {
216
        private String sender = "SMTDKN";
217
        @JsonProperty(value = "templateid")
218
        private String templateId = "54";
26711 amit.gupta 219
 
31828 amit.gupta 220
        private List<Message> message;
26711 amit.gupta 221
 
31828 amit.gupta 222
        @JsonProperty(value = "messagetype")
223
        private String messageType = "TXT";
26711 amit.gupta 224
 
31828 amit.gupta 225
        @Override
226
        public String toString() {
227
            return "SmsMessage [sender=" + sender + ", templateId=" + templateId + ", message=" + message
228
                    + ", messageType=" + messageType + "]";
229
        }
26711 amit.gupta 230
 
31828 amit.gupta 231
        public String getMessageType() {
232
            return messageType;
233
        }
26711 amit.gupta 234
 
31828 amit.gupta 235
        public void setMessageType(String messageType) {
236
            this.messageType = messageType;
237
        }
26711 amit.gupta 238
 
31828 amit.gupta 239
        public String getSender() {
240
            return sender;
241
        }
26711 amit.gupta 242
 
31828 amit.gupta 243
        public void setSender(String sender) {
244
            this.sender = sender;
245
        }
26711 amit.gupta 246
 
31828 amit.gupta 247
        public String getTemplateId() {
248
            return templateId;
249
        }
26711 amit.gupta 250
 
31828 amit.gupta 251
        public void setTemplateId(String templateId) {
252
            this.templateId = templateId;
253
        }
26711 amit.gupta 254
 
31828 amit.gupta 255
        public List<Message> getMessage() {
256
            return message;
257
        }
26711 amit.gupta 258
 
31828 amit.gupta 259
        public void setMessage(List<Message> message) {
260
            this.message = message;
261
        }
26711 amit.gupta 262
 
31828 amit.gupta 263
    }
26711 amit.gupta 264
 
31828 amit.gupta 265
    class Message {
266
        private String number;
33510 tejus.loha 267
        private Map<String, String> text;
26711 amit.gupta 268
 
31828 amit.gupta 269
        public String getNumber() {
270
            return number;
271
        }
26711 amit.gupta 272
 
31828 amit.gupta 273
        public void setNumber(String number) {
274
            this.number = number;
275
        }
26711 amit.gupta 276
 
31828 amit.gupta 277
        @Override
278
        public String toString() {
279
            return "Message [number=" + number + ", text=" + text + "]";
280
        }
26711 amit.gupta 281
 
31828 amit.gupta 282
        public Map<String, String> getText() {
283
            return text;
284
        }
26711 amit.gupta 285
 
31828 amit.gupta 286
        public void setText(Map<String, String> text) {
287
            this.text = text;
288
        }
21285 kshitij.so 289
 
31828 amit.gupta 290
    }
291
 
21285 kshitij.so 292
}