Subversion Repositories SmartDukaan

Rev

Rev 32854 | Rev 33025 | 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
        UserCampaign uc = null;
25822 amit.gupta 95
 
32253 amit.gupta 96
        Set<Integer> userIds = new HashSet<>();
97
        if (sendNotificationModel.getUserIds() != null && sendNotificationModel.getUserIds().size() > 0) {
98
            userIds.addAll(sendNotificationModel.getUserIds());
99
        }
29198 manish 100
 
32253 amit.gupta 101
        if (sendNotificationModel.getStateIds() != null && sendNotificationModel.getStateIds().size() > 0) {
32405 jai.hind 102
            userIds.addAll(fofoStoreRepository.selectByWarehouseIds(sendNotificationModel.getStateIds()).stream()
103
                    .map(x -> x.getId()).collect(Collectors.toList()));
32253 amit.gupta 104
        }
29927 amit.gupta 105
 
32253 amit.gupta 106
        LOGGER.info("userIds" + userIds);
29198 manish 107
 
32253 amit.gupta 108
        for (Integer userId : userIds) {
109
            uc = new UserCampaign();
110
            uc.setCampaignId(nc.getId());
111
            uc.setUserId(userId);
112
            uc.setPushTimestamp(LocalDateTime.now());
113
            userCampaignRepository.persist(uc);
114
        }
25822 amit.gupta 115
 
32405 jai.hind 116
        List<Device> devices = deviceRepository.selectByUserIdAndModifiedTimestamp(new ArrayList<>(userIds),
117
                LocalDateTime.now().minusMonths(3), LocalDateTime.now());
25822 amit.gupta 118
 
32253 amit.gupta 119
        LOGGER.info("devices" + devices);
120
        pushNotification(nc.getId(), devices);
30989 tejbeer 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
32405 jai.hind 190
    public void sendWhatsappMessage(String message, String title, String mobile)
191
            throws Exception {
32874 amit.gupta 192
        if (isProd) {
193
            this.sendWhatsappMessage(WhatsappMessageType.TEXT, message, title, mobile, null, null);
194
        }
32253 amit.gupta 195
    }
25822 amit.gupta 196
 
32253 amit.gupta 197
    @Override
32854 amit.gupta 198
    public void sendWhatsappMediaMessage(String message, String mobile, String mediaUrl, String fileName, WhatsappMessageType whatsappMessageType)
32405 jai.hind 199
            throws Exception {
32874 amit.gupta 200
        if(isProd) {
201
            this.sendWhatsappMessage(whatsappMessageType, message, null, mobile, mediaUrl, fileName);
202
        }
32508 amit.gupta 203
 
32253 amit.gupta 204
    }
25822 amit.gupta 205
 
32253 amit.gupta 206
    @Override
207
    public void optIn(String phoneNumber) throws Exception {
208
        Map<String, String> requestheaders = new HashMap<>();
209
        requestheaders.put("Content-Type", "application/x-www-form-urlencoded");
210
        Map<String, String> requestParams = new HashMap<>();
211
        requestParams.put("userid", String.valueOf(2000215976));
212
        requestParams.put("password", "MFRd!BBL");
213
        requestParams.put("phone_number", phoneNumber);
214
        requestParams.put("auth_scheme", "plain");
215
        requestParams.put("v", "1.1");
216
        requestParams.put("format", "json");
28400 tejbeer 217
 
32253 amit.gupta 218
        requestParams.put("method", "OPT_IN");
25822 amit.gupta 219
 
32253 amit.gupta 220
        requestParams.put("channel", "WHATSAPP");
221
        String response = restClient.get("https://media.smsgupshup.com/GatewayAPI/rest", requestParams, requestheaders);
222
        LOGGER.info("response" + response);
223
    }
29927 amit.gupta 224
 
32854 amit.gupta 225
    private void sendWhatsappMessage(WhatsappMessageType whatsappMessageType, String message, String title, String mobile, String mediaUrl, String fileName)
