Subversion Repositories SmartDukaan

Rev

Rev 34902 | Rev 35207 | 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));
34903 ranu 139
        authUsers.addAll(csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_ABM));
32253 amit.gupta 140
        List<String> emailIds = authUsers.stream().map(x -> x.getEmailId()).collect(Collectors.toList());
141
        emailIds.add("devkinandan.lal@smartdukaan.com");
142
        List<User> systemUsers = dtrUserRepository.selectAllByEmailIds(emailIds);
32405 jai.hind 143
        sendNotificationModel.getUserIds()
144
                .addAll(systemUsers.stream().map(x -> x.getId()).collect(Collectors.toList()));
32253 amit.gupta 145
        this.sendNotification(sendNotificationModel);
146
    }
25822 amit.gupta 147
 
32253 amit.gupta 148
    @Override
34550 vikas.jang 149
    public void sendNotificationToSystemUsers(SendNotificationModel sendNotificationModel) throws ProfitMandiBusinessException {
150
        Set<AuthUser> authUsers = new HashSet<>(csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_RBM));
151
        authUsers.addAll(csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_CATEGORY));
152
        authUsers.addAll(csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_SALES));
34903 ranu 153
        authUsers.addAll(csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_ABM));
34550 vikas.jang 154
        List<String> emailIds = authUsers.stream().map(x -> x.getEmailId()).collect(Collectors.toList());
155
        emailIds.add("devkinandan.lal@smartdukaan.com");
156
        List<User> systemUsers = dtrUserRepository.selectAllByEmailIds(emailIds);
157
        sendNotificationModel.setUserIds(systemUsers.stream().map(x -> x.getId()).collect(Collectors.toList()));
158
        this.sendNotification(sendNotificationModel);
159
    }
160
 
161
    @Override
32405 jai.hind 162
    public void sendNotification(int fofoId, String campaignName, MessageType messageType, String title, String message)
163
            throws ProfitMandiBusinessException {
32253 amit.gupta 164
        SendNotificationModel sendNotificationModel = this.getDefaultNotificationModel();
165
        sendNotificationModel.setCampaignName(campaignName);
166
        sendNotificationModel.setMessageType(messageType);
167
        sendNotificationModel.setTitle(title);
168
        sendNotificationModel.setMessage(message);
169
        int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
170
        sendNotificationModel.setUserIds(Arrays.asList(userId));
171
        sendNotificationModel.setMessageType(MessageType.wallet);
172
        this.sendNotification(sendNotificationModel);
173
    }
25822 amit.gupta 174
 
32253 amit.gupta 175
    public SendNotificationModel getDefaultNotificationModel() {
176
        SendNotificationModel sendNotificationModel = new SendNotificationModel();
177
        sendNotificationModel.setType("url");
34902 vikas 178
        sendNotificationModel.setUrl("https://smartdukaan.com/pages/home/notifications");
32253 amit.gupta 179
        sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
180
        sendNotificationModel.setMessageType(MessageType.notification);
181
        return sendNotificationModel;
182
    }
25822 amit.gupta 183
 
32253 amit.gupta 184
    public void pushNotification(int cid, List<Device> devices) {
29198 manish 185
 
32253 amit.gupta 186
        for (Device device : devices) {
187
            PushNotifications pn = new PushNotifications();
188
            pn.setNotificationCampaignid(cid);
189
            pn.setDeviceId(device.getId());
190
            pn.setUserId(device.getUser_id());
191
            pushNotificationRepository.persist(pn);
192
        }
29198 manish 193
 
32253 amit.gupta 194
    }
29198 manish 195
 
32253 amit.gupta 196
    @Override
34545 vikas.jang 197
    public void sendNotification(int fofoId, String campaignName, MessageType messageType, String title, String message, String url) throws ProfitMandiBusinessException {
32253 amit.gupta 198
        SendNotificationModel sendNotificationModel = this.getDefaultNotificationModel();
199
        sendNotificationModel.setCampaignName(campaignName);
200
        sendNotificationModel.setMessageType(messageType);
201
        sendNotificationModel.setTitle(title);
202
        sendNotificationModel.setMessage(message);
203
        int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
204
        sendNotificationModel.setUserIds(Arrays.asList(userId));
205
        sendNotificationModel.setMessageType(messageType);
206
        sendNotificationModel.setUrl(url);
207
        this.sendNotification(sendNotificationModel);
208
    }
29198 manish 209
 
32253 amit.gupta 210
    @Override
