Subversion Repositories SmartDukaan

Rev

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