Subversion Repositories SmartDukaan

Rev

Rev 33415 | Rev 33968 | 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());
102
            if(fofoIds.size() > 0) {
103
                userIds.addAll(userAccountRepository.selectUserIdsByRetailerIds(fofoIds));
104
            }
105
 
32253 amit.gupta 106
        }
29927 amit.gupta 107
 
33025 amit.gupta 108
        if(userIds.size() > 0) {
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
32405 jai.hind 191
    public void sendWhatsappMessage(String message, String title, String mobile)
192
            throws Exception {
32874 amit.gupta 193
        if (isProd) {
194
            this.sendWhatsappMessage(WhatsappMessageType.TEXT, message, title, mobile, null, null);
195
        }
32253 amit.gupta 196
    }
25822 amit.gupta 197
 
32253 amit.gupta 198
    @Override
32854 amit.gupta 199
    public void sendWhatsappMediaMessage(String message, String mobile, String mediaUrl, String fileName, WhatsappMessageType whatsappMessageType)
32405 jai.hind 200
            throws Exception {
33025 amit.gupta 201
        if (isProd) {
32874 amit.gupta 202
            this.sendWhatsappMessage(whatsappMessageType, message, null, mobile, mediaUrl, fileName);
203
        }
32508 amit.gupta 204
 
32253 amit.gupta 205
    }
25822 amit.gupta 206
 
32253 amit.gupta 207
    @Override
208
    public void optIn(String phoneNumber) throws Exception {
209
        Map<String, String> requestheaders = new HashMap<>();
210
        requestheaders.put("Content-Type", "application/x-www-form-urlencoded");
211
        Map<String, String> requestParams = new HashMap<>();
212
        requestParams.put("userid", String.valueOf(2000215976));
213
        requestParams.put("password", "MFRd!BBL");
214
        requestParams.put("phone_number", phoneNumber);
215
        requestParams.put("auth_scheme", "plain");
216
        requestParams.put("v", "1.1");
217
        requestParams.put("format", "json");
28400 tejbeer 218
 
32253 amit.gupta 219
        requestParams.put("method", "OPT_IN");
25822 amit.gupta 220
 
32253 amit.gupta 221
        requestParams.put("channel", "WHATSAPP");
222
        String response = restClient.get("https://media.smsgupshup.com/GatewayAPI/rest", requestParams, requestheaders);
223
        LOGGER.info("response" + response);
224
    }
29927 amit.gupta 225
 
32854 amit.gupta 226
    private void sendWhatsappMessage(WhatsappMessageType whatsappMessageType, String message, String title, String mobile, String mediaUrl, String fileName)
32405 jai.hind 227
            throws Exception {
32260 amit.gupta 228
        String sendTo = null;
32259 amit.gupta 229
        if (mobile.length() != 10) {
230
            return;
231
        } else {
32260 amit.gupta 232
            sendTo = 91 + mobile;
32259 amit.gupta 233
        }
32253 amit.gupta 234
        Map<String, String> requestheaders = new HashMap<>();
235
        requestheaders.put("Content-Type", "application/x-www-form-urlencoded");
236
        Map<String, String> requestParams = new HashMap<>();
237
        requestParams.put("userid", String.valueOf(2000215976));
238
        requestParams.put("password", "MFRd!BBL");
32285 amit.gupta 239
        requestParams.put("send_to", sendTo);
32253 amit.gupta 240
        requestParams.put("v", "1.1");
241
        requestParams.put("format", "json");
242
        requestParams.put("auth_scheme", "plain");
32777 amit.gupta 243
        Optin optin = optinRepository.selectByMobile(mobile);
244
        if (optin == null) {
245
            this.optIn(sendTo);
246
            optin = new Optin();
247
            optin.setCreated(LocalDateTime.now());
248
            optin.setMobile(mobile);
249
            optinRepository.persist(optin);
250
        }
32253 amit.gupta 251
        if (mediaUrl == null) {
32415 amit.gupta 252
            requestParams.put("method", "SENDMESSAGE");
32854 amit.gupta 253
            requestParams.put("msg_type", whatsappMessageType.name());
32253 amit.gupta 254
            requestParams.put("msg", message);
255
            requestParams.put("isTemplate", "true");
32777 amit.gupta 256
            requestParams.put("header", title);
32253 amit.gupta 257
        } else if (mediaUrl != null) {
32268 amit.gupta 258
            requestParams.put("method", "SENDMEDIAMESSAGE");
32854 amit.gupta 259
            requestParams.put("msg_type", whatsappMessageType.name());
32253 amit.gupta 260
            requestParams.put("caption", message);
32268 amit.gupta 261
            //requestParams.put("msg", message);
32253 amit.gupta 262
            requestParams.put("media_url", mediaUrl);
263
            requestParams.put("filename", fileName);
32777 amit.gupta 264
        }
265
        String response =
266
                restClient.post("https://media.smsgupshup.com/GatewayAPI/rest",
267
                        requestParams,
268
                        requestheaders);
269
        LOGGER.info("response  - {}", response);
32403 tejbeer 270
 
32777 amit.gupta 271
        JSONObject jsonObject = new JSONObject(response);
32401 tejbeer 272
 
32777 amit.gupta 273
        JSONObject whatsappResponse = (JSONObject) jsonObject.get("response");
32874 amit.gupta 274
        if (whatsappResponse.getString("status").equals("error")) {
275
            LOGGER.error("Invalid Whatsapp message, Reason - {}", whatsappResponse.getString("details"));
32850 amit.gupta 276
            return;
277
        }
32777 amit.gupta 278
        String externalId = whatsappResponse.getString("id");
279
        String phone = whatsappResponse.getString("phone");
32403 tejbeer 280
 
32777 amit.gupta 281
        WhatsappMessage whatsappMessage = new WhatsappMessage();
282
        whatsappMessage.setCreatedTimestamp(LocalDateTime.now());
283
        whatsappMessage.setExternalId(externalId);
284
        whatsappMessage.setDestAddr(phone);
285
        whatsappMessageRepository.persist(whatsappMessage);
32253 amit.gupta 286
    }
30025 amit.gupta 287
 
32405 jai.hind 288
    @Override
33415 amit.gupta 289
    public boolean shouldSendWhatsappMessage(String mobile) {
32405 jai.hind 290
        String destAddr = "91" + mobile;
33415 amit.gupta 291
        boolean shouldSend = true;
32508 amit.gupta 292
        List<WhatsappMessage> whatsappMessages = whatsappMessageRepository.selectByDestAddr(destAddr, LocalDate.now());
32405 jai.hind 293
        if (!whatsappMessages.isEmpty()) {
32508 amit.gupta 294
            long failedCount = whatsappMessages.stream().filter(x -> x.getFailed() != null && x.getFailed().equals("FAILED")).collect(Collectors.counting());
32405 jai.hind 295
            if (failedCount >= 2) {
33415 amit.gupta 296
                shouldSend = false;
32405 jai.hind 297
            }
298
        }
33415 amit.gupta 299
        return shouldSend;
32405 jai.hind 300
    }
33715 ranu 301
 
302
 
303
    @Override
304
    public void sendPaymentWhatsappMessage(String mobile, String message) throws Exception {
305
        //String sendTo = "91" + mobile;
306
        String sendTo = "917082253510";
307
 
308
        Map<String, String> requestHeaders = new HashMap<>();
309
        requestHeaders.put("Content-Type", "application/x-www-form-urlencoded");
310
        Map<String, String> requestParams = new HashMap<>();
311
        requestParams.put("userid", String.valueOf(2000215976));
312
        requestParams.put("password", "MFRd!BBL");
313
        requestParams.put("send_to", sendTo);
314
        requestParams.put("v", "1.1");
315
        requestParams.put("format", "json");
316
        requestParams.put("auth_scheme", "plain");
317
        requestParams.put("method", "SENDMESSAGE");
318
        requestParams.put("msg_type", "TEXT");
319
        requestParams.put("msg", message);
320
        requestParams.put("isTemplate", "true");
321
        requestParams.put("header", "Payment Link!");
322
 
323
        String response = restClient.post("https://media.smsgupshup.com/GatewayAPI/rest", requestParams, requestHeaders);
324
        LOGGER.info("response  - {}", response);
325
 
326
        JSONObject jsonObject = new JSONObject(response);
327
        JSONObject whatsappResponse = jsonObject.getJSONObject("response");
328
        if (whatsappResponse.getString("status").equals("error")) {
329
            LOGGER.error("Invalid Whatsapp message, Reason - {}", whatsappResponse.getString("details"));
330
            return;
331
        }
332
 
333
        String externalId = whatsappResponse.getString("id");
334
        String phone = whatsappResponse.getString("phone");
335
 
336
        WhatsappMessage whatsappMessage = new WhatsappMessage();
337
        whatsappMessage.setCreatedTimestamp(LocalDateTime.now());
338
        whatsappMessage.setExternalId(externalId);
339
        whatsappMessage.setDestAddr(phone);
340
        whatsappMessageRepository.persist(whatsappMessage);
341
    }
25822 amit.gupta 342
}