Subversion Repositories SmartDukaan

Rev

Rev 35601 | Rev 35607 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
24417 govind 1
package com.spice.profitmandi.web.controller;
2
 
3
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
4
import com.spice.profitmandi.common.model.CustomRetailer;
32812 shampa 5
import com.spice.profitmandi.common.model.ProfitMandiConstants;
24620 govind 6
import com.spice.profitmandi.common.util.Utils;
24417 govind 7
import com.spice.profitmandi.dao.entity.auth.AuthUser;
27690 amit.gupta 8
import com.spice.profitmandi.dao.entity.cs.*;
27270 tejbeer 9
import com.spice.profitmandi.dao.entity.dtr.Document;
24417 govind 10
import com.spice.profitmandi.dao.entity.fofo.ActivityType;
11
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
24699 govind 12
import com.spice.profitmandi.dao.enumuration.cs.TicketStatus;
25570 tejbeer 13
import com.spice.profitmandi.dao.model.CreatePositionModel;
24417 govind 14
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
27690 amit.gupta 15
import com.spice.profitmandi.dao.repository.cs.*;
27270 tejbeer 16
import com.spice.profitmandi.dao.repository.dtr.DocumentRepository;
25570 tejbeer 17
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
24417 govind 18
import com.spice.profitmandi.service.authentication.RoleManager;
19
import com.spice.profitmandi.service.user.RetailerService;
20
import com.spice.profitmandi.web.model.LoginDetails;
21
import com.spice.profitmandi.web.util.CookiesProcessor;
22
import com.spice.profitmandi.web.util.MVCResponseSender;
27690 amit.gupta 23
import org.apache.logging.log4j.LogManager;
24
import org.apache.logging.log4j.Logger;
25
import org.springframework.beans.factory.annotation.Autowired;
26
import org.springframework.mail.javamail.JavaMailSender;
27
import org.springframework.stereotype.Controller;
28
import org.springframework.transaction.annotation.Transactional;
29
import org.springframework.ui.Model;
30
import org.springframework.web.bind.annotation.*;
24417 govind 31
 
27690 amit.gupta 32
import javax.servlet.http.HttpServletRequest;
35571 amit 33
import javax.swing.SortOrder;
27690 amit.gupta 34
import java.time.LocalDateTime;
35
import java.util.*;
36
import java.util.stream.Collectors;
37
 
24417 govind 38
@Controller
39
@Transactional(rollbackFor = Throwable.class)
40
public class CsController {
41
 
31762 tejbeer 42
    private static final Logger LOGGER = LogManager.getLogger(CsController.class);
43
    private static final String ACTIVITY_SUBJECT = "Message related ticketId#%s";
44
    private static final String PARTNER_RESOLVED_TICKET_MAIL = "Dear Partner , we have resolved your ticket # %s , request to kindly accept the same. In case you still have any concerns regarding the same pls click on %s so that we can help you.Regards\nSmartdukaan";
45
    private static final String PARTNER_REOPEN = "Dear Partner , Your ticket # %s has been re-opened as per your confirmation & we are committed to resolve it on priority.Regards\nSmartdukaan";
46
    private static final String INTERNAL_REOPEN_MAIL = "Team, Pls note that the Ticket Id %s has been re-opened by %s , pls respond on priority";
47
    private static final String INTERNAL_REOPEN_ACTIVITY_MESSAGE = "Hi,My ticket is not resolved yet,so I have reopened it";
24699 govind 48
 
31762 tejbeer 49
    @Autowired
50
    JavaMailSender mailSender;
24620 govind 51
 
31762 tejbeer 52
    @Autowired
53
    private CsService csService;
24417 govind 54
 
31762 tejbeer 55
    @Autowired
56
    private CookiesProcessor cookiesProcessor;
24417 govind 57
 
31762 tejbeer 58
    @Autowired
59
    private TicketCategoryRepository ticketCategoryRepository;
24417 govind 60
 
31762 tejbeer 61
    @Autowired
62
    private TicketSubCategoryRepository ticketSubCategoryRepository;
24417 govind 63
 
31762 tejbeer 64
    @Autowired
65
    private RegionRepository regionRepository;
24417 govind 66
 
31762 tejbeer 67
    @Autowired
68
    private RetailerService retailerService;
24417 govind 69
 
31762 tejbeer 70
    @Autowired
71
    private MVCResponseSender mvcResponseSender;
24417 govind 72
 
31762 tejbeer 73
    @Autowired
74
    private AuthRepository authRepository;
24417 govind 75
 
31762 tejbeer 76
    @Autowired
77
    private PositionRepository positionRepository;
24417 govind 78
 
31762 tejbeer 79
    @Autowired
80
    private TicketRepository ticketRepository;
24417 govind 81
 
31762 tejbeer 82
    @Autowired
83
    private RoleManager roleManager;
24417 govind 84
 
31762 tejbeer 85
    @Autowired
86
    private ActivityRepository activityRepository;
24417 govind 87
 
31762 tejbeer 88
    @Autowired
89
    private ActivityAttachmentRepository activityAttachmentRepository;
27270 tejbeer 90
 
31762 tejbeer 91
    @Autowired
92
    private TicketAssignedRepository ticketAssignedRepository;
24569 govind 93
 
31762 tejbeer 94
    @Autowired
95
    private PartnerRegionRepository partnerRegionRepository;
24500 govind 96
 
31762 tejbeer 97
    @Autowired
32493 amit.gupta 98
    PartnerPositionRepository partnerPositionRepository;
25570 tejbeer 99
 
31762 tejbeer 100
    @Autowired
101
    FofoStoreRepository fofoStoreRepository;
25570 tejbeer 102
 
31762 tejbeer 103
    @Autowired
104
    DocumentRepository documentRepository;
27270 tejbeer 105
 
31762 tejbeer 106
    @GetMapping(value = "/cs/createCategory")
107
    public String getCreateCategory(HttpServletRequest request, Model model) {
108
        List<TicketCategory> ticketCategories = ticketCategoryRepository.selectAll();
109
        model.addAttribute("ticketCategories", ticketCategories);
110
        return "create-ticket-category";
111
    }
24417 govind 112
 
31762 tejbeer 113
    @PostMapping(value = "/cs/createCategory")
33081 ranu 114
    public String createCategory(HttpServletRequest request,
115
                                 @RequestParam(name = "name") String name,
116
                                 @RequestParam(name = "categoryType") int categoryType,
117
                                 @RequestParam(name = "description") String description,
118
                                 Model model) throws ProfitMandiBusinessException {
31762 tejbeer 119
        TicketCategory ticketCategory = ticketCategoryRepository.selectByName(name);
120
        if (ticketCategory != null) {
121
            throw new ProfitMandiBusinessException("name", name, "already exists!");
122
        }
33081 ranu 123
 
31762 tejbeer 124
        ticketCategory = new TicketCategory();
125
        ticketCategory.setName(name);
126
        ticketCategory.setDescription(description);
33081 ranu 127
 
128
        ticketCategory.setCategoryType(categoryType == 1);
31762 tejbeer 129
        ticketCategoryRepository.persist(ticketCategory);
130
        return "create-ticket-category";
131
    }
24417 govind 132
 
33081 ranu 133
 
31762 tejbeer 134
    @GetMapping(value = "/cs/createSubCategory")
135
    public String getCreateSubCategory(HttpServletRequest request, Model model) {
136
        List<TicketCategory> ticketCategories = ticketCategoryRepository.selectAll();
137
        model.addAttribute("ticketCategories", ticketCategories);
138
        return "create-ticket-sub-category";
139
    }
24417 govind 140
 
31762 tejbeer 141
    @GetMapping(value = "/cs/getSubCategoryByCategoryId")
142
    public String getSubCategoryByCategoryId(HttpServletRequest request, @RequestParam(name = "ticketCategoryId", defaultValue = "") int ticketCategoryId, Model model) {
143
        List<TicketSubCategory> ticketSubCategories = ticketSubCategoryRepository.selectAll(ticketCategoryId);
144
        TicketCategory ticketCategory = ticketCategoryRepository.selectById(ticketCategoryId);
33081 ranu 145
        LOGGER.info("ticketSubCategories {}", ticketSubCategories);
146
        LOGGER.info("ticketCategory {}", ticketCategory);
31762 tejbeer 147
        model.addAttribute("ticketSubCategories", ticketSubCategories);
148
        model.addAttribute("ticketCategory", ticketCategory);
149
        return "ticket-sub-category";
150
    }
24417 govind 151
 
31762 tejbeer 152
    @PostMapping(value = "/cs/createSubCategory")
153
    public String createSubCategory(HttpServletRequest request, @RequestParam(name = "categoryId", defaultValue = "0") int categoryId, @RequestParam(name = "name") String name, @RequestParam(name = "description") String description, Model model) throws ProfitMandiBusinessException {
24417 govind 154
 
31762 tejbeer 155
        TicketSubCategory ticketSubCategory = ticketSubCategoryRepository.selectTicketSubCategory(categoryId, name);
156
        if (ticketSubCategory != null) {
157
            throw new ProfitMandiBusinessException("name & categoryId", name + "  " + categoryId, "already exists!");
158
        }
24417 govind 159
 
31762 tejbeer 160
        ticketSubCategory = new TicketSubCategory();
161
        ticketSubCategory.setCategoryId(categoryId);
162
        ticketSubCategory.setName(name);
163
        ticketSubCategory.setDescription(description);
164
        ticketSubCategoryRepository.persist(ticketSubCategory);
165
        return "create-ticket-sub-category";
166
    }
24417 govind 167
 
31762 tejbeer 168
    @GetMapping(value = "/cs/createRegion")
169
    public String createRegion(HttpServletRequest request, Model model) {
170
        List<Region> regions = regionRepository.selectAll();
171
        model.addAttribute("regions", regions);
172
        return "create-region";
173
    }
24417 govind 174
 
31762 tejbeer 175
    @PostMapping(value = "/cs/createRegion")
176
    public String createRegion(HttpServletRequest request, @RequestParam(name = "name") String name, @RequestParam(name = "description") String description, Model model) throws Exception {
177
        Region region = regionRepository.selectByName(name);
178
        if (region != null) {
179
            throw new ProfitMandiBusinessException("name", name, "already exists!");
180
        }
181
        region = new Region();
182
        region.setName(name);
183
        region.setDescription(description);
184
        regionRepository.persist(region);
185
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
186
        return "response";
187
    }
24417 govind 188
 
31762 tejbeer 189
    @GetMapping(value = "/cs/getPartners")
33244 ranu 190
    public String getPartners(HttpServletRequest request, @RequestParam(name = "regionId", defaultValue = "0") int regionId, Model model) throws ProfitMandiBusinessException {
31762 tejbeer 191
        List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId()).collect(Collectors.toList());
192
        List<Integer> addedfofoIds = partnerRegionRepository.selectByRegionId(regionId).stream().map(x -> x.getFofoId()).collect(Collectors.toList());
30426 tejbeer 193
 
31762 tejbeer 194
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
195
        Map<Integer, CustomRetailer> fofoRetailers = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null).collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
196
        model.addAttribute("fofoRetailers", fofoRetailers);
197
        model.addAttribute("addedfofoIds", addedfofoIds);
198
        return "added-region-partners";
199
    }
24569 govind 200
 
31762 tejbeer 201
    @GetMapping(value = "/cs/getPartnersByRegion")
