Subversion Repositories SmartDukaan

Rev

Rev 33968 | Rev 34520 | 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;
24
import org.json.JSONObject;
25
import org.springframework.beans.factory.annotation.Autowired;
26
import org.springframework.beans.factory.annotation.Value;
27
import org.springframework.stereotype.Component;
25822 amit.gupta 28
 
32508 amit.gupta 29
import java.time.LocalDate;
32405 jai.hind 30
import java.time.LocalDateTime;
31
import java.util.*;
32
import java.util.stream.Collectors;
33
 
25835 amit.gupta 34
@Component
25822 amit.gupta 35
public class NotificationServiceImpl implements NotificationService {
36
 
32253 amit.gupta 37
    private static final Logger LOGGER = LogManager.getLogger(NotificationService.class);
38
    @Autowired
39
    UserCampaignRepository userCampaignRepository;
40
    @Autowired
41
    UserRepository dtrUserRepository;
42
    @Autowired
43
    UserAccountRepository userAccountRepository;
44
    @Autowired
45
    NotificationCampaignRepository notificationCampaignRepository;
46
    @Autowired
47
    DeviceRepository deviceRepository;
48
    @Autowired
49
    FofoStoreRepository fofoStoreRepository;
50
    @Autowired
51
    CsService csService;
52
    @Autowired
53
    OptinRepository optinRepository;
54
    @Autowired
55
    RetailerService retailerService;
56
    @Autowired
57
    PushNotificationRepository pushNotificationRepository;
58
    @Autowired
59
    private Gson gson;
60
    @Autowired
61
    private RestClient restClient;
62
    @Value("${prod}")
63
    private boolean isProd;
25822 amit.gupta 64
 
32405 jai.hind 65
    @Autowired
32417 amit.gupta 66
    private WhatsappMessageRepository whatsappMessageRepository;
32405 jai.hind 67
 
68
    @Autowired
69
    private WhatsappMessageService whatsappMessageService;
70
 
32253 amit.gupta 71
    @Override
72
    public void sendNotification(SendNotificationModel sendNotificationModel) throws ProfitMandiBusinessException {
29927 amit.gupta 73
 
32253 amit.gupta 74
        SimpleCampaignParams scp = new SimpleCampaignParams();
75
        scp.setMessage(sendNotificationModel.getMessage());
76
        scp.setTitle(sendNotificationModel.getTitle());
77
        scp.setImageUrl(sendNotificationModel.getImageUrl());
78
        scp.setType(sendNotificationModel.getType());
79
        scp.setUrl(sendNotificationModel.getUrl());
80
        scp.setShowImage(sendNotificationModel.getShowImage());
81
        scp.setExpireTimestamp(sendNotificationModel.getExpiresat());
82
        SimpleCampaign sc = new SimpleCampaign(scp);
83
        sc.setSimpleCampaignParams(scp);
30025 amit.gupta 84
 
32253 amit.gupta 85
        NotificationCampaign nc = new NotificationCampaign();
86
        nc.setName(sendNotificationModel.getCampaignName());
87
        nc.setImplementationType("SimpleCampaign");
88
        nc.setImplementationParams(gson.toJson(scp));
89
        nc.setMessageType(sendNotificationModel.getMessageType());
90
        nc.setDocumentId(sendNotificationModel.getDocumentId());
91
        nc.setCreatedTimestamp(LocalDateTime.now());
92
        notificationCampaignRepository.persist(nc);
25822 amit.gupta 93
 
32253 amit.gupta 94
        Set<Integer> userIds = new HashSet<>();
95
        if (sendNotificationModel.getUserIds() != null && sendNotificationModel.getUserIds().size() > 0) {
96
            userIds.addAll(sendNotificationModel.getUserIds());
97
        }
29198 manish 98
 
32253 amit.gupta 99
        if (sendNotificationModel.getStateIds() != null && sendNotificationModel.getStateIds().size() > 0) {
33025 amit.gupta 100
            List<Integer> fofoIds = fofoStoreRepository.selectByWarehouseIds(sendNotificationModel.getStateIds()).stream()
101
                    .map(x -> x.getId()).collect(Collectors.toList());
34204 tejus.loha 102
            if (fofoIds.size() > 0) {
33025 amit.gupta 103
                userIds.addAll(userAccountRepository.selectUserIdsByRetailerIds(fofoIds));
104
            }
105
 
32253 amit.gupta 106
        }
29927 amit.gupta 107
 
34204 tejus.loha 108
        if (userIds.size() > 0) {
33025 amit.gupta 109
            for (Integer userId : userIds) {
110
                UserCampaign uc = new UserCampaign();
111
                uc.setCampaignId(nc.getId());
112
                uc.setUserId(userId);
113
                uc.setPushTimestamp(LocalDateTime.now());
114
                userCampaignRepository.persist(uc);
115
            }
116
            List<Device> devices = deviceRepository.selectByUserIdAndModifiedTimestamp(new ArrayList<>(userIds),
117
                    LocalDateTime.now().minusMonths(1), LocalDateTime.now());
118
            pushNotification(nc.getId(), devices);
119
        } else {
120
            LOGGER.info("Failed to send notification to any retailer with this model - {}", sendNotificationModel);
32253 amit.gupta 121
        }
25822 amit.gupta 122
 
32253 amit.gupta 123
    }
25822 amit.gupta 124
 
32253 amit.gupta 125
    @Override
126
    public void sendNotificationToAll(SendNotificationModel sendNotificationModel) throws ProfitMandiBusinessException {
127
        sendNotificationModel.setUserIds(fofoStoreRepository.selectAllDtrUserIds());
128
        Set<AuthUser> authUsers = new HashSet<>(
129
                csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_RBM));
130
        authUsers.addAll(csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_CATEGORY));
