Subversion Repositories SmartDukaan

Rev

Rev 34204 | Rev 34522 | 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.stereotype.Component;
25822 amit.gupta 27
 
32508 amit.gupta 28
import java.time.LocalDate;
32405 jai.hind 29
import java.time.LocalDateTime;
30
import java.util.*;
31
import java.util.stream.Collectors;
32
 
25835 amit.gupta 33
@Component
25822 amit.gupta 34
public class NotificationServiceImpl implements NotificationService {
35
 
32253 amit.gupta 36
    private static final Logger LOGGER = LogManager.getLogger(NotificationService.class);
37
    @Autowired
38
    UserCampaignRepository userCampaignRepository;
39
    @Autowired
40
    UserRepository dtrUserRepository;
41
    @Autowired
42
    UserAccountRepository userAccountRepository;
43
    @Autowired
44
    NotificationCampaignRepository notificationCampaignRepository;
45
    @Autowired
46
    DeviceRepository deviceRepository;
47
    @Autowired
48
    FofoStoreRepository fofoStoreRepository;
49
    @Autowired
50
    CsService csService;
51
    @Autowired
52
    OptinRepository optinRepository;
53
    @Autowired
54
    RetailerService retailerService;
55
    @Autowired
56
    PushNotificationRepository pushNotificationRepository;
57
    @Autowired
58
    private Gson gson;
59
    @Autowired
60
    private RestClient restClient;
34520 amit.gupta 61
    //@Value("${prod}")
62
    private boolean isProd=true;
25822 amit.gupta 63
 
32405 jai.hind 64
    @Autowired
32417 amit.gupta 65
    private WhatsappMessageRepository whatsappMessageRepository;
32405 jai.hind 66
 
67
    @Autowired
68
    private WhatsappMessageService whatsappMessageService;
69
 
32253 amit.gupta 70
    @Override
71
    public void sendNotification(SendNotificationModel sendNotificationModel) throws ProfitMandiBusinessException {
29927 amit.gupta 72
 
32253 amit.gupta 73
        SimpleCampaignParams scp = new SimpleCampaignParams();
74
        scp.setMessage(sendNotificationModel.getMessage());
75
        scp.setTitle(sendNotificationModel.getTitle());
76
        scp.setImageUrl(sendNotificationModel.getImageUrl());
77
        scp.setType(sendNotificationModel.getType());
78
        scp.setUrl(sendNotificationModel.getUrl());
79
        scp.setShowImage(sendNotificationModel.getShowImage());
80
        scp.setExpireTimestamp(sendNotificationModel.getExpiresat());
81
        SimpleCampaign sc = new SimpleCampaign(scp);
82
        sc.setSimpleCampaignParams(scp);
30025 amit.gupta 83
 
32253 amit.gupta 84
        NotificationCampaign nc = new NotificationCampaign();
85
        nc.setName(sendNotificationModel.getCampaignName());
86
        nc.setImplementationType("SimpleCampaign");
87
        nc.setImplementationParams(gson.toJson(scp));
88
        nc.setMessageType(sendNotificationModel.getMessageType());
89
        nc.setDocumentId(sendNotificationModel.getDocumentId());
90
        nc.setCreatedTimestamp(LocalDateTime.now());
91
        notificationCampaignRepository.persist(nc);
25822 amit.gupta 92
 
32253 amit.gupta 93
        Set<Integer> userIds = new HashSet<>();
94
        if (sendNotificationModel.getUserIds() != null && sendNotificationModel.getUserIds().size() > 0) {
95
            userIds.addAll(sendNotificationModel.getUserIds());
96
        }
29198 manish 97
 
32253 amit.gupta 98
        if (sendNotificationModel.getStateIds() != null && sendNotificationModel.getStateIds().size() > 0) {
33025 amit.gupta 99
            List<Integer> fofoIds = fofoStoreRepository.selectByWarehouseIds(sendNotificationModel.getStateIds()).stream()
100
                    .map(x -> x.getId()).collect(Collectors.toList());
34204 tejus.loha 101
            if (fofoIds.size() > 0) {
33025 amit.gupta 102
                userIds.addAll(userAccountRepository.selectUserIdsByRetailerIds(fofoIds));
103
            }
104
 
32253 amit.gupta 105
        }
29927 amit.gupta 106
 
34204 tejus.loha 107
        if (userIds.size() > 0) {
33025 amit.gupta 108
            for (Integer userId : userIds) {
109
                UserCampaign uc = new UserCampaign();
110
                uc.setCampaignId(nc.getId());
111
                uc.setUserId(userId);
112
                uc.setPushTimestamp(LocalDateTime.now());
113
                userCampaignRepository.persist(uc);
114
            }
115
            List<Device> devices = deviceRepository.selectByUserIdAndModifiedTimestamp(new ArrayList<>(userIds),
116
                    LocalDateTime.now().minusMonths(1), LocalDateTime.now());
117
            pushNotification(nc.getId(), devices);
118
        } else {
119
            LOGGER.info("Failed to send notification to any retailer with this model - {}", sendNotificationModel);
32253 amit.gupta 120
        }
25822 amit.gupta 121
 
32253 amit.gupta 122
    }
25822 amit.gupta 123
 
32253 amit.gupta 124
    @Override
125
    public void sendNotificationToAll(SendNotificationModel sendNotificationModel) throws ProfitMandiBusinessException {
126
        sendNotificationModel.setUserIds(fofoStoreRepository.selectAllDtrUserIds());
127
        Set<AuthUser> authUsers = new HashSet<>(
128
                csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_RBM));
129
        authUsers.addAll(csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_CATEGORY));
