Subversion Repositories SmartDukaan

Rev

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