Subversion Repositories SmartDukaan

Rev

Rev 35948 | Go to most recent revision | 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;
35948 vikas 4
import java.time.format.DateTimeFormatter;
35927 vikas 5
import java.util.ArrayList;
35969 vikas 6
import java.util.Collections;
35927 vikas 7
import java.util.List;
8
 
9
import javax.mail.internet.InternetAddress;
10
import javax.mail.internet.MimeMessage;
35921 vikas 11
import javax.servlet.http.HttpServletRequest;
12
 
13
import org.apache.logging.log4j.LogManager;
14
import org.apache.logging.log4j.Logger;
15
import org.springframework.beans.factory.annotation.Autowired;
16
import org.springframework.http.MediaType;
17
import org.springframework.http.ResponseEntity;
35927 vikas 18
import org.springframework.mail.javamail.JavaMailSender;
19
import org.springframework.mail.javamail.MimeMessageHelper;
35921 vikas 20
import org.springframework.stereotype.Controller;
21
import org.springframework.transaction.annotation.Transactional;
35948 vikas 22
import org.springframework.web.bind.annotation.PathVariable;
35927 vikas 23
import org.springframework.web.bind.annotation.RequestBody;
35921 vikas 24
import org.springframework.web.bind.annotation.RequestMapping;
25
import org.springframework.web.bind.annotation.RequestMethod;
26
import org.springframework.web.bind.annotation.RequestParam;
27
 
28
import com.spice.profitmandi.common.model.ProfitMandiConstants;
35927 vikas 29
import com.spice.profitmandi.common.model.UserInfo;
35921 vikas 30
import com.spice.profitmandi.common.web.util.ResponseSender;
31
import com.spice.profitmandi.dao.entity.auth.AuthUser;
35927 vikas 32
import com.spice.profitmandi.dao.entity.dtr.User;
35921 vikas 33
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
34
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
35948 vikas 35
import com.spice.profitmandi.dao.entity.dtr.Retailer;
36
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
35969 vikas 37
import com.spice.profitmandi.dao.entity.cs.CallbackRequestReply;
38
import com.spice.profitmandi.dao.repository.cs.CallbackRequestReplyRepository;
35927 vikas 39
import com.spice.profitmandi.dao.repository.cs.CallbackRequestRepository;
35921 vikas 40
import com.spice.profitmandi.dao.repository.cs.CsService;
35948 vikas 41
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
42
import com.spice.profitmandi.dao.repository.dtr.RetailerRepository;
35927 vikas 43
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
35969 vikas 44
import com.spice.profitmandi.web.req.CallbackReplyRequest;
35927 vikas 45
import com.spice.profitmandi.web.req.CallbackRequest;
35948 vikas 46
import com.spice.profitmandi.web.req.ResolveCallbackRequest;
47
import com.spice.profitmandi.web.res.AssignedRequestResponse;
35969 vikas 48
import com.spice.profitmandi.web.res.CallbackReplyResponse;
35948 vikas 49
import com.spice.profitmandi.web.res.CallbackRequestResponse;
35921 vikas 50
import com.spice.profitmandi.web.res.SupportTeamResponse;
35927 vikas 51
import com.spice.profitmandi.web.res.SupportTeamResponse.ContactDetail;
35921 vikas 52
 
53
import io.swagger.annotations.ApiImplicitParam;
54
import io.swagger.annotations.ApiImplicitParams;
55
import io.swagger.annotations.ApiOperation;
56
 