34545 vikas.jang 211
    public boolean sendWhatsappMessage(String message, String title, String mobile) throws Exception {
34204 tejus.loha 212
        boolean isSend=false;
34520 amit.gupta 213
        LOGGER.info("Is Prod - {}", isProd);
32874 amit.gupta 214
        if (isProd) {
34204 tejus.loha 215
            isSend=this.sendWhatsappMessage(WhatsappMessageType.TEXT, message, title, mobile, null, null);
32874 amit.gupta 216
        }
34204 tejus.loha 217
        return isSend;
32253 amit.gupta 218
    }
25822 amit.gupta 219
 
32253 amit.gupta 220
    @Override
34545 vikas.jang 221
    public boolean sendWhatsappMediaMessage(String message, String mobile, String mediaUrl, String fileName, WhatsappMessageType whatsappMessageType) throws Exception {
34204 tejus.loha 222
        boolean isSend=false;
33025 amit.gupta 223
        if (isProd) {
34204 tejus.loha 224
            isSend=this.sendWhatsappMessage(whatsappMessageType, message, null, mobile, mediaUrl, fileName);
32874 amit.gupta 225
        }
34204 tejus.loha 226
        return isSend;
32253 amit.gupta 227
    }
25822 amit.gupta 228
 
32253 amit.gupta 229
    @Override
230
    public void optIn(String phoneNumber) throws Exception {
231
        Map<String, String> requestheaders = new HashMap<>();
232
        requestheaders.put("Content-Type", "application/x-www-form-urlencoded");
233
        Map<String, String> requestParams = new HashMap<>();
234
        requestParams.put("userid", String.valueOf(2000215976));
235
        requestParams.put("password", "MFRd!BBL");
236
        requestParams.put("phone_number", phoneNumber);
237
        requestParams.put("auth_scheme", "plain");
238
        requestParams.put("v", "1.1");
239
        requestParams.put("format", "json");
28400 tejbeer 240
 
32253 amit.gupta 241
        requestParams.put("method", "OPT_IN");
25822 amit.gupta 242
 
32253 amit.gupta 243
        requestParams.put("channel", "WHATSAPP");
244
        String response = restClient.get("https://media.smsgupshup.com/GatewayAPI/rest", requestParams, requestheaders);
245
        LOGGER.info("response" + response);
246
    }
29927 amit.gupta 247
 
34204 tejus.loha 248
    private boolean sendWhatsappMessage(WhatsappMessageType whatsappMessageType, String message, String title, String mobile, String mediaUrl, String fileName)
32405 jai.hind 249
            throws Exception {
32260 amit.gupta 250
        String sendTo = null;
34204 tejus.loha 251
        boolean isSend=false;
32259 amit.gupta 252
        if (mobile.length() != 10) {
34204 tejus.loha 253
            return isSend;
32259 amit.gupta 254
        } else {
32260 amit.gupta 255
            sendTo = 91 + mobile;
32259 amit.gupta 256
        }
32253 amit.gupta 257
        Map<String, String> requestheaders = new HashMap<>();
258
        requestheaders.put("Content-Type", "application/x-www-form-urlencoded");
259
        Map<String, String> requestParams = new HashMap<>();
260
        requestParams.put("userid", String.valueOf(2000215976));
261
        requestParams.put("password", "MFRd!BBL");
32285 amit.gupta 262
        requestParams.put("send_to", sendTo);
32253 amit.gupta 263
        requestParams.put("v", "1.1");
264
        requestParams.put("format", "json");
265
        requestParams.put("auth_scheme", "plain");
32777 amit.gupta 266
        Optin optin = optinRepository.selectByMobile(mobile);
267
        if (optin == null) {
268
            this.optIn(sendTo);
269
            optin = new Optin();
270
            optin.setCreated(LocalDateTime.now());
271
            optin.setMobile(mobile);
272
            optinRepository.persist(optin);
273
        }
32253 amit.gupta 274
        if (mediaUrl == null) {
32415 amit.gupta 275
            requestParams.put("method", "SENDMESSAGE");
32854 amit.gupta 276
            requestParams.put("msg_type", whatsappMessageType.name());
32253 amit.gupta 277
            requestParams.put("msg", message);
34522 ranu 278
            requestParams.put("isTemplate", "true");
279
            requestParams.put("header", title);
32253 amit.gupta 280
        } else if (mediaUrl != null) {
32268 amit.gupta 281
            requestParams.put("method", "SENDMEDIAMESSAGE");
32854 amit.gupta 282
            requestParams.put("msg_type", whatsappMessageType.name());
32253 amit.gupta 283
            requestParams.put("caption", message);
284
            requestParams.put("media_url", mediaUrl);
285
            requestParams.put("filename", fileName);
32777 amit.gupta 286
        }
34545 vikas.jang 287
        String response = restClient.post("https://media.smsgupshup.com/GatewayAPI/rest", requestParams, requestheaders);
32777 amit.gupta 288
        LOGGER.info("response  - {}", response);
32403 tejbeer 289
 
32777 amit.gupta 290
        JSONObject jsonObject = new JSONObject(response);
32401 tejbeer 291
 
32777 amit.gupta 292
        JSONObject whatsappResponse = (JSONObject) jsonObject.get("response");
32874 amit.gupta 293
        if (whatsappResponse.getString("status").equals("error")) {
294
            LOGGER.error("Invalid Whatsapp message, Reason - {}", whatsappResponse.getString("details"));
34204 tejus.loha 295
            return isSend;
296
        }else{
297
            isSend=true;
32850 amit.gupta 298
        }
32777 amit.gupta 299
        String externalId = whatsappResponse.getString("id");
300
        String phone = whatsappResponse.getString("phone");
32403 tejbeer 301
 
32777 amit.gupta 302
        WhatsappMessage whatsappMessage = new WhatsappMessage();
303
        whatsappMessage.setCreatedTimestamp(LocalDateTime.now());
304
        whatsappMessage.setExternalId(externalId);
305
        whatsappMessage.setDestAddr(phone);
306
        whatsappMessageRepository.persist(whatsappMessage);
34204 tejus.loha 307
        return isSend;
32253 amit.gupta 308
    }
