Subversion Repositories SmartDukaan

Rev

Rev 32508 | Rev 32850 | 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
 
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;
61
    @Value("${prod}")
62
    private boolean isProd;
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
        UserCampaign uc = null;
25822 amit.gupta 94
 
32253 amit.gupta 95
        Set<Integer> userIds = new HashSet<>();
96
        if (sendNotificationModel.getUserIds() != null && sendNotificationModel.getUserIds().size() > 0) {
97
            userIds.addAll(sendNotificationModel.getUserIds());
98
        }
29198 manish 99
 
32253 amit.gupta 100
        if (sendNotificationModel.getStateIds() != null && sendNotificationModel.getStateIds().size() > 0) {
32405 jai.hind 101
            userIds.addAll(fofoStoreRepository.selectByWarehouseIds(sendNotificationModel.getStateIds()).stream()
102
                    .map(x -> x.getId()).collect(Collectors.toList()));
32253 amit.gupta 103
        }
29927 amit.gupta 104
 
32253 amit.gupta 105
        LOGGER.info("userIds" + userIds);
29198 manish 106
 
32253 amit.gupta 107
        for (Integer userId : userIds) {
108
            uc = new UserCampaign();
109
            uc.setCampaignId(nc.getId());
110
            uc.setUserId(userId);
111
            uc.setPushTimestamp(LocalDateTime.now());
112
            userCampaignRepository.persist(uc);
113
        }
25822 amit.gupta 114
 
32405 jai.hind 115
        List<Device> devices = deviceRepository.selectByUserIdAndModifiedTimestamp(new ArrayList<>(userIds),
116
                LocalDateTime.now().minusMonths(3), LocalDateTime.now());
25822 amit.gupta 117
 
32253 amit.gupta 118
        LOGGER.info("devices" + devices);
119
        pushNotification(nc.getId(), devices);
30989 tejbeer 120
 
32253 amit.gupta 121
    }
25822 amit.gupta 122
 
32253 amit.gupta 123
    @Override
124
    public void sendNotificationToAll(SendNotificationModel sendNotificationModel) throws ProfitMandiBusinessException {
125
        sendNotificationModel.setUserIds(fofoStoreRepository.selectAllDtrUserIds());
126
        Set<AuthUser> authUsers = new HashSet<>(
127
                csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_RBM));
128
        authUsers.addAll(csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_CATEGORY));
129
        authUsers.addAll(csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_SALES));
130
        List<String> emailIds = authUsers.stream().map(x -> x.getEmailId()).collect(Collectors.toList());
131
        emailIds.add("devkinandan.lal@smartdukaan.com");
132
        List<User> systemUsers = dtrUserRepository.selectAllByEmailIds(emailIds);
32405 jai.hind 133
        sendNotificationModel.getUserIds()
134
                .addAll(systemUsers.stream().map(x -> x.getId()).collect(Collectors.toList()));
32253 amit.gupta 135
        this.sendNotification(sendNotificationModel);
136
    }
25822 amit.gupta 137
 
32253 amit.gupta 138
    @Override
32405 jai.hind 139
    public void sendNotification(int fofoId, String campaignName, MessageType messageType, String title, String message)
140
            throws ProfitMandiBusinessException {
32253 amit.gupta 141
        SendNotificationModel sendNotificationModel = this.getDefaultNotificationModel();
142
        sendNotificationModel.setCampaignName(campaignName);
143
        sendNotificationModel.setMessageType(messageType);
144
        sendNotificationModel.setTitle(title);
145
        sendNotificationModel.setMessage(message);
146
        int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
147
        sendNotificationModel.setUserIds(Arrays.asList(userId));
148
        sendNotificationModel.setMessageType(MessageType.wallet);
149
        this.sendNotification(sendNotificationModel);
150
    }
25822 amit.gupta 151
 
