Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
25822 amit.gupta 1
package com.spice.profitmandi.service;
2
 
3
import com.google.gson.Gson;
30025 amit.gupta 4
import com.spice.profitmandi.common.enumuration.MessageType;
29198 manish 5
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
29927 amit.gupta 6
import com.spice.profitmandi.common.model.ProfitMandiConstants;
25822 amit.gupta 7
import com.spice.profitmandi.common.model.SendNotificationModel;
30989 tejbeer 8
import com.spice.profitmandi.common.web.client.RestClient;
29927 amit.gupta 9
import com.spice.profitmandi.dao.entity.auth.AuthUser;
32405 jai.hind 10
import com.spice.profitmandi.dao.entity.dtr.*;
25822 amit.gupta 11
import com.spice.profitmandi.dao.entity.user.Device;
32405 jai.hind 12
import com.spice.profitmandi.dao.entity.whatsapp.WhatsappMessage;
25822 amit.gupta 13
import com.spice.profitmandi.dao.model.SimpleCampaign;
14
import com.spice.profitmandi.dao.model.SimpleCampaignParams;
15
import com.spice.profitmandi.dao.repository.catalog.DeviceRepository;
29927 amit.gupta 16
import com.spice.profitmandi.dao.repository.cs.CsService;
32405 jai.hind 17
import com.spice.profitmandi.dao.repository.dtr.*;
18
import com.spice.profitmandi.dao.repository.whatsapp.WhatsappMessageRepository;
29198 manish 19
import com.spice.profitmandi.service.user.RetailerService;
32405 jai.hind 20
import com.spice.profitmandi.service.whatsapp.WhatsappMessageService;
32854 amit.gupta 21
import com.spice.profitmandi.service.whatsapp.WhatsappMessageType;
32405 jai.hind 22
import org.apache.logging.log4j.LogManager;
23
import org.apache.logging.log4j.Logger;
34545 vikas.jang 24
import org.json.JSONArray;
32405 jai.hind 25
import org.json.JSONObject;
26
import org.springframework.beans.factory.annotation.Autowired;
34522 ranu 27
import org.springframework.beans.factory.annotation.Value;
32405 jai.hind 28
import org.springframework.stereotype.Component;
25822 amit.gupta 29
 
34545 vikas.jang 30
import java.io.BufferedReader;
31
import java.io.InputStreamReader;
32
import java.io.OutputStream;
33
import java.net.HttpURLConnection;
34
import java.net.URL;
35
import java.nio.charset.StandardCharsets;
32508 amit.gupta 36
import java.time.LocalDate;
32405 jai.hind 37
import java.time.LocalDateTime;
38
import java.util.*;
39
import java.util.stream.Collectors;
40
 