130
        authUsers.addAll(csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_SALES));
131
        List<String> emailIds = authUsers.stream().map(x -> x.getEmailId()).collect(Collectors.toList());
132
        emailIds.add("devkinandan.lal@smartdukaan.com");
133
        List<User> systemUsers = dtrUserRepository.selectAllByEmailIds(emailIds);
32405 jai.hind 134
        sendNotificationModel.getUserIds()
135
                .addAll(systemUsers.stream().map(x -> x.getId()).collect(Collectors.toList()));
32253 amit.gupta 136
        this.sendNotification(sendNotificationModel);
137
    }
25822 amit.gupta 138
 
32253 amit.gupta 139
    @Override
32405 jai.hind 140
    public void sendNotification(int fofoId, String campaignName, MessageType messageType, String title, String message)
141
            throws ProfitMandiBusinessException {
32253 amit.gupta 142
        SendNotificationModel sendNotificationModel = this.getDefaultNotificationModel();
143
        sendNotificationModel.setCampaignName(campaignName);
144
        sendNotificationModel.setMessageType(messageType);
145
        sendNotificationModel.setTitle(title);
146
        sendNotificationModel.setMessage(message);
147
        int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
148
        sendNotificationModel.setUserIds(Arrays.asList(userId));
149
        sendNotificationModel.setMessageType(MessageType.wallet);
150
        this.sendNotification(sendNotificationModel);
151
    }
25822 amit.gupta 152
 
32253 amit.gupta 153
    public SendNotificationModel getDefaultNotificationModel() {
154
        SendNotificationModel sendNotificationModel = new SendNotificationModel();
155
        sendNotificationModel.setType("url");
156
        sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
157
        sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
158
        sendNotificationModel.setMessageType(MessageType.notification);
159
        return sendNotificationModel;
160
    }
25822 amit.gupta 161
 
32253 amit.gupta 162
    public void pushNotification(int cid, List<Device> devices) {
29198 manish 163
 
32253 amit.gupta 164
        for (Device device : devices) {
165
            PushNotifications pn = new PushNotifications();
166
            pn.setNotificationCampaignid(cid);
167
            pn.setDeviceId(device.getId());
168
            pn.setUserId(device.getUser_id());
169
            pushNotificationRepository.persist(pn);
170
        }
29198 manish 171
 
32253 amit.gupta 172
    }
29198 manish 173
 
32253 amit.gupta 174
    @Override
32405 jai.hind 175
    public void sendNotification(int fofoId, String campaignName, MessageType messageType, String title, String message,
176
                                 String url) throws ProfitMandiBusinessException {
32253 amit.gupta 177
        SendNotificationModel sendNotificationModel = this.getDefaultNotificationModel();
178
        sendNotificationModel.setCampaignName(campaignName);
179
        sendNotificationModel.setMessageType(messageType);
180
        sendNotificationModel.setTitle(title);
181
        sendNotificationModel.setMessage(message);
182
        int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
183
        sendNotificationModel.setUserIds(Arrays.asList(userId));
184
        sendNotificationModel.setMessageType(messageType);
185
        sendNotificationModel.setUrl(url);
186
        this.sendNotification(sendNotificationModel);
187
    }
29198 manish 188
 
32253 amit.gupta 189
    @Override
34204 tejus.loha 190
    public boolean sendWhatsappMessage(String message, String title, String mobile)
32405 jai.hind 191
            throws Exception {
34204 tejus.loha 192
        boolean isSend=false;
34520 amit.gupta 193
        LOGGER.info("Is Prod - {}", isProd);
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);
34520 amit.gupta 259
            //requestParams.put("isTemplate", "true");
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
}