33244 ranu 202
    public String getPartnersByRegion(HttpServletRequest request, @RequestParam(name = "regionId", defaultValue = "0") int regionId, Model model) throws ProfitMandiBusinessException {
31762 tejbeer 203
        List<Integer> fofoIds = null;
204
        fofoIds = partnerRegionRepository.selectByRegionId(regionId).stream().map(x -> x.getFofoId()).collect(Collectors.toList());
25570 tejbeer 205
 
31762 tejbeer 206
        if (fofoIds.contains(0)) {
207
            fofoIds = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive()).collect(Collectors.toList()).stream().map(x -> x.getId()).collect(Collectors.toList());
25570 tejbeer 208
 
31762 tejbeer 209
        }
210
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
25570 tejbeer 211
 
31762 tejbeer 212
        Map<Integer, CustomRetailer> fofoRetailers = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null).collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
213
        model.addAttribute("fofoRetailers", fofoRetailers);
214
        return "added-subregion-partners";
215
    }
25570 tejbeer 216
 
31762 tejbeer 217
    @GetMapping(value = "/cs/createPartnerRegion")
218
    public String createPartnerRegion(HttpServletRequest request, Model model) {
219
        List<Region> regions = regionRepository.selectAll();
220
        model.addAttribute("regions", regions);
221
        return "create-partner-region";
222
    }
24417 govind 223
 
31762 tejbeer 224
    @PostMapping(value = "/cs/createPartnerRegion")
225
    public String createPartnerRegion(HttpServletRequest request, @RequestParam(name = "regionId") int regionId, @RequestBody List<Integer> selectedFofoIds, Model model) throws Exception {
226
        partnerRegionRepository.delete(regionId);
227
        LOGGER.info("successfully removed");
228
        LOGGER.info(selectedFofoIds.size());
229
        csService.addPartnerToRegion(regionId, selectedFofoIds);
230
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
231
        return "response";
232
    }
24417 govind 233
 
31762 tejbeer 234
    @GetMapping(value = "/cs/getPosition")
33244 ranu 235
    public String getPosition(HttpServletRequest request, @RequestParam int positionId, Model model) throws ProfitMandiBusinessException {
27410 tejbeer 236
 
31762 tejbeer 237
        Position position = positionRepository.selectById(positionId);
27410 tejbeer 238
 
31762 tejbeer 239
        List<CustomRetailer> positionIdCustomRetailer = csService.getPositionCustomRetailerMap(Arrays.asList(position)).get(position.getId());
27410 tejbeer 240
 
31762 tejbeer 241
        Map<Integer, CustomRetailer> regionRetailerMap = csService.getRegionPartners(Arrays.asList(position)).get(position.getRegionId()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
27410 tejbeer 242
 
31762 tejbeer 243
        model.addAttribute("position", position);
244
        model.addAttribute("regionRetailerMap", regionRetailerMap);
245
        model.addAttribute("positionIdCustomRetailer", positionIdCustomRetailer);
27410 tejbeer 246
 
31762 tejbeer 247
        return "position-partner";
248
    }
27410 tejbeer 249
 
31762 tejbeer 250
    @GetMapping(value = "/cs/createPosition")
251
    public String createPosition(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "10") int limit, Model model) {
252
        List<AuthUser> authUsers = authRepository.selectAllActiveUser();
253
        List<TicketCategory> ticketCategories = ticketCategoryRepository.selectAll();
254
        List<Region> regions = regionRepository.selectAll();
255
        model.addAttribute("escalationTypes", EscalationType.values());
256
        model.addAttribute("authUsers", authUsers);
257
        model.addAttribute("ticketCategories", ticketCategories);
258
        model.addAttribute("regions", regions);
24500 govind 259
 
31762 tejbeer 260
        List<Position> positions = positionRepository.selectAllPosition();
261
        LOGGER.info("positions" + positions);
30426 tejbeer 262
 
31762 tejbeer 263
        Map<Integer, AuthUser> authUserIdAndAuthUserMap = csService.getAuthUserIdAndAuthUserMapUsingPositions(positions);
264
        Map<Integer, TicketCategory> categoryIdAndCategoryMap = csService.getCategoryIdAndCategoryUsingPositions(positions);
265
        Map<Integer, Region> regionIdAndRegionMap = csService.getRegionIdAndRegionMap(positions);
25570 tejbeer 266
 
27410 tejbeer 267
//	    Map<Integer, List<CustomRetailer>> positionIdAndpartnerRegionMap = csService
268
//			.getpositionIdAndpartnerRegionMap(positions);
25570 tejbeer 269
 
27410 tejbeer 270
//	     Map<Integer, List<CustomRetailer>> addedpositionIdAndCustomRetailerMap = csService
271
//				.getPositionCustomRetailerMap(positions);
272
//		LOGGER.info("fofoIdAndCustomRetailerMap" + addedpositionIdAndCustomRetailerMap);
24500 govind 273
 
31762 tejbeer 274
        model.addAttribute("start", offset + 1);
30426 tejbeer 275
 
31762 tejbeer 276
        model.addAttribute("positions", positions);
277
        model.addAttribute("authUserIdAndAuthUserMap", authUserIdAndAuthUserMap);
278
        model.addAttribute("categoryIdAndCategoryMap", categoryIdAndCategoryMap);
279
        model.addAttribute("regionIdAndRegionMap", regionIdAndRegionMap);
280
        // model.addAttribute("positionIdAndCustomRetailerMap",
281
        // addedpositionIdAndCustomRetailerMap);
282
        // model.addAttribute("positionIdAndpartnerRegionMap",
27410 tejbeer 283
// positionIdAndpartnerRegionMap);
25570 tejbeer 284
 
31762 tejbeer 285
        return "create-position";
286
    }
24500 govind 287
 
31762 tejbeer 288
    @GetMapping(value = "/cs/position-paginated")
289
    public String positionPaginated(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "10") int limit, Model model) {
24500 govind 290
 
31762 tejbeer 291
        List<Position> positions = positionRepository.selectAll(offset, limit);
292
        Map<Integer, AuthUser> authUserIdAndAuthUserMap = csService.getAuthUserIdAndAuthUserMapUsingPositions(positions);
293
        Map<Integer, TicketCategory> categoryIdAndCategoryMap = csService.getCategoryIdAndCategoryUsingPositions(positions);
294
        Map<Integer, Region> regionIdAndRegionMap = csService.getRegionIdAndRegionMap(positions);
295
        /*
296
         * Map<Integer, List<CustomRetailer>> positionIdAndpartnerRegionMap = csService
297
         * .getpositionIdAndpartnerRegionMap(positions);
298
         * 
299
         * Map<Integer, List<CustomRetailer>> addedpositionIdAndCustomRetailerMap =
300
         * csService .getPositionCustomRetailerMap(positions);
301
         */
25570 tejbeer 302
 
31762 tejbeer 303
        model.addAttribute("positions", positions);
304
        model.addAttribute("authUserIdAndAuthUserMap", authUserIdAndAuthUserMap);
305
        model.addAttribute("categoryIdAndCategoryMap", categoryIdAndCategoryMap);
306
        model.addAttribute("regionIdAndRegionMap", regionIdAndRegionMap);
307
        // model.addAttribute("positionIdAndCustomRetailerMap",
308
        // addedpositionIdAndCustomRetailerMap);
309
        // model.addAttribute("positionIdAndpartnerRegionMap",
310
        // positionIdAndpartnerRegionMap);
25570 tejbeer 311
 
31762 tejbeer 312
        return "position-paginated";
313
    }
24417 govind 314
 
31762 tejbeer 315
    @PostMapping(value = "/cs/createPosition")
316
    public String createPosition(HttpServletRequest request, @RequestBody CreatePositionModel createPositionModel, Model model) throws Exception {
24417 govind 317
 
35570 amit 318
        LOGGER.info("partnerPosition" + createPositionModel.isTicketAssigned());
25570 tejbeer 319
 
35570 amit 320
        // Validate authUserId exists
321
        int authUserId = createPositionModel.getAuthUserId();
322
        if (authUserId <= 0 || authRepository.selectById(authUserId) == null) {
323
            throw new ProfitMandiBusinessException("Position", authUserId, "Invalid authUserId");
324
        }
325
 
326
        // Validate categoryId exists (0 means "All Categories")
327
        int categoryId = createPositionModel.getCategoryId();
328
        if (categoryId > 0 && ticketCategoryRepository.selectById(categoryId) == null) {
329
            throw new ProfitMandiBusinessException("Position", categoryId, "Invalid categoryId");
330
        }
331
 
332
        // Validate regionId exists (0 or 5 typically means "All Partners/Regions")
333
        int regionId = createPositionModel.getRegionId();
334
        if (regionId > 0 && regionId != 5 && regionRepository.selectById(regionId) == null) {
335
            throw new ProfitMandiBusinessException("Position", regionId, "Invalid regionId");
336
        }
337
 
35589 amit 338
        // Validate fofoIds exist (0 means "All Partners")
35570 amit 339
        List<Integer> fofoIds = createPositionModel.getFofoIds();
35590 amit 340
        if (fofoIds == null || fofoIds.isEmpty()) {
341
            throw new ProfitMandiBusinessException("Position", 0, "At least one partner must be specified");
342
        }
343
        boolean hasAllPartners = fofoIds.contains(0);
344
        if (hasAllPartners && fofoIds.size() > 1) {
345
            throw new ProfitMandiBusinessException("Position", 0, "Cannot mix 'All Partners' (0) with specific partner IDs");
346
        }
347
        if (!hasAllPartners) {
348
            Map<Integer, CustomRetailer> validRetailers = retailerService.getFofoRetailers(false);
349
            for (int fofoId : fofoIds) {
350
                if (!validRetailers.containsKey(fofoId)) {
351
                    throw new ProfitMandiBusinessException("Position", fofoId, "Invalid fofoId");
35570 amit 352
                }
353
            }
354
        }
355
 
356
        Position position = positionRepository.selectPosition(authUserId, categoryId, regionId, createPositionModel.getEscalationType());
31762 tejbeer 357
        if (position == null) {
358
            position = new Position();
35570 amit 359
            position.setAuthUserId(authUserId);
360
            position.setCategoryId(categoryId);
31762 tejbeer 361
            position.setEscalationType(createPositionModel.getEscalationType());
35570 amit 362
            position.setRegionId(regionId);
31762 tejbeer 363
            position.setCreateTimestamp(LocalDateTime.now());
364
            position.setTicketAssignee(createPositionModel.isTicketAssigned());
365
            positionRepository.persist(position);
25570 tejbeer 366
 
35570 amit 367
            if (fofoIds != null) {
368
                for (int fofoId : fofoIds) {
369
                    PartnerPosition partnerPosition = new PartnerPosition();
370
                    partnerPosition.setFofoId(fofoId);
371
                    partnerPosition.setRegionId(regionId);
372
                    partnerPosition.setPositionId(position.getId());
373
                    partnerPositionRepository.persist(partnerPosition);
374
                    LOGGER.info("partnerPosition" + partnerPosition);
375
                }
31762 tejbeer 376
            }
24417 govind 377
 
31762 tejbeer 378
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
379
        } else {
35570 amit 380
            throw new ProfitMandiBusinessException("Position", authUserId, "already exists!");
31762 tejbeer 381
        }
382
        return "response";
383
    }
25570 tejbeer 384
 
31762 tejbeer 385
    @PostMapping(value = "/cs/updatePartnerPosition")
