Subversion Repositories SmartDukaan

Rev

Rev 37051 | Rev 37409 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 37051 Rev 37388
Line 3... Line 3...
3
import com.google.gson.Gson;
3
import com.google.gson.Gson;
4
import com.spice.profitmandi.common.enumuration.MessageType;
4
import com.spice.profitmandi.common.enumuration.MessageType;
5
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
5
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
6
import com.spice.profitmandi.common.model.ProfitMandiConstants;
6
import com.spice.profitmandi.common.model.ProfitMandiConstants;
7
import com.spice.profitmandi.common.model.SendNotificationModel;
7
import com.spice.profitmandi.common.model.SendNotificationModel;
8
import com.spice.profitmandi.common.web.client.RestClient;
-
 
9
import com.spice.profitmandi.dao.entity.auth.AuthUser;
8
import com.spice.profitmandi.dao.entity.auth.AuthUser;
10
import com.spice.profitmandi.dao.entity.dtr.*;
9
import com.spice.profitmandi.dao.entity.dtr.*;
11
import com.spice.profitmandi.dao.entity.fofo.Customer;
10
import com.spice.profitmandi.dao.entity.fofo.Customer;
12
import com.spice.profitmandi.dao.entity.user.Device;
11
import com.spice.profitmandi.dao.entity.user.Device;
13
import com.spice.profitmandi.dao.entity.whatsapp.WhatsappMessage;
12
import com.spice.profitmandi.dao.entity.whatsapp.WhatsappMessage;
Line 18... Line 17...
18
import com.spice.profitmandi.dao.repository.cs.PartnerRegionRepository;
17
import com.spice.profitmandi.dao.repository.cs.PartnerRegionRepository;
19
import com.spice.profitmandi.dao.repository.dtr.*;
18
import com.spice.profitmandi.dao.repository.dtr.*;
20
import com.spice.profitmandi.dao.repository.fofo.CustomerRepository;
19
import com.spice.profitmandi.dao.repository.fofo.CustomerRepository;
21
import com.spice.profitmandi.dao.repository.whatsapp.WhatsappMessageRepository;
20
import com.spice.profitmandi.dao.repository.whatsapp.WhatsappMessageRepository;
22
import com.spice.profitmandi.service.user.RetailerService;
21
import com.spice.profitmandi.service.user.RetailerService;
23
import com.spice.profitmandi.service.whatsapp.CpassWhatsappService;
22
import com.spice.profitmandi.service.whatsapp.WhatsappFlow;
24
import com.spice.profitmandi.service.whatsapp.WhatsappMessageService;
23
import com.spice.profitmandi.service.whatsapp.WhatsappMessageService;
25
import com.spice.profitmandi.service.whatsapp.WhatsappMessageType;
24
import com.spice.profitmandi.service.whatsapp.WhatsappMessageType;
-
 
25
import com.spice.profitmandi.service.whatsapp.WhatsappNumbers;
-
 
26
import com.spice.profitmandi.service.whatsapp.WhatsappProviderResolver;
26
import org.apache.logging.log4j.LogManager;
27
import org.apache.logging.log4j.LogManager;
27
import org.apache.logging.log4j.Logger;
28
import org.apache.logging.log4j.Logger;
28
import org.json.JSONObject;
-
 
29
import org.springframework.beans.factory.annotation.Autowired;
29
import org.springframework.beans.factory.annotation.Autowired;
30
import org.springframework.beans.factory.annotation.Value;
30
import org.springframework.beans.factory.annotation.Value;
31
import org.springframework.stereotype.Component;
31
import org.springframework.stereotype.Component;
32
 
32
 
33
import java.nio.charset.StandardCharsets;
33
import java.nio.charset.StandardCharsets;
Line 63... Line 63...
63
    @Autowired
63
    @Autowired
64
    FofoStoreRepository fofoStoreRepository;
64
    FofoStoreRepository fofoStoreRepository;
65
    @Autowired
65
    @Autowired
66
    CsService csService;
66
    CsService csService;
67
    @Autowired
67
    @Autowired
68
    OptinRepository optinRepository;
-
 
69
    @Autowired
-
 
70
    RetailerService retailerService;
68
    RetailerService retailerService;
71
    @Autowired