25835 amit.gupta 41
@Component
25822 amit.gupta 42
public class NotificationServiceImpl implements NotificationService {
43
 
32253 amit.gupta 44
    private static final Logger LOGGER = LogManager.getLogger(NotificationService.class);
45
    @Autowired
46
    UserCampaignRepository userCampaignRepository;
47
    @Autowired
48
    UserRepository dtrUserRepository;
49
    @Autowired
50
    UserAccountRepository userAccountRepository;
51
    @Autowired
52
    NotificationCampaignRepository notificationCampaignRepository;
53
    @Autowired
54
    DeviceRepository deviceRepository;
55
    @Autowired
56
    FofoStoreRepository fofoStoreRepository;
57
    @Autowired
58
    CsService csService;
59
    @Autowired
60
    OptinRepository optinRepository;
61
    @Autowired
62
    RetailerService retailerService;
63
    @Autowired
64
    PushNotificationRepository pushNotificationRepository;
65
    @Autowired
66
    private Gson gson;
67
    @Autowired
68
    private RestClient restClient;
34522 ranu 69
    @Value("${prod}")
70
    private boolean isProd;
25822 amit.gupta 71
 
32405 jai.hind 72
    @Autowired
32417 amit.gupta 73
    private WhatsappMessageRepository whatsappMessageRepository;
32405 jai.hind 74
 
75
    @Autowired
76
    private WhatsappMessageService whatsappMessageService;
77
 
32253 amit.gupta 78
    @Override
79
    public void sendNotification(SendNotificationModel sendNotificationModel) throws ProfitMandiBusinessException {
29927 amit.gupta 80
 
32253 amit.gupta 81
        SimpleCampaignParams scp = new SimpleCampaignParams();
82
        scp.setMessage(sendNotificationModel.getMessage());
83
        scp.setTitle(sendNotificationModel.getTitle());
84
        scp.setImageUrl(sendNotificationModel.getImageUrl());
85
        scp.setType(sendNotificationModel.getType());
86
        scp.setUrl(sendNotificationModel.getUrl());
87
        scp.setShowImage(sendNotificationModel.getShowImage());
88
        scp.setExpireTimestamp(sendNotificationModel.getExpiresat());
89
        SimpleCampaign sc = new SimpleCampaign(scp);
90
        sc.setSimpleCampaignParams(scp);
30025 amit.gupta 91
 
32253 amit.gupta 92
        NotificationCampaign nc = new NotificationCampaign();
93
        nc.setName(sendNotificationModel.getCampaignName());
94
        nc.setImplementationType("SimpleCampaign");
95
        nc.setImplementationParams(gson.toJson(scp));
96
        nc.setMessageType(sendNotificationModel.getMessageType());
97
        nc.setDocumentId(sendNotificationModel.getDocumentId());
98
        nc.setCreatedTimestamp(LocalDateTime.now());
99
        notificationCampaignRepository.persist(nc);
25822 amit.gupta 100
 
32253 amit.gupta 101
        Set<Integer> userIds = new HashSet<>();
102
        if (sendNotificationModel.getUserIds() != null && sendNotificationModel.getUserIds().size() > 0) {
103
            userIds.addAll(sendNotificationModel.getUserIds());
104
        }
29198 manish 105
 
32253 amit.gupta 106
        if (sendNotificationModel.getStateIds() != null && sendNotificationModel.getStateIds().size() > 0) {
33025 amit.gupta 107
            List<Integer> fofoIds = fofoStoreRepository.selectByWarehouseIds(sendNotificationModel.getStateIds()).stream()
108
                    .map(x -> x.getId()).collect(Collectors.toList());
34204 tejus.loha 109
            if (fofoIds.size() > 0) {
33025 amit.gupta 110
                userIds.addAll(userAccountRepository.selectUserIdsByRetailerIds(fofoIds));
111
            }
112
 
32253 amit.gupta 113
        }
29927 amit.gupta 114
 
34204 tejus.loha 115
        if (userIds.size() > 0) {
33025 amit.gupta 116
            for (Integer userId : userIds) {
117
                UserCampaign uc = new UserCampaign();
118
                uc.setCampaignId(nc.getId());
119
                uc.setUserId(userId);
120
                uc.setPushTimestamp(LocalDateTime.now());
121
                userCampaignRepository.persist(uc);
122
            }
123
            List<Device> devices = deviceRepository.selectByUserIdAndModifiedTimestamp(new ArrayList<>(userIds),
124
                    LocalDateTime.now().minusMonths(1), LocalDateTime.now());
125
            pushNotification(nc.getId(), devices);
126
        } else {
127
            LOGGER.info("Failed to send notification to any retailer with this model - {}", sendNotificationModel);
32253 amit.gupta 128
        }
25822 amit.gupta 129
 
32253 amit.gupta 130
    }
25822 amit.gupta 131
 
32253 amit.gupta 132
    @Override
133
    public void sendNotificationToAll(SendNotificationModel sendNotificationModel) throws ProfitMandiBusinessException {
134
        sendNotificationModel.setUserIds(fofoStoreRepository.selectAllDtrUserIds());
135
        Set<AuthUser> authUsers = new HashSet<>(
136
                csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_RBM));
137
        authUsers.addAll(csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_CATEGORY));
138
        authUsers.addAll(csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_SALES));
139
        List<String> emailIds = authUsers.stream().map(x -> x.getEmailId()).collect(Collectors.toList());
140
        emailIds.add("devkinandan.lal@smartdukaan.com");
141
        List<User> systemUsers = dtrUserRepository.selectAllByEmailIds(emailIds);
32405 jai.hind 142
        sendNotificationModel.getUserIds()
143
                .addAll(systemUsers.stream().map(x -> x.getId()).collect(Collectors.toList()));
32253 amit.gupta 144
        this.sendNotification(sendNotificationModel);
145
    }
25822 amit.gupta 146
 
32253 amit.gupta 147
    @Override