32405 jai.hind 226
            throws Exception {
32260 amit.gupta 227
        String sendTo = null;
32259 amit.gupta 228
        if (mobile.length() != 10) {
229
            return;
230
        } else {
32260 amit.gupta 231
            sendTo = 91 + mobile;
32259 amit.gupta 232
        }
32253 amit.gupta 233
        Map<String, String> requestheaders = new HashMap<>();
234
        requestheaders.put("Content-Type", "application/x-www-form-urlencoded");
235
        Map<String, String> requestParams = new HashMap<>();
236
        requestParams.put("userid", String.valueOf(2000215976));
237
        requestParams.put("password", "MFRd!BBL");
32285 amit.gupta 238
        requestParams.put("send_to", sendTo);
32253 amit.gupta 239
        requestParams.put("v", "1.1");
240
        requestParams.put("format", "json");
241
        requestParams.put("auth_scheme", "plain");
32777 amit.gupta 242
        Optin optin = optinRepository.selectByMobile(mobile);
243
        if (optin == null) {
244
            this.optIn(sendTo);
245
            optin = new Optin();
246
            optin.setCreated(LocalDateTime.now());
247
            optin.setMobile(mobile);
248
            optinRepository.persist(optin);
249
        }
32253 amit.gupta 250
        if (mediaUrl == null) {
32415 amit.gupta 251
            requestParams.put("method", "SENDMESSAGE");
32854 amit.gupta 252
            requestParams.put("msg_type", whatsappMessageType.name());
32253 amit.gupta 253
            requestParams.put("msg", message);
254
            requestParams.put("isTemplate", "true");
32777 amit.gupta 255
            requestParams.put("header", title);
32253 amit.gupta 256
        } else if (mediaUrl != null) {
32268 amit.gupta 257
            requestParams.put("method", "SENDMEDIAMESSAGE");
32854 amit.gupta 258
            requestParams.put("msg_type", whatsappMessageType.name());
32253 amit.gupta 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);
32777 amit.gupta 263
        }
264
        String response =
265
                restClient.post("https://media.smsgupshup.com/GatewayAPI/rest",
266
                        requestParams,
267
                        requestheaders);
268
        LOGGER.info("response  - {}", response);
32403 tejbeer 269
 
32777 amit.gupta 270
        JSONObject jsonObject = new JSONObject(response);
32401 tejbeer 271
 
32777 amit.gupta 272
        JSONObject whatsappResponse = (JSONObject) jsonObject.get("response");
32874 amit.gupta 273
        if (whatsappResponse.getString("status").equals("error")) {
274
            LOGGER.error("Invalid Whatsapp message, Reason - {}", whatsappResponse.getString("details"));
32850 amit.gupta 275
            return;
276
        }
32777 amit.gupta 277
        String externalId = whatsappResponse.getString("id");
278
        String phone = whatsappResponse.getString("phone");
32403 tejbeer 279
 
32777 amit.gupta 280
        WhatsappMessage whatsappMessage = new WhatsappMessage();
281
        whatsappMessage.setCreatedTimestamp(LocalDateTime.now());
282
        whatsappMessage.setExternalId(externalId);
283
        whatsappMessage.setDestAddr(phone);
284
        whatsappMessageRepository.persist(whatsappMessage);
32253 amit.gupta 285
    }
30025 amit.gupta 286
 
32405 jai.hind 287
    @Override
288
    public boolean isWhatMessageSend(String mobile) {
289
        String destAddr = "91" + mobile;
290
        boolean isSent = true;
32508 amit.gupta 291
        List<WhatsappMessage> whatsappMessages = whatsappMessageRepository.selectByDestAddr(destAddr, LocalDate.now());
32405 jai.hind 292
        if (!whatsappMessages.isEmpty()) {
32508 amit.gupta 293
            long failedCount = whatsappMessages.stream().filter(x -> x.getFailed() != null && x.getFailed().equals("FAILED")).collect(Collectors.counting());
32405 jai.hind 294
            if (failedCount >= 2) {
295
                isSent = false;
296
            }
297
        }
298
        return isSent;
299
    }
25822 amit.gupta 300
}