69
    @Autowired
72
    CustomerRepository customerRepository;
70
    CustomerRepository customerRepository;
73
    @Autowired
71
    @Autowired
74
    PushNotificationRepository pushNotificationRepository;
72
    PushNotificationRepository pushNotificationRepository;
75
    @Autowired
73
    @Autowired
76
    private Gson gson;
74
    private Gson gson;
77
    @Autowired
-
 
78
    private RestClient restClient;
-
 
79
    @Value("${prod}")
75
    @Value("${prod}")
80
    private boolean isProd;
76
    private boolean isProd;
81
 
77
 
82
    @Autowired
78
    @Autowired
83
    private WhatsappMessageRepository whatsappMessageRepository;
79
    private WhatsappMessageRepository whatsappMessageRepository;
84
 
80
 
85
    @Autowired
81
    @Autowired
86
    private WhatsappMessageService whatsappMessageService;
82
    private WhatsappMessageService whatsappMessageService;
87
 
83
 
88
    @Autowired
84
    @Autowired
89
    private CpassWhatsappService cpassWhatsappService;
85
    private WhatsappProviderResolver whatsappProviders;
90
 
-
 
91
    @Value("${whatsapp.provider:gupshup}")
-
 
92
    private String whatsappProvider;
-
 
93
 
-
 
94
    private boolean isCpass() {
-
 
95
        return "cpass".equalsIgnoreCase(whatsappProvider);
-
 
96
    }
-
 
97
 
86
 
98
    @Override
87
    @Override
99
    public void sendNotification(SendNotificationModel sendNotificationModel) throws ProfitMandiBusinessException {
88
    public void sendNotification(SendNotificationModel sendNotificationModel) throws ProfitMandiBusinessException {
100
 
89
 
101
        SimpleCampaignParams scp = new SimpleCampaignParams();
90
        SimpleCampaignParams scp = new SimpleCampaignParams();
Line 241... Line 230...
241
    @Override
230
    @Override
242
    public boolean sendWhatsappMessage(String message, String title, String mobile) throws Exception {
231
    public boolean sendWhatsappMessage(String message, String title, String mobile) throws Exception {
243
        boolean isSend=false;
232
        boolean isSend=false;
244
        LOGGER.info("Is Prod - {}", isProd);
233
        LOGGER.info("Is Prod - {}", isProd);
245
        if (isProd) {
234
        if (isProd) {
246
            isSend=this.sendWhatsappMessage(WhatsappMessageType.TEXT, message, title, mobile, null, null);
235
            isSend=this.sendWhatsappMessage(WhatsappFlow.GENERIC, WhatsappMessageType.TEXT, message, title, mobile, null, null);
247
        }
236
        }
248
        return isSend;
237
        return isSend;
249
    }
238
    }
250
 
239
 
251
    @Override
240
    @Override
Line 258... Line 247...
258
                    "Accidental Damage Protection\n" +
247
                    "Accidental Damage Protection\n" +
259
                    "अपने फोन को महंगे रिपेयर खर्च से बचाएं।\n" +
248
                    "अपने फोन को महंगे रिपेयर खर्च से बचाएं।\n" +
260
                    "अभी जानकारी लें और अपने फोन को सुरक्षित बनाएं!";
249
                    "अभी जानकारी लें और अपने फोन को सुरक्षित बनाएं!";
261
            String title = "SmartDukaan से खरीदारी करने के लिए धन्यवाद!";
250
            String title = "SmartDukaan से खरीदारी करने के लिए धन्यवाद!";
262
 
251
 
263
            this.sendWhatsappMessage(WhatsappMessageType.TEXT, message, title, mobile, null, null);
252
            this.sendWhatsappMessage(WhatsappFlow.ADLD, WhatsappMessageType.TEXT, message, title, mobile, null, null);
264
        }
253
        }
265
    }
254
    }
266
 
255
 
267
    @Override
256
    @Override