34550 vikas.jang 148
    public void sendNotificationToSystemUsers(SendNotificationModel sendNotificationModel) throws ProfitMandiBusinessException {
149
        Set<AuthUser> authUsers = new HashSet<>(csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_RBM));
150
        authUsers.addAll(csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_CATEGORY));
151
        authUsers.addAll(csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_SALES));
152
        List<String> emailIds = authUsers.stream().map(x -> x.getEmailId()).collect(Collectors.toList());
153
        emailIds.add("devkinandan.lal@smartdukaan.com");
154
        List<User> systemUsers = dtrUserRepository.selectAllByEmailIds(emailIds);
155
        sendNotificationModel.setUserIds(systemUsers.stream().map(x -> x.getId()).collect(Collectors.toList()));
156
        this.sendNotification(sendNotificationModel);
157
    }
158
 
159
    @Override
32405 jai.hind 160
    public void sendNotification(int fofoId, String campaignName, MessageType messageType, String title, String message)
161
            throws ProfitMandiBusinessException {
32253 amit.gupta 162
        SendNotificationModel sendNotificationModel = this.getDefaultNotificationModel();
163
        sendNotificationModel.setCampaignName(campaignName);
164
        sendNotificationModel.setMessageType(messageType);
165
        sendNotificationModel.setTitle(title);
166
        sendNotificationModel.setMessage(message);
167
        int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
168
        sendNotificationModel.setUserIds(Arrays.asList(userId));
169
        sendNotificationModel.setMessageType(MessageType.wallet);
170
        this.sendNotification(sendNotificationModel);
171
    }
25822 amit.gupta 172
 
32253 amit.gupta 173
    public SendNotificationModel getDefaultNotificationModel() {
174
        SendNotificationModel sendNotificationModel = new SendNotificationModel();
175
        sendNotificationModel.setType("url");
34902 vikas 176
        sendNotificationModel.setUrl("https://smartdukaan.com/pages/home/notifications");
32253 amit.gupta 177
        sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
178
        sendNotificationModel.setMessageType(MessageType.notification);
179
        return sendNotificationModel;
180
    }
25822 amit.gupta 181
 
32253 amit.gupta 182
    public void pushNotification(int cid, List<Device> devices) {
29198 manish 183
 
32253 amit.gupta 184
        for (Device device : devices) {
185
            PushNotifications pn = new PushNotifications();
186
            pn.setNotificationCampaignid(cid);
187
            pn.setDeviceId(device.getId());
188
            pn.setUserId(device.getUser_id());
189
            pushNotificationRepository.persist(pn);
190
        }
29198 manish 191
 
32253 amit.gupta 192
    }
29198 manish 193
 
32253 amit.gupta 194
    @Override
34545 vikas.jang 195
    public void sendNotification(int fofoId, String campaignName, MessageType messageType, String title, String message, String url) throws ProfitMandiBusinessException {
32253 amit.gupta 196
        SendNotificationModel sendNotificationModel = this.getDefaultNotificationModel();
197
        sendNotificationModel.setCampaignName(campaignName);
198
        sendNotificationModel.setMessageType(messageType);
199
        sendNotificationModel.setTitle(title);
200
        sendNotificationModel.setMessage(message);
201
        int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
202
        sendNotificationModel.setUserIds(Arrays.asList(userId));
203
        sendNotificationModel.setMessageType(messageType);
204
        sendNotificationModel.setUrl(url);
205
        this.sendNotification(sendNotificationModel);
206
    }
29198 manish 207
 
32253 amit.gupta 208
    @Override
34545 vikas.jang 209
    public boolean sendWhatsappMessage(String message, String title, String mobile) throws Exception {
34204 tejus.loha 210
        boolean isSend=false;
34520 amit.gupta 211
        LOGGER.info("Is Prod - {}", isProd);
32874 amit.gupta 212
        if (isProd) {
34204 tejus.loha 213
            isSend=this.sendWhatsappMessage(WhatsappMessageType.TEXT, message, title, mobile, null, null);
32874 amit.gupta 214
        }
34204 tejus.loha 215
        return isSend;
32253 amit.gupta 216
    }
25822 amit.gupta 217
 
32253 amit.gupta 218
    @Override
