Subversion Repositories SmartDukaan

Rev

Rev 35921 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
35921 vikas 1
package com.spice.profitmandi.web.controller;
2
 
35927 vikas 3
import java.time.LocalDateTime;
4
import java.util.ArrayList;
5
import java.util.List;
6
 
7
import javax.mail.internet.InternetAddress;
8
import javax.mail.internet.MimeMessage;
35921 vikas 9
import javax.servlet.http.HttpServletRequest;
10
 
11
import org.apache.logging.log4j.LogManager;
12
import org.apache.logging.log4j.Logger;
13
import org.springframework.beans.factory.annotation.Autowired;
14
import org.springframework.http.MediaType;
15
import org.springframework.http.ResponseEntity;
35927 vikas 16
import org.springframework.mail.javamail.JavaMailSender;
17
import org.springframework.mail.javamail.MimeMessageHelper;
35921 vikas 18
import org.springframework.stereotype.Controller;
19
import org.springframework.transaction.annotation.Transactional;
35927 vikas 20
import org.springframework.web.bind.annotation.RequestBody;
35921 vikas 21
import org.springframework.web.bind.annotation.RequestMapping;
22
import org.springframework.web.bind.annotation.RequestMethod;
23
import org.springframework.web.bind.annotation.RequestParam;
24
 
25
import com.spice.profitmandi.common.model.ProfitMandiConstants;
35927 vikas 26
import com.spice.profitmandi.common.model.UserInfo;
35921 vikas 27
import com.spice.profitmandi.common.web.util.ResponseSender;
28
import com.spice.profitmandi.dao.entity.auth.AuthUser;
35927 vikas 29
import com.spice.profitmandi.dao.entity.dtr.User;
35921 vikas 30
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
31
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
35927 vikas 32
import com.spice.profitmandi.dao.repository.cs.CallbackRequestRepository;
35921 vikas 33
import com.spice.profitmandi.dao.repository.cs.CsService;
35927 vikas 34
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
35
import com.spice.profitmandi.web.req.CallbackRequest;
35921 vikas 36
import com.spice.profitmandi.web.res.SupportTeamResponse;
35927 vikas 37
import com.spice.profitmandi.web.res.SupportTeamResponse.ContactDetail;
35921 vikas 38
 
39
import io.swagger.annotations.ApiImplicitParam;
40
import io.swagger.annotations.ApiImplicitParams;
41
import io.swagger.annotations.ApiOperation;
42
 