386
    public String updatePartnerPosition(HttpServletRequest request, @RequestParam(name = "regionId") int regionId, @RequestBody List<Integer> selectedFofoIds, @RequestParam(name = "positionId") int positionId, Model model) throws Exception {
25570 tejbeer 387
 
35571 amit 388
        // Validate positionId exists
389
        Position position = positionRepository.selectById(positionId);
390
        if (position == null) {
391
            throw new ProfitMandiBusinessException("Position", positionId, "Position not found");
392
        }
393
 
394
        // Validate regionId exists (0 or 5 typically means "All Partners/Regions")
395
        if (regionId > 0 && regionId != 5 && regionRepository.selectById(regionId) == null) {
396
            throw new ProfitMandiBusinessException("Position", regionId, "Invalid regionId");
397
        }
398
 
35589 amit 399
        // Validate fofoIds exist (0 means "All Partners")
35590 amit 400
        if (selectedFofoIds == null || selectedFofoIds.isEmpty()) {
401
            throw new ProfitMandiBusinessException("Position", 0, "At least one partner must be specified");
402
        }
403
        boolean hasAllPartners = selectedFofoIds.contains(0);
404
        if (hasAllPartners && selectedFofoIds.size() > 1) {
405
            throw new ProfitMandiBusinessException("Position", 0, "Cannot mix 'All Partners' (0) with specific partner IDs");
406
        }
407
        if (!hasAllPartners) {
408
            Map<Integer, CustomRetailer> validRetailers = retailerService.getFofoRetailers(false);
409
            for (int fofoId : selectedFofoIds) {
410
                if (!validRetailers.containsKey(fofoId)) {
411
                    throw new ProfitMandiBusinessException("Position", fofoId, "Invalid fofoId");
35571 amit 412
                }
413
            }
414
        }
415
 
32493 amit.gupta 416
        partnerPositionRepository.delete(positionId);
35571 amit 417
        if (selectedFofoIds != null) {
418
            for (int fofoId : selectedFofoIds) {
419
                PartnerPosition partnerPosition = new PartnerPosition();
420
                partnerPosition.setFofoId(fofoId);
421
                partnerPosition.setRegionId(regionId);
422
                partnerPosition.setPositionId(positionId);
423
                partnerPositionRepository.persist(partnerPosition);
424
            }
31762 tejbeer 425
        }
25570 tejbeer 426
 
31762 tejbeer 427
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
25570 tejbeer 428
 
31762 tejbeer 429
        return "response";
430
    }
24417 govind 431
 
31762 tejbeer 432
    @GetMapping(value = "/cs/createTicket")
433
    public String createTicket(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
434
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
35594 amit 435
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
436
        boolean isCrmUser = false;
437
 
31762 tejbeer 438
        List<TicketCategory> ticketCategories = csService.getAllTicketCategotyFromSubCategory();
35594 amit 439
 
440
        if (isAdmin) {
441
            AuthUser currentAuthUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
442
            isCrmUser = positionRepository.hasCategory(currentAuthUser.getId(), ProfitMandiConstants.TICKET_CATEGORY_CRM);
443
 
444
            // CRM users should not see Sales and RBM categories
445
            if (isCrmUser) {
446
                ticketCategories = ticketCategories.stream()
447
                        .filter(tc -> tc.getId() != ProfitMandiConstants.TICKET_CATEGORY_SALES
448
                                && tc.getId() != ProfitMandiConstants.TICKET_CATEGORY_RBM)
449
                        .collect(Collectors.toList());
450
            }
451
        }
452
 
453
        model.addAttribute("roleType", isAdmin);
31762 tejbeer 454
        model.addAttribute("ticketCategories", ticketCategories);
35594 amit 455
        model.addAttribute("isCrmUser", isCrmUser);
31762 tejbeer 456
        return "create-ticket";
457
    }
24417 govind 458
 
31762 tejbeer 459
    @GetMapping(value = "/cs/getSubCategoriesByCategoryId")
35594 amit 460
    public String getSubCategoriesByCategoryId(HttpServletRequest request, @RequestParam(name = "categoryId", defaultValue = "0") int categoryId, Model model) throws ProfitMandiBusinessException {
461
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
462
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
463
        boolean isCrmUser = false;
464
 
465
        if (isAdmin) {
466
            AuthUser currentAuthUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
467
            isCrmUser = positionRepository.hasCategory(currentAuthUser.getId(), ProfitMandiConstants.TICKET_CATEGORY_CRM);
468
        }
469
 
31830 amit.gupta 470
        List<TicketSubCategory> ticketSubCategories = ticketSubCategoryRepository.selectAllVisible(categoryId);
35594 amit 471
 
472
        // CRM users should not see Sales Escalation and RBM Escalation subcategories
473
        if (isCrmUser) {
474
            ticketSubCategories = ticketSubCategories.stream()
475
                    .filter(tsc -> tsc.getId() != ProfitMandiConstants.TICKET_SUBCATEGORY_SALES_ESCALATION
476
                            && tsc.getId() != ProfitMandiConstants.TICKET_SUBCATEGORY_RBM_ESCALATION)
477
                    .collect(Collectors.toList());
478
        }
479
 
31762 tejbeer 480
        LOGGER.info(ticketSubCategories);
481
        model.addAttribute("ticketSubCategories", ticketSubCategories);
482
        return "ticket-sub-categories";
483
    }
24417 govind 484
 
24791 govind 485
 
31762 tejbeer 486
    @GetMapping(value = "/cs/getEscalationTypeByCategoryId")
487
    public String getEscalationTypeByCategoryId(HttpServletRequest request, @RequestParam(name = "categoryId", defaultValue = "0") int categoryId, @RequestParam(name = "authId", defaultValue = "0") int authId, Model model) {
488
        List<Position> positions = positionRepository.selectPositionbyCategoryIdAndAuthId(categoryId, authId);
489
        List<EscalationType> escalationTypes = new ArrayList<>();
24791 govind 490
 
31762 tejbeer 491
        if (!positions.isEmpty()) {
492
            escalationTypes = positions.stream().map(x -> x.getEscalationType()).distinct().collect(Collectors.toList());
493
        }
24620 govind 494
 
31762 tejbeer 495
        LOGGER.info("escalationTypes {}", escalationTypes);
24500 govind 496
 
31762 tejbeer 497
        model.addAttribute("escalationTypes", escalationTypes);
498
        return "ticket-escalationtype";
499
    }
24500 govind 500
 
24824 govind 501
 
31762 tejbeer 502
    @GetMapping(value = "/cs/getCategoriesByAuthId")
503
    public String getCategoriesByAuthId(HttpServletRequest request, @RequestParam(name = "authId", defaultValue = "0") int authId, Model model) {
24824 govind 504
 
24787 govind 505
 
31762 tejbeer 506
        List<Position> positions = positionRepository.selectPositionByAuthId(authId);
24791 govind 507
 
31762 tejbeer 508
        LOGGER.info("positions {}", positions);
24417 govind 509
 
31762 tejbeer 510
        List<TicketCategory> ticketCategories = new ArrayList<TicketCategory>();
24417 govind 511
 
31762 tejbeer 512
        if (!positions.isEmpty()) {
24417 govind 513
 
31762 tejbeer 514
            List<Integer> categoryIds = positions.stream().map(x -> x.getCategoryId()).collect(Collectors.toList());
515
            ticketCategories = ticketCategoryRepository.selectAll(categoryIds);
516
        }
517
        LOGGER.info("ticketCategories {}", ticketCategories);
518
        model.addAttribute("ticketCategories", ticketCategories);
519
        return "ticket-categories";
520
    }
27270 tejbeer 521
 
31762 tejbeer 522
    @PostMapping(value = "/cs/createTicket")
523
    public String createTicket(HttpServletRequest request, @RequestParam(name = "categoryId") int categoryId, @RequestParam(name = "subCategoryId") int subCategoryId, @RequestParam(name = "message") String message, Model model) throws Exception {
524
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
525
        List<Ticket> tickets = ticketRepository.selectAllResolvedMarkedTicketByCreator(loginDetails.getFofoId());
526
        if (tickets.size() > 3 || tickets.size() == 3) {
527
            model.addAttribute("response1", mvcResponseSender.createResponseString(false));
528
        } else {
529
            csService.createTicket(loginDetails.getFofoId(), categoryId, subCategoryId, message);
530
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
531
        }
532
        return "response";
533
    }
27270 tejbeer 534
 
31762 tejbeer 535
    @GetMapping(value = "/cs/myticket")