34545 vikas.jang 219
    public boolean sendWhatsappMediaMessage(String message, String mobile, String mediaUrl, String fileName, WhatsappMessageType whatsappMessageType) throws Exception {
34204 tejus.loha 220
        boolean isSend=false;
33025 amit.gupta 221
        if (isProd) {
34204 tejus.loha 222
            isSend=this.sendWhatsappMessage(whatsappMessageType, message, null, mobile, mediaUrl, fileName);
32874 amit.gupta 223
        }
34204 tejus.loha 224
        return isSend;
32253 amit.gupta 225
    }
25822 amit.gupta 226
 
32253 amit.gupta 227
    @Override
228
    public void optIn(String phoneNumber) throws Exception {
229
        Map<String, String> requestheaders = new HashMap<>();
230
        requestheaders.put("Content-Type", "application/x-www-form-urlencoded");
231
        Map<String, String> requestParams = new HashMap<>();
232
        requestParams.put("userid", String.valueOf(2000215976));
233
        requestParams.put("password", "MFRd!BBL");
234
        requestParams.put("phone_number", phoneNumber);
235
        requestParams.put("auth_scheme", "plain");
236
        requestParams.put("v", "1.1");
237
        requestParams.put("format", "json");
28400 tejbeer 238
 
32253 amit.gupta 239
        requestParams.put("method", "OPT_IN");
25822 amit.gupta 240
 
32253 amit.gupta 241
        requestParams.put("channel", "WHATSAPP");
242
        String response = restClient.get("https://media.smsgupshup.com/GatewayAPI/rest", requestParams, requestheaders);
243
        LOGGER.info("response" + response);
244
    }
29927 amit.gupta 245
 
34204 tejus.loha 246
    private boolean sendWhatsappMessage(WhatsappMessageType whatsappMessageType, String message, String title, String mobile, String mediaUrl, String fileName)
32405 jai.hind 247
            throws Exception {
32260 amit.gupta 248
        String sendTo = null;
34204 tejus.loha 249
        boolean isSend=false;
32259 amit.gupta 250
        if (mobile.length() != 10) {
34204 tejus.loha 251
            return isSend;
32259 amit.gupta 252
        } else {
32260 amit.gupta 253
            sendTo = 91 + mobile;
32259 amit.gupta 254
        }
32253 amit.gupta 255
        Map<String, String> requestheaders = new HashMap<>();
256
        requestheaders.put("Content-Type", "application/x-www-form-urlencoded");
257
        Map<String, String> requestParams = new HashMap<>();
258
        requestParams.put("userid", String.valueOf(2000215976));
259
        requestParams.put("password", "MFRd!BBL");
32285 amit.gupta 260
        requestParams.put("send_to", sendTo);
32253 amit.gupta 261
        requestParams.put("v", "1.1");
262
        requestParams.put("format", "json");
263
        requestParams.put("auth_scheme", "plain");
32777 amit.gupta 264
        Optin optin = optinRepository.selectByMobile(mobile);
265
        if (optin == null) {
266
            this.optIn(sendTo);
267
            optin = new Optin();
268
            optin.setCreated(LocalDateTime.now());
269
            optin.setMobile(mobile);
270
            optinRepository.persist(optin);
271
        }
32253 amit.gupta 272
        if (mediaUrl == null) {
32415 amit.gupta 273
            requestParams.put("method", "SENDMESSAGE");
32854 amit.gupta 274
            requestParams.put("msg_type", whatsappMessageType.name());
32253 amit.gupta 275
            requestParams.put("msg", message);
34522 ranu 276
            requestParams.put("isTemplate", "true");
277
            requestParams.put("header", title);
32253 amit.gupta 278
        } else if (mediaUrl != null) {
32268 amit.gupta 279
            requestParams.put("method", "SENDMEDIAMESSAGE");
32854 amit.gupta 280
            requestParams.put("msg_type", whatsappMessageType.name());
32253 amit.gupta 281
            requestParams.put("caption", message);
282
            requestParams.put("media_url", mediaUrl);
283
            requestParams.put("filename", fileName);
32777 amit.gupta 284
        }
34545 vikas.jang 285
        String response = restClient.post("https://media.smsgupshup.com/GatewayAPI/rest", requestParams, requestheaders);
32777 amit.gupta 286
        LOGGER.info("response  - {}", response);
32403 tejbeer 287
 
32777 amit.gupta 288
        JSONObject jsonObject = new JSONObject(response);
32401 tejbeer 289
 
32777 amit.gupta 290
        JSONObject whatsappResponse = (JSONObject) jsonObject.get("response");
32874 amit.gupta 291
        if (whatsappResponse.getString("status").equals("error")) {
292
            LOGGER.error("Invalid Whatsapp message, Reason - {}", whatsappResponse.getString("details"));
34204 tejus.loha 293
            return isSend;
294
        }else{
295
            isSend=true;
32850 amit.gupta 296
        }
32777 amit.gupta 297
        String externalId = whatsappResponse.getString("id");
298
        String phone = whatsappResponse.getString("phone");
32403 tejbeer 299
 
32777 amit.gupta 300
        WhatsappMessage whatsappMessage = new WhatsappMessage();
301
        whatsappMessage.setCreatedTimestamp(LocalDateTime.now());
302
        whatsappMessage.setExternalId(externalId);
303
        whatsappMessage.setDestAddr(phone);
304
        whatsappMessageRepository.persist(whatsappMessage);
34204 tejus.loha 305
        return isSend;
32253 amit.gupta 306
    }
