Subversion Repositories SmartDukaan

Rev

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