536
    public String getTicket(HttpServletRequest request, @RequestParam(name = "orderby", defaultValue = "DESCENDING") SortOrder sortOrder, @RequestParam(name = "ticketStatus", defaultValue = "OPENED") TicketStatus ticketStatus, @RequestParam(name = "ticketSearchType", defaultValue = "") TicketSearchType ticketSearchType, @RequestParam(name = "searchTerm", defaultValue = "0") int searchTerm, Model model) throws ProfitMandiBusinessException {
537
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
538
        List<Ticket> tickets = null;
539
        List<TicketAssigned> ticketAssigneds = null;
540
        long size = 0;
541
        Map<Integer, AuthUser> authUserIdAndAuthUserMap = null;
35569 amit 542
        boolean isAdmin = roleManager.isAdmin(new HashSet<>(loginDetails.getRoleIds()));
543
        AuthUser currentAuthUser = isAdmin ? authRepository.selectByEmailOrMobile(loginDetails.getEmailId()) : null;
544
 
35592 amit 545
        // Check if user is CRM category - CRM users see ALL tickets to handle partner communications
546
        boolean isCrmUser = isAdmin && currentAuthUser != null && positionRepository.hasCategory(currentAuthUser.getId(), ProfitMandiConstants.TICKET_CATEGORY_CRM);
35603 amit 547
        // Check if user is Sales category - Sales users can resolve their own Sales tickets
548
        boolean isSalesUser = isAdmin && currentAuthUser != null && positionRepository.hasCategory(currentAuthUser.getId(), ProfitMandiConstants.TICKET_CATEGORY_SALES);
549
        // Check if user is RBM category - RBM users can resolve their own RBM tickets
550
        boolean isRbmUser = isAdmin && currentAuthUser != null && positionRepository.hasCategory(currentAuthUser.getId(), ProfitMandiConstants.TICKET_CATEGORY_RBM);
35592 amit 551
 
35569 amit 552
        if (isAdmin) {
553
            int authUserId = currentAuthUser.getId();
35592 amit 554
 
555
            if (isCrmUser) {
35601 amit 556
                // CRM users see ALL tickets EXCEPT Sales Escalation and RBM Escalation subcategories
31762 tejbeer 557
                if (ticketStatus.equals(TicketStatus.RESOLVED)) {
35592 amit 558
                    tickets = ticketRepository.selectAllTickets(Optional.empty(), sortOrder, ticketSearchType, searchTerm);
31762 tejbeer 559
                } else {
35592 amit 560
                    tickets = ticketRepository.selectAllTickets(Optional.of(TicketStatus.CLOSED.equals(ticketStatus)), sortOrder, ticketSearchType, searchTerm);
31762 tejbeer 561
                }
35601 amit 562
 
563
                // Filter out Sales Escalation and RBM Escalation subcategory tickets for CRM users
564
                tickets = tickets.stream()
565
                        .filter(t -> t.getSubCategoryId() != ProfitMandiConstants.TICKET_SUBCATEGORY_SALES_ESCALATION
566
                                && t.getSubCategoryId() != ProfitMandiConstants.TICKET_SUBCATEGORY_RBM_ESCALATION)
567
                        .collect(Collectors.toList());
568
                size = tickets.size();
31762 tejbeer 569
            } else {
35592 amit 570
                // Non-CRM admins see only tickets assigned to them
571
                if (ticketSearchType == null) {
572
                    if (ticketStatus.equals(TicketStatus.RESOLVED)) {
573
                        tickets = ticketRepository.selectAllByAssignee(authUserId, Optional.empty(), sortOrder, null, searchTerm);
574
                        size = ticketRepository.selectAllCountByAssignee(authUserId, Optional.empty(), null, searchTerm);
575
                    } else {
576
                        tickets = ticketRepository.selectAllByAssignee(authUserId, Optional.of(TicketStatus.CLOSED.equals(ticketStatus)), sortOrder, null, searchTerm);
577
                        size = ticketRepository.selectAllCountByAssignee(authUserId, Optional.of(TicketStatus.CLOSED.equals(ticketStatus)), null, searchTerm);
578
                    }
31762 tejbeer 579
                } else {
35592 amit 580
                    if (ticketStatus.equals(TicketStatus.RESOLVED)) {
581
                        tickets = ticketRepository.selectAllByAssignee(authUserId, Optional.empty(), sortOrder, ticketSearchType, searchTerm);
582
                        size = ticketRepository.selectAllCountByAssignee(authUserId, Optional.empty(), ticketSearchType, searchTerm);
583
                    } else {
584
                        tickets = ticketRepository.selectAllByAssignee(authUserId, Optional.of(TicketStatus.CLOSED.equals(ticketStatus)), sortOrder, ticketSearchType, searchTerm);
585
                        size = ticketRepository.selectAllCountByAssignee(authUserId, Optional.of(TicketStatus.CLOSED.equals(ticketStatus)), ticketSearchType, searchTerm);
586
                    }
31762 tejbeer 587
                }
588
            }
589
            // LOGGER.info(size + "size");
590
            if (tickets.size() > 0) {
591
                ticketAssigneds = ticketAssignedRepository.selectByTicketIds(tickets.stream().map(x -> x.getId()).collect(Collectors.toList()));
592
                authUserIdAndAuthUserMap = csService.getAuthUserIdAndAuthUserMap(ticketAssigneds);
593
                Map<Integer, CustomRetailer> fofoIdsAndCustomRetailer = csService.getPartnerByFofoIds(tickets);
594
                model.addAttribute("fofoIdsAndCustomRetailer", fofoIdsAndCustomRetailer);
595
            }
24500 govind 596
 
31762 tejbeer 597
        } else {
598
            tickets = ticketRepository.selectAllByCreator(loginDetails.getFofoId(), Optional.of(TicketStatus.OPENED.equals(ticketStatus)), sortOrder);
599
            size = ticketRepository.selectAllCountByCreator(loginDetails.getFofoId(), Optional.of(TicketStatus.OPENED.equals(ticketStatus)));
600
        }
601
        authUserIdAndAuthUserMap = csService.getTicketIdAndAuthUserMapUsingTickets(tickets);
35571 amit 602
        if (authUserIdAndAuthUserMap == null) {
603
            authUserIdAndAuthUserMap = new HashMap<>();
604
        }
24620 govind 605
 
31762 tejbeer 606
        model.addAttribute("size", size);
35569 amit 607
        model.addAttribute("roleType", isAdmin);
35592 amit 608
        // isCrmUser already calculated at start of method
35569 amit 609
        model.addAttribute("isCrmUser", isCrmUser);
35603 amit 610
        model.addAttribute("isSalesUser", isSalesUser);
611
        model.addAttribute("salesCategoryId", ProfitMandiConstants.TICKET_CATEGORY_SALES);
612
        model.addAttribute("isRbmUser", isRbmUser);
613
        model.addAttribute("rbmCategoryId", ProfitMandiConstants.TICKET_CATEGORY_RBM);
24500 govind 614
 
31762 tejbeer 615
        List<Integer> subCategoryIds = tickets.stream().map(x -> x.getSubCategoryId()).collect(Collectors.toList());
616
        Map<Integer, TicketSubCategory> subCategoryIdAndSubCategoryMap = csService.getSubCategoryIdAndSubCategoryMap(subCategoryIds);
35571 amit 617
        if (subCategoryIdAndSubCategoryMap == null) {
618
            subCategoryIdAndSubCategoryMap = new HashMap<>();
619
        }
24747 govind 620
 
31762 tejbeer 621
        Map<Integer, TicketCategory> subCategoryIdAndCategoryMap = csService.getSubCategoryIdAndCategoryMap(subCategoryIds);
35571 amit 622
        if (subCategoryIdAndCategoryMap == null) {
623
            subCategoryIdAndCategoryMap = new HashMap<>();
624
        }
27318 amit.gupta 625
 
31762 tejbeer 626
        List<Integer> ticketIds = tickets.stream().map(x -> x.getId()).collect(Collectors.toList());
24500 govind 627
 
35569 amit 628
        Map<Integer, List<Activity>> activityMap = new HashMap<>();
33864 ranu 629
        Map<Integer, List<Activity>> activityMapWithActivityId = new HashMap<>();
35569 amit 630
        Map<Integer, AuthUser> authUserMap = new HashMap<>();
24500 govind 631
 
31762 tejbeer 632
        if (!ticketIds.isEmpty()) {
35569 amit 633
            // Fetch activities once and group by both ticketId and activityId
634
            List<Activity> allActivities = activityRepository.selectAll(ticketIds);
635
            activityMap = allActivities.stream().collect(Collectors.groupingBy(Activity::getTicketId));
636
            activityMapWithActivityId = allActivities.stream().collect(Collectors.groupingBy(Activity::getId));
24787 govind 637
 
35569 amit 638
            // Only fetch AuthUsers who created activities (instead of all users)
639
            Set<Integer> activityCreatorIds = allActivities.stream()
640
                    .map(Activity::getCreatedBy)
641
                    .filter(id -> id > 0)
642
                    .collect(Collectors.toSet());
643
            if (!activityCreatorIds.isEmpty()) {
644
                authUserMap = authRepository.selectByIds(new ArrayList<>(activityCreatorIds))
645
                        .stream().collect(Collectors.toMap(AuthUser::getId, x -> x));
646
            }
31762 tejbeer 647
        }
24787 govind 648
 
31762 tejbeer 649
        model.addAttribute("tickets", tickets);
650
        model.addAttribute("resolved", ActivityType.RESOLVED);
651
        model.addAttribute("resolved-accepted", ActivityType.RESOLVED_ACCEPTED);
652
        model.addAttribute("resolved-rejected", ActivityType.RESOLVED_REJECTED);
653
        model.addAttribute("authUserIdAndAuthUserMap", authUserIdAndAuthUserMap);
654
        model.addAttribute("subCategoryIdAndSubCategoryMap", subCategoryIdAndSubCategoryMap);
27318 amit.gupta 655
 
31762 tejbeer 656
        model.addAttribute("subCategoryIdAndCategoryMap", subCategoryIdAndCategoryMap);
657
        model.addAttribute("activityMap", activityMap);
33864 ranu 658
        model.addAttribute("authUserMap", authUserMap);
659
        model.addAttribute("activityMapWithActivityId", activityMapWithActivityId);
24500 govind 660
 
31762 tejbeer 661
        model.addAttribute("ticketStatusValues", TicketStatus.values());
662
        model.addAttribute("orderByValues", SortOrder.values());
663
        model.addAttribute("selectedticketStatus", ticketStatus);
664
        model.addAttribute("selectedorderby", sortOrder);
665
        model.addAttribute("ticketSearchTypes", TicketSearchType.values());
666
        model.addAttribute("ticketSearchType", ticketSearchType);
667
        model.addAttribute("searchTerm", searchTerm);
668
        return "ticket";
669
    }
24500 govind 670
 
27124 amit.gupta 671
 
31762 tejbeer 672
    @GetMapping(value = "/cs/getActivities")
673
    public String getActivity(HttpServletRequest request, @RequestParam(name = "ticketId", defaultValue = "0") int ticketId, Model model) throws Exception {
35592 amit 674
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
675
        Ticket ticket = ticketRepository.selectById(ticketId);
676
 
677
        if (ticket == null) {
678
            throw new ProfitMandiBusinessException("Ticket", ticketId, "Ticket not found");
679
        }
680
 
681
        // Authorization check: verify user has access to this ticket
682
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
683
        if (!isAdmin) {
684
            // Partners can only view their own tickets
685
            if (ticket.getFofoId() != loginDetails.getFofoId()) {
686
                throw new ProfitMandiBusinessException("Ticket", ticketId, "You do not have permission to view this ticket");
687
            }
688
        } else {
689
            // Admins must be assigned to the ticket OR be CRM user OR be in the escalation chain
690
            AuthUser currentAuthUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
691
            boolean isCrmUser = positionRepository.hasCategory(currentAuthUser.getId(), ProfitMandiConstants.TICKET_CATEGORY_CRM);
692
 
693
            if (!isCrmUser) {
694
                // Check if user is assigned or in escalation chain
695
                List<TicketAssigned> assignments = ticketAssignedRepository.selectByTicketIds(Arrays.asList(ticketId));
696
                boolean isAssigned = assignments.stream().anyMatch(ta -> ta.getAssineeId() == currentAuthUser.getId() || ta.getManagerId() == currentAuthUser.getId());
697
                boolean isInEscalationChain = ticket.getL1AuthUser() == currentAuthUser.getId() ||
698
                        ticket.getL2AuthUser() == currentAuthUser.getId() ||
699
                        ticket.getL3AuthUser() == currentAuthUser.getId() ||
700
                        ticket.getL4AuthUser() == currentAuthUser.getId() ||
701
                        ticket.getL5AuthUser() == currentAuthUser.getId();
702
 
703
                if (!isAssigned && !isInEscalationChain) {
704
                    throw new ProfitMandiBusinessException("Ticket", ticketId, "You do not have permission to view this ticket");
705
                }
706
            }
707
        }
708
 
31762 tejbeer 709
        List<Activity> allactivities = activityRepository.selectAll(ticketId);
35570 amit 710
 
711
        // Batch fetch all documents for attachments (fix N+1 query)
712
        List<Integer> documentIds = allactivities.stream()
713
                .flatMap(a -> a.getActivityAttachment().stream())
714
                .map(ActivityAttachment::getDocumentId)
715
                .distinct()
716
                .collect(Collectors.toList());
717
 
718
        Map<Integer, Document> documentMap = Collections.emptyMap();
719
        if (!documentIds.isEmpty()) {
720
            documentMap = documentRepository.selectByIds(documentIds).stream()
721
                    .collect(Collectors.toMap(Document::getId, d -> d));
722
        }
723
 
724
        // Set document names transiently (do not persist during GET)
725
        for (Activity activity : allactivities) {
726
            for (ActivityAttachment attachment : activity.getActivityAttachment()) {
727
                Document document = documentMap.get(attachment.getDocumentId());
728
                if (document != null) {
729
                    attachment.setDocumentName(document.getDisplayName());
730
                }
31762 tejbeer 731
            }
732
        }
733
        List<Activity> activities = null;
35592 amit 734
        if (isAdmin) {
31762 tejbeer 735
            Set<Integer> authUserIds = allactivities.stream().map(x -> x.getCreatedBy()).collect(Collectors.toSet());
35395 amit 736
            List<AuthUser> users = authRepository.selectByIds(new ArrayList<>(authUserIds));
31762 tejbeer 737
            Map<Integer, String> authUserNameMap = users.stream().collect(Collectors.toMap(AuthUser::getId, x -> x.getFirstName() + " " + x.getLastName()));
738
            allactivities.stream().forEach(x -> x.setName(authUserNameMap.get(x.getCreatedBy())));
739
            activities = allactivities;
740
        } else {
741
            activities = allactivities.stream().filter(x -> ActivityType.PARTNER_ACTIVITIES.contains(x.getType())).collect(Collectors.toList());
742
        }
743
        if (activities == null) {
744
            throw new ProfitMandiBusinessException("Activity", ticketId, "No Activity Found");
745
        }
746
        model.addAttribute("response1", mvcResponseSender.createResponseString(activities));
747
        return "response";
24500 govind 748
 
31762 tejbeer 749
    }
