Subversion Repositories SmartDukaan

Rev

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