43
@Controller
44
@Transactional(rollbackFor = Throwable.class)
45
public class SupportController {
46
 
47
    private static final Logger LOGGER = LogManager.getLogger(SupportController.class);
48
 
49
    @Autowired
50
    private ResponseSender<?> responseSender;
51
 
52
    @Autowired
53
    private CsService csService;
54
 
55
    @Autowired
56
    private AuthRepository authRepository;
57
 
35927 vikas 58
    @Autowired
59
    private UserRepository userRepository;
60
 
61
    @Autowired
62
    private JavaMailSender mailSender;
63
 
64
    @Autowired
65
    private CallbackRequestRepository callbackRequestRepository;
66
 
35921 vikas 67
    @RequestMapping(value = "/support/team", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
68
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
35927 vikas 69
    @ApiOperation(value = "Get assigned support team for a FOFO store grouped by escalation level")
35921 vikas 70
    public ResponseEntity<?> getSupportTeam(HttpServletRequest request, @RequestParam(value = "fofoId") int fofoId) throws Throwable {
71
        LOGGER.info("Getting support team for fofoId: {}", fofoId);
72
 
35927 vikas 73
        List<SupportTeamResponse> response = new ArrayList<>();
74
 
75
        // --- LEVEL 1 - IMMEDIATE SUPPORT ---
76
        List<ContactDetail> l1Contacts = new ArrayList<>();
77
 
78
        // RBM = RBM category, L1
35921 vikas 79
        try {
35927 vikas 80
            int rbmAuthUserId = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L1, fofoId);
81
            if (rbmAuthUserId > 0) {
82
                AuthUser user = authRepository.selectById(rbmAuthUserId);
83
                if (user != null) {
84
                    l1Contacts.add(buildContact(user, "RBM", "#1a7a4c",
85
                            "First point of contact for all queries", true, true, false, true));
35921 vikas 86
                }
87
            }
88
        } catch (Exception e) {
35927 vikas 89
            LOGGER.warn("Could not fetch RBM for fofoId: {}", fofoId, e);
35921 vikas 90
        }
91
 
35927 vikas 92
        // ABM = SALES category, L1
35921 vikas 93
        try {
35927 vikas 94
            int abmAuthUserId = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L1, fofoId);
95
            if (abmAuthUserId > 0) {
96
                AuthUser user = authRepository.selectById(abmAuthUserId);
97
                if (user != null) {
98
                    l1Contacts.add(buildContact(user, "ASM", "#1a7a4c",
99
                            "Sales support and regional queries", true, true, false, false));
35921 vikas 100
                }
101
            }
102
        } catch (Exception e) {
35927 vikas 103
            LOGGER.warn("Could not fetch ABM for fofoId: {}", fofoId, e);
35921 vikas 104
        }
105
 
35927 vikas 106
        if (!l1Contacts.isEmpty()) {
107
            response.add(new SupportTeamResponse("LEVEL 1 - IMMEDIATE SUPPORT", l1Contacts));
35921 vikas 108
        }
109
 
35927 vikas 110
        // --- LEVEL 2 - SPECIALIZED SUPPORT ---
111
        List<ContactDetail> l2Contacts = new ArrayList<>();
112
 
35921 vikas 113
        // RBM Manager = RBM category, L2
114
        try {
115
            int rbmManagerAuthUserId = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L2, fofoId);
116
            if (rbmManagerAuthUserId > 0) {
35927 vikas 117
                AuthUser user = authRepository.selectById(rbmManagerAuthUserId);
118
                if (user != null) {
119
                    l2Contacts.add(buildContact(user, "RBM MANAGER", "#7c3aed",
120
                            "For escalated regional matters", false, false, true, true));
35921 vikas 121
                }
122
            }
123
        } catch (Exception e) {
124
            LOGGER.warn("Could not fetch RBM Manager for fofoId: {}", fofoId, e);
125
        }
126
 
35927 vikas 127
        // BM = SALES category, L2
35921 vikas 128
        try {
35927 vikas 129
            int bmAuthUserId = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L2, fofoId);
130
            if (bmAuthUserId > 0) {
131
                AuthUser user = authRepository.selectById(bmAuthUserId);
132
                if (user != null) {
133
                    l2Contacts.add(buildContact(user, "BM", "#1e6091",
134
                            "Handles: Orders, Stock, Schemes", false, false, true, false));
35921 vikas 135
                }
136
            }
137
        } catch (Exception e) {
35927 vikas 138
            LOGGER.warn("Could not fetch BM for fofoId: {}", fofoId, e);
35921 vikas 139
        }
140
 
35927 vikas 141
        // Affordability Operations = FINANCIAL_SERVICES category, L2
35921 vikas 142
        try {
35927 vikas 143
            int affordAuthUserId = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_FINANCIAL_SERVICES, EscalationType.L2, fofoId);
144
            if (affordAuthUserId > 0) {
145
                AuthUser user = authRepository.selectById(affordAuthUserId);
146
                if (user != null) {
147
                    l2Contacts.add(buildContact(user, "AFFORDABILITY & OPERATIONS", "#d97706",
148
                            "Credit, payment plans, and operations", false, false, true, false));
35921 vikas 149
                }
150
            }
151
        } catch (Exception e) {
152
            LOGGER.warn("Could not fetch Affordability Manager for fofoId: {}", fofoId, e);
153
        }
154
 
35927 vikas 155
        // Branding Manager = DESIGN category, L1
35921 vikas 156
        try {
35927 vikas 157
            int brandingAuthUserId = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_DESIGN, EscalationType.L1, fofoId);