57
@Controller
58
@Transactional(rollbackFor = Throwable.class)
59
public class SupportController {
60
 
61
    private static final Logger LOGGER = LogManager.getLogger(SupportController.class);
62
 
63
    @Autowired
64
    private ResponseSender<?> responseSender;
65
 
66
    @Autowired
67
    private CsService csService;
68
 
69
    @Autowired
70
    private AuthRepository authRepository;
71
 
35927 vikas 72
    @Autowired
73
    private UserRepository userRepository;
74
 
75
    @Autowired
76
    private JavaMailSender mailSender;
77
 
78
    @Autowired
79
    private CallbackRequestRepository callbackRequestRepository;
80
 
35948 vikas 81
    @Autowired
35969 vikas 82
    private CallbackRequestReplyRepository callbackRequestReplyRepository;
83
 
84
    @Autowired
35948 vikas 85
    private RetailerRepository retailerRepository;
86
 
87
    @Autowired
88
    private FofoStoreRepository fofoStoreRepository;
89
 
35921 vikas 90
    @RequestMapping(value = "/support/team", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
91
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
35927 vikas 92
    @ApiOperation(value = "Get assigned support team for a FOFO store grouped by escalation level")
35921 vikas 93
    public ResponseEntity<?> getSupportTeam(HttpServletRequest request, @RequestParam(value = "fofoId") int fofoId) throws Throwable {
94
        LOGGER.info("Getting support team for fofoId: {}", fofoId);
95
 
35927 vikas 96
        List<SupportTeamResponse> response = new ArrayList<>();
97
 
98
        // --- LEVEL 1 - IMMEDIATE SUPPORT ---
99
        List<ContactDetail> l1Contacts = new ArrayList<>();
100
 
101
        // RBM = RBM category, L1
35921 vikas 102
        try {
35927 vikas 103
            int rbmAuthUserId = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L1, fofoId);
104
            if (rbmAuthUserId > 0) {
105
                AuthUser user = authRepository.selectById(rbmAuthUserId);
106
                if (user != null) {
107
                    l1Contacts.add(buildContact(user, "RBM", "#1a7a4c",
108
                            "First point of contact for all queries", true, true, false, true));
35921 vikas 109
                }
110
            }
111
        } catch (Exception e) {
35927 vikas 112
            LOGGER.warn("Could not fetch RBM for fofoId: {}", fofoId, e);
35921 vikas 113
        }
114
 
35927 vikas 115
        // ABM = SALES category, L1
35921 vikas 116
        try {
35927 vikas 117
            int abmAuthUserId = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L1, fofoId);
118
            if (abmAuthUserId > 0) {
119
                AuthUser user = authRepository.selectById(abmAuthUserId);
120
                if (user != null) {
121
                    l1Contacts.add(buildContact(user, "ASM", "#1a7a4c",
35969 vikas 122
                            "Sales support and regional queries", true, true, false, true));
35921 vikas 123
                }
124
            }
125
        } catch (Exception e) {
35927 vikas 126
            LOGGER.warn("Could not fetch ABM for fofoId: {}", fofoId, e);
35921 vikas 127
        }
128
 
35927 vikas 129
        if (!l1Contacts.isEmpty()) {
130
            response.add(new SupportTeamResponse("LEVEL 1 - IMMEDIATE SUPPORT", l1Contacts));
35921 vikas 131
        }
132
 
35927 vikas 133
        // --- LEVEL 2 - SPECIALIZED SUPPORT ---
134
        List<ContactDetail> l2Contacts = new ArrayList<>();
135
 
35921 vikas 136
        // RBM Manager = RBM category, L2
137
        try {
138
            int rbmManagerAuthUserId = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L2, fofoId);
139
            if (rbmManagerAuthUserId > 0) {
35927 vikas 140
                AuthUser user = authRepository.selectById(rbmManagerAuthUserId);
141
                if (user != null) {
142
                    l2Contacts.add(buildContact(user, "RBM MANAGER", "#7c3aed",
35969 vikas 143
                            "For escalated regional matters", true, true, false, true));
35921 vikas 144
                }
145
            }
146
        } catch (Exception e) {
147
            LOGGER.warn("Could not fetch RBM Manager for fofoId: {}", fofoId, e);
148
        }
149
 
35927 vikas 150
        // BM = SALES category, L2
35921 vikas 151
        try {
35927 vikas 152
            int bmAuthUserId = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L2, fofoId);
153
            if (bmAuthUserId > 0) {
154
                AuthUser user = authRepository.selectById(bmAuthUserId);
155
                if (user != null) {
156
                    l2Contacts.add(buildContact(user, "BM", "#1e6091",
35969 vikas 157
                            "Handles: Orders, Stock, Schemes", true, true, false, true));
35921 vikas 158
                }
159
            }