32253 amit.gupta 152
    public SendNotificationModel getDefaultNotificationModel() {
153
        SendNotificationModel sendNotificationModel = new SendNotificationModel();
154
        sendNotificationModel.setType("url");
155
        sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
156
        sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
157
        sendNotificationModel.setMessageType(MessageType.notification);
158
        return sendNotificationModel;
159
    }
25822 amit.gupta 160
 
32253 amit.gupta 161
    public void pushNotification(int cid, List<Device> devices) {
29198 manish 162
 
32253 amit.gupta 163
        for (Device device : devices) {
164
            PushNotifications pn = new PushNotifications();
165
            pn.setNotificationCampaignid(cid);
166
            pn.setDeviceId(device.getId());
167
            pn.setUserId(device.getUser_id());
168
            pushNotificationRepository.persist(pn);
169
        }
29198 manish 170
 
32253 amit.gupta 171
    }
29198 manish 172
 
32253 amit.gupta 173
    @Override
32405 jai.hind 174
    public void sendNotification(int fofoId, String campaignName, MessageType messageType, String title, String message,
175
                                 String url) throws ProfitMandiBusinessException {
32253 amit.gupta 176
        SendNotificationModel sendNotificationModel = this.getDefaultNotificationModel();
177
        sendNotificationModel.setCampaignName(campaignName);
178
        sendNotificationModel.setMessageType(messageType);
179
        sendNotificationModel.setTitle(title);
180
        sendNotificationModel.setMessage(message);
181
        int userId = userAccountRepository.selectUserIdByRetailerId(fofoId);
182
        sendNotificationModel.setUserIds(Arrays.asList(userId));
183
        sendNotificationModel.setMessageType(messageType);
184
        sendNotificationModel.setUrl(url);
185
        this.sendNotification(sendNotificationModel);
186
    }
29198 manish 187
 
32253 amit.gupta 188
    @Override
32405 jai.hind 189
    public void sendWhatsappMessage(String message, String title, String mobile)
190
            throws Exception {
32415 amit.gupta 191
        this.sendWhatsappMessage(message, title, mobile, null, null);
32253 amit.gupta 192
    }
25822 amit.gupta 193
 
32253 amit.gupta 194
    @Override
32405 jai.hind 195
    public void sendWhatsappMediaMessage(String message, String mobile, String mediaUrl, String fileName)
196
            throws Exception {
32508 amit.gupta 197
        this.sendWhatsappMessage(message, null, mobile, mediaUrl, fileName);
198
 
32253 amit.gupta 199
    }
25822 amit.gupta 200
 
32253 amit.gupta 201
    @Override
202
    public void optIn(String phoneNumber) throws Exception {
203
        Map<String, String> requestheaders = new HashMap<>();
204
        requestheaders.put("Content-Type", "application/x-www-form-urlencoded");
205
        Map<String, String> requestParams = new HashMap<>();
206
        requestParams.put("userid", String.valueOf(2000215976));
207
        requestParams.put("password", "MFRd!BBL");
208
        requestParams.put("phone_number", phoneNumber);
209
        requestParams.put("auth_scheme", "plain");
210
        requestParams.put("v", "1.1");
211
        requestParams.put("format", "json");
28400 tejbeer 212
 
32253 amit.gupta 213
        requestParams.put("method", "OPT_IN");
25822 amit.gupta 214
 
32253 amit.gupta 215
        requestParams.put("channel", "WHATSAPP");
216
        String response = restClient.get("https://media.smsgupshup.com/GatewayAPI/rest", requestParams, requestheaders);
217
        LOGGER.info("response" + response);
218
    }
29927 amit.gupta 219
 
32405 jai.hind 220
    private void sendWhatsappMessage(String message, String title, String mobile, String mediaUrl, String fileName)