158
            if (brandingAuthUserId > 0) {
159
                AuthUser user = authRepository.selectById(brandingAuthUserId);
160
                if (user != null) {
161
                    l2Contacts.add(buildContact(user, "BRANDING", "#1a7a4c",
162
                            "Brand guidelines and marketing support", false, false, true, false));
35921 vikas 163
                }
164
            }
165
        } catch (Exception e) {
166
            LOGGER.warn("Could not fetch Branding Manager for fofoId: {}", fofoId, e);
167
        }
168
 
35927 vikas 169
        if (!l2Contacts.isEmpty()) {
170
            response.add(new SupportTeamResponse("LEVEL 2 - SPECIALIZED SUPPORT", l2Contacts));
171
        }
172
 
173
        // --- LEVEL 3 - ESCALATION ---
174
        List<ContactDetail> l3Contacts = new ArrayList<>();
175
 
176
        // Grievance Manager = LEGAL category, L3
177
        try {
178
            int grievanceAuthUserId = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_LEGAL, EscalationType.L1, fofoId);
179
            if (grievanceAuthUserId > 0) {
180
                AuthUser user = authRepository.selectById(grievanceAuthUserId);
181
                if (user != null) {
182
                    l3Contacts.add(buildContact(user, "GRIEVANCE OFFICER", "#dc2626",
183
                            "For unresolved issues & formal complaints", false, false, true, true));
184
                }
185
            }
186
        } catch (Exception e) {
187
            LOGGER.warn("Could not fetch Grievance Manager for fofoId: {}", fofoId, e);
188
        }
189
 
190
        if (!l3Contacts.isEmpty()) {
191
            response.add(new SupportTeamResponse("LEVEL 3 - ESCALATION", l3Contacts));
192
        }
193
 
35921 vikas 194
        return responseSender.ok(response);
195
    }
196
 