131
        authUsers.addAll(csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_SALES));
132
        List<String> emailIds = authUsers.stream().map(x -> x.getEmailId()).collect(Collectors.toList());
133
        emailIds.add("devkinandan.lal@smartdukaan.com");
134
        List<User> systemUsers = dtrUserRepository.selectAllByEmailIds(emailIds);
32405 jai.hind 135
        sendNotificationModel.getUserIds()
136
                .addAll(systemUsers.stream().map(x -> x.getId()).collect(Collectors.toList()));
32253 amit.gupta 137
        this.sendNotification(sendNotificationModel);
138
    }
25822 amit.gupta 139
 
32253 amit.gupta 140
    @Override
32405 jai.hind 141
    public void sendNotification(int fofoId, String campaignName, MessageType messageType, String title, String message)
142
            throws ProfitMandiBusinessException {
32253 amit.gupta 143
        SendNotificationModel sendNotificationModel = this.getDefaultNotificationModel();
144
        sendNotificationModel.setCampaignName(campaignName);
145
        sendNotificationModel.setMessageType(messageType);
146
        sendNotificationModel.setTitle(title);
147
        sendNotificationModel.setMessage(message);
148
        int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
149
        sendNotificationModel.setUserIds(Arrays.asList(userId));
150
        sendNotificationModel.setMessageType(MessageType.wallet);
151
        this.sendNotification(sendNotificationModel);
152
    }
25822 amit.gupta 153
 
32253 amit.gupta 154
    public SendNotificationModel getDefaultNotificationModel() {
155
        SendNotificationModel sendNotificationModel = new SendNotificationModel();
156
        sendNotificationModel.setType("url");
157
        sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
158
        sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
159
        sendNotificationModel.setMessageType(MessageType.notification);
160
        return sendNotificationModel;
161
    }
25822 amit.gupta 162
 
32253 amit.gupta 163
    public void pushNotification(int cid, List<Device> devices) {
29198 manish 164
 
32253 amit.gupta 165
        for (Device device : devices) {
166
            PushNotifications pn = new PushNotifications();
167
            pn.setNotificationCampaignid(cid);
168
            pn.setDeviceId(device.getId());
169
            pn.setUserId(device.getUser_id());
170
            pushNotificationRepository.persist(pn);
171
        }
29198 manish 172
 
32253 amit.gupta 173
    }
29198 manish 174
 
32253 amit.gupta 175
    @Override
32405 jai.hind 176
    public void sendNotification(int fofoId, String campaignName, MessageType messageType, String title, String message,
177
                                 String url) throws ProfitMandiBusinessException {
32253 amit.gupta 178
        SendNotificationModel sendNotificationModel = this.getDefaultNotificationModel();
179
        sendNotificationModel.setCampaignName(campaignName);
180
        sendNotificationModel.setMessageType(messageType);
181
        sendNotificationModel.setTitle(title);
182
        sendNotificationModel.setMessage(message);
183
        int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
184
        sendNotificationModel.setUserIds(Arrays.asList(userId));
185
        sendNotificationModel.setMessageType(messageType);
186
        sendNotificationModel.setUrl(url);
187
        this.sendNotification(sendNotificationModel);
188
    }
29198 manish 189
 
32253 amit.gupta 190
    @Override
34204 tejus.loha 191
    public boolean sendWhatsappMessage(String message, String title, String mobile)