268
    public boolean sendWhatsappInvoice(int customerId, int fofoId, String invoiceNumber, String whatsAppNo) throws Exception {
257
    public boolean sendWhatsappInvoice(int customerId, int fofoId, String invoiceNumber, String whatsAppNo) throws Exception {
Line 290... Line 279...
290
        String mediaUrl = "https://partners.smartdukaan.com/wa-invoice-send/"
279
        String mediaUrl = "https://partners.smartdukaan.com/wa-invoice-send/"
291
                + Base64.getMimeEncoder().encodeToString(invoiceNumber.getBytes(StandardCharsets.UTF_8)) + ".pdf";
280
                + Base64.getMimeEncoder().encodeToString(invoiceNumber.getBytes(StandardCharsets.UTF_8)) + ".pdf";
292
        String fileName = "INV-" + invoiceNumber.replace("/", "-") + ".pdf";
281
        String fileName = "INV-" + invoiceNumber.replace("/", "-") + ".pdf";
293
 
282
 
294
        LOGGER.info("sendWhatsappInvoice: mobile={} mediaUrl={}", mobileNumber, mediaUrl);
283
        LOGGER.info("sendWhatsappInvoice: mobile={} mediaUrl={}", mobileNumber, mediaUrl);
-
 
284
        // Goes straight to the provider rather than through sendWhatsappMediaMessage so the INVOICE flow
-
 
285
        // is named: a template-first provider needs it to pick the approved invoice template.
295
        return sendWhatsappMediaMessage(message, mobileNumber, mediaUrl, fileName, WhatsappMessageType.DOCUMENT);
286
        return this.sendWhatsappMessage(WhatsappFlow.INVOICE, WhatsappMessageType.DOCUMENT, message, null,
-
 
287
                mobileNumber, mediaUrl, fileName);
296
    }
288
    }
297
 
289
 
298
    @Override
290
    @Override
299
    public boolean sendWhatsappMediaMessage(String message, String mobile, String mediaUrl, String fileName, WhatsappMessageType whatsappMessageType) throws Exception {
291
    public boolean sendWhatsappMediaMessage(String message, String mobile, String mediaUrl, String fileName, WhatsappMessageType whatsappMessageType) throws Exception {
300
        boolean isSend=false;
292
        boolean isSend=false;
301
//        if (isProd) {
293
//        if (isProd) {
302
//            isSend=this.sendWhatsappMessage(whatsappMessageType, message, null, mobile, mediaUrl, fileName);
294
//            isSend=this.sendWhatsappMessage(whatsappMessageType, message, null, mobile, mediaUrl, fileName);
303
//        }
295
//        }
304
        isSend = this.sendWhatsappMessage(whatsappMessageType, message, null, mobile, mediaUrl, fileName);
296
        isSend = this.sendWhatsappMessage(WhatsappFlow.GENERIC, whatsappMessageType, message, null, mobile, mediaUrl, fileName);
305
        return isSend;
297
        return isSend;
306
    }
298
    }
307
 
299
 
-
 
300
    /**
-
 
301
     * Kept on this interface because cron calls it directly; it delegates to the active provider and is
-
 
302
     * a no-op for providers with no opt-in concept.
-
 
303
     */
308
    @Override
304
    @Override
309
    public void optIn(String phoneNumber) throws Exception {
305
    public void optIn(String phoneNumber) throws Exception {
310
        Map<String, String> requestheaders = new HashMap<>();
-
 
311
        requestheaders.put("Content-Type", "application/x-www-form-urlencoded");
-
 
312
        Map<String, String> requestParams = new HashMap<>();
-
 
313
        requestParams.put("userid", String.valueOf(2000215976));
-
 
314
        requestParams.put("password", "MFRd!BBL");
-
 
315
        requestParams.put("phone_number", phoneNumber);
306
        whatsappProviders.active().optIn(phoneNumber);
316
        requestParams.put("auth_scheme", "plain");
-
 
317
        requestParams.put("v", "1.1");
-
 
318
        requestParams.put("format", "json");
-
 
319
 
-
 
320
        requestParams.put("method", "OPT_IN");
-
 
321
 
-
 
322
        requestParams.put("channel", "WHATSAPP");
-
 
323
        String response = restClient.get("https://media.smsgupshup.com/GatewayAPI/rest", requestParams, requestheaders);
-
 
324
        LOGGER.info("response" + response);
-
 
325
    }
307
    }
326
 
308
 
327
    private boolean sendWhatsappMessage(WhatsappMessageType whatsappMessageType, String message, String title, String mobile, String mediaUrl, String fileName)