160
        } catch (Exception e) {
35927 vikas 161
            LOGGER.warn("Could not fetch BM for fofoId: {}", fofoId, e);
35921 vikas 162
        }
163
 
35969 vikas 164
        // Finance Partner Mapping Operations = FINANCIAL_SERVICES category, L2
35921 vikas 165
        try {
35927 vikas 166
            int affordAuthUserId = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_FINANCIAL_SERVICES, EscalationType.L2, fofoId);
167
            if (affordAuthUserId > 0) {
168
                AuthUser user = authRepository.selectById(affordAuthUserId);
169
                if (user != null) {
35948 vikas 170
                    l2Contacts.add(buildContact(user, "Finance Partner Mapping", "#d97706",
35927 vikas 171
                            "Credit, payment plans, and operations", false, false, true, false));
35921 vikas 172
                }
173
            }
174
        } catch (Exception e) {
35969 vikas 175
            LOGGER.warn("Could not fetch Finance Partner Mapping Manager for fofoId: {}", fofoId, e);
35921 vikas 176
        }
177
 
35927 vikas 178
        // Branding Manager = DESIGN category, L1
35921 vikas 179
        try {
35927 vikas 180
            int brandingAuthUserId = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_DESIGN, EscalationType.L1, fofoId);
181
            if (brandingAuthUserId > 0) {
182
                AuthUser user = authRepository.selectById(brandingAuthUserId);
183
                if (user != null) {
184
                    l2Contacts.add(buildContact(user, "BRANDING", "#1a7a4c",
185
                            "Brand guidelines and marketing support", false, false, true, false));
35921 vikas 186
                }
187
            }
188
        } catch (Exception e) {
189
            LOGGER.warn("Could not fetch Branding Manager for fofoId: {}", fofoId, e);
190
        }
191
 
35927 vikas 192
        if (!l2Contacts.isEmpty()) {
193
            response.add(new SupportTeamResponse("LEVEL 2 - SPECIALIZED SUPPORT", l2Contacts));
194
        }
195
 
196
        // --- LEVEL 3 - ESCALATION ---
197
        List<ContactDetail> l3Contacts = new ArrayList<>();
198
 
199
        // Grievance Manager = LEGAL category, L3
200
        try {
201
            int grievanceAuthUserId = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_LEGAL, EscalationType.L1, fofoId);
202
            if (grievanceAuthUserId > 0) {
203
                AuthUser user = authRepository.selectById(grievanceAuthUserId);
204
                if (user != null) {
205
                    l3Contacts.add(buildContact(user, "GRIEVANCE OFFICER", "#dc2626",
206
                            "For unresolved issues & formal complaints", false, false, true, true));
207
                }
208
            }
209
        } catch (Exception e) {
210
            LOGGER.warn("Could not fetch Grievance Manager for fofoId: {}", fofoId, e);
211
        }
212
 
213
        if (!l3Contacts.isEmpty()) {
214
            response.add(new SupportTeamResponse("LEVEL 3 - ESCALATION", l3Contacts));
215
        }
216
 
35921 vikas 217
        return responseSender.ok(response);
218
    }
219
 