32405 jai.hind 192
            throws Exception {
34204 tejus.loha 193
        boolean isSend=false;
32874 amit.gupta 194
        if (isProd) {
34204 tejus.loha 195
            isSend=this.sendWhatsappMessage(WhatsappMessageType.TEXT, message, title, mobile, null, null);
32874 amit.gupta 196
        }
34204 tejus.loha 197
        return isSend;
32253 amit.gupta 198
    }
25822 amit.gupta 199
 
32253 amit.gupta 200
    @Override
34204 tejus.loha 201
    public boolean sendWhatsappMediaMessage(String message, String mobile, String mediaUrl, String fileName, WhatsappMessageType whatsappMessageType)
32405 jai.hind 202
            throws Exception {
34204 tejus.loha 203
        boolean isSend=false;
33025 amit.gupta 204
        if (isProd) {
34204 tejus.loha 205
            isSend=this.sendWhatsappMessage(whatsappMessageType, message, null, mobile, mediaUrl, fileName);
32874 amit.gupta 206
        }
34204 tejus.loha 207
        return isSend;
32253 amit.gupta 208
    }
25822 amit.gupta 209
 
32253 amit.gupta 210
    @Override
211
    public void optIn(String phoneNumber) throws Exception {
212
        Map<String, String> requestheaders = new HashMap<>();
213
        requestheaders.put("Content-Type", "application/x-www-form-urlencoded");
214
        Map<String, String> requestParams = new HashMap<>();
215
        requestParams.put("userid", String.valueOf(2000215976));
216
        requestParams.put("password", "MFRd!BBL");
217
        requestParams.put("phone_number", phoneNumber);
218
        requestParams.put("auth_scheme", "plain");
219
        requestParams.put("v", "1.1");
220
        requestParams.put("format", "json");
28400 tejbeer 221
 
32253 amit.gupta 222
        requestParams.put("method", "OPT_IN");
25822 amit.gupta 223
 
32253 amit.gupta 224
        requestParams.put("channel", "WHATSAPP");
225
        String response = restClient.get("https://media.smsgupshup.com/GatewayAPI/rest", requestParams, requestheaders);
226
        LOGGER.info("response" + response);
227
    }
29927 amit.gupta 228
 
34204 tejus.loha 229
    private boolean sendWhatsappMessage(WhatsappMessageType whatsappMessageType, String message, String title, String mobile, String mediaUrl, String fileName)
32405 jai.hind 230
            throws Exception {
32260 amit.gupta 231
        String sendTo = null;
34204 tejus.loha 232
        boolean isSend=false;
32259 amit.gupta 233
        if (mobile.length() != 10) {
34204 tejus.loha 234
            return isSend;
32259 amit.gupta 235
        } else {
32260 amit.gupta 236
            sendTo = 91 + mobile;
32259 amit.gupta 237
        }
32253 amit.gupta 238
        Map<String, String> requestheaders = new HashMap<>();
239
        requestheaders.put("Content-Type", "application/x-www-form-urlencoded");
240
        Map<String, String> requestParams = new HashMap<>();
241
        requestParams.put("userid", String.valueOf(2000215976));
242
        requestParams.put("password", "MFRd!BBL");
32285 amit.gupta 243
        requestParams.put("send_to", sendTo);
32253 amit.gupta 244
        requestParams.put("v", "1.1");
245
        requestParams.put("format", "json");
246
        requestParams.put("auth_scheme", "plain");
32777 amit.gupta 247
        Optin optin = optinRepository.selectByMobile(mobile);
248
        if (optin == null) {
249
            this.optIn(sendTo);
250
            optin = new Optin();
251
            optin.setCreated(LocalDateTime.now());
252
            optin.setMobile(mobile);
253
            optinRepository.persist(optin);
254
        }
32253 amit.gupta 255
        if (mediaUrl == null) {
32415 amit.gupta 256
            requestParams.put("method", "SENDMESSAGE");
32854 amit.gupta 257
            requestParams.put("msg_type", whatsappMessageType.name());
32253 amit.gupta 258
            requestParams.put("msg", message);
259
            requestParams.put("isTemplate", "true");
32777 amit.gupta 260
            requestParams.put("header", title);
32253 amit.gupta 261
        } else if (mediaUrl != null) {
32268 amit.gupta 262
            requestParams.put("method", "SENDMEDIAMESSAGE");
32854 amit.gupta 263
            requestParams.put("msg_type", whatsappMessageType.name());
32253 amit.gupta 264
            requestParams.put("caption", message);
32268 amit.gupta 265
            //requestParams.put("msg", message);
32253 amit.gupta 266
            requestParams.put("media_url", mediaUrl);
267
            requestParams.put("filename", fileName);
32777 amit.gupta 268
        }
269
        String response =
270
                restClient.post("https://media.smsgupshup.com/GatewayAPI/rest",
271
                        requestParams,
272
                        requestheaders);
273
        LOGGER.info("response  - {}", response);
32403 tejbeer 274
 
32777 amit.gupta 275
        JSONObject jsonObject = new JSONObject(response);
32401 tejbeer 276
 
32777 amit.gupta 277
        JSONObject whatsappResponse = (JSONObject) jsonObject.get("response");
32874 amit.gupta 278
        if (whatsappResponse.getString("status").equals("error")) {
279
            LOGGER.error("Invalid Whatsapp message, Reason - {}", whatsappResponse.getString("details"));
34204 tejus.loha 280
            return isSend;
281
        }else{
282
            isSend=true;
32850 amit.gupta 283
        }
32777 amit.gupta 284
        String externalId = whatsappResponse.getString("id");
285
        String phone = whatsappResponse.getString("phone");
32403 tejbeer 286
 
32777 amit.gupta 287
        WhatsappMessage whatsappMessage = new WhatsappMessage();
288
        whatsappMessage.setCreatedTimestamp(LocalDateTime.now());
289
        whatsappMessage.setExternalId(externalId);
290
        whatsappMessage.setDestAddr(phone);
291
        whatsappMessageRepository.persist(whatsappMessage);
34204 tejus.loha 292
        return isSend;
32253 amit.gupta 293
    }