309
    private boolean sendWhatsappMessage(WhatsappFlow flow, WhatsappMessageType whatsappMessageType, String message,
-
 
310
                                        String title, String mobile, String mediaUrl, String fileName)
328
            throws Exception {
311
            throws Exception {
329
        if (isCpass()) {
312
        return whatsappProviders.active()
330
            return cpassWhatsappService.sendBasic(whatsappMessageType, message, title, mobile, mediaUrl, fileName);
313
                .sendBasic(flow, whatsappMessageType, message, title, mobile, mediaUrl, fileName);
331
        }
-
 
332
        String sendTo = null;
-
 
333
        boolean isSend=false;
-
 
334
        if (mobile.length() != 10) {
-
 
335
            return isSend;
-
 
336
        } else {
-
 
337
            sendTo = 91 + mobile;
-
 
338
        }
-
 
339
        Map<String, String> requestheaders = new HashMap<>();
-
 
340
        requestheaders.put("Content-Type", "application/x-www-form-urlencoded");
-
 
341
        Map<String, String> requestParams = new HashMap<>();
-
 
342
        requestParams.put("userid", String.valueOf(2000215976));
-
 
343
        requestParams.put("password", "MFRd!BBL");
-
 
344
        requestParams.put("send_to", sendTo);
-
 
345
        requestParams.put("v", "1.1");
-
 
346
        requestParams.put("format", "json");
-
 
347
        requestParams.put("auth_scheme", "plain");
-
 
348
        Optin optin = optinRepository.selectByMobile(mobile);
-
 
349
        if (optin == null) {
-
 
350
            this.optIn(sendTo);
-
 
351
            optin = new Optin();
-
 
352
            optin.setCreated(LocalDateTime.now());
-
 
353
            optin.setMobile(mobile);
-
 
354
            optinRepository.persist(optin);
-
 
355
        }
-
 
356
        if (mediaUrl == null) {
-
 
357
            requestParams.put("method", "SENDMESSAGE");
-
 
358
            requestParams.put("msg_type", whatsappMessageType.name());
-
 
359
            requestParams.put("msg", message);
-
 
360
            requestParams.put("isTemplate", "true");
-
 
361
            requestParams.put("header", title);
-
 
362
        } else if (mediaUrl != null) {
-
 
363
            requestParams.put("method", "SENDMEDIAMESSAGE");
-
 
364
            requestParams.put("msg_type", whatsappMessageType.name());
-
 
365
            requestParams.put("caption", message);
-
 
366
            requestParams.put("media_url", mediaUrl);
-
 
367
            requestParams.put("filename", fileName);
-
 
368
        }
-
 
369
        String response = restClient.post("https://media.smsgupshup.com/GatewayAPI/rest", requestParams, requestheaders);
-
 
370
        LOGGER.info("response  - {}", response);
-
 
371
 
-
 
372
        JSONObject jsonObject = new JSONObject(response);
-
 
373
 
-
 
374
        JSONObject whatsappResponse = (JSONObject) jsonObject.get("response");
-
 
375
        if (whatsappResponse.getString("status").equals("error")) {
-
 
376
            LOGGER.error("Invalid Whatsapp message, Reason - {}", whatsappResponse.getString("details"));
-
 
377
            return isSend;
-
 
378
        }else{
-
 
379
            isSend=true;
-
 
380
        }
-
 
381
        String externalId = whatsappResponse.getString("id");
-
 
382
        String phone = whatsappResponse.getString("phone");
-
 
383
 
-
 
384
        WhatsappMessage whatsappMessage = new WhatsappMessage();
-
 
385
        whatsappMessage.setCreatedTimestamp(LocalDateTime.now());
-
 
386
        whatsappMessage.setExternalId(externalId);
-
 
387
        whatsappMessage.setDestAddr(phone);
-
 
388
        whatsappMessageRepository.persist(whatsappMessage);
-
 
389
        return isSend;
-
 
390
    }
314
    }
391
 
315
 
392
    @Override
316
    @Override