221
            throws Exception {
32260 amit.gupta 222
        String sendTo = null;
32259 amit.gupta 223
        if (mobile.length() != 10) {
224
            return;
225
        } else {
32260 amit.gupta 226
            sendTo = 91 + mobile;
32259 amit.gupta 227
        }
32253 amit.gupta 228
        Map<String, String> requestheaders = new HashMap<>();
229
        requestheaders.put("Content-Type", "application/x-www-form-urlencoded");
230
        Map<String, String> requestParams = new HashMap<>();
231
        requestParams.put("userid", String.valueOf(2000215976));
232
        requestParams.put("password", "MFRd!BBL");
32285 amit.gupta 233
        requestParams.put("send_to", sendTo);
32253 amit.gupta 234
        requestParams.put("v", "1.1");
235
        requestParams.put("format", "json");
236
        requestParams.put("auth_scheme", "plain");
32777 amit.gupta 237
        Optin optin = optinRepository.selectByMobile(mobile);
238
        if (optin == null) {
239
            this.optIn(sendTo);
240
            optin = new Optin();
241
            optin.setCreated(LocalDateTime.now());
242
            optin.setMobile(mobile);
243
            optinRepository.persist(optin);
244
        }
32253 amit.gupta 245
        if (mediaUrl == null) {
32415 amit.gupta 246
            requestParams.put("method", "SENDMESSAGE");
32777 amit.gupta 247
            requestParams.put("msg_type", "TEXT");
32253 amit.gupta 248
            requestParams.put("msg", message);
249
            requestParams.put("isTemplate", "true");
32777 amit.gupta 250
            requestParams.put("header", title);
32253 amit.gupta 251
        } else if (mediaUrl != null) {
32268 amit.gupta 252
            requestParams.put("method", "SENDMEDIAMESSAGE");
32253 amit.gupta 253
            requestParams.put("msg_type", "DOCUMENT");
254
            requestParams.put("caption", message);
32268 amit.gupta 255
            //requestParams.put("msg", message);
32253 amit.gupta 256
            requestParams.put("media_url", mediaUrl);
257
            requestParams.put("filename", fileName);
32777 amit.gupta 258
        }
259
        String response =
260
                restClient.post("https://media.smsgupshup.com/GatewayAPI/rest",
261
                        requestParams,
262
                        requestheaders);
263
        LOGGER.info("response  - {}", response);
32403 tejbeer 264
 
32777 amit.gupta 265
        JSONObject jsonObject = new JSONObject(response);
32401 tejbeer 266
 
32777 amit.gupta 267
        JSONObject whatsappResponse = (JSONObject) jsonObject.get("response");
32403 tejbeer 268
 
32777 amit.gupta 269
        String externalId = whatsappResponse.getString("id");
270
        String phone = whatsappResponse.getString("phone");
32403 tejbeer 271
 
32777 amit.gupta 272
        WhatsappMessage whatsappMessage = new WhatsappMessage();
273
        whatsappMessage.setCreatedTimestamp(LocalDateTime.now());
274
        whatsappMessage.setExternalId(externalId);
275
        whatsappMessage.setDestAddr(phone);
276
        whatsappMessageRepository.persist(whatsappMessage);
32253 amit.gupta 277
    }
30025 amit.gupta 278
 
32405 jai.hind 279
    @Override
280
    public boolean isWhatMessageSend(String mobile) {
281
        String destAddr = "91" + mobile;
282
        boolean isSent = true;
32508 amit.gupta 283
        List<WhatsappMessage> whatsappMessages = whatsappMessageRepository.selectByDestAddr(destAddr, LocalDate.now());
32405 jai.hind 284
        if (!whatsappMessages.isEmpty()) {
32508 amit.gupta 285
            long failedCount = whatsappMessages.stream().filter(x -> x.getFailed() != null && x.getFailed().equals("FAILED")).collect(Collectors.counting());
32405 jai.hind 286
            if (failedCount >= 2) {
287
                isSent = false;
288
            }
289
        }
290
        return isSent;
291
    }
25822 amit.gupta 292
}