24620 govind 750
 
31762 tejbeer 751
    @PostMapping(value = "/cs/createActivity")
752
    public String createActivity(HttpServletRequest request, @RequestParam(name = "ticketId", defaultValue = "0") int ticketId, @RequestParam(name = "assigneeId", defaultValue = "0") int assigneeId, @RequestParam(name = "internal", defaultValue = "true") boolean internal, @RequestParam(name = "message", defaultValue = "") String message, @RequestBody List<Integer> documentIds,
24620 govind 753
 
31762 tejbeer 754
                                 Model model) throws Exception {
24620 govind 755
 
31762 tejbeer 756
        LOGGER.info("documentIds" + documentIds);
757
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
758
        Ticket ticket = ticketRepository.selectById(ticketId);
35592 amit 759
 
760
        if (ticket == null) {
761
            throw new ProfitMandiBusinessException("Ticket", ticketId, "Ticket not found");
762
        }
763
 
764
        // Authorization check: verify user has access to add activity to this ticket
765
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
766
        if (!isAdmin) {
767
            // Partners can only add activity to their own tickets
768
            if (ticket.getFofoId() != loginDetails.getFofoId()) {
769
                throw new ProfitMandiBusinessException("Ticket", ticketId, "You do not have permission to add activity to this ticket");
770
            }
771
        } else {
772
            // Admins must be assigned to the ticket OR be CRM user OR be in the escalation chain
773
            AuthUser currentAuthUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
774
            boolean isCrmUser = positionRepository.hasCategory(currentAuthUser.getId(), ProfitMandiConstants.TICKET_CATEGORY_CRM);
775
 
776
            if (!isCrmUser) {
777
                List<TicketAssigned> assignments = ticketAssignedRepository.selectByTicketIds(Arrays.asList(ticketId));
778
                boolean isAssigned = assignments.stream().anyMatch(ta -> ta.getAssineeId() == currentAuthUser.getId() || ta.getManagerId() == currentAuthUser.getId());
779
                boolean isInEscalationChain = ticket.getL1AuthUser() == currentAuthUser.getId() ||
780
                        ticket.getL2AuthUser() == currentAuthUser.getId() ||
781
                        ticket.getL3AuthUser() == currentAuthUser.getId() ||
782
                        ticket.getL4AuthUser() == currentAuthUser.getId() ||
783
                        ticket.getL5AuthUser() == currentAuthUser.getId();
784
 
785
                if (!isAssigned && !isInEscalationChain) {
786
                    throw new ProfitMandiBusinessException("Ticket", ticketId, "You do not have permission to add activity to this ticket");
787
                }
788
            }
789
        }
31762 tejbeer 790
        List<TicketAssigned> ticketAssignedList = ticketAssignedRepository.selectByTicketIds(Arrays.asList(ticketId));
791
        List<Integer> authUserIds = ticketAssignedList.stream().map(x -> x.getAssineeId()).collect(Collectors.toList());
792
        authUserIds.add(ticketAssignedList.get(ticketAssignedList.size() - 1).getManagerId());
35395 amit 793
        Map<Integer, AuthUser> authUsersMap = authRepository.selectByIds(authUserIds).stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
31762 tejbeer 794
        if (ticket.getCloseTimestamp() == null) {
795
            Activity activity = new Activity();
796
            activity.setCreatedBy(0);
797
            activity.setCreateTimestamp(LocalDateTime.now());
798
            String subject = null;
799
            String mailMessage = null;
800
            activity.setMessage(message);
801
            if (!roleManager.isAdmin(new HashSet<>(loginDetails.getRoleIds()))) {
802
                CustomRetailer customRetailer = retailerService.getFofoRetailers(true).get(loginDetails.getFofoId());
803
                activity.setType(ActivityType.COMMUNICATION_IN);
804
                subject = String.format("Ticket Update #%s by franchisee %s", ticket.getId(), customRetailer.getBusinessName() + "(" + customRetailer.getCode() + ")");
805
                mailMessage = String.format("Franchisee message - %s", message);
806
            } else {
807
                AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
808
                activity.setCreatedBy(authUser.getId());
809
                authUsersMap.remove(authUser.getId());
810
                subject = String.format("Ticket Update #%s by %s", ticket.getId(), authUser.getName());
811
                mailMessage = String.format("%s's message - %s", authUser.getFirstName(), message);
35569 amit 812
                // Only CRM users can send external communications
813
                boolean isCrmUser = positionRepository.hasCategory(authUser.getId(), ProfitMandiConstants.TICKET_CATEGORY_CRM);
814
                if (internal || !isCrmUser) {
31762 tejbeer 815
                    activity.setType(ActivityType.COMMUNICATION_INTERNAL);
816
                } else {
817
                    String updatedBy = "SD Team";
31854 amit.gupta 818
                    CustomRetailer customRetailer = retailerService.getFofoRetailers(false).get(ticket.getFofoId());
31762 tejbeer 819
                    subject = String.format("Ticket Update #%s by %s", ticket.getId(), updatedBy);
820
                    String partnerMessage = String.format("%s's message - %s", updatedBy, message);
821
                    this.activityRelatedMail(customRetailer.getEmail(), null, "subject", partnerMessage);
822
                    activity.setType(ActivityType.COMMUNICATION_OUT);
823
                }
824
            }
825
            activityRepository.persist(activity);
826
 
827
            for (Integer documentId : documentIds) {
828
                ActivityAttachment activityAttachment = new ActivityAttachment();
829
                activityAttachment.setActivityId(activity.getId());
830
                activityAttachment.setDocumentId(documentId);
831
                activityAttachmentRepository.persist(activityAttachment);
832
            }
833
 
834
            csService.addActivity(ticket, activity);
835
            AuthUser authUser = authUsersMap.remove(authUserIds.get(0));
836
            if (authUser == null) {
837
                authUser = authUsersMap.remove(authUserIds.get(1));
838
            }
839
            model.addAttribute("response1", mvcResponseSender.createResponseString(authUser));
840
            String[] cc = authUsersMap.entrySet().stream().map(x -> x.getValue().getEmailId()).toArray(String[]::new);
841
            this.activityRelatedMail(authUser.getEmailId(), cc, subject, mailMessage);
842
        } else {
843
            throw new ProfitMandiBusinessException("Ticket", ticket.getId(), "Already closed ticket");
844
        }
845
        return "response";
846
    }
847
 
848
    private void activityRelatedMail(String to, String[] cc, String subject, String message) throws ProfitMandiBusinessException {
849
        try {
850
            Utils.sendMailWithAttachments(mailSender, to, cc, subject, message, null);
851
        } catch (Exception e) {
852
            throw new ProfitMandiBusinessException("Ticket Activity", to, "Could not send ticket activity mail");
853
        }
854
    }
855
 
856
    @PostMapping(value = "/cs/closeTicket")
857
    public String closeTicket(HttpServletRequest request, @RequestParam(name = "ticketId", defaultValue = "0") int ticketId, @RequestParam(name = "happyCode") String happyCode, Model model) throws Exception {
35592 amit 858
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
31762 tejbeer 859
        Ticket ticket = ticketRepository.selectById(ticketId);
35592 amit 860
 
861
        if (ticket == null) {
862
            throw new ProfitMandiBusinessException("Ticket", ticketId, "Ticket not found");
863
        }
864
 
865
        // Authorization check: only the ticket owner (partner) can close the ticket
866
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
867
        if (isAdmin) {
868
            throw new ProfitMandiBusinessException("Ticket", ticketId, "Only partners can close tickets using happy code");
869
        }
870
 
871
        // Verify the partner owns this ticket
872
        if (ticket.getFofoId() != loginDetails.getFofoId()) {
873
            throw new ProfitMandiBusinessException("Ticket", ticketId, "You do not have permission to close this ticket");
874
        }
875
 
31762 tejbeer 876
        if (ticket.getHappyCode().equals(happyCode)) {
877
            ticket.setCloseTimestamp(LocalDateTime.now());
878
            ticketRepository.persist(ticket);
879
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
880
        } else {
881
            throw new ProfitMandiBusinessException("Ticket", ticketId, "Happy Code can't match");
882
        }
883
        return "response";
884
    }
885
 
34913 ranu 886
    @GetMapping(value = "/cs/myPartyTicketTicket")