393
    public boolean shouldSendWhatsappMessage(String mobile) {
317
    public boolean shouldSendWhatsappMessage(String mobile) {
-
 
318
        // Normalised rather than concatenated: cpass and BotPenguin store the normalised MSISDN, so for
-
 
319
        // anything that is not already a bare ten digits the old "91" + mobile key could never match a
-
 
320
        // stored row and the throttle quietly never fired. Identical result for clean input.
394
        String destAddr = "91" + mobile;
321
        String destAddr = WhatsappNumbers.toMsisdn(mobile);
-
 
322
        if (destAddr == null) {
-
 
323
            return true;
-
 
324
        }
395
        boolean shouldSend = true;
325
        boolean shouldSend = true;
396
        List<WhatsappMessage> whatsappMessages = whatsappMessageRepository.selectByDestAddr(destAddr, LocalDate.now());
326
        List<WhatsappMessage> whatsappMessages = whatsappMessageRepository.selectByDestAddr(destAddr, LocalDate.now());
397
        if (!whatsappMessages.isEmpty()) {
327
        if (!whatsappMessages.isEmpty()) {
398
            long failedCount = whatsappMessages.stream().filter(x -> x.getFailed() != null && x.getFailed().equals("FAILED")).collect(Collectors.counting());
328
            long failedCount = whatsappMessages.stream().filter(x -> x.getFailed() != null && x.getFailed().equals("FAILED")).collect(Collectors.counting());
399
            if (failedCount >= 2) {
329
            if (failedCount >= 2) {
Line 404... Line 334...
404
    }
334
    }
405
 
335
 
406
 
336
 
407
    @Override
337
    @Override
408
    public void sendPaymentWhatsappMessage(String mobile, String message) throws Exception {
338
    public void sendPaymentWhatsappMessage(String mobile, String message) throws Exception {
409
        if (isCpass()) {
-
 
410
            cpassWhatsappService.sendText(mobile, message);
-
 
411
            return;
-
 
412
        }
-
 
413
        String sendTo = "91" + mobile;
-
 
414
//        String sendTo = "917082253510";
-
 
415
 
-
 
416
        Map<String, String> requestHeaders = new HashMap<>();
-
 
417
        requestHeaders.put("Content-Type", "application/x-www-form-urlencoded");
-
 
418
        Map<String, String> requestParams = new HashMap<>();
-
 
419
        requestParams.put("userid", String.valueOf(2000215976));
-
 
420
        requestParams.put("password", "MFRd!BBL");
-
 
421
        requestParams.put("send_to", sendTo);
-
 
422
        requestParams.put("v", "1.1");
-
 
423
        requestParams.put("format", "json");
-
 
424
        requestParams.put("auth_scheme", "plain");
-
 
425
        requestParams.put("method", "SENDMESSAGE");
-
 
426
        requestParams.put("msg_type", "TEXT");
-
 
427
        requestParams.put("msg", message);
-
 
428
        requestParams.put("isTemplate", "true");
-
 
429
        requestParams.put("header", "Payment Link!");
-
 
430
 
-
 
431
        String response = restClient.post("https://media.smsgupshup.com/GatewayAPI/rest", requestParams, requestHeaders);
-
 
432
        LOGGER.info("response  - {}", response);
-
 
433
 
-
 
434
        JSONObject jsonObject = new JSONObject(response);
-
 
435
        JSONObject whatsappResponse = jsonObject.getJSONObject("response");
-
 
436
        if (whatsappResponse.getString("status").equals("error")) {
-
 
437
            LOGGER.error("Invalid Whatsapp message, Reason - {}", whatsappResponse.getString("details"));
-
 
438
            return;
-
 
439
        }
-
 
440
 
-
 
441
        String externalId = whatsappResponse.getString("id");
-
 
442
        String phone = whatsappResponse.getString("phone");
-
 
443
 
-
 
444
        WhatsappMessage whatsappMessage = new WhatsappMessage();
-
 
445
        whatsappMessage.setCreatedTimestamp(LocalDateTime.now());
-
 
446
        whatsappMessage.setExternalId(externalId);
-
 
447
        whatsappMessage.setDestAddr(phone);
-
 
448
        whatsappMessageRepository.persist(whatsappMessage);
339
        whatsappProviders.active().sendText(WhatsappFlow.PAYMENT_LINK, mobile, message);
449
    }
340
    }
450
 
341
 
451
}
342
}