30025 amit.gupta 307
 
32405 jai.hind 308
    @Override
33415 amit.gupta 309
    public boolean shouldSendWhatsappMessage(String mobile) {
32405 jai.hind 310
        String destAddr = "91" + mobile;
33415 amit.gupta 311
        boolean shouldSend = true;
32508 amit.gupta 312
        List<WhatsappMessage> whatsappMessages = whatsappMessageRepository.selectByDestAddr(destAddr, LocalDate.now());
32405 jai.hind 313
        if (!whatsappMessages.isEmpty()) {
32508 amit.gupta 314
            long failedCount = whatsappMessages.stream().filter(x -> x.getFailed() != null && x.getFailed().equals("FAILED")).collect(Collectors.counting());
32405 jai.hind 315
            if (failedCount >= 2) {
33415 amit.gupta 316
                shouldSend = false;
32405 jai.hind 317
            }
318
        }
33415 amit.gupta 319
        return shouldSend;
32405 jai.hind 320
    }
33715 ranu 321
 
322
 
323
    @Override
324
    public void sendPaymentWhatsappMessage(String mobile, String message) throws Exception {
33968 ranu 325
        String sendTo = "91" + mobile;
326
//        String sendTo = "917082253510";
33715 ranu 327
 
328
        Map<String, String> requestHeaders = new HashMap<>();
329
        requestHeaders.put("Content-Type", "application/x-www-form-urlencoded");
330
        Map<String, String> requestParams = new HashMap<>();
331
        requestParams.put("userid", String.valueOf(2000215976));
332
        requestParams.put("password", "MFRd!BBL");
333
        requestParams.put("send_to", sendTo);
334
        requestParams.put("v", "1.1");
335
        requestParams.put("format", "json");
336
        requestParams.put("auth_scheme", "plain");
337
        requestParams.put("method", "SENDMESSAGE");
338
        requestParams.put("msg_type", "TEXT");
339
        requestParams.put("msg", message);
340
        requestParams.put("isTemplate", "true");
341
        requestParams.put("header", "Payment Link!");
342
 
343
        String response = restClient.post("https://media.smsgupshup.com/GatewayAPI/rest", requestParams, requestHeaders);
344
        LOGGER.info("response  - {}", response);
345
 
346
        JSONObject jsonObject = new JSONObject(response);
347
        JSONObject whatsappResponse = jsonObject.getJSONObject("response");
348
        if (whatsappResponse.getString("status").equals("error")) {
349
            LOGGER.error("Invalid Whatsapp message, Reason - {}", whatsappResponse.getString("details"));
350
            return;
351
        }
352
 
353
        String externalId = whatsappResponse.getString("id");
354
        String phone = whatsappResponse.getString("phone");
355
 
356
        WhatsappMessage whatsappMessage = new WhatsappMessage();
357
        whatsappMessage.setCreatedTimestamp(LocalDateTime.now());
358
        whatsappMessage.setExternalId(externalId);
359
        whatsappMessage.setDestAddr(phone);
360
        whatsappMessageRepository.persist(whatsappMessage);
361
    }
34545 vikas.jang 362
 