887
    public String getMyPartyTicketTicket(HttpServletRequest request, @RequestParam(name = "orderby", defaultValue = "DESCENDING") SortOrder sortOrder, @RequestParam(name = "ticketStatus", defaultValue = "OPENED") TicketStatus ticketStatus, @RequestParam(name = "ticketSearchType", defaultValue = "") TicketSearchType ticketSearchType, @RequestParam(name = "searchTerm", defaultValue = "0") int searchTerm, Model model) throws ProfitMandiBusinessException {
888
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
889
        long size = 0;
890
        AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
891
        List<Ticket> tickets = new ArrayList<>();
892
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
893
        Set<Integer> fofoIds = storeGuyMap.get(authUser.getEmailId());
894
 
895
        Map<Integer, List<AuthUser>> authUserListMap = null;
896
        if (fofoIds != null && !fofoIds.isEmpty()) {
35571 amit 897
            // Batch fetch all open tickets for all fofoIds (fix N+1 query)
898
            List<Ticket> allPartnerTickets = ticketRepository.selectAllOpenTickets(new ArrayList<>(fofoIds));
899
            if (allPartnerTickets != null && !allPartnerTickets.isEmpty()) {
900
                // Filter tickets where last_activity is not "RESOLVED"
901
                tickets = allPartnerTickets.stream()
902
                        .filter(ticket -> ticket.getLastActivity() == null ||
903
                                ticket.getLastActivity() != ActivityType.RESOLVED)
904
                        .collect(Collectors.toList());
34913 ranu 905
            }
906
        }
907
 
908
        authUserListMap = csService.getAssignedAuthList(tickets);
909
 
910
 
911
        if (tickets.size() > 0) {
912
            Map<Integer, CustomRetailer> fofoIdsAndCustomRetailer = csService.getPartnerByFofoIds(tickets);
913
            model.addAttribute("fofoIdsAndCustomRetailer", fofoIdsAndCustomRetailer);
914
        }
915
 
916
        model.addAttribute("size", tickets.size());
917
        model.addAttribute("tickets", tickets);
918
 
919
        List<Integer> subCategoryIds = tickets.stream().map(x -> x.getSubCategoryId()).collect(Collectors.toList());
920
        Map<Integer, TicketSubCategory> subCategoryIdAndSubCategoryMap = csService.getSubCategoryIdAndSubCategoryMap(subCategoryIds);
35571 amit 921
        if (subCategoryIdAndSubCategoryMap == null) {
922
            subCategoryIdAndSubCategoryMap = new HashMap<>();
923
        }
34913 ranu 924
 
925
        Map<Integer, TicketCategory> subCategoryIdAndCategoryMap = csService.getSubCategoryIdAndCategoryMap(subCategoryIds);
35571 amit 926
        if (subCategoryIdAndCategoryMap == null) {
927
            subCategoryIdAndCategoryMap = new HashMap<>();
928
        }
34913 ranu 929
 
930
        List<Integer> ticketIds = tickets.stream().map(x -> x.getId()).collect(Collectors.toList());
931
        Map<Integer, List<Activity>> activityMap = new HashMap<>();
932
        Map<Integer, List<Activity>> activityMapWithActivityId = new HashMap<>();
35569 amit 933
        Map<Integer, AuthUser> authUserMap = new HashMap<>();
34913 ranu 934
 
935
        if (!ticketIds.isEmpty()) {
35569 amit 936
            // Fetch activities once and group by both ticketId and activityId
937
            List<Activity> allActivities = activityRepository.selectAll(ticketIds);
938
            activityMap = allActivities.stream().collect(Collectors.groupingBy(Activity::getTicketId));
939
            activityMapWithActivityId = allActivities.stream().collect(Collectors.groupingBy(Activity::getId));
34913 ranu 940
 
35569 amit 941
            // Only fetch AuthUsers who created activities (instead of all users)
942
            Set<Integer> activityCreatorIds = allActivities.stream()
943
                    .map(Activity::getCreatedBy)
944
                    .filter(id -> id > 0)
945
                    .collect(Collectors.toSet());
946
            if (!activityCreatorIds.isEmpty()) {
947
                authUserMap = authRepository.selectByIds(new ArrayList<>(activityCreatorIds))
948
                        .stream().collect(Collectors.toMap(AuthUser::getId, x -> x));
949
            }
34913 ranu 950
        }
951
 
952
        model.addAttribute("ticketStatusValues", TicketStatus.values());
953
        model.addAttribute("orderByValues", SortOrder.values());
954
        model.addAttribute("selectedticketStatus", ticketStatus);
955
        model.addAttribute("selectedorderby", sortOrder);
956
        model.addAttribute("tickets", tickets);
957
        model.addAttribute("ticketSearchTypes", TicketSearchType.values());
958
        model.addAttribute("ticketSearchType", ticketSearchType);
959
        model.addAttribute("searchTerm", searchTerm);
35571 amit 960
        model.addAttribute("authUserListMap", authUserListMap != null ? authUserListMap : new HashMap<>());
34913 ranu 961
        model.addAttribute("subCategoryIdAndSubCategoryMap", subCategoryIdAndSubCategoryMap);
962
 
963
        model.addAttribute("subCategoryIdAndCategoryMap", subCategoryIdAndCategoryMap);
964
 
965
        model.addAttribute("activityMap", activityMap);
966
        model.addAttribute("authUserMap", authUserMap);
967
        model.addAttribute("activityMapWithActivityId", activityMapWithActivityId);
35569 amit 968
        // Check if user is in CRM category (only CRM can send external communications)
969
        boolean isCrmUser = positionRepository.hasCategory(authUser.getId(), ProfitMandiConstants.TICKET_CATEGORY_CRM);
970
        model.addAttribute("isCrmUser", isCrmUser);
34913 ranu 971
 
972
        return "my-partner-tickets";
973
    }
974
 
31762 tejbeer 975
    @GetMapping(value = "/cs/managerTicket")
976
    public String getManagerTickets(HttpServletRequest request, @RequestParam(name = "orderby", defaultValue = "DESCENDING") SortOrder sortOrder, @RequestParam(name = "ticketStatus", defaultValue = "OPENED") TicketStatus ticketStatus, @RequestParam(name = "ticketSearchType", defaultValue = "") TicketSearchType ticketSearchType, @RequestParam(name = "searchTerm", defaultValue = "0") int searchTerm, Model model) throws ProfitMandiBusinessException {
977
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
978
        long size = 0;
979
        AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
35594 amit 980
        boolean isCrmUser = positionRepository.hasCategory(authUser.getId(), ProfitMandiConstants.TICKET_CATEGORY_CRM);
981
 
31762 tejbeer 982
        List<Ticket> tickets = null;
983
        Map<Integer, List<AuthUser>> authUserListMap = null;
35594 amit 984
 
985
        // CRM users can see all tickets to assign them (like managers)
986
        if (isCrmUser) {
31762 tejbeer 987
            if (ticketStatus.equals(TicketStatus.RESOLVED)) {
35594 amit 988
                tickets = ticketRepository.selectAllTickets(Optional.empty(), sortOrder, ticketSearchType, searchTerm);
989
                size = ticketRepository.selectAllTicketsCount(Optional.empty(), ticketSearchType, searchTerm);
990
            } else {
991
                tickets = ticketRepository.selectAllTickets(Optional.of(TicketStatus.CLOSED.equals(ticketStatus)), sortOrder, ticketSearchType, searchTerm);
992
                size = ticketRepository.selectAllTicketsCount(Optional.of(TicketStatus.CLOSED.equals(ticketStatus)), ticketSearchType, searchTerm);
993
            }
994
        } else if (ticketSearchType == null) {
995
            if (ticketStatus.equals(TicketStatus.RESOLVED)) {
31762 tejbeer 996
                tickets = ticketRepository.selectAllManagerTicket(authUser.getId(), sortOrder, Optional.empty(), null, searchTerm);
997
                size = ticketRepository.selectAllCountByManagerTicket(authUser.getId(), Optional.empty(), null, 0);
998
            } else {
999
                tickets = ticketRepository.selectAllManagerTicket(authUser.getId(), sortOrder, Optional.of(TicketStatus.CLOSED.equals(ticketStatus)), null, searchTerm);
1000
                size = ticketRepository.selectAllCountByManagerTicket(authUser.getId(), Optional.of(TicketStatus.CLOSED.equals(ticketStatus)), null, 0);
1001
            }
1002
        } else {
1003
            if (ticketStatus.equals(TicketStatus.RESOLVED)) {
1004
                tickets = ticketRepository.selectAllManagerTicket(authUser.getId(), sortOrder, Optional.empty(), ticketSearchType, searchTerm);
1005
                size = ticketRepository.selectAllCountByManagerTicket(authUser.getId(), Optional.empty(), ticketSearchType, searchTerm);
1006
            } else {
1007
                tickets = ticketRepository.selectAllManagerTicket(authUser.getId(), sortOrder, Optional.of(TicketStatus.CLOSED.equals(ticketStatus)), ticketSearchType, searchTerm);
1008
                size = ticketRepository.selectAllCountByManagerTicket(authUser.getId(), Optional.of(TicketStatus.CLOSED.equals(ticketStatus)), ticketSearchType, searchTerm);
1009
            }
1010
 
1011
        }
1012
        authUserListMap = csService.getAssignedAuthList(tickets);
1013
 
1014
        if (tickets.size() > 0) {
1015
            Map<Integer, CustomRetailer> fofoIdsAndCustomRetailer = csService.getPartnerByFofoIds(tickets);
1016
            model.addAttribute("fofoIdsAndCustomRetailer", fofoIdsAndCustomRetailer);
1017
        }
1018
 
1019
        model.addAttribute("size", size);
1020
        model.addAttribute("tickets", tickets);
1021
 
1022
        List<Integer> subCategoryIds = tickets.stream().map(x -> x.getSubCategoryId()).collect(Collectors.toList());
1023
        Map<Integer, TicketSubCategory> subCategoryIdAndSubCategoryMap = csService.getSubCategoryIdAndSubCategoryMap(subCategoryIds);
35571 amit 1024
        if (subCategoryIdAndSubCategoryMap == null) {
1025
            subCategoryIdAndSubCategoryMap = new HashMap<>();
1026
        }
31762 tejbeer 1027
 
1028
        Map<Integer, TicketCategory> subCategoryIdAndCategoryMap = csService.getSubCategoryIdAndCategoryMap(subCategoryIds);
35571 amit 1029
        if (subCategoryIdAndCategoryMap == null) {
1030
            subCategoryIdAndCategoryMap = new HashMap<>();
1031
        }
31762 tejbeer 1032
 
1033
        List<Integer> ticketIds = tickets.stream().map(x -> x.getId()).collect(Collectors.toList());
1034
        Map<Integer, List<Activity>> activityMap = new HashMap<>();
33778 ranu 1035
        Map<Integer, List<Activity>> activityMapWithActivityId = new HashMap<>();
35570 amit 1036
        Map<Integer, AuthUser> authUserMap = new HashMap<>();
31762 tejbeer 1037
 
1038
        if (!ticketIds.isEmpty()) {
35570 amit 1039
            // Fetch activities once and reuse for both maps (fix duplicate query)
1040
            List<Activity> allActivities = activityRepository.selectAll(ticketIds);
1041
            activityMap = allActivities.stream().collect(Collectors.groupingBy(Activity::getTicketId));
1042
            activityMapWithActivityId = allActivities.stream().collect(Collectors.groupingBy(Activity::getId));
31762 tejbeer 1043
 
35570 amit 1044
            // Only fetch users who created activities (fix loading ALL users)
1045
            Set<Integer> activityCreatorIds = allActivities.stream()
1046
                    .map(Activity::getCreatedBy)
1047
                    .filter(id -> id > 0)
1048
                    .collect(Collectors.toSet());
1049
            if (!activityCreatorIds.isEmpty()) {
1050
                authUserMap = authRepository.selectByIds(new ArrayList<>(activityCreatorIds))
1051
                        .stream().collect(Collectors.toMap(AuthUser::getId, x -> x));
1052
            }
31762 tejbeer 1053
        }
33778 ranu 1054
 
31762 tejbeer 1055
        model.addAttribute("ticketStatusValues", TicketStatus.values());
1056
        model.addAttribute("orderByValues", SortOrder.values());
1057
        model.addAttribute("selectedticketStatus", ticketStatus);
1058
        model.addAttribute("selectedorderby", sortOrder);
1059
        model.addAttribute("tickets", tickets);
1060
        model.addAttribute("ticketSearchTypes", TicketSearchType.values());
1061
        model.addAttribute("ticketSearchType", ticketSearchType);
1062
        model.addAttribute("searchTerm", searchTerm);
1063
        model.addAttribute("authUserListMap", authUserListMap);
1064
        model.addAttribute("subCategoryIdAndSubCategoryMap", subCategoryIdAndSubCategoryMap);
1065
 
1066
        model.addAttribute("subCategoryIdAndCategoryMap", subCategoryIdAndCategoryMap);
1067
 
1068
        model.addAttribute("activityMap", activityMap);
33778 ranu 1069
        model.addAttribute("authUserMap", authUserMap);
1070
        model.addAttribute("activityMapWithActivityId", activityMapWithActivityId);
35594 amit 1071
        model.addAttribute("isCrmUser", isCrmUser);
31762 tejbeer 1072
 
1073
        return "managerTicket";
1074
    }
1075
 
1076
 
1077
    @GetMapping(value = "/cs/edit-ticket")