30025 amit.gupta 294
 
32405 jai.hind 295
    @Override
33415 amit.gupta 296
    public boolean shouldSendWhatsappMessage(String mobile) {
32405 jai.hind 297
        String destAddr = "91" + mobile;
33415 amit.gupta 298
        boolean shouldSend = true;
32508 amit.gupta 299
        List<WhatsappMessage> whatsappMessages = whatsappMessageRepository.selectByDestAddr(destAddr, LocalDate.now());
32405 jai.hind 300
        if (!whatsappMessages.isEmpty()) {
32508 amit.gupta 301
            long failedCount = whatsappMessages.stream().filter(x -> x.getFailed() != null && x.getFailed().equals("FAILED")).collect(Collectors.counting());
32405 jai.hind 302
            if (failedCount >= 2) {
33415 amit.gupta 303
                shouldSend = false;
32405 jai.hind 304
            }
305
        }
33415 amit.gupta 306
        return shouldSend;
32405 jai.hind 307
    }
33715 ranu 308
 
309
 
310
    @Override
311
    public void sendPaymentWhatsappMessage(String mobile, String message) throws Exception {
33968 ranu 312
        String sendTo = "91" + mobile;
313
//        String sendTo = "917082253510";
33715 ranu 314
 
315
        Map<String, String> requestHeaders = new HashMap<>();
316
        requestHeaders.put("Content-Type", "application/x-www-form-urlencoded");
317
        Map<String, String> requestParams = new HashMap<>();
318
        requestParams.put("userid", String.valueOf(2000215976));
319
        requestParams.put("password", "MFRd!BBL");
320
        requestParams.put("send_to", sendTo);
321
        requestParams.put("v", "1.1");
322
        requestParams.put("format", "json");
323
        requestParams.put("auth_scheme", "plain");
324
        requestParams.put("method", "SENDMESSAGE");
325
        requestParams.put("msg_type", "TEXT");
326
        requestParams.put("msg", message);
327
        requestParams.put("isTemplate", "true");
328
        requestParams.put("header", "Payment Link!");
329
 
330
        String response = restClient.post("https://media.smsgupshup.com/GatewayAPI/rest", requestParams, requestHeaders);
331
        LOGGER.info("response  - {}", response);
332
 
333
        JSONObject jsonObject = new JSONObject(response);
334
        JSONObject whatsappResponse = jsonObject.getJSONObject("response");
335
        if (whatsappResponse.getString("status").equals("error")) {
336
            LOGGER.error("Invalid Whatsapp message, Reason - {}", whatsappResponse.getString("details"));
337
            return;
338
        }
339
 
340
        String externalId = whatsappResponse.getString("id");
341
        String phone = whatsappResponse.getString("phone");
342
 
343
        WhatsappMessage whatsappMessage = new WhatsappMessage();
344
        whatsappMessage.setCreatedTimestamp(LocalDateTime.now());
345
        whatsappMessage.setExternalId(externalId);
346
        whatsappMessage.setDestAddr(phone);
347
        whatsappMessageRepository.persist(whatsappMessage);
348
    }
25822 amit.gupta 349
}