363
    private boolean sendWhatsAppMessageByMeta(WhatsappMessageType whatsappMessageType, String message, String title, String mobile, String mediaUrl, String fileName) throws Exception {
364
 
365
        mobile = this.optInUsersByMobiles(mobile);
366
 
367
        String token = "###############";
368
        String phoneNumberId = "000000000000000000";
369
        String url = "https://graph.facebook.com/v22.0/" + phoneNumberId + "/messages";
370
 
371
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
372
        conn.setRequestMethod("POST");
373
        conn.setRequestProperty("Authorization", "Bearer " + token);
374
        conn.setRequestProperty("Content-Type", "application/json");
375
        conn.setDoOutput(true);
376
 
377
        // Construct the payload
378
        JSONObject payload = new JSONObject();
379
        payload.put("messaging_product", "whatsapp");
380
        payload.put("to", "918529003611");
381
 
382
        if (mediaUrl != null) {
383
            JSONObject image = new JSONObject();
384
            image.put("link", mediaUrl);
385
            if (fileName != null) image.put("caption", message);
386
            payload.put("type", "image");
387
            payload.put("image", image);
388
        } else {
389
            payload.put("type", "template");
390
            JSONObject template = new JSONObject();
391
            template.put("name", "bid_live");
392
            JSONObject language = new JSONObject();
393
            language.put("code", "en_US");
394
            template.put("language", language);
395
            JSONArray components = new JSONArray();
396
            JSONObject body = new JSONObject();
397
            body.put("type", "body");
398
 
399
            JSONArray parameters = new JSONArray();
400
            parameters.put(new JSONObject().put("type", "text").put("text", "*Oppo Reno 10 Pro 5G (12GB 256GB) Silvery Grey* at 54.55% Off"));
401
            parameters.put(new JSONObject().put("type", "text").put("text", "44000.0"));
402
            parameters.put(new JSONObject().put("type", "text").put("text", "20000.0"));
403
            parameters.put(new JSONObject().put("type", "text").put("text", "05/05/2025 06:00PM"));
404
            body.put("parameters", parameters);
405
            components.put(body);
406
 
407
            template.put("components", components);
408
            payload.put("template", template);
409
        }
410
        LOGGER.info("Final WhatsApp payload: \n{}", payload.toString(2));
411
        try (OutputStream os = conn.getOutputStream()) {
412
            os.write(payload.toString().getBytes(StandardCharsets.UTF_8));
413
        }
414
 
415
        int status = conn.getResponseCode();
416
        String response = new BufferedReader(new InputStreamReader(status >= 400 ? conn.getErrorStream() : conn.getInputStream())).lines().collect(Collectors.joining("\n"));
417
 
418
        LOGGER.info("WhatsApp API response: {}", response);
419
 
420
        if (status != 200 && status != 201) {
421
            LOGGER.error("Failed to send WhatsApp message. Status: {}, Response: {}", status, response);
422
            return false;
423
        }
424
 
425
        JSONObject jsonResponse = new JSONObject(response);
426
        JSONArray messages = jsonResponse.optJSONArray("messages");
427
        String externalId = null;
428
 
429
        if (messages != null && messages.length() > 0) {
430
            externalId = messages.getJSONObject(0).optString("id");
431
            WhatsappMessage whatsappMessage = new WhatsappMessage();
432
            whatsappMessage.setCreatedTimestamp(LocalDateTime.now());
433
            whatsappMessage.setExternalId(externalId);
434
            whatsappMessage.setDestAddr(mobile);
435
            whatsappMessageRepository.persist(whatsappMessage);
436
        }
437
 
438
        return externalId != null;
439
    }
440
 
441
    private String optInUsersByMobiles(String mobiles) throws Exception {
442
        List<String> savedMobiles = new ArrayList<>();
443
        if (mobiles == null || mobiles.isEmpty()) return String.join(",",savedMobiles);
444
        String[] mobileNumbers = mobiles.split(",");
445
        for (String mobile : mobileNumbers) {
446
            mobile = mobile.trim();
447
            if (mobile.isEmpty()) continue;
448
            Optin optin = optinRepository.selectByMobile(mobile);
449
            if (optin == null) {
450
                this.optIn(mobile);
451
                optin = new Optin();
452
                optin.setCreated(LocalDateTime.now());
453
                optin.setMobile(mobile);
454
                optinRepository.persist(optin);
455
            }
456
            savedMobiles.add("91"+mobile);
457
        }
458
        return String.join(",",savedMobiles);
459
    }
25822 amit.gupta 460
}