35594 amit 1078
    public String getEditTicket(HttpServletRequest request, @RequestParam(name = "ticketId", defaultValue = "0") int ticketId, Model model) throws ProfitMandiBusinessException {
1079
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1080
        AuthUser currentAuthUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
1081
        boolean isCrmUser = positionRepository.hasCategory(currentAuthUser.getId(), ProfitMandiConstants.TICKET_CATEGORY_CRM);
1082
 
31762 tejbeer 1083
        Ticket ticket = ticketRepository.selectById(ticketId);
1084
        List<TicketCategory> ticketCategories = csService.getAllTicketCategotyFromSubCategory();
1085
        TicketSubCategory ticketSubCategory = ticketSubCategoryRepository.selectById(ticket.getSubCategoryId());
1086
        List<TicketSubCategory> ticketSubCategories = ticketSubCategoryRepository.selectAll(ticketSubCategory.getCategoryId());
1087
        List<AuthUser> authUsers = authRepository.selectAllActiveUser();
35594 amit 1088
 
1089
        // CRM users should not see Sales/RBM categories and their Escalation subcategories
1090
        if (isCrmUser) {
1091
            ticketCategories = ticketCategories.stream()
1092
                    .filter(tc -> tc.getId() != ProfitMandiConstants.TICKET_CATEGORY_SALES
1093
                            && tc.getId() != ProfitMandiConstants.TICKET_CATEGORY_RBM)
1094
                    .collect(Collectors.toList());
1095
            ticketSubCategories = ticketSubCategories.stream()
1096
                    .filter(tsc -> tsc.getId() != ProfitMandiConstants.TICKET_SUBCATEGORY_SALES_ESCALATION
1097
                            && tsc.getId() != ProfitMandiConstants.TICKET_SUBCATEGORY_RBM_ESCALATION)
1098
                    .collect(Collectors.toList());
1099
        }
1100
 
1101
        // Get partner name for modal title
1102
        String partnerName = retailerService.getFofoRetailer(ticket.getFofoId()).getBusinessName();
1103
 
31762 tejbeer 1104
        model.addAttribute("ticket", ticket);
1105
        model.addAttribute("ticketCategories", ticketCategories);
1106
        model.addAttribute("ticketSubCategories", ticketSubCategories);
1107
        model.addAttribute("ticketSubCategory", ticketSubCategory);
1108
        model.addAttribute("authUsers", authUsers);
35594 amit 1109
        model.addAttribute("isCrmUser", isCrmUser);
1110
        model.addAttribute("partnerName", partnerName);
31762 tejbeer 1111
        return "edit-ticket-modal";
1112
    }
1113
 
34913 ranu 1114
    @GetMapping(value = "/cs/edit-partner-ticket")
35594 amit 1115
    public String getEditPartnerTicket(HttpServletRequest request, @RequestParam(name = "ticketId", defaultValue = "0") int ticketId, Model model) throws ProfitMandiBusinessException {
1116
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1117
        AuthUser currentAuthUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
1118
        boolean isCrmUser = positionRepository.hasCategory(currentAuthUser.getId(), ProfitMandiConstants.TICKET_CATEGORY_CRM);
1119
 
34913 ranu 1120
        Ticket ticket = ticketRepository.selectById(ticketId);
1121
        List<TicketCategory> ticketCategories = csService.getAllTicketCategotyFromSubCategory();
1122
        TicketSubCategory ticketSubCategory = ticketSubCategoryRepository.selectById(ticket.getSubCategoryId());
1123
        List<TicketSubCategory> ticketSubCategories = ticketSubCategoryRepository.selectAll(ticketSubCategory.getCategoryId());
1124
        List<AuthUser> authUsers = authRepository.selectAllActiveUser();
35594 amit 1125
 
1126
        // CRM users should not see Sales/RBM categories and their Escalation subcategories
1127
        if (isCrmUser) {
1128
            ticketCategories = ticketCategories.stream()
1129
                    .filter(tc -> tc.getId() != ProfitMandiConstants.TICKET_CATEGORY_SALES
1130
                            && tc.getId() != ProfitMandiConstants.TICKET_CATEGORY_RBM)
1131
                    .collect(Collectors.toList());
1132
            ticketSubCategories = ticketSubCategories.stream()
1133
                    .filter(tsc -> tsc.getId() != ProfitMandiConstants.TICKET_SUBCATEGORY_SALES_ESCALATION
1134
                            && tsc.getId() != ProfitMandiConstants.TICKET_SUBCATEGORY_RBM_ESCALATION)
1135
                    .collect(Collectors.toList());
1136
        }
1137
 
1138
        // Get partner name for modal title
1139
        String partnerName = retailerService.getFofoRetailer(ticket.getFofoId()).getBusinessName();
1140
 
34913 ranu 1141
        model.addAttribute("ticket", ticket);
1142
        model.addAttribute("ticketCategories", ticketCategories);
1143
        model.addAttribute("ticketSubCategories", ticketSubCategories);
1144
        model.addAttribute("ticketSubCategory", ticketSubCategory);
1145
        model.addAttribute("authUsers", authUsers);
35594 amit 1146
        model.addAttribute("isCrmUser", isCrmUser);
1147
        model.addAttribute("partnerName", partnerName);
34913 ranu 1148
        return "edit-ticket-partner-modal";
1149
    }
1150
 
31762 tejbeer 1151
    @PostMapping(value = "/cs/edit-ticket")
1152
    public String editTicket(HttpServletRequest request, @RequestParam(name = "ticketId", defaultValue = "0") int ticketId, @RequestParam(name = "subCategoryId", defaultValue = "0") int subCategoryId, @RequestParam(name = "categoryId", defaultValue = "0") int categoryId, @RequestParam(name = "authUserId", defaultValue = "0") int authUserId, @RequestParam(name = "escalationType", defaultValue = "L1") EscalationType escalationType, Model model) throws Exception {
1153
        LOGGER.info("Ticket Id {}, CategoryId {}, SubCategory Id {} authUserId {}", ticketId, categoryId, subCategoryId, authUserId);
35592 amit 1154
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1155
 
1156
        // Only admins can edit tickets
1157
        if (!roleManager.isAdmin(loginDetails.getRoleIds())) {
1158
            throw new ProfitMandiBusinessException("Ticket", ticketId, "Only admins can edit tickets");
1159
        }
1160
 
31762 tejbeer 1161
        Ticket ticket = ticketRepository.selectById(ticketId);
35592 amit 1162
        if (ticket == null) {
1163
            throw new ProfitMandiBusinessException("Ticket", ticketId, "Ticket not found");
1164
        }
1165
 
1166
        // Verify admin has access to this ticket (assigned, manager, escalation chain, or CRM)
1167
        AuthUser currentAuthUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
1168
        boolean isCrmUser = positionRepository.hasCategory(currentAuthUser.getId(), ProfitMandiConstants.TICKET_CATEGORY_CRM);
1169
 
1170
        if (!isCrmUser) {
1171
            List<TicketAssigned> assignments = ticketAssignedRepository.selectByTicketIds(Arrays.asList(ticketId));
1172
            boolean isAssigned = assignments.stream().anyMatch(ta -> ta.getAssineeId() == currentAuthUser.getId() || ta.getManagerId() == currentAuthUser.getId());
1173
            boolean isInEscalationChain = ticket.getL1AuthUser() == currentAuthUser.getId() ||
1174
                    ticket.getL2AuthUser() == currentAuthUser.getId() ||
1175
                    ticket.getL3AuthUser() == currentAuthUser.getId() ||
1176
                    ticket.getL4AuthUser() == currentAuthUser.getId() ||
1177
                    ticket.getL5AuthUser() == currentAuthUser.getId();
1178
 
1179
            if (!isAssigned && !isInEscalationChain) {
1180
                throw new ProfitMandiBusinessException("Ticket", ticketId, "You do not have permission to edit this ticket");
1181
            }
1182
        }
1183
 
31762 tejbeer 1184
        csService.updateTicket(categoryId, subCategoryId, ticket, authUserId, escalationType);
1185
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1186
        return "response";
1187
 
1188
    }
1189
 
34913 ranu 1190
    @PostMapping(value = "/cs/edit-partner-ticket")
1191
    public String editPartnerTicket(HttpServletRequest request, @RequestParam(name = "ticketId", defaultValue = "0") int ticketId, @RequestParam(name = "subCategoryId", defaultValue = "0") int subCategoryId, @RequestParam(name = "categoryId", defaultValue = "0") int categoryId, @RequestParam(name = "authUserId", defaultValue = "0") int authUserId, @RequestParam(name = "escalationType", defaultValue = "L1") EscalationType escalationType, Model model) throws Exception {
1192
        LOGGER.info("Ticket Id {}, CategoryId {}, SubCategory Id {} authUserId {}", ticketId, categoryId, subCategoryId, authUserId);
35592 amit 1193
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1194
 
1195
        // Only admins can edit partner tickets
1196
        if (!roleManager.isAdmin(loginDetails.getRoleIds())) {
1197
            throw new ProfitMandiBusinessException("Ticket", ticketId, "Only admins can edit partner tickets");
1198
        }
1199
 
34913 ranu 1200
        Ticket ticket = ticketRepository.selectById(ticketId);
35592 amit 1201
        if (ticket == null) {
1202
            throw new ProfitMandiBusinessException("Ticket", ticketId, "Ticket not found");
1203
        }
1204
 
1205
        // Verify admin has access (must be in Sales, ABM, or RBM position for the partner)
1206
        AuthUser currentAuthUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
1207
        Map<String, Set<Integer>> authUserPartnerMap = csService.getAuthUserPartnerIdMapping();
1208
        Set<Integer> allowedPartnerIds = authUserPartnerMap.get(currentAuthUser.getEmailId());
1209
 
1210
        if (allowedPartnerIds == null || !allowedPartnerIds.contains(ticket.getFofoId())) {
1211
            // Also allow CRM users
1212
            boolean isCrmUser = positionRepository.hasCategory(currentAuthUser.getId(), ProfitMandiConstants.TICKET_CATEGORY_CRM);
1213
            if (!isCrmUser) {
1214
                throw new ProfitMandiBusinessException("Ticket", ticketId, "You do not have permission to edit this partner's ticket");
1215
            }
1216
        }
1217
 
34913 ranu 1218
        csService.updateTicket(categoryId, subCategoryId, ticket, authUserId, escalationType);
1219
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1220
        return "response";
1221
 
1222
    }
1223
 
31762 tejbeer 1224
    @PostMapping(value = "/cs/changeTicketAssignee")
1225
    public String changeTicketAssignee(HttpServletRequest request, @RequestParam(name = "positionId", defaultValue = "0") int positionId, Model model) throws Exception {
1226
        Position position = positionRepository.selectById(positionId);
1227
        if (position.isTicketAssignee()) {
1228
            position.setTicketAssignee(false);
1229
        } else {
1230
            position.setTicketAssignee(true);
1231
        }
1232
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1233
        return "response";
1234
    }
1235
 
1236
 
1237
    @DeleteMapping(value = "/cs/removePosition")
1238
    public String removePosition(HttpServletRequest request, @RequestParam(name = "positionId", defaultValue = "0") int positionId, Model model) throws Exception {
1239
        positionRepository.delete(positionId);
1240
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1241
        return "response";
1242
    }
1243
 
1244
    @PostMapping(value = "/cs/create-last-activity")