35927 vikas 220
    @RequestMapping(value = "/support/callback-request", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
221
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
222
    @ApiOperation(value = "Submit a callback request to a support contact")
223
    public ResponseEntity<?> requestCallback(HttpServletRequest request, @RequestBody CallbackRequest callbackRequest) throws Throwable {
224
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
225
        User user = userRepository.selectById(userInfo.getUserId());
226
 
227
        LOGGER.info("Callback request from userId: {} to contactId: {} subject: {}",
228
                userInfo.getUserId(), callbackRequest.getContactId(), callbackRequest.getSubject());
229
 
230
        // Save to database
231
        com.spice.profitmandi.dao.entity.cs.CallbackRequest entity = new com.spice.profitmandi.dao.entity.cs.CallbackRequest();
232
        entity.setFofoId(userInfo.getRetailerId());
233
        entity.setUserId(userInfo.getUserId());
234
        entity.setContactId(callbackRequest.getContactId());
235
        entity.setContactName(callbackRequest.getContactName());
236
        entity.setContactRole(callbackRequest.getContactRole());
237
        entity.setSubject(callbackRequest.getSubject());
238
        entity.setMessage(callbackRequest.getMessage());
239
        entity.setTiming(callbackRequest.getTiming());
240
        entity.setStatus("PENDING");
241
        entity.setCreateTimestamp(LocalDateTime.now());
242
        entity.setUpdateTimestamp(LocalDateTime.now());
243
        callbackRequestRepository.persist(entity);
244
        LOGGER.info("Callback request saved with id: {}", entity.getId());
245
 
246
        String timingLabel = "11-15".equals(callbackRequest.getTiming()) ? "11:00 AM - 3:00 PM" : "3:00 PM - 7:00 PM";
247
 
248
        // Send email to the support contact
249
        AuthUser contactUser = authRepository.selectById(callbackRequest.getContactId());
250
        if (contactUser == null || contactUser.getEmailId() == null) {
251
            LOGGER.warn("Contact user not found or has no email for contactId: {}", callbackRequest.getContactId());
252
            return responseSender.ok(true);
253
        }
254
 
255
        MimeMessage message = mailSender.createMimeMessage();
256
        MimeMessageHelper helper = new MimeMessageHelper(message);
257
        helper.setSubject("Callback Request: " + callbackRequest.getSubject());
258
 
259
        String emailContent = "<html>"
260
                + "<body style='font-family: Arial, sans-serif; color: #333;'>"
261
                + "<h2 style='color: #d5282c;'>New Callback Request</h2>"
262
                + "<table style='border-collapse: collapse; width: 100%; max-width: 500px;'>"
263
                + "<tr><td style='padding: 8px; font-weight: bold; color: #555;'>From:</td>"
264
                + "<td style='padding: 8px;'>" + user.getFirstName() + " (" + user.getMobileNumber() + ")</td></tr>"
265
                + "<tr><td style='padding: 8px; font-weight: bold; color: #555;'>Email:</td>"
266
                + "<td style='padding: 8px;'>" + user.getEmailId() + "</td></tr>"
267
                + "<tr><td style='padding: 8px; font-weight: bold; color: #555;'>To:</td>"
268
                + "<td style='padding: 8px;'>" + callbackRequest.getContactName() + " (" + callbackRequest.getContactRole() + ")</td></tr>"
269
                + "<tr><td style='padding: 8px; font-weight: bold; color: #555;'>Subject:</td>"
270
                + "<td style='padding: 8px;'>" + callbackRequest.getSubject() + "</td></tr>"
271
                + "<tr><td style='padding: 8px; font-weight: bold; color: #555;'>Message:</td>"
272
                + "<td style='padding: 8px;'>" + callbackRequest.getMessage() + "</td></tr>"
273
                + "<tr><td style='padding: 8px; font-weight: bold; color: #555;'>Preferred Timing:</td>"
274
                + "<td style='padding: 8px;'>" + timingLabel + "</td></tr>"
275
                + "</table>"
276
                + "<br><p style='color: #999; font-size: 12px;'>This callback request was submitted via the SmartDukaan Support page.</p>"
277
                + "</body></html>";
278
 
279
        helper.setText(emailContent, true);
280
        InternetAddress senderAddress = new InternetAddress("care@smartdukaan.com", "SmartDukaan Support");
281
        helper.setFrom(senderAddress);
282
        helper.setTo(contactUser.getEmailId());
283
        helper.setReplyTo(user.getEmailId());
284
 
285
        mailSender.send(message);
286
        LOGGER.info("Callback request email sent to: {}", contactUser.getEmailId());
287
 
288
        return responseSender.ok(true);
35921 vikas 289
    }
35927 vikas 290
 
35948 vikas 291
    @RequestMapping(value = "/support/callback-requests", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
292
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
293
    @ApiOperation(value = "Get callback requests for the logged-in fofo associate")
294
    public ResponseEntity<?> getCallbackRequests(HttpServletRequest request) throws Throwable {
295
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
296
        int fofoId = userInfo.getRetailerId();
297
        LOGGER.info("Getting callback requests for fofoId: {}", fofoId);
298
 
299
        List<com.spice.profitmandi.dao.entity.cs.CallbackRequest> callbackRequests = callbackRequestRepository.selectAllByFofoId(fofoId);
300
 
301
        List<CallbackRequestResponse> responseList = new ArrayList<>();
302
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMM yyyy, hh:mm a");
303
 
304
        for (com.spice.profitmandi.dao.entity.cs.CallbackRequest entity : callbackRequests) {
305
            CallbackRequestResponse res = new CallbackRequestResponse();
306
            res.setId(entity.getId());
307
            res.setContactId(entity.getContactId());
308
            res.setContactName(entity.getContactName());
309
            res.setContactInitials(getInitials(entity.getContactName()));
310
            res.setContactRole(entity.getContactRole());
311
            res.setSubject(entity.getSubject());
312
            res.setMessage(entity.getMessage());
313
            res.setTiming(entity.getTiming());
314
            res.setTimingLabel("11-15".equals(entity.getTiming()) ? "11:00 AM - 3:00 PM" : "3:00 PM - 7:00 PM");
315
            res.setStatus(entity.getStatus());
35969 vikas 316
            res.setResolutionNotes(entity.getResolutionNotes());
317
            res.setReplyCount(callbackRequestReplyRepository.countByCallbackRequestId(entity.getId()));
318
            res.setUnread(entity.isUnread());
35948 vikas 319
            if (entity.getCreateTimestamp() != null) {
320
                res.setCreateTimestamp(entity.getCreateTimestamp().format(formatter));
321
            }
322
            responseList.add(res);
323
        }
324
 
325
        return responseSender.ok(responseList);
326
    }
327
 
35969 vikas 328
    @RequestMapping(value = "/support/callback-requests/unread-count", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
329
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
330
    @ApiOperation(value = "Get count of unread callback requests for the logged-in retailer")
331
    public ResponseEntity<?> getUnreadCount(HttpServletRequest request) throws Throwable {
332
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
333
        int fofoId = userInfo.getRetailerId();
334
        LOGGER.info("Getting unread callback request count for fofoId: {}", fofoId);
335
        long count = callbackRequestRepository.countUnreadByFofoId(fofoId);
336
        return responseSender.ok(count);
337
    }
338
 
339
    @RequestMapping(value = "/support/callback-requests/mark-read", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
340
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
341
    @ApiOperation(value = "Mark all callback requests as read for the logged-in retailer")
342
    public ResponseEntity<?> markRequestsAsRead(HttpServletRequest request) throws Throwable {
343
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
344
        int fofoId = userInfo.getRetailerId();
345
        LOGGER.info("Marking all callback requests as read for fofoId: {}", fofoId);
346
        callbackRequestRepository.markAllReadByFofoId(fofoId);
347
        return responseSender.ok(true);
348
    }
349
 
35948 vikas 350
    @RequestMapping(value = "/support/assigned-requests", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
351
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
352
    @ApiOperation(value = "Get callback requests assigned to the logged-in internal user")
353
    public ResponseEntity<?> getAssignedRequests(HttpServletRequest request) throws Throwable {
354
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
355
        int contactId = userInfo.getUserId();
356
        LOGGER.info("Getting assigned requests for contactId: {}", contactId);
357
 
358
        List<com.spice.profitmandi.dao.entity.cs.CallbackRequest> callbackRequests = callbackRequestRepository.selectAllByContactId(contactId);
359
 
360
        List<AssignedRequestResponse> responseList = new ArrayList<>();
361
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMM yyyy, hh:mm a");
362
 
363
        for (com.spice.profitmandi.dao.entity.cs.CallbackRequest entity : callbackRequests) {
364
            AssignedRequestResponse res = new AssignedRequestResponse();
365
            res.setId(entity.getId());
366
            res.setSubject(entity.getSubject());
367
            res.setMessage(entity.getMessage());
368
            res.setTiming(entity.getTiming());
369
            res.setTimingLabel("11-15".equals(entity.getTiming()) ? "11:00 AM - 3:00 PM" : "3:00 PM - 7:00 PM");
370
            res.setStatus(entity.getStatus());
371
            res.setResolutionNotes(entity.getResolutionNotes());
35969 vikas 372
            res.setReplyCount(callbackRequestReplyRepository.countByCallbackRequestId(entity.getId()));
35948 vikas 373
 
374
            if (entity.getCreateTimestamp() != null) {
375
                res.setCreateTimestamp(entity.getCreateTimestamp().format(formatter));
376
            }
377
            if (entity.getUpdateTimestamp() != null) {
378
                res.setUpdateTimestamp(entity.getUpdateTimestamp().format(formatter));
379
            }
380
 
381
            // Fetch retailer info
382
            try {
383
                User retailerUser = userRepository.selectById(entity.getUserId());
384
                if (retailerUser != null) {
385
                    res.setRetailerName(retailerUser.getFirstName());
386
                    res.setRetailerPhone(retailerUser.getMobileNumber());
387
                }
388
            } catch (Exception e) {
389
                LOGGER.warn("Could not fetch user for userId: {}", entity.getUserId(), e);
390
            }
391
 
392
            // Fetch store info
393
            try {
394
                Retailer retailer = retailerRepository.selectById(entity.getFofoId());
395
                if (retailer != null) {
396
                    res.setStoreName(retailer.getName());
397
                }
398
                FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(entity.getFofoId());
399
                if (fofoStore != null) {
400
                    res.setStoreCode(fofoStore.getCode());
401
                }
402
            } catch (Exception e) {
403
                LOGGER.warn("Could not fetch store info for fofoId: {}", entity.getFofoId(), e);
404
            }
405
 
406
            responseList.add(res);
407
        }
408
 
409
        return responseSender.ok(responseList);
410
    }
411
 
412
    @RequestMapping(value = "/support/assigned-requests/{id}/resolve", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
413
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
414
    @ApiOperation(value = "Update status and resolution notes for a callback request")
415
    public ResponseEntity<?> resolveAssignedRequest(HttpServletRequest request, @PathVariable("id") int id,
416
                                                     @RequestBody ResolveCallbackRequest resolveRequest) throws Throwable {
417
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
418
        LOGGER.info("Resolving callback request id: {} by userId: {} status: {}", id, userInfo.getUserId(), resolveRequest.getStatus());
419
 
420
        com.spice.profitmandi.dao.entity.cs.CallbackRequest entity = callbackRequestRepository.selectById(id);
421
        if (entity == null) {
422
            LOGGER.warn("Callback request not found for id: {}", id);
423
            return responseSender.ok(false);
424
        }
425
 
426
        entity.setStatus(resolveRequest.getStatus());
427
        entity.setResolutionNotes(resolveRequest.getResolutionNotes());
428
        entity.setUpdateTimestamp(LocalDateTime.now());
429
        callbackRequestRepository.persist(entity);
430
 
431
        LOGGER.info("Callback request id: {} resolved with status: {}", id, resolveRequest.getStatus());
432
        return responseSender.ok(true);
433
    }
434
 
35969 vikas 435
    @RequestMapping(value = "/support/callback-requests/{id}/replies", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
436
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
437
    @ApiOperation(value = "Get all replies for a callback request")
438
    public ResponseEntity<?> getReplies(HttpServletRequest request, @PathVariable("id") int id) throws Throwable {
439
        LOGGER.info("Getting replies for callback request id: {}", id);
440
 
441
        List<CallbackRequestReply> replies = callbackRequestReplyRepository.selectAllByCallbackRequestId(id);
442
        Collections.reverse(replies); // oldest first for chat order
443
 
444
        List<CallbackReplyResponse> responseList = new ArrayList<>();
445
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMM yyyy, hh:mm a");
446
 
447
        for (CallbackRequestReply reply : replies) {
448
            CallbackReplyResponse res = new CallbackReplyResponse();
449
            res.setId(reply.getId());
450
            res.setMessage(reply.getMessage());
451
            res.setSenderType(reply.getSenderType());
452
            res.setSenderName(reply.getSenderName());
453
            if (reply.getCreateTimestamp() != null) {
454
                res.setCreateTimestamp(reply.getCreateTimestamp().format(formatter));
455
            }
456
            responseList.add(res);
457
        }
458
 
459
        return responseSender.ok(responseList);
460
    }
461
 
462
    @RequestMapping(value = "/support/callback-requests/{id}/reply", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
463
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
464
    @ApiOperation(value = "Add a reply to a callback request")
465
    public ResponseEntity<?> addReply(HttpServletRequest request, @PathVariable("id") int id,
466
                                       @RequestBody CallbackReplyRequest replyRequest) throws Throwable {
467
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
468
 
469
        com.spice.profitmandi.dao.entity.cs.CallbackRequest callbackReq = callbackRequestRepository.selectById(id);
470
        if (callbackReq == null) {
471
            LOGGER.warn("Callback request not found for id: {}", id);
472
            return responseSender.ok(false);
473
        }
474
 
475
        // Determine sender type: if userId matches the request creator, it's RETAILER; otherwise INTERNAL
476
        String senderType = (userInfo.getUserId() == callbackReq.getUserId()) ? "RETAILER" : "INTERNAL";
477
        User senderUser = userRepository.selectById(userInfo.getUserId());
478
        String senderName = senderUser != null ? senderUser.getFirstName() : "Unknown";
479
 
480
        LOGGER.info("Adding reply to callback request id: {} by userId: {} senderType: {}", id, userInfo.getUserId(), senderType);
481
 
482
        CallbackRequestReply reply = new CallbackRequestReply();
483
        reply.setCallbackRequestId(id);
484
        reply.setMessage(replyRequest.getMessage());
485
        reply.setSenderType(senderType);
486
        reply.setSenderName(senderName);
487
        reply.setSenderId(userInfo.getUserId());
488
        reply.setCreateTimestamp(LocalDateTime.now());
489
        callbackRequestReplyRepository.persist(reply);
490
 
491
        // Update the parent request's updateTimestamp
492
        callbackReq.setUpdateTimestamp(LocalDateTime.now());
493
        // Mark as unread for the retailer when an internal user replies
494
        if ("INTERNAL".equals(senderType)) {
495
            callbackReq.setUnread(true);
496
        }
497
        callbackRequestRepository.persist(callbackReq);
498
 
499
        LOGGER.info("Reply added with id: {} to callback request id: {}", reply.getId(), id);
500
        return responseSender.ok(true);
501
    }
502
 
35927 vikas 503
    private ContactDetail buildContact(AuthUser authUser, String badge, String badgeColor,
504
                                       String description, boolean showCall, boolean showMessage,
505
                                       boolean showCallback, boolean expanded) {
506
        ContactDetail contact = new ContactDetail();
507
        contact.setId(authUser.getId());
508
        contact.setName(authUser.getFullName());
509
        contact.setInitials(getInitials(authUser.getFirstName(), authUser.getLastName()));
510
        contact.setRole(badge);
511
        contact.setBadge(badge);
512
        contact.setBadgeColor(badgeColor);
513
        contact.setDescription(description);
514
        contact.setPhone("tel:+91" + authUser.getMobileNumber());
515
        contact.setWhatsapp("https://wa.me/91" + authUser.getMobileNumber());
516
        contact.setEmail(authUser.getEmailId());
517
        contact.setShowCall(showCall);
518
        contact.setShowMessage(showMessage);
519
        contact.setShowCallback(showCallback);
520
        contact.setExpanded(expanded);
521
        return contact;
522
    }
523
 
524
    private String getInitials(String firstName, String lastName) {
525
        StringBuilder initials = new StringBuilder();
526
        if (firstName != null && !firstName.isEmpty()) {
527
            initials.append(firstName.charAt(0));
528
        }
529
        if (lastName != null && !lastName.isEmpty()) {
530
            initials.append(lastName.charAt(0));
531
        }
532
        return initials.toString().toUpperCase();
533
    }
35948 vikas 534
 
535
    private String getInitials(String fullName) {
536
        if (fullName == null || fullName.isEmpty()) {
537
            return "";
538
        }
539
        String[] parts = fullName.trim().split("\\s+");
540
        StringBuilder initials = new StringBuilder();
541
        initials.append(parts[0].charAt(0));
542
        if (parts.length > 1) {
543
            initials.append(parts[parts.length - 1].charAt(0));
544
        }
545
        return initials.toString().toUpperCase();
546
    }
35921 vikas 547
}