35927 vikas 197
    @RequestMapping(value = "/support/callback-request", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
198
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
199
    @ApiOperation(value = "Submit a callback request to a support contact")
200
    public ResponseEntity<?> requestCallback(HttpServletRequest request, @RequestBody CallbackRequest callbackRequest) throws Throwable {
201
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
202
        User user = userRepository.selectById(userInfo.getUserId());
203
 
204
        LOGGER.info("Callback request from userId: {} to contactId: {} subject: {}",
205
                userInfo.getUserId(), callbackRequest.getContactId(), callbackRequest.getSubject());
206
 
207
        // Save to database
208
        com.spice.profitmandi.dao.entity.cs.CallbackRequest entity = new com.spice.profitmandi.dao.entity.cs.CallbackRequest();
209
        entity.setFofoId(userInfo.getRetailerId());
210
        entity.setUserId(userInfo.getUserId());
211
        entity.setContactId(callbackRequest.getContactId());
212
        entity.setContactName(callbackRequest.getContactName());
213
        entity.setContactRole(callbackRequest.getContactRole());
214
        entity.setSubject(callbackRequest.getSubject());
215
        entity.setMessage(callbackRequest.getMessage());
216
        entity.setTiming(callbackRequest.getTiming());
217
        entity.setStatus("PENDING");
218
        entity.setCreateTimestamp(LocalDateTime.now());
219
        entity.setUpdateTimestamp(LocalDateTime.now());
220
        callbackRequestRepository.persist(entity);
221
        LOGGER.info("Callback request saved with id: {}", entity.getId());
222
 
223
        String timingLabel = "11-15".equals(callbackRequest.getTiming()) ? "11:00 AM - 3:00 PM" : "3:00 PM - 7:00 PM";
224
 
225
        // Send email to the support contact
226
        AuthUser contactUser = authRepository.selectById(callbackRequest.getContactId());
227
        if (contactUser == null || contactUser.getEmailId() == null) {
228
            LOGGER.warn("Contact user not found or has no email for contactId: {}", callbackRequest.getContactId());
229
            return responseSender.ok(true);
230
        }
231
 
232
        MimeMessage message = mailSender.createMimeMessage();
233
        MimeMessageHelper helper = new MimeMessageHelper(message);
234
        helper.setSubject("Callback Request: " + callbackRequest.getSubject());
235
 
236
        String emailContent = "<html>"
237
                + "<body style='font-family: Arial, sans-serif; color: #333;'>"
238
                + "<h2 style='color: #d5282c;'>New Callback Request</h2>"
239
                + "<table style='border-collapse: collapse; width: 100%; max-width: 500px;'>"
240
                + "<tr><td style='padding: 8px; font-weight: bold; color: #555;'>From:</td>"
241
                + "<td style='padding: 8px;'>" + user.getFirstName() + " (" + user.getMobileNumber() + ")</td></tr>"
242
                + "<tr><td style='padding: 8px; font-weight: bold; color: #555;'>Email:</td>"
243
                + "<td style='padding: 8px;'>" + user.getEmailId() + "</td></tr>"
244
                + "<tr><td style='padding: 8px; font-weight: bold; color: #555;'>To:</td>"
245
                + "<td style='padding: 8px;'>" + callbackRequest.getContactName() + " (" + callbackRequest.getContactRole() + ")</td></tr>"
246
                + "<tr><td style='padding: 8px; font-weight: bold; color: #555;'>Subject:</td>"
247
                + "<td style='padding: 8px;'>" + callbackRequest.getSubject() + "</td></tr>"
248
                + "<tr><td style='padding: 8px; font-weight: bold; color: #555;'>Message:</td>"
249
                + "<td style='padding: 8px;'>" + callbackRequest.getMessage() + "</td></tr>"
250
                + "<tr><td style='padding: 8px; font-weight: bold; color: #555;'>Preferred Timing:</td>"
251
                + "<td style='padding: 8px;'>" + timingLabel + "</td></tr>"
252
                + "</table>"
253
                + "<br><p style='color: #999; font-size: 12px;'>This callback request was submitted via the SmartDukaan Support page.</p>"
254
                + "</body></html>";
255
 
256
        helper.setText(emailContent, true);
257
        InternetAddress senderAddress = new InternetAddress("care@smartdukaan.com", "SmartDukaan Support");
258
        helper.setFrom(senderAddress);
259
        helper.setTo(contactUser.getEmailId());
260
        helper.setReplyTo(user.getEmailId());
261
 
262
        mailSender.send(message);
263
        LOGGER.info("Callback request email sent to: {}", contactUser.getEmailId());
264
 
265
        return responseSender.ok(true);
35921 vikas 266
    }
35927 vikas 267
 
268
    private ContactDetail buildContact(AuthUser authUser, String badge, String badgeColor,
269
                                       String description, boolean showCall, boolean showMessage,
270
                                       boolean showCallback, boolean expanded) {
271
        ContactDetail contact = new ContactDetail();
272
        contact.setId(authUser.getId());
273
        contact.setName(authUser.getFullName());
274
        contact.setInitials(getInitials(authUser.getFirstName(), authUser.getLastName()));
275
        contact.setRole(badge);
276
        contact.setBadge(badge);
277
        contact.setBadgeColor(badgeColor);
278
        contact.setDescription(description);
279
        contact.setPhone("tel:+91" + authUser.getMobileNumber());
280
        contact.setWhatsapp("https://wa.me/91" + authUser.getMobileNumber());
281
        contact.setEmail(authUser.getEmailId());
282
        contact.setShowCall(showCall);
283
        contact.setShowMessage(showMessage);
284
        contact.setShowCallback(showCallback);
285
        contact.setExpanded(expanded);
286
        return contact;
287
    }
288
 
289
    private String getInitials(String firstName, String lastName) {
290
        StringBuilder initials = new StringBuilder();
291
        if (firstName != null && !firstName.isEmpty()) {
292
            initials.append(firstName.charAt(0));
293
        }
294
        if (lastName != null && !lastName.isEmpty()) {
295
            initials.append(lastName.charAt(0));
296
        }
297
        return initials.toString().toUpperCase();
298
    }
35921 vikas 299
}