1245
    public String createlastActivity(HttpServletRequest request, @RequestParam(name = "ticketId") int ticketId, @RequestParam(name = "lastactivity") ActivityType lastActivity, Model model) throws Exception {
1246
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1247
        Ticket ticket = ticketRepository.selectById(ticketId);
35592 amit 1248
 
1249
        if (ticket == null) {
1250
            throw new ProfitMandiBusinessException("Ticket", ticketId, "Ticket not found");
1251
        }
1252
 
1253
        // Authorization check for partners: can only update their own tickets
1254
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1255
        if (!isAdmin && ticket.getFofoId() != loginDetails.getFofoId()) {
1256
            throw new ProfitMandiBusinessException("Ticket", ticketId, "You do not have permission to update this ticket");
1257
        }
1258
 
31762 tejbeer 1259
        Activity activity = new Activity();
1260
        String subject = String.format(ACTIVITY_SUBJECT, ticket.getId());
35592 amit 1261
        if (isAdmin) {
35603 amit 1262
            // CRM team members can resolve any ticket
1263
            // Sales team members can resolve their own Sales category tickets
1264
            // RBM team members can resolve their own RBM category tickets
35592 amit 1265
            AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
1266
            boolean isCrmUser = positionRepository.hasCategory(authUser.getId(), ProfitMandiConstants.TICKET_CATEGORY_CRM);
35603 amit 1267
            boolean isSalesUser = positionRepository.hasCategory(authUser.getId(), ProfitMandiConstants.TICKET_CATEGORY_SALES);
1268
            boolean isRbmUser = positionRepository.hasCategory(authUser.getId(), ProfitMandiConstants.TICKET_CATEGORY_RBM);
1269
 
1270
            // Check if ticket belongs to Sales or RBM category
1271
            TicketSubCategory ticketSubCategory = ticketSubCategoryRepository.selectById(ticket.getSubCategoryId());
1272
            boolean isSalesTicket = ticketSubCategory != null && ticketSubCategory.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES;
1273
            boolean isRbmTicket = ticketSubCategory != null && ticketSubCategory.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_RBM;
1274
 
1275
            // Allow if CRM user OR (Sales user AND Sales ticket) OR (RBM user AND RBM ticket)
1276
            if (!isCrmUser && !(isSalesUser && isSalesTicket) && !(isRbmUser && isRbmTicket)) {
1277
                throw new ProfitMandiBusinessException("Ticket", ticketId, "Only CRM, Sales (for Sales tickets), or RBM (for RBM tickets) team can mark tickets as resolved");
35592 amit 1278
            }
31762 tejbeer 1279
            ticket.setLastActivity(lastActivity);
1280
            String to = retailerService.getFofoRetailer(ticket.getFofoId()).getEmail();
1281
            String message = String.format(PARTNER_RESOLVED_TICKET_MAIL, ticketId, "REOPEN");
1282
            activity.setMessage(message);
35592 amit 1283
            activity.setCreatedBy(authUser.getId());
31762 tejbeer 1284
            activity.setTicketId(ticketId);
1285
            activity.setCreateTimestamp(LocalDateTime.now());
1286
            activity.setType(ActivityType.COMMUNICATION_OUT);
1287
            this.activityRelatedMail(to, null, subject, message);
1288
        } else {
1289
            if (ActivityType.RESOLVED_ACCEPTED == lastActivity) {
1290
                ticket.setLastActivity(lastActivity);
1291
                ticket.setCloseTimestamp(LocalDateTime.now());
1292
                activity.setMessage(ActivityType.RESOLVED_ACCEPTED.toString());
1293
                activity.setCreatedBy(0);
1294
                activity.setTicketId(ticketId);
1295
                activity.setType(ActivityType.COMMUNICATION_IN);
1296
                activity.setCreateTimestamp(LocalDateTime.now());
1297
            } else {
1298
                String message = String.format(INTERNAL_REOPEN_MAIL, ticketId, retailerService.getFofoRetailer(loginDetails.getFofoId()).getBusinessName());
1299
                String to = authRepository.selectById(ticket.getL1AuthUser()).getEmailId();
35395 amit 1300
                String[] ccTo = authRepository.selectByIds(Arrays.asList(ticket.getL2AuthUser(), ticket.getL3AuthUser(), ticket.getL4AuthUser(), ticket.getL5AuthUser())).stream().map(x -> x.getEmailId()).toArray(String[]::new);
31762 tejbeer 1301
                ticket.setLastActivity(lastActivity);
1302
                ticket.setUpdateTimestamp(LocalDateTime.now());
1303
                ticketAssignedRepository.deleteByTicketId(ticketId);
1304
                TicketAssigned ticketAssigned = new TicketAssigned();
1305
                ticketAssigned.setAssineeId(ticket.getL1AuthUser());
1306
                ticketAssigned.setTicketId(ticketId);
1307
                ticketAssignedRepository.persist(ticketAssigned);
1308
                activity.setMessage(INTERNAL_REOPEN_ACTIVITY_MESSAGE);
1309
                activity.setCreatedBy(0);
1310
                activity.setTicketId(ticketId);
1311
                activity.setType(ActivityType.COMMUNICATION_IN);
1312
                activity.setCreateTimestamp(LocalDateTime.now());
1313
                this.activityRelatedMail(to, ccTo, subject, message);
1314
                this.activityRelatedMail(retailerService.getFofoRetailer(loginDetails.getFofoId()).getEmail(), null, subject, String.format(PARTNER_REOPEN, ticketId));
1315
            }
1316
 
1317
        }
1318
        activityRepository.persist(activity);
1319
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1320
        return "response";
1321
    }
1322
 
32812 shampa 1323
 
1324
 
1325
 
1326
 
1327
    @PostMapping(value = "/partner-position/update")
1328
    public String positionUpdated(Model model, @RequestBody List<PartnerPositonUpdateModel> partnerPositionUpdateModels)
1329
            throws Exception {
1330
 
32821 shampa 1331
        Map<Integer, List<String>> positionIdsToAddMap = partnerPositionUpdateModels.stream().filter(x->x.getPositionIdTo()!=0).collect(Collectors.groupingBy(x->x.getPositionIdTo(),
32812 shampa 1332
                Collectors.mapping(x->x.getStoreCode(), Collectors.toList())));
1333
 
32821 shampa 1334
        Map<Integer, List<String>> positionIdsToRemoveMap = partnerPositionUpdateModels.stream().filter(x->x.getPositionIdFrom()!=0).collect(Collectors.groupingBy(x->x.getPositionIdFrom(),
32812 shampa 1335
                Collectors.mapping(x->x.getStoreCode(), Collectors.toList())));
1336
 
1337
        List<Integer> positionIdsToUpdate = new ArrayList<>();
1338
        positionIdsToUpdate.addAll(positionIdsToAddMap.keySet());
1339
        positionIdsToUpdate.addAll(positionIdsToRemoveMap.keySet());
1340
 
35395 amit 1341
        Map<Integer, Position> positionsToUpdateMap =  positionRepository.selectByIds(positionIdsToUpdate).stream().collect(Collectors.toMap(x->x.getId(), x->x));
32812 shampa 1342
        List<Integer> invalidPositionIds = positionsToUpdateMap.values().stream().filter(x-> x.getCategoryId()!= ProfitMandiConstants.TICKET_CATEGORY_RBM
34908 ranu 1343
                && x.getCategoryId() != ProfitMandiConstants.TICKET_CATEGORY_SALES && x.getCategoryId() != ProfitMandiConstants.TICKET_CATEGORY_ABM).map(x -> x.getId()).collect(Collectors.toList());
32812 shampa 1344
        if(invalidPositionIds.size() > 0) {
34908 ranu 1345
            String message = "Non RBM/Sales/ABM are not allowed - " + invalidPositionIds;
32812 shampa 1346
            throw new ProfitMandiBusinessException(message, message, message);
1347
        }
1348
 
1349
        for (Map.Entry<Integer, List<String>> positionIdStoreMapEntry : positionIdsToAddMap.entrySet()) {
1350
            int positionId = positionIdStoreMapEntry.getKey();
1351
            Position position = positionsToUpdateMap.get(positionId);
32821 shampa 1352
            LOGGER.info("positionId - {}, Position - {}", positionId, position);
32812 shampa 1353
            List<String> storeCodesToAdd = positionIdStoreMapEntry.getValue();
1354
            List<Integer> retailerIdsToAdd = fofoStoreRepository.selectByStoreCodes(storeCodesToAdd).stream().map(x->x.getId()).collect(Collectors.toList());
1355
            Map<Integer, PartnerPosition> partnerPositionsMapByFofoId  = partnerPositionRepository
32821 shampa 1356
                    .selectByRegionIdAndPostionId(Arrays.asList(position.getRegionId())
1357
                            ,Arrays.asList(positionId)).stream().collect(Collectors.toMap(x->x.getFofoId(),x->x));
32812 shampa 1358
            for (Integer retailerIdToAdd : retailerIdsToAdd) {
1359
                if (!partnerPositionsMapByFofoId.containsKey(retailerIdToAdd)) {
1360
                    PartnerPosition partnerPositionNew = new PartnerPosition();
1361
                    partnerPositionNew.setPositionId(positionId);
1362
                    partnerPositionNew.setFofoId(retailerIdToAdd);
1363
                    partnerPositionNew.setRegionId(position.getRegionId());
32865 amit.gupta 1364
                    partnerPositionRepository.persist(partnerPositionNew);
32812 shampa 1365
                }
1366
            }
1367
        }
1368
 
1369
        for (Map.Entry<Integer, List<String>> positionIdStoreMapEntry : positionIdsToRemoveMap.entrySet()) {
1370
 
1371
            int positionId = positionIdStoreMapEntry.getKey();
1372
            Position position = positionsToUpdateMap.get(positionId);
1373
            List<String> storeCodesToRemove = positionIdStoreMapEntry.getValue();
1374
            List<Integer> retailerIdsToRemove = fofoStoreRepository.selectByStoreCodes(storeCodesToRemove).stream().map(x->x.getId()).collect(Collectors.toList());
1375
            Map<Integer, PartnerPosition> partnerPositionsMapByFofoId  = partnerPositionRepository
1376
                    .selectByRegionIdAndPostionId(Arrays.asList(position.getRegionId()),Arrays.asList(positionId)).stream().collect(Collectors.toMap(x->x.getFofoId(),x->x));
1377
            for (Integer retailerIdToRemove : retailerIdsToRemove) {
1378
                if (partnerPositionsMapByFofoId.containsKey(retailerIdToRemove)) {
1379
                   PartnerPosition partnerPositionToRemove =  partnerPositionsMapByFofoId.get(retailerIdToRemove);
1380
                   partnerPositionRepository.delete(partnerPositionToRemove);
1381
                }
1382
            }
1383
        }
1384
 
1385
 
1386
 
1387
        /*partnerPositionUpdateModels.str
1388
 
1389
        Map<Integer, Position> positionIdMap = positionsToUpdate.stream().collect(Collectors.toMap(x->x.getId(), x->x));
1390
        for (PartnerPositonUpdateModel partnerPositionUpdateModel : partnerPositionUpdateModels) {
1391
            FofoStore fofoStore = fofoStoreRepository.selectByStoreCode(partnerPositionUpdateModel.getStoreCode());
1392
            Position positionFrom = positionIdMap.get(partnerPositionUpdateModel.getPositionIdFrom());
1393
            Position positionTo = positionIdMap.get(partnerPositionUpdateModel.getPositionIdTo());
1394
            if(positionFrom != null) {
1395
                partnerPositionRepository.selectByRegionIdAndPostionId(Arrays.)
1396
              int regionId = positionFrom.getRegionId()
1397
            }
1398
            if(positionTo != null) {
1399
 
1400
            }
1401
        }*/
1402
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1403
        return "response";
1404
 
1405
    }
1406
 
1407
 
24417 govind 1408
}