30025 amit.gupta 309
 
32405 jai.hind 310
    @Override
33415 amit.gupta 311
    public boolean shouldSendWhatsappMessage(String mobile) {
32405 jai.hind 312
        String destAddr = "91" + mobile;
33415 amit.gupta 313
        boolean shouldSend = true;
32508 amit.gupta 314
        List<WhatsappMessage> whatsappMessages = whatsappMessageRepository.selectByDestAddr(destAddr, LocalDate.now());
32405 jai.hind 315
        if (!whatsappMessages.isEmpty()) {
32508 amit.gupta 316
            long failedCount = whatsappMessages.stream().filter(x -> x.getFailed() != null && x.getFailed().equals("FAILED")).collect(Collectors.counting());
32405 jai.hind 317
            if (failedCount >= 2) {
33415 amit.gupta 318
                shouldSend = false;
32405 jai.hind 319
            }
320
        }
33415 amit.gupta 321
        return shouldSend;
32405 jai.hind 322
    }
33715 ranu 323
 
324
 
325
    @Override
326
    public void sendPaymentWhatsappMessage(String mobile, String message) throws Exception {
33968 ranu 327
        String sendTo = "91" + mobile;
328
//        String sendTo = "917082253510";
33715 ranu 329
 
330
        Map<String, String> requestHeaders = new HashMap<>();
331
        requestHeaders.put("Content-Type", "application/x-www-form-urlencoded");
332
        Map<String, String> requestParams = new HashMap<>();
333
        requestParams.put("userid", String.valueOf(2000215976));
334
        requestParams.put("password", "MFRd!BBL");
335
        requestParams.put("send_to", sendTo);
336
        requestParams.put("v", "1.1");
337
        requestParams.put("format", "json");
338
        requestParams.put("auth_scheme", "plain");
339
        requestParams.put("method", "SENDMESSAGE");
340
        requestParams.put("msg_type", "TEXT");
341
        requestParams.put("msg", message);
342
        requestParams.put("isTemplate", "true");
343
        requestParams.put("header", "Payment Link!");
344
 
345
        String response = restClient.post("https://media.smsgupshup.com/GatewayAPI/rest", requestParams, requestHeaders);
346
        LOGGER.info("response  - {}", response);
347
 
348
        JSONObject jsonObject = new JSONObject(response);
349
        JSONObject whatsappResponse = jsonObject.getJSONObject("response");
350
        if (whatsappResponse.getString("status").equals("error")) {
351
            LOGGER.error("Invalid Whatsapp message, Reason - {}", whatsappResponse.getString("details"));
352
            return;
353
        }
354
 
355
        String externalId = whatsappResponse.getString("id");
356
        String phone = whatsappResponse.getString("phone");
357
 
358
        WhatsappMessage whatsappMessage = new WhatsappMessage();
359
        whatsappMessage.setCreatedTimestamp(LocalDateTime.now());
360
        whatsappMessage.setExternalId(externalId);
361
        whatsappMessage.setDestAddr(phone);
362
        whatsappMessageRepository.persist(whatsappMessage);
363
    }
34545 vikas.jang 364
 
365
    private boolean sendWhatsAppMessageByMeta(WhatsappMessageType whatsappMessageType, String message, String title, String mobile, String mediaUrl, String fileName) throws Exception {
366
 
367
        mobile = this.optInUsersByMobiles(mobile);
368
 
369
        String token = "###############";
370
        String phoneNumberId = "000000000000000000";
371
        String url = "https://graph.facebook.com/v22.0/" + phoneNumberId + "/messages";
372
 
373
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
374
        conn.setRequestMethod("POST");
375
        conn.setRequestProperty("Authorization", "Bearer " + token);
376
        conn.setRequestProperty("Content-Type", "application/json");
377
        conn.setDoOutput(true);
378
 
379
        // Construct the payload
380
        JSONObject payload = new JSONObject();
381
        payload.put("messaging_product", "whatsapp");
382
        payload.put("to", "918529003611");
383
 
384
        if (mediaUrl != null) {
385
            JSONObject image = new JSONObject();
386
            image.put("link", mediaUrl);
387
            if (fileName != null) image.put("caption", message);
388
            payload.put("type", "image");
389
            payload.put("image", image);
390
        } else {
391
            payload.put("type", "template");
392
            JSONObject template = new JSONObject();
393
            template.put("name", "bid_live");
394
            JSONObject language = new JSONObject();
395
            language.put("code", "en_US");
396
            template.put("language", language);
397
            JSONArray components = new JSONArray();
398
            JSONObject body = new JSONObject();
399
            body.put("type", "body");
400
 
401
            JSONArray parameters = new JSONArray();
402
            parameters.put(new JSONObject().put("type", "text").put("text", "*Oppo Reno 10 Pro 5G (12GB 256GB) Silvery Grey* at 54.55% Off"));
403
            parameters.put(new JSONObject().put("type", "text").put("text", "44000.0"));
404
            parameters.put(new JSONObject().put("type", "text").put("text", "20000.0"));
405
            parameters.put(new JSONObject().put("type", "text").put("text", "05/05/2025 06:00PM"));
406
            body.put("parameters", parameters);
407
            components.put(body);
408
 
409
            template.put("components", components);
410
            payload.put("template", template);
411
        }
412
        LOGGER.info("Final WhatsApp payload: \n{}", payload.toString(2));
413
        try (OutputStream os = conn.getOutputStream()) {
414
            os.write(payload.toString().getBytes(StandardCharsets.UTF_8));
415
        }
416
 
417
        int status = conn.getResponseCode();
418
        String response = new BufferedReader(new InputStreamReader(status >= 400 ? conn.getErrorStream() : conn.getInputStream())).lines().collect(Collectors.joining("\n"));
419
 
420
        LOGGER.info("WhatsApp API response: {}", response);
421
 
422
        if (status != 200 && status != 201) {
423
            LOGGER.error("Failed to send WhatsApp message. Status: {}, Response: {}", status, response);
424
            return false;
425
        }
426
 
427
        JSONObject jsonResponse = new JSONObject(response);
428
        JSONArray messages = jsonResponse.optJSONArray("messages");
429
        String externalId = null;
430
 
431
        if (messages != null && messages.length() > 0) {
432
            externalId = messages.getJSONObject(0).optString("id");
433
            WhatsappMessage whatsappMessage = new WhatsappMessage();
434
            whatsappMessage.setCreatedTimestamp(LocalDateTime.now());
435
            whatsappMessage.setExternalId(externalId);
436
            whatsappMessage.setDestAddr(mobile);
437
            whatsappMessageRepository.persist(whatsappMessage);
438
        }
439
 
440
        return externalId != null;
441
    }
442
 
443
    private String optInUsersByMobiles(String mobiles) throws Exception {
444
        List<String> savedMobiles = new ArrayList<>();
445
        if (mobiles == null || mobiles.isEmpty()) return String.join(",",savedMobiles);
446
        String[] mobileNumbers = mobiles.split(",");
447
        for (String mobile : mobileNumbers) {
448
            mobile = mobile.trim();
449
            if (mobile.isEmpty()) continue;
450
            Optin optin = optinRepository.selectByMobile(mobile);
451
            if (optin == null) {
452
                this.optIn(mobile);
453
                optin = new Optin();
454
                optin.setCreated(LocalDateTime.now());
455
                optin.setMobile(mobile);
456
                optinRepository.persist(optin);
457
            }
458
            savedMobiles.add("91"+mobile);
459
        }
460
        return String.join(",",savedMobiles);
461
    }
25822 amit.gupta 462
}