Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
24383 amit.gupta 1
package com.spice.profitmandi.dao.repository.cs;
24500 govind 2
 
24383 amit.gupta 3
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
24417 govind 4
import com.spice.profitmandi.common.model.CustomRetailer;
24439 govind 5
import com.spice.profitmandi.common.model.ProfitMandiConstants;
24417 govind 6
import com.spice.profitmandi.dao.entity.auth.AuthUser;
31829 amit.gupta 7
import com.spice.profitmandi.dao.entity.cs.*;
24383 amit.gupta 8
import com.spice.profitmandi.dao.entity.fofo.ActivityType;
30003 tejbeer 9
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
32923 ranu 10
import com.spice.profitmandi.dao.enumuration.auth.CollectionRemark;
24417 govind 11
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
34905 ranu 12
import com.spice.profitmandi.dao.model.*;
24417 govind 13
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
25570 tejbeer 14
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
35635 ranu 15
import com.spice.profitmandi.service.EmailService;
35963 amit 16
import com.spice.profitmandi.service.mail.MailOutboxService;
24417 govind 17
import com.spice.profitmandi.service.user.RetailerService;
31829 amit.gupta 18
import org.apache.commons.collections4.map.HashedMap;
19
import org.apache.commons.lang.RandomStringUtils;
20
import org.apache.commons.lang.StringUtils;
21
import org.apache.logging.log4j.LogManager;
22
import org.apache.logging.log4j.Logger;
34082 ranu 23
import org.hibernate.Session;
24
import org.hibernate.SessionFactory;
31829 amit.gupta 25
import org.springframework.beans.factory.annotation.Autowired;
26
import org.springframework.cache.annotation.Cacheable;
27
import org.springframework.mail.javamail.JavaMailSender;
28
import org.springframework.stereotype.Component;
24383 amit.gupta 29
 
34082 ranu 30
import javax.persistence.TypedQuery;
31829 amit.gupta 31
import java.time.LocalDateTime;
32
import java.util.*;
33
import java.util.stream.Collectors;
34
 
24383 amit.gupta 35
@Component
36
public class CsServiceImpl implements CsService {
24417 govind 37
 
31762 tejbeer 38
    private static final int ALL_PARTNERS_REGION = 5;
27124 amit.gupta 39
 
31762 tejbeer 40
    private static final Logger LOGGER = LogManager.getLogger(CsServiceImpl.class);
24439 govind 41
 
31762 tejbeer 42
    private static final String ASSIGNED_TICKET = "Dear %s, New ticket #%s #%s created by %s has been assigned to you. Regards\nSmartdukaan";
43
    private static final String ESCALATED_TICKET = "Dear %s, Ticket #%s #%s created by %s has been escalated to you. Regards\nSmartdukaan";
44
    private static final String CATEGORY_CHANGED_TICKET = "Dear team, Category of Ticket #%s created by %s has been changed to %s. Regards\nSmartdukaan";
45
    private static final String ASSINMENT_SUBJECT = "Assignment Ticket";
24439 govind 46
 
31762 tejbeer 47
    @Autowired
48
    TicketRepository ticketRepository;
24417 govind 49
 
31762 tejbeer 50
    @Autowired
36399 amit 51
    JavaMailSender gmailRelaySender;
24439 govind 52
 
31762 tejbeer 53
    @Autowired
35963 amit 54
    MailOutboxService mailOutboxService;
55
 
56
    @Autowired
31762 tejbeer 57
    TicketCategoryRepository ticketCategoryRepository;
24417 govind 58
 
31762 tejbeer 59
    @Autowired
60
    TicketSubCategoryRepository ticketSubCategoryRepository;
24417 govind 61
 
31762 tejbeer 62
    @Autowired
63
    ActivityRepository activityRepository;
24417 govind 64
 
31762 tejbeer 65
    @Autowired
32923 ranu 66
    TicketActivityMediaRepository activityMediaRepository;
67
 
68
    @Autowired
31762 tejbeer 69
    PartnerRegionRepository partnerRegionRepository;
24417 govind 70
 
31762 tejbeer 71
    @Autowired
72
    private PositionRepository positionRepository;
24417 govind 73
 
31762 tejbeer 74
    @Autowired
75
    private AuthRepository authRepository;
24417 govind 76
 
31762 tejbeer 77
    @Autowired
78
    private RetailerService retailerService;
24500 govind 79
 
31762 tejbeer 80
    @Autowired
81
    private RegionRepository regionRepository;
24417 govind 82
 
31762 tejbeer 83
    @Autowired
84
    private TicketAssignedRepository ticketAssignedRepository;
24500 govind 85
 
31762 tejbeer 86
    @Autowired
32493 amit.gupta 87
    private PartnerPositionRepository partnerPositionRepository;
25570 tejbeer 88
 
31762 tejbeer 89
    @Autowired
90
    private FofoStoreRepository fofoStoreRepository;
25570 tejbeer 91
 
34082 ranu 92
    @Autowired
93
    private SessionFactory sessionFactory;
94
 
35635 ranu 95
    @Autowired
96
    EmailService emailService;
97
 
98
    @Autowired
99
    TicketReadStatusRepository ticketReadStatusRepository;
100
 
101
 
31762 tejbeer 102
    @Override
103
    public void createTicket(int fofoId, int categoryId, int subcategoryId, String message) throws ProfitMandiBusinessException {
32923 ranu 104
        this.createTicket(fofoId, categoryId, subcategoryId, message, 0);
105
    }
24417 govind 106
 
32923 ranu 107
 
108
    @Override
109
    public void createTicket(int fofoId, int categoryId, int subcategoryId, String message, int createdByAuthId) throws ProfitMandiBusinessException {
110
 
31762 tejbeer 111
        ActivityType type = ActivityType.OPENED;
112
        Ticket ticket = new Ticket();
113
        ticket.setSubCategoryId(subcategoryId);
114
        ticket.setFofoId(fofoId);
115
        ticket.setCreateTimestamp(LocalDateTime.now());
116
        ticket.setUpdateTimestamp(LocalDateTime.now());
117
        ticket.setHappyCode(getRandomString());
118
        ticketRepository.persist(ticket);
32923 ranu 119
        this.addActivity(ticket, this.createActivity(type, message, createdByAuthId));
120
        ticket.setFirstActivityId(ticket.getLastActivityId());
33041 ranu 121
        if (createdByAuthId != 0) {
122
            int l2AuthUser = this.getAuthUserId(categoryId, EscalationType.L2, fofoId);
32923 ranu 123
            this.updateTicket(categoryId, subcategoryId, ticket, l2AuthUser, EscalationType.L2);
33041 ranu 124
        } else {
32923 ranu 125
            this.assignTicket(ticket);
126
        }
27124 amit.gupta 127
 
31762 tejbeer 128
    }
27124 amit.gupta 129
 
31762 tejbeer 130
    @Override
32923 ranu 131
    public void createTicketWithMedia(int fofoId, int categoryId, int subcategoryId, String message, int createdByAuthId, ActivityMediaModel selectedRecording) throws ProfitMandiBusinessException {
132
        ActivityType type = ActivityType.OPENED;
133
        Ticket ticket = new Ticket();
134
        ticket.setSubCategoryId(subcategoryId);
135
        ticket.setFofoId(fofoId);
136
        ticket.setCreateTimestamp(LocalDateTime.now());
137
        ticket.setUpdateTimestamp(LocalDateTime.now());
138
        ticket.setHappyCode(getRandomString());
139
        ticketRepository.persist(ticket);
140
        this.addActivity(ticket, this.createActivity(type, message, createdByAuthId));
141
        this.addMediaActivity(ticket, this.createMediaActivity(selectedRecording));
142
        ticket.setFirstActivityId(ticket.getLastActivityId());
33041 ranu 143
        if (createdByAuthId != 0) {
144
            int l2AuthUser = this.getAuthUserId(categoryId, EscalationType.L2, fofoId);
32923 ranu 145
            this.updateTicket(categoryId, subcategoryId, ticket, l2AuthUser, EscalationType.L2);
33041 ranu 146
        } else {
32923 ranu 147
            this.assignTicket(ticket);
148
        }
149
    }
150
 
33204 ranu 151
    @Override
36210 ranu 152
    public void createTicket(int fofoId, int categoryId, int subcategoryId, String message, int createdByAuthId, EscalationType targetEscalation) throws ProfitMandiBusinessException {
153
        ActivityType type = ActivityType.OPENED;
154
        Ticket ticket = new Ticket();
155
        ticket.setSubCategoryId(subcategoryId);
156
        ticket.setFofoId(fofoId);
157
        ticket.setCreateTimestamp(LocalDateTime.now());
158
        ticket.setUpdateTimestamp(LocalDateTime.now());
159
        ticket.setHappyCode(getRandomString());
160
        ticketRepository.persist(ticket);
161
        this.addActivity(ticket, this.createActivity(type, message, createdByAuthId));
162
        ticket.setFirstActivityId(ticket.getLastActivityId());
163
        if (createdByAuthId != 0) {
164
            int authUser = this.getAuthUserIdWithFallback(categoryId, targetEscalation, fofoId);
165
            this.updateTicket(categoryId, subcategoryId, ticket, authUser, targetEscalation);
166
        } else {
167
            this.assignTicket(ticket);
168
        }
169
    }
170
 
171
    @Override
172
    public void createTicketWithMedia(int fofoId, int categoryId, int subcategoryId, String message, int createdByAuthId, ActivityMediaModel selectedRecording, EscalationType targetEscalation) throws ProfitMandiBusinessException {
173
        ActivityType type = ActivityType.OPENED;
174
        Ticket ticket = new Ticket();
175
        ticket.setSubCategoryId(subcategoryId);
176
        ticket.setFofoId(fofoId);
177
        ticket.setCreateTimestamp(LocalDateTime.now());
178
        ticket.setUpdateTimestamp(LocalDateTime.now());
179
        ticket.setHappyCode(getRandomString());
180
        ticketRepository.persist(ticket);
181
        this.addActivity(ticket, this.createActivity(type, message, createdByAuthId));
182
        this.addMediaActivity(ticket, this.createMediaActivity(selectedRecording));
183
        ticket.setFirstActivityId(ticket.getLastActivityId());
184
        if (createdByAuthId != 0) {
185
            int authUser = this.getAuthUserIdWithFallback(categoryId, targetEscalation, fofoId);
186
            this.updateTicket(categoryId, subcategoryId, ticket, authUser, targetEscalation);
187
        } else {
188
            this.assignTicket(ticket);
189
        }
190
    }
191
 
192
    /**
193
     * Gets auth user ID for given escalation level. If not found, falls back to next level (L1 -> L2 -> L3 -> L4 -> L5)
36212 ranu 194
     * Returns both the auth user ID and the actual escalation level that was used.
36210 ranu 195
     */
36212 ranu 196
    @Override
197
    public EscalationAssignmentResult getAuthUserWithFallback(int categoryId, EscalationType targetEscalation, int fofoId) throws ProfitMandiBusinessException {
36210 ranu 198
        EscalationType currentEscalation = targetEscalation;
199
        while (currentEscalation != null && !currentEscalation.equals(EscalationType.Final)) {
200
            try {
201
                int authUserId = this.getAuthUserId(categoryId, currentEscalation, fofoId);
202
                if (authUserId > 0) {
203
                    LOGGER.info("Found auth user {} for escalation level {} and fofoId {}", authUserId, currentEscalation, fofoId);
36212 ranu 204
                    return new EscalationAssignmentResult(authUserId, currentEscalation);
36210 ranu 205
                }
206
            } catch (Exception e) {
207
                LOGGER.warn("No auth user found for escalation level {} and fofoId {}, trying next level", currentEscalation, fofoId);
208
            }
209
            currentEscalation = currentEscalation.next();
210
        }
36212 ranu 211
        // If no user found at any level, return 0 with the target escalation
36210 ranu 212
        LOGGER.warn("No auth user found for any escalation level for categoryId {} and fofoId {}", categoryId, fofoId);
36212 ranu 213
        return new EscalationAssignmentResult(0, targetEscalation);
36210 ranu 214
    }
215
 
36212 ranu 216
    /**
217
     * Gets auth user ID with fallback (for backward compatibility)
218
     */
219
    private int getAuthUserIdWithFallback(int categoryId, EscalationType targetEscalation, int fofoId) throws ProfitMandiBusinessException {
220
        return getAuthUserWithFallback(categoryId, targetEscalation, fofoId).getAuthUserId();
221
    }
222
 
36210 ranu 223
    @Override
32923 ranu 224
    public TicketActivityMedia createMediaActivity(ActivityMediaModel selectedRecording) {
225
        TicketActivityMedia activity = new TicketActivityMedia();
226
        activity.setMobile(selectedRecording.getMobile());
33588 ranu 227
        activity.setMediaUrl(selectedRecording.getMediaUrl());
32923 ranu 228
        activity.setDurationInSec(selectedRecording.getDurationInSec());
229
        activity.setCallTime(selectedRecording.getCallConnectTime());
230
        activity.setCreatedBy(0);
231
        activity.setCreateTimestamp(LocalDateTime.now());
232
        activityMediaRepository.persist(activity);
233
        return activity;
234
    }
235
 
33204 ranu 236
    @Override
32923 ranu 237
    public void addMediaActivity(Ticket ticket, TicketActivityMedia activity) {
32940 ranu 238
        activity.setActivityId(ticket.getLastActivityId());
32923 ranu 239
    }
240
 
241
    @Override
242
    public void createTicketRemarkEscalation(int fofoId, int authId, int categoryId, int subcategoryId, String message, CollectionRemark remark) throws ProfitMandiBusinessException {
243
 
244
        ActivityType type = ActivityType.OPENED;
245
        Ticket ticket = new Ticket();
246
        ticket.setSubCategoryId(subcategoryId);
247
        ticket.setFofoId(fofoId);
248
        ticket.setCreateTimestamp(LocalDateTime.now());
249
        ticket.setUpdateTimestamp(LocalDateTime.now());
250
        ticket.setHappyCode(getRandomString());
251
        ticketRepository.persist(ticket);
252
        this.addActivity(ticket, this.createActivity(type, String.valueOf(remark), authId));
253
        ticket.setFirstActivityId(ticket.getLastActivityId());
33041 ranu 254
        this.assignTicketByAuthId(ticket, authId, EscalationType.L2);
32923 ranu 255
 
256
    }
257
 
258
 
259
    @Override
31762 tejbeer 260
    public void assignTicket(Ticket ticket) throws ProfitMandiBusinessException {
35683 ranu 261
        this.assignTicket(ticket,0);
262
    }
263
 
264
    @Override
265
    public void assignTicket(Ticket ticket,int currentUserId) throws ProfitMandiBusinessException {
31762 tejbeer 266
        TicketAssigned ticketAssigned = null;
267
        EscalationType newEscalationType = EscalationType.L1;
268
        if (ticket.getAssignmentId() > 0) {
269
            ticketAssigned = ticketAssignedRepository.selectById(ticket.getAssignmentId());
270
            newEscalationType = ticketAssigned.getEscalationType().next();
271
            if (newEscalationType == null || newEscalationType.equals(EscalationType.Final)) {
272
                LOGGER.info("Cant escalate further");
273
                return;
274
            }
275
        }
276
        ticket.setUpdateTimestamp(LocalDateTime.now());
27124 amit.gupta 277
 
31762 tejbeer 278
        TicketSubCategory ticketSubCategory = ticketSubCategoryRepository.selectById(ticket.getSubCategoryId());
279
        TicketCategory ticketCategory = ticketCategoryRepository.selectById(ticketSubCategory.getCategoryId());
27545 tejbeer 280
 
37145 ranu 281
        // One-step escalation: pick the current-level assignee (with fallback to next level if
282
        // the current level has no one configured), then pick one more level up as the manager.
283
        // History is preserved in ticket_assigned; Ticket only carries current state.
284
        EscalationAssignmentResult assigneeResult =
285
                this.getAuthUserWithFallback(ticketCategory.getId(), newEscalationType, ticket.getFofoId());
27124 amit.gupta 286
 
37145 ranu 287
        int assigneeAuthId;
288
        EscalationType assigneeEscalationType;
289
        int managerAuthId;
27545 tejbeer 290
 
37145 ranu 291
        if (assigneeResult.getAuthUserId() == 0) {
31762 tejbeer 292
            assigneeAuthId = ProfitMandiConstants.FINAL_AUTH_ID;
293
            assigneeEscalationType = EscalationType.Final;
294
            managerAuthId = ProfitMandiConstants.FINAL_AUTH_ID;
295
        } else {
37145 ranu 296
            assigneeAuthId = assigneeResult.getAuthUserId();
297
            assigneeEscalationType = assigneeResult.getActualEscalationType();
298
 
299
            EscalationType managerLevel = assigneeEscalationType.next();
300
            if (managerLevel == null || managerLevel.equals(EscalationType.Final)) {
31762 tejbeer 301
                managerAuthId = ProfitMandiConstants.FINAL_AUTH_ID;
37145 ranu 302
            } else {
303
                EscalationAssignmentResult managerResult =
304
                        this.getAuthUserWithFallback(ticketCategory.getId(), managerLevel, ticket.getFofoId());
305
                managerAuthId = managerResult.getAuthUserId() > 0
306
                        ? managerResult.getAuthUserId()
307
                        : ProfitMandiConstants.FINAL_AUTH_ID;
31762 tejbeer 308
            }
309
        }
27545 tejbeer 310
 
37145 ranu 311
        ticket.setCurrentAssigneeId(assigneeAuthId);
312
        ticket.setCurrentManagerId(managerAuthId);
313
        ticket.setCurrentEscalationLevel(assigneeEscalationType);
314
 
31762 tejbeer 315
        TicketAssigned ticketAssignedNew = new TicketAssigned();
316
        ticketAssignedNew.setTicketId(ticket.getId());
317
        ticketAssignedNew.setAssineeId(assigneeAuthId);
318
        ticketAssignedNew.setEscalationType(assigneeEscalationType);
319
        ticketAssignedNew.setManagerId(managerAuthId);
35683 ranu 320
        ticketAssignedNew.setAssignedBy(currentUserId);
31762 tejbeer 321
        ticketAssignedNew.setCreateTimestamp(LocalDateTime.now());
322
        ticketAssignedRepository.persist(ticketAssignedNew);
323
        LOGGER.info(ticketAssigned);
24383 amit.gupta 324
 
31762 tejbeer 325
        AuthUser authUser = authRepository.selectById(ticketAssignedNew.getAssineeId());
326
        AuthUser authUserManager = null;
27124 amit.gupta 327
 
31762 tejbeer 328
        // Dont send cc mail if both are same
329
        if (managerAuthId != assigneeAuthId) {
330
            authUserManager = authRepository.selectById(managerAuthId);
331
        }
332
        ticket.setAssignmentId(ticketAssignedNew.getId());
27124 amit.gupta 333
 
31762 tejbeer 334
        List<Activity> activities = activityRepository.selectAll(ticket.getId());
335
        this.sendAssignedTicketMail(authUser, Arrays.asList(authUserManager), ticket, ticketAssigned != null, activities);
336
        if (!ticketAssignedNew.getEscalationType().equals(EscalationType.L1)) {
35683 ranu 337
            this.addActivity(ticket, this.createActivity(ActivityType.ESCALATED, "Ticket ecalated and assigned to " + authUser.getName(), currentUserId));
31762 tejbeer 338
        } else {
35683 ranu 339
            this.addActivity(ticket, this.createActivity(ActivityType.ASSIGNED, "Ticket assigned to " + authUser.getName(), currentUserId));
31762 tejbeer 340
        }
341
    }
27124 amit.gupta 342
 
37145 ranu 343
    @Override
344
    public boolean isInEscalationChain(int ticketId, int authId) {
345
        if (ticketId <= 0 || authId <= 0) {
346
            return false;
347
        }
348
        return ticketAssignedRepository.selectByAssigneeIdAndTicketId(authId, ticketId) != null;
349
    }
350
 
351
    @Override
352
    public Set<Integer> ticketsInEscalationChain(int authId, List<Integer> ticketIds) {
353
        if (authId <= 0 || ticketIds == null || ticketIds.isEmpty()) {
354
            return Collections.emptySet();
355
        }
356
        return ticketAssignedRepository.selectByTicketIds(ticketIds).stream()
357
                .filter(ta -> ta.getAssineeId() == authId)
358
                .map(TicketAssigned::getTicketId)
359
                .collect(Collectors.toSet());
360
    }
361
 
31762 tejbeer 362
    public void updateTicket(int categoryId, int subCategoryId, Ticket ticket, int authUserId, EscalationType escalationType) throws ProfitMandiBusinessException {
35683 ranu 363
        this.updateTicket(categoryId, subCategoryId, ticket, authUserId, escalationType, null,0);
33204 ranu 364
    }
27545 tejbeer 365
 
33204 ranu 366
    @Override
35683 ranu 367
    public void updateTicket(int categoryId, int subCategoryId, Ticket ticket, int authUserId, EscalationType escalationType, ActivityMediaModel recording,int currentUserId) throws ProfitMandiBusinessException {
35647 ranu 368
        LOGGER.info("subCategoryId {}",subCategoryId);
31762 tejbeer 369
        TicketSubCategory ticketSubCategory = ticketSubCategoryRepository.getTicketSubCategoryMap().get(subCategoryId);
370
        if (ticketSubCategory == null) {
371
            throw new ProfitMandiBusinessException("Could not find subCategoryId " + subCategoryId + "- " + categoryId, "Problem", "Problem");
372
        }
373
        String storeName = retailerService.getAllFofoRetailers().get(ticket.getFofoId()).getBusinessName();
374
        List<TicketAssigned> oldTicketAssignedList = ticketAssignedRepository.selectByTicketIds(Arrays.asList(ticket.getId()));
375
        for (TicketAssigned oldTicketAssigned : oldTicketAssignedList) {
376
            ticketAssignedRepository.delete(oldTicketAssigned);
377
        }
27124 amit.gupta 378
 
31762 tejbeer 379
        if (ticket.getSubCategoryId() != ticketSubCategory.getId()) {
380
            ticket.setSubCategoryId(ticketSubCategory.getId());
381
            List<Integer> oldAssignedAuthUserIds = oldTicketAssignedList.stream().map(x -> x.getAssineeId()).collect(Collectors.toList());
35394 amit 382
            List<String> oldAssignedEmailIds = authRepository.selectByIds(oldAssignedAuthUserIds).stream().map(x -> x.getEmailId()).collect(Collectors.toList());
31762 tejbeer 383
            String mailTo = oldAssignedEmailIds.remove(0);
384
            String message = String.format(CATEGORY_CHANGED_TICKET, ticket.getId(), storeName, ticketSubCategory.getTicketCategory().getName() + " - " + ticketSubCategory.getName());
385
            try {
35963 amit 386
                mailOutboxService.queueMail(mailTo, oldAssignedEmailIds.toArray(new String[0]), "Ticket Category/Subcategory Changed", message, "CsServiceImpl.updateTicket");
31762 tejbeer 387
            } catch (Exception e) {
388
                LOGGER.info("Could not send mail for ticket {}", ticket.toString());
389
            }
24417 govind 390
 
31762 tejbeer 391
            Activity categoryChangedActivity = this.createActivity(ActivityType.CATEGORY_CHANGED, "Category changed to " + ticketSubCategory.getTicketCategory().getName() + " - " + ticketSubCategory.getName(), 0);
392
            this.addActivity(ticket, categoryChangedActivity);
34158 tejus.loha 393
            if (recording != null) {
33204 ranu 394
                this.addMediaActivity(ticket, this.createMediaActivity(recording));
395
            }
24439 govind 396
 
24383 amit.gupta 397
 
31762 tejbeer 398
        }
24383 amit.gupta 399
 
31762 tejbeer 400
        if (authUserId > 0) {
35683 ranu 401
            LOGGER.info("authUserId--1111444 {}",authUserId);
31762 tejbeer 402
            this.assignTicketByAuthId(ticket, authUserId, escalationType);
24417 govind 403
 
31762 tejbeer 404
        } else {
35683 ranu 405
            LOGGER.info("authUserId--11113355 {}",authUserId);
31762 tejbeer 406
            ticket.setAssignmentId(0);
35683 ranu 407
            this.assignTicket(ticket,currentUserId);
31762 tejbeer 408
        }
24417 govind 409
 
31762 tejbeer 410
    }
24500 govind 411
 
31762 tejbeer 412
    private void assignTicketByAuthId(Ticket ticket, int authUserId, EscalationType escalationType) throws ProfitMandiBusinessException {
24500 govind 413
 
31762 tejbeer 414
        AuthUser authUser = authRepository.selectById(authUserId);
24500 govind 415
 
31762 tejbeer 416
        LOGGER.info("authUser {}", authUser);
24417 govind 417
 
31762 tejbeer 418
        int managerAuthId = authUser.getManagerId();
24417 govind 419
 
37145 ranu 420
        // One-step model: the manual assignment records the current assignee and the
421
        // configured next-level manager. Downstream escalations still walk one level per
422
        // cron cycle in assignTicket(). History remains in ticket_assigned.
423
        int nextLevelManagerId = 0;
424
        if (escalationType != null) {
425
            EscalationType nextLevel = escalationType.next();
426
            if (nextLevel != null && !nextLevel.equals(EscalationType.Final)) {
427
                TicketSubCategory ticketSubCategory = ticketSubCategoryRepository.selectById(ticket.getSubCategoryId());
428
                TicketCategory ticketCategory = ticketCategoryRepository.selectById(ticketSubCategory.getCategoryId());
429
                EscalationAssignmentResult mgr =
430
                        this.getAuthUserWithFallback(ticketCategory.getId(), nextLevel, ticket.getFofoId());
431
                nextLevelManagerId = mgr.getAuthUserId();
432
            }
31762 tejbeer 433
        }
37145 ranu 434
        if (nextLevelManagerId <= 0) {
435
            nextLevelManagerId = managerAuthId > 0 ? managerAuthId : ProfitMandiConstants.FINAL_AUTH_ID;
31762 tejbeer 436
        }
30426 tejbeer 437
 
37145 ranu 438
        ticket.setCurrentAssigneeId(authUserId);
439
        ticket.setCurrentManagerId(nextLevelManagerId);
440
        ticket.setCurrentEscalationLevel(escalationType);
30426 tejbeer 441
 
31762 tejbeer 442
        TicketAssigned ticketAssignedNew = new TicketAssigned();
443
        ticketAssignedNew.setTicketId(ticket.getId());
444
        ticketAssignedNew.setAssineeId(authUserId);
445
        ticketAssignedNew.setEscalationType(escalationType);
446
        ticketAssignedNew.setManagerId(managerAuthId);
447
        ticketAssignedNew.setCreateTimestamp(LocalDateTime.now());
448
        ticketAssignedRepository.persist(ticketAssignedNew);
24439 govind 449
 
31762 tejbeer 450
        LOGGER.info("ticketAssignedNew {}", ticketAssignedNew);
24439 govind 451
 
24500 govind 452
 
31762 tejbeer 453
        AuthUser authUserManager = null;
24439 govind 454
 
24500 govind 455
 
31762 tejbeer 456
        // Dont send cc mail if both are same
457
        if (managerAuthId != authUserId) {
458
            authUserManager = authRepository.selectById(managerAuthId);
459
        }
460
        ticket.setAssignmentId(ticketAssignedNew.getId());
27124 amit.gupta 461
 
25570 tejbeer 462
 
31762 tejbeer 463
        List<Activity> activities = activityRepository.selectAll(ticket.getId());
25570 tejbeer 464
 
31762 tejbeer 465
        this.sendAssignedTicketMail(authUser, Arrays.asList(authUserManager), ticket, false, activities);
466
        if (!ticketAssignedNew.getEscalationType().equals(EscalationType.L1)) {
467
            this.addActivity(ticket, this.createActivity(ActivityType.ESCALATED, "Ticket ecalated and assigned to " + authUser.getName(), 0));
468
        } else {
469
            this.addActivity(ticket, this.createActivity(ActivityType.ASSIGNED, "Ticket assigned to " + authUser.getName(), 0));
470
        }
25570 tejbeer 471
 
31762 tejbeer 472
    }
25570 tejbeer 473
 
31762 tejbeer 474
    @Override
475
    public Activity createActivity(ActivityType activityType, String message, int createdBy) {
476
        Activity activity = new Activity();
477
        activity.setMessage(message);
478
        activity.setCreatedBy(createdBy);
479
        activity.setType(activityType);
480
        activity.setCreateTimestamp(LocalDateTime.now());
481
        activityRepository.persist(activity);
482
        return activity;
483
    }
25570 tejbeer 484
 
31762 tejbeer 485
    @Override
33244 ranu 486
    public int getAuthUserId(int categoryId, EscalationType escalationType, int fofoId) throws ProfitMandiBusinessException {
31762 tejbeer 487
        int authUserId = 0;
488
        List<Position> positions = positionRepository.selectPositionbyCategoryIdAndEscalationType(categoryId, escalationType);
489
        List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId()).collect(Collectors.toList());
490
        // Add all Partner regions id
491
        regionIds.add(ALL_PARTNERS_REGION);
492
        LOGGER.info("Escalation Type {}, Region Ids {}", escalationType, regionIds);
32493 amit.gupta 493
        List<Integer> partnerPositionsIds = partnerPositionRepository.selectByRegionIdAndPartnerId(regionIds, Arrays.asList(0, fofoId)).stream().map(x -> x.getPositionId()).collect(Collectors.toList());
33022 amit.gupta 494
 
31829 amit.gupta 495
        List<Position> positionAssignee = positions.stream().filter(x -> x.isTicketAssignee() && partnerPositionsIds.contains(x.getId())).collect(Collectors.toList());
31762 tejbeer 496
        LOGGER.info("User List List {}", positions.stream().map(x -> x.getAuthUserId()).collect(Collectors.toList()));
34276 ranu 497
        LOGGER.info("positionAssignee List {}", positionAssignee);
31829 amit.gupta 498
        if (positionAssignee.size() > 0) {
34276 ranu 499
 
35394 amit 500
            List<AuthUser> authUsers = authRepository.selectByIds(
33022 amit.gupta 501
                    positionAssignee.stream().map(x -> x.getAuthUserId()).collect(Collectors.toList()));
31762 tejbeer 502
            authUsers = authUsers.stream().filter(x -> x.isActive()).collect(Collectors.toList());
34276 ranu 503
            LOGGER.info("Auth User List {}", authUsers);
31762 tejbeer 504
            if (authUsers.size() > 0) {
505
                authUserId = authUsers.get(0).getId();
506
                /*
507
                 * Random rand = new Random(); authUserId =
508
                 * authUsers.get(rand.nextInt(authUsers.size())).getId();
509
                 */
510
            }
511
        }
512
        return authUserId;
25570 tejbeer 513
 
31762 tejbeer 514
    }
25597 amit.gupta 515
 
34921 ranu 516
    @Override
517
    public int getAuthUserIdWithoutTicketAssignee(int categoryId, EscalationType escalationType, int fofoId) throws ProfitMandiBusinessException {
518
        int authUserId = 0;
519
        List<Position> positions = positionRepository.selectPositionbyCategoryIdAndEscalationType(categoryId, escalationType);
520
        List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId()).collect(Collectors.toList());
521
        // Add all Partner regions id
522
        regionIds.add(ALL_PARTNERS_REGION);
523
        LOGGER.info("Escalation Type {}, Region Ids {}", escalationType, regionIds);
524
        List<Integer> partnerPositionsIds = partnerPositionRepository.selectByRegionIdAndPartnerId(regionIds, Arrays.asList(0, fofoId)).stream().map(x -> x.getPositionId()).collect(Collectors.toList());
33022 amit.gupta 525
 
34921 ranu 526
        List<Position> positionAssignee = positions.stream().filter(x -> partnerPositionsIds.contains(x.getId())).collect(Collectors.toList());
527
        LOGGER.info("User List List {}", positions.stream().map(x -> x.getAuthUserId()).collect(Collectors.toList()));
528
        LOGGER.info("positionAssignee List {}", positionAssignee);
529
        if (positionAssignee.size() > 0) {
530
 
35394 amit 531
            List<AuthUser> authUsers = authRepository.selectByIds(
34921 ranu 532
                    positionAssignee.stream().map(x -> x.getAuthUserId()).collect(Collectors.toList()));
533
            authUsers = authUsers.stream().filter(x -> x.isActive()).collect(Collectors.toList());
534
            LOGGER.info("Auth User List {}", authUsers);
535
            if (authUsers.size() > 0) {
536
                authUserId = authUsers.get(0).getId();
537
                /*
538
                 * Random rand = new Random(); authUserId =
539
                 * authUsers.get(rand.nextInt(authUsers.size())).getId();
540
                 */
541
            }
542
        }
543
        return authUserId;
544
 
545
    }
546
 
547
 
31762 tejbeer 548
    @Override
549
    public void addActivity(Ticket ticket, Activity activity) {
550
        activity.setTicketId(ticket.getId());
551
        ticket.setLastActivity(activity.getType());
552
        ticket.setLastActivityId(activity.getId());
553
    }
25597 amit.gupta 554
 
31762 tejbeer 555
    private String getRandomString() {
556
        int length = 4;
557
        boolean useLetters = false;
558
        boolean useNumbers = true;
559
        String generatedString = RandomStringUtils.random(length, useLetters, useNumbers);
560
        return generatedString;
561
    }
25721 tejbeer 562
 
31762 tejbeer 563
    @Override
564
    public void addPartnerToRegion(int regionId, List<Integer> fofoIds) {
25721 tejbeer 565
 
31762 tejbeer 566
        for (int fofoId : fofoIds) {
567
            PartnerRegion partnerRegion = new PartnerRegion();
568
            partnerRegion.setFofoId(fofoId);
569
            partnerRegion.setRegionId(regionId);
570
            partnerRegionRepository.persist(partnerRegion);
571
        }
572
    }
25721 tejbeer 573
 
31762 tejbeer 574
    @Override
575
    public Map<Integer, AuthUser> getAuthUserIdAndAuthUserMap(List<TicketAssigned> ticketAssigneds) {
35454 amit 576
        if (ticketAssigneds == null || ticketAssigneds.isEmpty()) {
577
            return new HashMap<>();
578
        }
579
        // OPTIMIZED: Batch fetch all AuthUsers instead of N+1 queries
580
        List<Integer> assigneeIds = ticketAssigneds.stream()
581
                .map(TicketAssigned::getAssineeId)
582
                .distinct()
583
                .collect(Collectors.toList());
584
        Map<Integer, AuthUser> authUserById = authRepository.selectByIds(assigneeIds).stream()
585
                .collect(Collectors.toMap(AuthUser::getId, au -> au, (a, b) -> a));
586
 
31762 tejbeer 587
        Map<Integer, AuthUser> authUserIdAndAuthUserMap = new HashMap<>();
588
        for (TicketAssigned ticketAssigned : ticketAssigneds) {
35454 amit 589
            authUserIdAndAuthUserMap.put(ticketAssigned.getTicketId(), authUserById.get(ticketAssigned.getAssineeId()));
31762 tejbeer 590
        }
591
        return authUserIdAndAuthUserMap;
592
    }
31465 tejbeer 593
 
31762 tejbeer 594
    @Override
595
    public Map<Integer, AuthUser> getTicketIdAndAuthUserMapUsingTickets(List<Ticket> tickets) {
35454 amit 596
        if (tickets == null || tickets.isEmpty()) {
597
            return new HashMap<>();
598
        }
37145 ranu 599
        // Batch fetch AuthUsers by current_assignee_id (one owner per ticket in the new model).
35454 amit 600
        List<Integer> authUserIds = tickets.stream()
37145 ranu 601
                .map(Ticket::getCurrentAssigneeId)
602
                .filter(id -> id > 0)
35454 amit 603
                .distinct()
604
                .collect(Collectors.toList());
605
        Map<Integer, AuthUser> authUserById = authRepository.selectByIds(authUserIds).stream()
606
                .collect(Collectors.toMap(AuthUser::getId, au -> au, (a, b) -> a));
607
 
31762 tejbeer 608
        Map<Integer, AuthUser> authUserIdAndAuthUserMap = new HashMap<>();
609
        for (Ticket ticket : tickets) {
37145 ranu 610
            authUserIdAndAuthUserMap.put(ticket.getId(), authUserById.get(ticket.getCurrentAssigneeId()));
31762 tejbeer 611
        }
612
        return authUserIdAndAuthUserMap;
613
    }
31152 tejbeer 614
 
35562 ranu 615
 
31762 tejbeer 616
    @Override
617
    public Map<Integer, TicketSubCategory> getSubCategoryIdAndSubCategoryMap(List<Integer> subCategoryIds) {
618
        Map<Integer, TicketSubCategory> subCategoryIdAndSubCategoryMap = new HashMap<>();
619
        subCategoryIdAndSubCategoryMap = ticketSubCategoryRepository.selectByIds(subCategoryIds).stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
620
        return subCategoryIdAndSubCategoryMap;
621
    }
31152 tejbeer 622
 
31762 tejbeer 623
    @Override
33244 ranu 624
    public Map<Integer, CustomRetailer> getPartnerByFofoIds(List<Ticket> tickets) throws ProfitMandiBusinessException {
31762 tejbeer 625
        List<Integer> fofoIds = new ArrayList<>();
626
        LOGGER.info(tickets);
627
        if (tickets == null) {
628
            return null;
629
        }
630
        for (Ticket ticket : tickets) {
631
            fofoIds.add(ticket.getFofoId());
632
        }
25721 tejbeer 633
 
31762 tejbeer 634
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
25721 tejbeer 635
 
31762 tejbeer 636
        Map<Integer, CustomRetailer> fofoIdsAndCustomRetailer = fofoIds.stream().distinct().map(x -> customRetailerMap.get(x)).filter(x -> x != null).collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
637
        return fofoIdsAndCustomRetailer;
638
    }
25799 tejbeer 639
 
31762 tejbeer 640
    @Override
641
    public List<TicketCategory> getAllTicketCategotyFromSubCategory() {
25721 tejbeer 642
 
31830 amit.gupta 643
        Collection<TicketSubCategory> ticketSubCategories = ticketSubCategoryRepository.getTicketSubCategoryMap().values();
644
        return new ArrayList<>(ticketSubCategories.stream().map(x -> x.getTicketCategory()).collect(Collectors.toSet()));
31762 tejbeer 645
    }
25799 tejbeer 646
 
31762 tejbeer 647
    @Override
648
    public Map<Integer, AuthUser> getAuthUserIdAndAuthUserMapUsingPositions(List<Position> positions) {
35454 amit 649
        if (positions == null || positions.isEmpty()) {
650
            return new HashMap<>();
31762 tejbeer 651
        }
35454 amit 652
        // OPTIMIZED: Batch fetch all AuthUsers instead of N+1 queries
653
        List<Integer> authUserIds = positions.stream()
654
                .map(Position::getAuthUserId)
655
                .filter(id -> id != null && id > 0)
656
                .distinct()
657
                .collect(Collectors.toList());
658
        return authRepository.selectByIds(authUserIds).stream()
659
                .collect(Collectors.toMap(AuthUser::getId, au -> au, (a, b) -> a));
31762 tejbeer 660
    }
25721 tejbeer 661
 
31762 tejbeer 662
    @Override
663
    public Map<Integer, TicketCategory> getCategoryIdAndCategoryUsingPositions(List<Position> positions) {
35454 amit 664
        if (positions == null || positions.isEmpty()) {
665
            return new HashMap<>();
31762 tejbeer 666
        }
35454 amit 667
        // OPTIMIZED: Batch fetch all categories instead of N+1 queries
668
        List<Integer> categoryIds = positions.stream()
669
                .map(Position::getCategoryId)
670
                .filter(id -> id != null && id > 0)
671
                .distinct()
672
                .collect(Collectors.toList());
673
        return ticketCategoryRepository.selectAll(categoryIds).stream()
674
                .collect(Collectors.toMap(TicketCategory::getId, tc -> tc, (a, b) -> a));
31762 tejbeer 675
    }
29318 tejbeer 676
 
31762 tejbeer 677
    @Override
678
    public Map<Integer, Region> getRegionIdAndRegionMap(List<Position> positions) {
35454 amit 679
        if (positions == null || positions.isEmpty()) {
680
            return new HashMap<>();
31762 tejbeer 681
        }
35454 amit 682
        // OPTIMIZED: Batch fetch all regions instead of N+1 queries
683
        Set<Integer> regionIds = positions.stream()
684
                .map(Position::getRegionId)
685
                .filter(id -> id != null && id > 0)
686
                .collect(Collectors.toSet());
687
        return regionRepository.selectAll().stream()
688
                .filter(r -> regionIds.contains(r.getId()))
689
                .collect(Collectors.toMap(Region::getId, r -> r, (a, b) -> a));
31762 tejbeer 690
    }
29318 tejbeer 691
 
31762 tejbeer 692
    private void sendAssignedTicketMail(AuthUser authUserTo, List<AuthUser> authUsersCc, Ticket ticket, boolean isEscalated, List<Activity> activities) throws ProfitMandiBusinessException {
693
        try {
694
            String[] ccTo = authUsersCc.stream().filter(x -> x != null).map(x -> x.getEmailId()).toArray(String[]::new);
25721 tejbeer 695
 
31762 tejbeer 696
            String messageFormat = null;
697
            if (isEscalated) {
698
                messageFormat = ESCALATED_TICKET;
699
            } else {
700
                messageFormat = ASSIGNED_TICKET;
701
            }
702
            String message = String.format(messageFormat, authUserTo.getName(), ticket.getId(), activities.get(0).getMessage(), retailerService.getFofoRetailer(ticket.getFofoId()).getBusinessName());
35963 amit 703
            mailOutboxService.queueMail(authUserTo.getEmailId(), ccTo, ASSINMENT_SUBJECT, message, "CsServiceImpl.sendAssignedTicketMail");
31762 tejbeer 704
        } catch (Exception e) {
705
            e.printStackTrace();
706
            throw new ProfitMandiBusinessException("Ticket Assingment", authUserTo.getEmailId(), "Could not send ticket assignment mail");
707
        }
708
    }
26298 tejbeer 709
 
31762 tejbeer 710
    @Override
33244 ranu 711
    public Map<Integer, List<CustomRetailer>> getPositionCustomRetailerMap(List<Position> positions) throws ProfitMandiBusinessException {
31762 tejbeer 712
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
713
        Map<Integer, List<CustomRetailer>> positionRetailerMap = new HashMap<>();
35443 amit 714
 
715
        // Batch fetch all PartnerPositions upfront to avoid N+1 queries
716
        List<Integer> positionIds = positions.stream().map(Position::getId).collect(Collectors.toList());
717
        Map<Integer, List<Integer>> positionIdToFofoIdsMap = partnerPositionRepository.selectByPositionIds(positionIds)
718
                .stream()
719
                .collect(Collectors.groupingBy(
720
                        pp -> pp.getPositionId(),
721
                        Collectors.mapping(pp -> pp.getFofoId(), Collectors.toList())
722
                ));
723
 
724
        // Collect all region IDs that might need lookup (positions with fofoId=0)
725
        Set<Integer> regionIdsNeedingLookup = new HashSet<>();
31762 tejbeer 726
        for (Position position : positions) {
35443 amit 727
            List<Integer> fofoIds = positionIdToFofoIdsMap.get(position.getId());
728
            if (fofoIds != null && fofoIds.contains(0)) {
729
                regionIdsNeedingLookup.add(position.getRegionId());
730
            }
731
        }
26978 tejbeer 732
 
35443 amit 733
        // Batch fetch all PartnerRegions for regions needing lookup
734
        Map<Integer, List<Integer>> regionIdToFofoIdsMap = new HashMap<>();
735
        if (!regionIdsNeedingLookup.isEmpty()) {
736
            regionIdToFofoIdsMap = partnerRegionRepository.selectAllByRegionIds(new ArrayList<>(regionIdsNeedingLookup))
737
                    .stream()
738
                    .collect(Collectors.groupingBy(
739
                            pr -> pr.getRegionId(),
740
                            Collectors.mapping(pr -> pr.getFofoId(), Collectors.toList())
741
                    ));
742
        }
26978 tejbeer 743
 
35443 amit 744
        // Build the result map using pre-fetched data
745
        for (Position position : positions) {
746
            List<Integer> fofoIds = positionIdToFofoIdsMap.get(position.getId());
747
            if (fofoIds == null || fofoIds.isEmpty()) {
748
                continue;
749
            }
750
 
751
            if (fofoIds.contains(0)) {
752
                // Need region-based lookup
753
                fofoIds = regionIdToFofoIdsMap.get(position.getRegionId());
754
                if (fofoIds == null || fofoIds.contains(0)) {
755
                    fofoIds = new ArrayList<>(customRetailerMap.keySet());
31762 tejbeer 756
                }
35443 amit 757
            }
26978 tejbeer 758
 
35443 amit 759
            positionRetailerMap.put(position.getId(),
760
                    fofoIds.stream()
761
                            .map(customRetailerMap::get)
762
                            .filter(x -> x != null)
763
                            .collect(Collectors.toList()));
31762 tejbeer 764
        }
765
        return positionRetailerMap;
766
    }
26978 tejbeer 767
 
31762 tejbeer 768
    @Override
33244 ranu 769
    public Map<Integer, List<CustomRetailer>> getRegionPartners(List<Position> positions) throws ProfitMandiBusinessException {
31762 tejbeer 770
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
771
        Map<Integer, List<CustomRetailer>> positionIdAndpartnerRegionMap = new HashedMap<>();
26978 tejbeer 772
 
35443 amit 773
        // Batch fetch all PartnerRegions upfront to avoid N+1 queries
774
        List<Integer> regionIds = positions.stream().map(Position::getRegionId).distinct().collect(Collectors.toList());
775
        Map<Integer, List<Integer>> regionIdToFofoIdsMap = partnerRegionRepository.selectAllByRegionIds(regionIds)
776
                .stream()
777
                .collect(Collectors.groupingBy(
778
                        pr -> pr.getRegionId(),
779
                        Collectors.mapping(pr -> pr.getFofoId(), Collectors.toList())
780
                ));
26978 tejbeer 781
 
35443 amit 782
        // Fetch all store IDs once in case any region has fofoId=0
783
        List<Integer> allStoreIds = null;
26978 tejbeer 784
 
35443 amit 785
        for (Position position : positions) {
786
            List<Integer> fofoIds = regionIdToFofoIdsMap.get(position.getRegionId());
787
            if (fofoIds == null || fofoIds.isEmpty()) {
788
                continue;
31762 tejbeer 789
            }
26978 tejbeer 790
 
35443 amit 791
            if (fofoIds.contains(0)) {
792
                if (allStoreIds == null) {
793
                    allStoreIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId()).collect(Collectors.toList());
794
                }
795
                fofoIds = allStoreIds;
796
            }
797
 
798
            Map<Integer, CustomRetailer> fofoRetailers = fofoIds.stream()
799
                    .map(customRetailerMap::get)
800
                    .filter(x -> x != null)
801
                    .collect(Collectors.toMap(x -> x.getPartnerId(), x -> x, (a, b) -> a));
802
            positionIdAndpartnerRegionMap.put(position.getRegionId(), new ArrayList<>(fofoRetailers.values()));
31762 tejbeer 803
        }
26978 tejbeer 804
 
31762 tejbeer 805
        return positionIdAndpartnerRegionMap;
806
    }
26978 tejbeer 807
 
31762 tejbeer 808
    @Override
809
    @Cacheable(value = "authUserEmailMapping", cacheManager = "thirtyMinsTimeOutCacheManager")
33244 ranu 810
    public Map<String, Set<String>> getAuthUserPartnerEmailMapping() throws ProfitMandiBusinessException {
31762 tejbeer 811
        Map<String, Set<String>> storeGuyMap = new HashMap<>();
812
        Set<Integer> activeFofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId()).collect(Collectors.toSet());
35443 amit 813
 
814
        // Batch fetch positions by category IDs instead of multiple calls
815
        List<Position> categoryPositions = positionRepository.selectPositionByCategoryIds(Arrays.asList(
816
                ProfitMandiConstants.TICKET_CATEGORY_SALES,
817
                ProfitMandiConstants.TICKET_CATEGORY_RBM,
818
                ProfitMandiConstants.TICKET_CATEGORY_ABM));
31762 tejbeer 819
        Map<Integer, Position> positionsMap = categoryPositions.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
29229 tejbeer 820
 
35443 amit 821
        // Batch fetch all AuthUsers upfront to avoid N+1 queries
822
        Set<Integer> authUserIds = categoryPositions.stream().map(Position::getAuthUserId).collect(Collectors.toSet());
823
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(new ArrayList<>(authUserIds)).stream()
824
                .collect(Collectors.toMap(AuthUser::getId, x -> x));
825
 
31762 tejbeer 826
        Map<Integer, List<CustomRetailer>> positonPartnerMap = this.getPositionCustomRetailerMap(categoryPositions);
827
        for (Map.Entry<Integer, List<CustomRetailer>> positionPartnerEntry : positonPartnerMap.entrySet()) {
828
            int authUserId = positionsMap.get(positionPartnerEntry.getKey()).getAuthUserId();
829
            Set<String> partnerEmails = positionPartnerEntry.getValue().stream().filter(x -> activeFofoIds.contains(x.getPartnerId())).map(x -> x.getEmail()).collect(Collectors.toSet());
35443 amit 830
            AuthUser authUser = authUserMap.get(authUserId);
831
            if (authUser != null && authUser.isActive()) {
31762 tejbeer 832
                if (!storeGuyMap.containsKey(authUser.getEmailId())) {
833
                    storeGuyMap.put(authUser.getEmailId(), partnerEmails);
834
                } else {
835
                    storeGuyMap.get(authUser.getEmailId()).addAll(partnerEmails);
836
                }
837
            }
838
        }
839
        return storeGuyMap;
840
    }
29229 tejbeer 841
 
31762 tejbeer 842
    @Override
843
    @Cacheable(value = "authUserEmailPartnerIdMapping", cacheManager = "thirtyMinsTimeOutCacheManager")
33244 ranu 844
    public Map<String, Set<Integer>> getAuthUserPartnerIdMapping() throws ProfitMandiBusinessException {
31762 tejbeer 845
        Map<String, Set<Integer>> storeGuyMap = new HashMap<>();
846
        Set<Integer> activeFofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId()).collect(Collectors.toSet());
35443 amit 847
 
848
        // Batch fetch positions by category IDs instead of multiple calls
849
        List<Position> categoryPositions = positionRepository.selectPositionByCategoryIds(Arrays.asList(
850
                ProfitMandiConstants.TICKET_CATEGORY_SALES,
851
                ProfitMandiConstants.TICKET_CATEGORY_RBM,
852
                ProfitMandiConstants.TICKET_CATEGORY_ABM,
853
                ProfitMandiConstants.TICKET_CATEGORY_BUSINESSINTELLIGENT,
854
                ProfitMandiConstants.TICKET_CATEGORY_TRAINING));
31762 tejbeer 855
        Map<Integer, Position> positionsMap = categoryPositions.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
31161 tejbeer 856
 
35443 amit 857
        // Batch fetch all AuthUsers upfront to avoid N+1 queries
858
        Set<Integer> authUserIds = categoryPositions.stream().map(Position::getAuthUserId).collect(Collectors.toSet());
859
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(new ArrayList<>(authUserIds)).stream()
860
                .collect(Collectors.toMap(AuthUser::getId, x -> x));
861
 
31762 tejbeer 862
        Map<Integer, List<CustomRetailer>> positonPartnerMap = this.getPositionCustomRetailerMap(categoryPositions);
863
        for (Map.Entry<Integer, List<CustomRetailer>> positionPartnerEntry : positonPartnerMap.entrySet()) {
864
            int authUserId = positionsMap.get(positionPartnerEntry.getKey()).getAuthUserId();
865
            Set<Integer> partnerIds = positionPartnerEntry.getValue().stream().filter(x -> activeFofoIds.contains(x.getPartnerId())).map(x -> x.getPartnerId()).collect(Collectors.toSet());
35443 amit 866
            AuthUser authUser = authUserMap.get(authUserId);
867
            if (authUser != null && authUser.isActive()) {
31762 tejbeer 868
                if (!storeGuyMap.containsKey(authUser.getEmailId())) {
869
                    storeGuyMap.put(authUser.getEmailId(), partnerIds);
870
                } else {
871
                    storeGuyMap.get(authUser.getEmailId()).addAll(partnerIds);
872
                }
873
            }
874
        }
875
        return storeGuyMap;
876
    }
31472 tejbeer 877
 
31762 tejbeer 878
    @Override
35920 ranu 879
    @Cacheable(value = "authUserEmailInactivePartnerIdMapping", cacheManager = "thirtyMinsTimeOutCacheManager")
880
    public Map<String, Set<Integer>> getAuthUserInactivePartnerIdMapping() throws ProfitMandiBusinessException {
881
        Map<String, Set<Integer>> storeGuyMap = new HashMap<>();
882
        Set<Integer> activeFofoIds = fofoStoreRepository.selectInActiveStore().stream().map(x -> x.getId()).collect(Collectors.toSet());
883
 
884
        // Batch fetch positions by category IDs instead of multiple calls
885
        List<Position> categoryPositions = positionRepository.selectPositionByCategoryIds(Arrays.asList(
886
                ProfitMandiConstants.TICKET_CATEGORY_SALES,
887
                ProfitMandiConstants.TICKET_CATEGORY_RBM,
888
                ProfitMandiConstants.TICKET_CATEGORY_ABM,
889
                ProfitMandiConstants.TICKET_CATEGORY_BUSINESSINTELLIGENT,
890
                ProfitMandiConstants.TICKET_CATEGORY_TRAINING));
891
        Map<Integer, Position> positionsMap = categoryPositions.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
892
 
893
        // Batch fetch all AuthUsers upfront to avoid N+1 queries
894
        Set<Integer> authUserIds = categoryPositions.stream().map(Position::getAuthUserId).collect(Collectors.toSet());
895
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(new ArrayList<>(authUserIds)).stream()
896
                .collect(Collectors.toMap(AuthUser::getId, x -> x));
897
 
898
        Map<Integer, List<CustomRetailer>> positonPartnerMap = this.getPositionCustomRetailerMap(categoryPositions);
899
        for (Map.Entry<Integer, List<CustomRetailer>> positionPartnerEntry : positonPartnerMap.entrySet()) {
900
            int authUserId = positionsMap.get(positionPartnerEntry.getKey()).getAuthUserId();
901
            Set<Integer> partnerIds = positionPartnerEntry.getValue().stream().filter(x -> activeFofoIds.contains(x.getPartnerId())).map(x -> x.getPartnerId()).collect(Collectors.toSet());
902
            AuthUser authUser = authUserMap.get(authUserId);
903
            if (authUser != null && authUser.isActive()) {
904
                if (!storeGuyMap.containsKey(authUser.getEmailId())) {
905
                    storeGuyMap.put(authUser.getEmailId(), partnerIds);
906
                } else {
907
                    storeGuyMap.get(authUser.getEmailId()).addAll(partnerIds);
908
                }
909
            }
910
        }
911
        return storeGuyMap;
912
    }
913
 
914
    @Override
31762 tejbeer 915
    @Cacheable(value = "authUserPartnerEmailPartnerIdMapping", cacheManager = "thirtyMinsTimeOutCacheManager")
33244 ranu 916
    public Map<String, Set<Integer>> getAuthUserPartnerIdMappingByCategoryIds(List<Integer> categoryIds, boolean activeOnly) throws ProfitMandiBusinessException {
31762 tejbeer 917
        Map<String, Set<Integer>> authUserPartnerMap = new HashMap<>();
918
        Set<Integer> activeFofoIds;
919
        if (activeOnly) {
920
            activeFofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId()).collect(Collectors.toSet());
26298 tejbeer 921
 
31762 tejbeer 922
        } else {
923
            activeFofoIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId()).collect(Collectors.toSet());
26298 tejbeer 924
 
31762 tejbeer 925
        }
26298 tejbeer 926
 
31762 tejbeer 927
        List<Position> categoryPositions = positionRepository.selectPositionByCategoryIds(categoryIds);
928
        Map<Integer, Position> positionsMap = categoryPositions.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
26298 tejbeer 929
 
35454 amit 930
        // OPTIMIZED: Batch fetch all AuthUsers instead of N+1 queries
931
        List<Integer> authUserIds = categoryPositions.stream()
932
                .map(Position::getAuthUserId)
933
                .filter(id -> id != null && id > 0)
934
                .distinct()
935
                .collect(Collectors.toList());
936
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(authUserIds).stream()
937
                .collect(Collectors.toMap(AuthUser::getId, au -> au, (a, b) -> a));
938
 
31762 tejbeer 939
        Map<Integer, List<CustomRetailer>> positonPartnerMap = this.getPositionCustomRetailerMap(categoryPositions);
940
        for (Map.Entry<Integer, List<CustomRetailer>> positionPartnerEntry : positonPartnerMap.entrySet()) {
941
            int authUserId = positionsMap.get(positionPartnerEntry.getKey()).getAuthUserId();
942
            Set<Integer> partnerIds = positionPartnerEntry.getValue().stream().filter(x -> activeFofoIds.contains(x.getPartnerId())).map(x -> x.getPartnerId()).collect(Collectors.toSet());
35454 amit 943
            AuthUser authUser = authUserMap.get(authUserId);
944
            if (authUser != null && authUser.isActive()) {
31762 tejbeer 945
                if (!authUserPartnerMap.containsKey(authUser.getEmailId())) {
946
                    authUserPartnerMap.put(authUser.getEmailId(), partnerIds);
947
                } else {
948
                    authUserPartnerMap.get(authUser.getEmailId()).addAll(partnerIds);
949
                }
950
            }
951
        }
952
        return authUserPartnerMap;
953
    }
26298 tejbeer 954
 
31762 tejbeer 955
    @Override
34082 ranu 956
    public Map<Integer, List<Integer>> authUserpartnerIdMap(int authId, int categoryId) {
957
        Session session = sessionFactory.getCurrentSession();
958
 
34084 ranu 959
        Map<Integer, List<Integer>> authUserpartnerIdMap = new HashMap<>();
34082 ranu 960
 
34158 tejus.loha 961
        List<Position> authPositions = positionRepository.selectPositionbyCategoryIdAndAuthId(categoryId, authId);
34082 ranu 962
 
35454 amit 963
        // OPTIMIZED: Batch fetch all PartnerPositions instead of N+1 queries
964
        List<Integer> positionIds = authPositions.stream()
965
                .map(Position::getId)
34084 ranu 966
                .collect(Collectors.toList());
35454 amit 967
        List<PartnerPosition> partnerPositions = partnerPositionRepository.selectByPositionIds(positionIds);
34082 ranu 968
 
34084 ranu 969
        if (partnerPositions.stream().anyMatch(partnerPosition -> partnerPosition.getFofoId() == 0)) {
970
            List<FofoStore> activeFofoStores = fofoStoreRepository.selectActiveStores();
971
 
972
            List<Integer> fofoStoreIds = activeFofoStores.stream()
973
                    .map(FofoStore::getId) // Extract the IDs of FofoStores
974
                    .collect(Collectors.toList());
975
 
976
            authUserpartnerIdMap.put(authId, fofoStoreIds);
977
 
34158 tejus.loha 978
        } else {
34084 ranu 979
            final TypedQuery<AuthUserPartnerMapModel> typedQuerySimilar = session
980
                    .createNamedQuery("Position.Auth_User_Partner_Maping", AuthUserPartnerMapModel.class);
981
 
982
            typedQuerySimilar.setParameter("authId", authId);
983
            typedQuerySimilar.setParameter("categoryId", categoryId);
984
 
985
            List<AuthUserPartnerMapModel> authUserPartnerMapModels = typedQuerySimilar.getResultList();
986
 
987
            authUserpartnerIdMap = authUserPartnerMapModels.stream()
988
                    .collect(Collectors.groupingBy(
989
                            AuthUserPartnerMapModel::getAuthId,
990
                            Collectors.mapping(AuthUserPartnerMapModel::getFofoId, Collectors.toList())
991
                    ));
992
 
993
        }
994
 
34082 ranu 995
        LOGGER.info("partnerusermap {}", authUserpartnerIdMap);
996
        return authUserpartnerIdMap;
997
    }
998
 
999
    @Override
33244 ranu 1000
    public List<String> getAuthUserByPartnerId(int fofoId) throws ProfitMandiBusinessException {
26298 tejbeer 1001
 
31762 tejbeer 1002
        List<String> emails = new ArrayList<>();
1003
        List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId()).collect(Collectors.toList());
26298 tejbeer 1004
 
31762 tejbeer 1005
        regionIds.add(5);// All partners Id;
26298 tejbeer 1006
 
32493 amit.gupta 1007
        List<Integer> partnerPositionIds = partnerPositionRepository.selectByRegionIdAndPartnerId(regionIds, Arrays.asList(fofoId, 0)).stream().map(x -> x.getPositionId()).collect(Collectors.toList());
26448 amit.gupta 1008
 
31762 tejbeer 1009
        LOGGER.info("partnerPositionIds" + partnerPositionIds);
27205 amit.gupta 1010
 
35394 amit 1011
        List<Position> positions = positionRepository.selectByIds(partnerPositionIds);
27548 tejbeer 1012
 
34905 ranu 1013
        positions = positions.stream().filter(x -> (x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES || x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_RBM || x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_ABM)).collect(Collectors.toList());
27548 tejbeer 1014
 
31762 tejbeer 1015
        if (!positions.isEmpty()) {
35454 amit 1016
            // OPTIMIZED: Batch fetch all AuthUsers instead of N+1 queries
1017
            List<Integer> authUserIds = positions.stream()
1018
                    .map(Position::getAuthUserId)
1019
                    .filter(id -> id != null && id > 0)
1020
                    .distinct()
1021
                    .collect(Collectors.toList());
1022
            Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(authUserIds).stream()
1023
                    .collect(Collectors.toMap(AuthUser::getId, au -> au, (a, b) -> a));
1024
 
31762 tejbeer 1025
            for (Position partnerPostionId : positions) {
35454 amit 1026
                AuthUser authUser = authUserMap.get(partnerPostionId.getAuthUserId());
31762 tejbeer 1027
                LOGGER.info("authUser" + authUser);
35454 amit 1028
                if (authUser != null) {
1029
                    emails.add(authUser.getEmailId());
1030
                }
31762 tejbeer 1031
            }
1032
        }
27548 tejbeer 1033
 
31762 tejbeer 1034
        return emails;
1035
    }
27548 tejbeer 1036
 
31762 tejbeer 1037
    @Override
33244 ranu 1038
    public Map<EscalationType, String> getAuthUserAndEsclationTypeByPartnerId(int fofoId) throws ProfitMandiBusinessException {
27548 tejbeer 1039
 
31762 tejbeer 1040
        List<String> emails = new ArrayList<>();
1041
        Map<EscalationType, String> emailEsclationTypeMap = new HashMap<>();
1042
        List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId()).collect(Collectors.toList());
27548 tejbeer 1043
 
31762 tejbeer 1044
        regionIds.add(5);// All partners Id;
1045
        List<Integer> fofoIds = new ArrayList<>();
1046
        fofoIds.add(fofoId);
1047
        fofoIds.add(0);
27548 tejbeer 1048
 
33074 amit.gupta 1049
        //LOGGER.info("fofoIds" + fofoIds);
32493 amit.gupta 1050
        List<Integer> partnerPositionIds = partnerPositionRepository.selectByRegionIdAndPartnerId(regionIds, fofoIds).stream().map(x -> x.getPositionId()).collect(Collectors.toList());
27548 tejbeer 1051
 
33074 amit.gupta 1052
        //LOGGER.info("partnerPositionIds" + partnerPositionIds);
28377 tejbeer 1053
 
35454 amit 1054
        // OPTIMIZED: Batch fetch all positions instead of N+1 queries
1055
        List<Position> positions = positionRepository.selectByIds(partnerPositionIds).stream()
1056
                .filter(p -> p.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES)
1057
                .collect(Collectors.toList());
28377 tejbeer 1058
 
35454 amit 1059
        if (!positions.isEmpty()) {
1060
            // OPTIMIZED: Batch fetch all AuthUsers instead of N+1 queries
1061
            List<Integer> authUserIds = positions.stream()
1062
                    .map(Position::getAuthUserId)
1063
                    .filter(id -> id != null && id > 0)
1064
                    .distinct()
1065
                    .collect(Collectors.toList());
1066
            Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(authUserIds).stream()
1067
                    .collect(Collectors.toMap(AuthUser::getId, au -> au, (a, b) -> a));
1068
 
1069
            for (Position position : positions) {
1070
                AuthUser authUser = authUserMap.get(position.getAuthUserId());
33074 amit.gupta 1071
                //LOGGER.info("authUser" + authUser);
35454 amit 1072
                if (authUser != null) {
1073
                    emailEsclationTypeMap.put(position.getEscalationType(), authUser.getEmailId());
1074
                }
31762 tejbeer 1075
            }
1076
        }
28377 tejbeer 1077
 
33074 amit.gupta 1078
        //LOGGER.info("emailEsclationTypeMap" + emailEsclationTypeMap);
28377 tejbeer 1079
 
31762 tejbeer 1080
        return emailEsclationTypeMap;
1081
    }
31020 tejbeer 1082
 
31762 tejbeer 1083
    @Override
1084
    @Cacheable(value = "authUserIdPartnerIdMapping", cacheManager = "thirtyMinsTimeOutCacheManager")
33244 ranu 1085
    public Map<Integer, List<Integer>> getAuthUserIdPartnerIdMapping() throws ProfitMandiBusinessException {
36802 ranu 1086
        return buildAuthUserIdPartnerIdMapping(true);
1087
    }
1088
 
1089
    @Override
1090
    @Cacheable(value = "authUserIdAllPartnerIdMapping", cacheManager = "thirtyMinsTimeOutCacheManager")
1091
    public Map<Integer, List<Integer>> getAuthUserIdAllPartnerIdMapping() throws ProfitMandiBusinessException {
1092
        return buildAuthUserIdPartnerIdMapping(false);
1093
    }
1094
 
1095
    private Map<Integer, List<Integer>> buildAuthUserIdPartnerIdMapping(boolean activeOnly) throws ProfitMandiBusinessException {
31762 tejbeer 1096
        Map<Integer, List<Integer>> storeGuyMap = new HashMap<>();
36802 ranu 1097
        Set<Integer> fofoIdsScope = (activeOnly
1098
                ? fofoStoreRepository.selectActiveStores()
1099
                : fofoStoreRepository.selectAllFranchiseStores())
1100
                .stream().map(x -> x.getId()).collect(Collectors.toSet());
31020 tejbeer 1101
 
34077 tejus.loha 1102
        List<Position> categoryPositions = positionRepository.selectAllPosition();
31020 tejbeer 1103
 
31762 tejbeer 1104
        Map<Integer, Position> positionsMap = categoryPositions.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
29229 tejbeer 1105
 
35454 amit 1106
        // OPTIMIZED: Batch fetch all AuthUsers instead of N+1 queries
1107
        List<Integer> authUserIds = categoryPositions.stream()
1108
                .map(Position::getAuthUserId)
1109
                .filter(id -> id != null && id > 0)
1110
                .distinct()
1111
                .collect(Collectors.toList());
1112
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(authUserIds).stream()
1113
                .collect(Collectors.toMap(AuthUser::getId, au -> au, (a, b) -> a));
1114
 
31762 tejbeer 1115
        Map<Integer, List<CustomRetailer>> positonPartnerMap = this.getPositionCustomRetailerMap(categoryPositions);
1116
        for (Map.Entry<Integer, List<CustomRetailer>> positionPartnerEntry : positonPartnerMap.entrySet()) {
1117
            int authUserId = positionsMap.get(positionPartnerEntry.getKey()).getAuthUserId();
36802 ranu 1118
            List<Integer> partnerIds = positionPartnerEntry.getValue().stream().filter(x -> fofoIdsScope.contains(x.getPartnerId())).map(x -> x.getPartnerId()).collect(Collectors.toList());
35454 amit 1119
            AuthUser authUser = authUserMap.get(authUserId);
31762 tejbeer 1120
            if (authUser != null && authUser.isActive()) {
1121
                if (!storeGuyMap.containsKey(authUserId)) {
1122
                    storeGuyMap.put(authUserId, partnerIds);
1123
                } else {
1124
                    storeGuyMap.get(authUserId).addAll(partnerIds);
1125
                }
1126
            }
1127
        }
1128
        storeGuyMap.keySet().stream().forEach(x -> {
1129
            List<Integer> fofoIds = storeGuyMap.get(x);
1130
            storeGuyMap.put(x, fofoIds.stream().distinct().collect(Collectors.toList()));
1131
        });
1132
        return storeGuyMap;
1133
    }
28908 tejbeer 1134
 
31762 tejbeer 1135
    @Override
1136
    @Cacheable(value = "L1L2Mapping", cacheManager = "thirtyMinsTimeOutCacheManager")
33244 ranu 1137
    public Map<Integer, List<Integer>> getL2L1Mapping() throws ProfitMandiBusinessException {
31762 tejbeer 1138
        List<Position> l1SalesPositions = positionRepository.selectPositionbyCategoryIdAndEscalationType(
1139
                ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L1);
1140
        List<Position> l2SalesPositions = positionRepository.selectPositionbyCategoryIdAndEscalationType(
1141
                ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L2);
28908 tejbeer 1142
 
33074 amit.gupta 1143
        //LOGGER.info("position" + l1SalesPositions);
31762 tejbeer 1144
        Map<Integer, List<Integer>> authUserPartnerListMap = this.getAuthUserIdPartnerIdMapping();
33074 amit.gupta 1145
        //LOGGER.info("map" + authUserPartnerListMap);
28908 tejbeer 1146
 
31762 tejbeer 1147
        Map<Integer, List<Integer>> l2l1ListMap = new HashMap<>();
29318 tejbeer 1148
 
31762 tejbeer 1149
        for (Position l2SalePosition : l2SalesPositions) {
1150
            int l2AuthUserId = l2SalePosition.getAuthUserId();
1151
            if (authUserPartnerListMap.containsKey(l2SalePosition.getAuthUserId())) {
1152
                List<Integer> mappedL1AuthUsers = new ArrayList<>();
1153
                l2l1ListMap.put(l2AuthUserId, mappedL1AuthUsers);
1154
                List<Integer> l2FofoIds = authUserPartnerListMap.get(l2AuthUserId);
1155
                for (Position l1SalePosition : l1SalesPositions) {
1156
                    int l1AuthUserId = l1SalePosition.getAuthUserId();
1157
                    if (authUserPartnerListMap.containsKey(l1AuthUserId)) {
1158
                        List<Integer> l1FofoIds = authUserPartnerListMap.get(l1SalePosition.getAuthUserId());
1159
                        if (l2FofoIds.containsAll(l1FofoIds)) {
1160
                            mappedL1AuthUsers.add(l1AuthUserId);
1161
                        }
1162
                    }
28856 manish 1163
 
31762 tejbeer 1164
                }
1165
            }
29296 manish 1166
 
31762 tejbeer 1167
        }
29296 manish 1168
 
31762 tejbeer 1169
        return l2l1ListMap;
1170
    }
29296 manish 1171
 
31762 tejbeer 1172
    @Override
1173
    public Map<Integer, List<AuthUser>> getAssignedAuthList(List<Ticket> tickets) {
1174
        if (tickets.size() == 0) {
1175
            return new HashMap<>();
1176
        }
1177
        List<TicketAssigned> ticketAssignedList = ticketAssignedRepository.selectByTicketIds(tickets.stream().map(x -> x.getId()).collect(Collectors.toList()));
1178
        List<Integer> authUserIds = ticketAssignedList.stream().map(x -> x.getAssineeId()).distinct().collect(Collectors.toList());
35394 amit 1179
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(authUserIds).stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
31762 tejbeer 1180
        return ticketAssignedList.stream().collect(Collectors.groupingBy(x -> x.getTicketId(), Collectors.mapping(x -> authUserMap.get(x.getAssineeId()), Collectors.toList())));
1181
    }
28908 tejbeer 1182
 
31762 tejbeer 1183
    @Override
33244 ranu 1184
    public Map<EscalationType, AuthUser> getAuthUserAndEsclationByPartnerId(int fofoId) throws ProfitMandiBusinessException {
31762 tejbeer 1185
        Map<EscalationType, AuthUser> authuserEsclationTypeMap = new HashMap<>();
1186
        List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId()).collect(Collectors.toList());
28908 tejbeer 1187
 
35592 amit 1188
        regionIds.add(ALL_PARTNERS_REGION);// All partners Id;
31762 tejbeer 1189
        List<Integer> fofoIds = new ArrayList<>();
1190
        fofoIds.add(fofoId);
1191
        fofoIds.add(0);
28908 tejbeer 1192
 
32493 amit.gupta 1193
        List<Integer> partnerPositionIds = partnerPositionRepository.selectByRegionIdAndPartnerId(regionIds, fofoIds).stream().map(x -> x.getPositionId()).collect(Collectors.toList());
28908 tejbeer 1194
 
35592 amit 1195
        if (partnerPositionIds.isEmpty()) {
1196
            return authuserEsclationTypeMap;
1197
        }
30003 tejbeer 1198
 
35592 amit 1199
        // OPTIMIZED: Batch fetch all positions instead of N+1 queries
1200
        List<Position> salesPositions = positionRepository.selectByIds(partnerPositionIds).stream()
1201
                .filter(p -> p.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES)
1202
                .collect(Collectors.toList());
30003 tejbeer 1203
 
35592 amit 1204
        if (salesPositions.isEmpty()) {
1205
            return authuserEsclationTypeMap;
1206
        }
30003 tejbeer 1207
 
35592 amit 1208
        // OPTIMIZED: Batch fetch all AuthUsers instead of N+1 queries
1209
        List<Integer> authUserIds = salesPositions.stream()
1210
                .map(Position::getAuthUserId)
1211
                .filter(id -> id != null && id > 0)
1212
                .distinct()
1213
                .collect(Collectors.toList());
1214
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(authUserIds).stream()
1215
                .collect(Collectors.toMap(AuthUser::getId, au -> au, (a, b) -> a));
1216
 
1217
        for (Position position : salesPositions) {
1218
            AuthUser authUser = authUserMap.get(position.getAuthUserId());
1219
            if (authUser != null) {
31762 tejbeer 1220
                authuserEsclationTypeMap.put(position.getEscalationType(), authUser);
1221
            }
1222
        }
30003 tejbeer 1223
 
31762 tejbeer 1224
        return authuserEsclationTypeMap;
1225
    }
30044 tejbeer 1226
 
31762 tejbeer 1227
    @Override
35394 amit 1228
    public Map<Integer, Map<EscalationType, AuthUser>> getAuthUserAndEsclationByPartnerIds(Set<Integer> fofoIds) throws ProfitMandiBusinessException {
1229
        Map<Integer, Map<EscalationType, AuthUser>> result = new HashMap<>();
1230
 
1231
        if (fofoIds == null || fofoIds.isEmpty()) {
1232
            return result;
1233
        }
1234
 
1235
        // Initialize result map
1236
        for (Integer fofoId : fofoIds) {
1237
            result.put(fofoId, new HashMap<>());
1238
        }
1239
 
1240
        // Batch fetch all partner regions
1241
        List<Integer> fofoIdListWithZero = new ArrayList<>(fofoIds);
1242
        fofoIdListWithZero.add(0);
1243
        List<PartnerRegion> allPartnerRegions = partnerRegionRepository.selectByfofoIds(fofoIdListWithZero);
1244
 
1245
        // Build fofoId -> regionIds map
1246
        Map<Integer, Set<Integer>> fofoRegionMap = new HashMap<>();
1247
        for (Integer fofoId : fofoIds) {
1248
            fofoRegionMap.put(fofoId, new HashSet<>());
1249
            fofoRegionMap.get(fofoId).add(ALL_PARTNERS_REGION);
1250
        }
1251
        for (PartnerRegion pr : allPartnerRegions) {
1252
            int prFofoId = pr.getFofoId();
1253
            if (prFofoId == 0) {
1254
                for (Integer fid : fofoIds) {
1255
                    fofoRegionMap.get(fid).add(pr.getRegionId());
1256
                }
1257
            } else if (fofoIds.contains(prFofoId)) {
1258
                fofoRegionMap.get(prFofoId).add(pr.getRegionId());
1259
            }
1260
        }
1261
 
1262
        // Collect all region IDs
1263
        Set<Integer> allRegionIds = fofoRegionMap.values().stream()
1264
                .flatMap(Set::stream).collect(Collectors.toSet());
1265
 
1266
        // Batch fetch all partner positions
1267
        List<PartnerPosition> allPartnerPositions = partnerPositionRepository.selectByRegionIdAndPartnerId(
1268
                new ArrayList<>(allRegionIds), fofoIdListWithZero);
1269
 
1270
        // Collect all position IDs
1271
        Set<Integer> allPositionIds = allPartnerPositions.stream()
1272
                .map(PartnerPosition::getPositionId).collect(Collectors.toSet());
1273
 
1274
        // Batch fetch all positions for SALES category
1275
        List<Position> salesPositions = positionRepository.selectPositionbyCategoryIdAndEscalationType(
1276
                ProfitMandiConstants.TICKET_CATEGORY_SALES, null);
1277
        Map<Integer, Position> positionMap = salesPositions.stream()
1278
                .filter(p -> allPositionIds.contains(p.getId()))
1279
                .collect(Collectors.toMap(Position::getId, p -> p, (a, b) -> a));
1280
 
1281
        // Collect all auth user IDs and batch fetch
1282
        Set<Integer> authUserIds = positionMap.values().stream()
1283
                .map(Position::getAuthUserId).collect(Collectors.toSet());
1284
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(new ArrayList<>(authUserIds))
1285
                .stream().collect(Collectors.toMap(AuthUser::getId, au -> au, (a, b) -> a));
1286
 
1287
        // For each fofoId, find matching positions and build result
1288
        for (Integer fofoId : fofoIds) {
1289
            Set<Integer> regionIds = fofoRegionMap.get(fofoId);
1290
            Map<EscalationType, AuthUser> escalationMap = result.get(fofoId);
1291
 
1292
            for (PartnerPosition pp : allPartnerPositions) {
1293
                if (regionIds.contains(pp.getRegionId()) &&
1294
                    (pp.getFofoId() == 0 || pp.getFofoId() == fofoId)) {
1295
                    Position position = positionMap.get(pp.getPositionId());
1296
                    if (position != null) {
1297
                        AuthUser authUser = authUserMap.get(position.getAuthUserId());
1298
                        if (authUser != null) {
1299
                            escalationMap.put(position.getEscalationType(), authUser);
1300
                        }
1301
                    }
1302
                }
1303
            }
1304
        }
1305
 
1306
        return result;
1307
    }
1308
 
1309
    @Override
33244 ranu 1310
    public List<AuthUser> getAuthUserIdByPartnerId(int fofoId) throws ProfitMandiBusinessException {
33041 ranu 1311
        return this.getAuthUserIdByPartnerId(fofoId, EscalationType.escalations.toArray(new EscalationType[0]));
1312
    }
1313
 
1314
    @Override
33244 ranu 1315
    public List<AuthUser> getAuthUserIdByPartnerId(int fofoId, EscalationType... escalationTypes) throws ProfitMandiBusinessException {
31762 tejbeer 1316
        List<AuthUser> authUsers = new ArrayList<>();
1317
        List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId()).collect(Collectors.toList());
30044 tejbeer 1318
 
31762 tejbeer 1319
        regionIds.add(5);// All partners Id;
1320
        List<Integer> fofoIds = new ArrayList<>();
1321
        fofoIds.add(fofoId);
1322
        fofoIds.add(0);
30044 tejbeer 1323
 
33074 amit.gupta 1324
        //LOGGER.info("fofoIds" + fofoIds);
32493 amit.gupta 1325
        List<Integer> partnerPositionIds = partnerPositionRepository.selectByRegionIdAndPartnerId(regionIds, fofoIds).stream().map(x -> x.getPositionId()).collect(Collectors.toList());
30003 tejbeer 1326
 
33074 amit.gupta 1327
        //LOGGER.info("partnerPositionIds" + partnerPositionIds);
34905 ranu 1328
        List<Integer> allowedTicketCategoryIds = Arrays.asList(ProfitMandiConstants.TICKET_CATEGORY_SALES, ProfitMandiConstants.TICKET_CATEGORY_RBM,ProfitMandiConstants.TICKET_CATEGORY_ABM);
30003 tejbeer 1329
 
30044 tejbeer 1330
 
35394 amit 1331
        List<Position> escalationBasedPositions = positionRepository.selectByIds(partnerPositionIds).stream().filter(x -> allowedTicketCategoryIds.contains(x.getCategoryId()) &&
33041 ranu 1332
                Arrays.stream(escalationTypes)
1333
                        .anyMatch(y -> y.equals(x.getEscalationType()))).collect(Collectors.toList());
30003 tejbeer 1334
 
33041 ranu 1335
        List<Integer> authUserIds = escalationBasedPositions.stream().map(x -> x.getAuthUserId()).collect(Collectors.toList());
30003 tejbeer 1336
 
35394 amit 1337
        return authRepository.selectByIds(authUserIds);
30003 tejbeer 1338
 
31762 tejbeer 1339
    }
30044 tejbeer 1340
 
31762 tejbeer 1341
    @Override
37357 amit 1342
    public List<AuthUser> getAuthUsersByPartnerIdAndCategory(int fofoId, int categoryId, EscalationType... escalationTypes) throws ProfitMandiBusinessException {
1343
        List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId()).collect(Collectors.toList());
1344
        regionIds.add(ALL_PARTNERS_REGION);
1345
 
1346
        List<Integer> partnerPositionIds = partnerPositionRepository.selectByRegionIdAndPartnerId(regionIds, Arrays.asList(fofoId, 0))
1347
                .stream().map(x -> x.getPositionId()).distinct().collect(Collectors.toList());
1348
        if (partnerPositionIds.isEmpty()) {
1349
            return new ArrayList<>();
1350
        }
1351
 
1352
        List<EscalationType> escalations = (escalationTypes == null || escalationTypes.length == 0)
1353
                ? EscalationType.escalations : Arrays.asList(escalationTypes);
1354
 
1355
        List<Integer> authUserIds = positionRepository.selectByIds(partnerPositionIds).stream()
1356
                .filter(x -> x.getCategoryId() == categoryId)
1357
                .filter(x -> escalations.contains(x.getEscalationType()))
1358
                .map(x -> x.getAuthUserId())
1359
                .filter(x -> x > 0)
1360
                .distinct().collect(Collectors.toList());
1361
        LOGGER.info("fofoId {}, categoryId {}, escalations {}, authUserIds {}", fofoId, categoryId, escalations, authUserIds);
1362
        if (authUserIds.isEmpty()) {
1363
            return new ArrayList<>();
1364
        }
1365
 
1366
        return authRepository.selectByIds(authUserIds).stream()
1367
                .filter(x -> Boolean.TRUE.equals(x.getActive()))
1368
                .collect(Collectors.toList());
1369
    }
1370
 
1371
    @Override
31762 tejbeer 1372
    public List<AuthUser> getAuthUserIds(int categoryId, List<EscalationType> escalationType) {
30044 tejbeer 1373
 
31762 tejbeer 1374
        List<Position> positions = positionRepository.selectPositionbyCategoryIdAndEscalationTypes(categoryId, escalationType);
1375
        List<Integer> authIds = positions.stream().map(x -> x.getAuthUserId()).distinct().collect(Collectors.toList());
30003 tejbeer 1376
 
33074 amit.gupta 1377
        //LOGGER.info("authIds" + authIds);
35058 amit 1378
        List<AuthUser> authUsers = null;
1379
        if (authIds.size() > 0) {
35394 amit 1380
            authUsers = authRepository.selectByIds(authIds);
35058 amit 1381
        } else {
1382
            authUsers = new ArrayList<>();
1383
        }
30003 tejbeer 1384
 
31762 tejbeer 1385
        LOGGER.info("authUsers" + authUsers);
1386
        return authUsers;
1387
    }
1388
 
1389
    @Override
1390
    public List<AuthUser> getAuthUserByCategoryId(int categoryId, EscalationType escalationType) {
1391
 
1392
        List<Position> positions = positionRepository.selectPositionbyCategoryIdAndEscalationType(categoryId, escalationType);
1393
        List<Integer> authIds = positions.stream().map(x -> x.getAuthUserId()).distinct().collect(Collectors.toList());
1394
 
1395
        LOGGER.info("authIds" + authIds);
1396
        List<AuthUser> authUsers = new ArrayList<>();
1397
        if (!authIds.isEmpty()) {
35394 amit 1398
            authUsers = authRepository.selectByIds(authIds);
31762 tejbeer 1399
        }
1400
 
1401
        LOGGER.info("authUsers" + authUsers);
1402
        return authUsers;
1403
    }
1404
 
1405
    @Override
1406
    @Cacheable(value = "authUserByCategoryId", cacheManager = "thirtyMinsTimeOutCacheManager")
1407
    public List<AuthUser> getAuthUserByCategoryId(int categoryId) {
1408
        List<Position> positions = positionRepository.selectPositionByCategoryId(categoryId);
1409
        List<Integer> authIds = positions.stream().map(x -> x.getAuthUserId()).distinct().collect(Collectors.toList());
1410
 
1411
        LOGGER.info("authIds" + authIds);
1412
 
35394 amit 1413
        List<AuthUser> authUsers = authRepository.selectByIds(authIds).stream().filter(x -> x.getActive()).collect(Collectors.toList());
31762 tejbeer 1414
 
1415
        LOGGER.info("authUsers" + authUsers);
1416
        return authUsers;
1417
    }
1418
 
34380 amit.gupta 1419
    private class SaleRoles1 {
31762 tejbeer 1420
 
1421
        private List<String> l1;
1422
        private List<String> l2;
1423
        private List<String> l3;
1424
        private List<String> l4;
1425
 
34380 amit.gupta 1426
        public SaleRoles1() {
31762 tejbeer 1427
            l1 = new ArrayList<>();
1428
            l2 = new ArrayList<>();
1429
            l3 = new ArrayList<>();
1430
            l4 = new ArrayList<>();
1431
        }
1432
 
1433
        public List<String> getL1() {
1434
            return l1;
1435
        }
1436
 
1437
        public List<String> getL2() {
1438
            return l2;
1439
        }
1440
 
1441
        public List<String> getL3() {
1442
            return l3;
1443
        }
1444
 
1445
        public List<String> getL4() {
1446
            return l4;
1447
        }
1448
 
1449
        @Override
1450
        public String toString() {
1451
            return "SaleRoles [l1=" + l1 + ", l2=" + l2 + ", l3=" + l3 + ", l4=" + l4 + "]";
1452
        }
1453
 
1454
    }
1455
 
33161 ranu 1456
 
31762 tejbeer 1457
    @Override
1458
    @Cacheable(value = "partnerSaleHeader", cacheManager = "oneDayCacheManager")
33244 ranu 1459
    public Map<Integer, FofoReportingModel> getPartnerIdSalesHeaders() throws ProfitMandiBusinessException {
34380 amit.gupta 1460
        Map<String, SaleRoles1> partnerEmailSalesMap = new HashMap<>();
31762 tejbeer 1461
 
1462
        List<Position> positions = positionRepository.selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_SALES);
1463
        Map<Integer, AuthUser> authUsersMap = authRepository.selectAllActiveUser().stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
1464
        Map<Integer, List<CustomRetailer>> positionIdRetailerMap = this.getPositionCustomRetailerMap(positions);
1465
        for (Position position : positions) {
1466
            List<CustomRetailer> crList = positionIdRetailerMap.get(position.getId());
1467
            if (crList == null)
1468
                continue;
1469
            for (CustomRetailer cr : crList) {
1470
                if (!partnerEmailSalesMap.containsKey(cr.getEmail())) {
34380 amit.gupta 1471
                    partnerEmailSalesMap.put(cr.getEmail(), new SaleRoles1());
31762 tejbeer 1472
                }
34380 amit.gupta 1473
                SaleRoles1 saleRoles1 = partnerEmailSalesMap.get(cr.getEmail());
31762 tejbeer 1474
                AuthUser authUser = authUsersMap.get(position.getAuthUserId());
1475
                if (authUser == null) {
1476
                    continue;
1477
                }
1478
                String name = authUser.getFirstName() + " " + authUser.getLastName();
1479
                if (position.getEscalationType().equals(EscalationType.L1)) {
34380 amit.gupta 1480
                    saleRoles1.getL1().add(name);
31762 tejbeer 1481
                } else if (position.getEscalationType().equals(EscalationType.L2)) {
34380 amit.gupta 1482
                    saleRoles1.getL2().add(name);
31762 tejbeer 1483
                }
1484
 
1485
            }
1486
        }
1487
 
1488
        Set<CustomRetailer> allCrList = new HashSet<>();
1489
        for (List<CustomRetailer> cr : positionIdRetailerMap.values()) {
1490
            allCrList.addAll(cr);
1491
        }
1492
 
1493
        Map<Integer, FofoStore> fofoStoresMap = fofoStoreRepository.selectActiveStores().stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
1494
 
1495
        Map<Integer, FofoReportingModel> partnerIdSalesHeadersMap = new HashMap<>();
1496
 
33378 ranu 1497
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
1498
        for (Map.Entry<Integer, CustomRetailer> customRetailerEntry : customRetailerMap.entrySet()) {
1499
 
1500
            CustomRetailer customRetailer = customRetailerEntry.getValue();
1501
 
1502
            String code = customRetailer.getCode();
31762 tejbeer 1503
            // String storeName = "SmartDukaan-" +
1504
            // fofoStore.getCode().replaceAll("[a-zA-Z]", "");
33378 ranu 1505
            String businessName = customRetailer.getBusinessName();
31762 tejbeer 1506
            try {
37351 ranu 1507
                String stateManager = StringUtils.join(new HashSet(partnerEmailSalesMap.get(customRetailer.getEmail()).getL4()), ", ");
34158 tejus.loha 1508
                String territoryManager = StringUtils.join(new HashSet(partnerEmailSalesMap.get(customRetailer.getEmail()).getL1()), ", ");
37351 ranu 1509
                String salesL2Manager = StringUtils.join(new HashSet(partnerEmailSalesMap.get(customRetailer.getEmail()).getL2()), ", ");
31762 tejbeer 1510
 
1511
                FofoReportingModel reportingModel = new FofoReportingModel();
1512
                reportingModel.setBusinessName(businessName);
1513
                reportingModel.setCode(code);
33378 ranu 1514
                reportingModel.setFofoId(customRetailer.getPartnerId());
31762 tejbeer 1515
                reportingModel.setRegionalManager(stateManager);
1516
                reportingModel.setTerritoryManager(territoryManager);
37351 ranu 1517
                reportingModel.setSalesL2Manager(salesL2Manager);
33378 ranu 1518
                partnerIdSalesHeadersMap.put(customRetailer.getPartnerId(), reportingModel);
31762 tejbeer 1519
            } catch (Exception e) {
33378 ranu 1520
                LOGGER.warn("Could not find partner with email - {}", customRetailer.getEmail());
31762 tejbeer 1521
            }
1522
        }
1523
        return partnerIdSalesHeadersMap;
1524
 
1525
    }
1526
 
33161 ranu 1527
 
34905 ranu 1528
    private class ABMRoles {
1529
 
1530
        private List<String> l1;
1531
        private List<String> l2;
1532
        private List<String> l3;
1533
        private List<String> l4;
1534
 
1535
        public ABMRoles() {
1536
            l1 = new ArrayList<>();
1537
            l2 = new ArrayList<>();
1538
            l3 = new ArrayList<>();
1539
            l4 = new ArrayList<>();
1540
        }
1541
 
1542
        public List<String> getL1() {
1543
            return l1;
1544
        }
1545
 
1546
        public List<String> getL2() {
1547
            return l2;
1548
        }
1549
 
1550
        public List<String> getL3() {
1551
            return l3;
1552
        }
1553
 
1554
        public List<String> getL4() {
1555
            return l4;
1556
        }
1557
 
1558
        @Override
1559
        public String toString() {
1560
            return "SaleRoles [l1=" + l1 + ", l2=" + l2 + ", l3=" + l3 + ", l4=" + l4 + "]";
1561
        }
1562
 
1563
    }
1564
 
1565
 
1566
    @Override
1567
    @Cacheable(value = "partnerABMHeader", cacheManager = "oneDayCacheManager")
1568
    public Map<Integer, FofoAbmReportingModel> getPartnerIdABMHeaders() throws ProfitMandiBusinessException {
1569
        Map<String, ABMRoles> partnerEmailABMMap = new HashMap<>();
1570
 
1571
        List<Position> positions = positionRepository.selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_ABM);
1572
        Map<Integer, AuthUser> authUsersMap = authRepository.selectAllActiveUser().stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
1573
        Map<Integer, List<CustomRetailer>> positionIdRetailerMap = this.getPositionCustomRetailerMap(positions);
1574
        for (Position position : positions) {
1575
            List<CustomRetailer> crList = positionIdRetailerMap.get(position.getId());
1576
            if (crList == null)
1577
                continue;
1578
            for (CustomRetailer cr : crList) {
1579
                if (!partnerEmailABMMap.containsKey(cr.getEmail())) {
1580
                    partnerEmailABMMap.put(cr.getEmail(), new ABMRoles());
1581
                }
1582
                ABMRoles abmRoles = partnerEmailABMMap.get(cr.getEmail());
1583
                AuthUser authUser = authUsersMap.get(position.getAuthUserId());
1584
                if (authUser == null) {
1585
                    continue;
1586
                }
1587
                String name = authUser.getFirstName() + " " + authUser.getLastName();
1588
                if (position.getEscalationType().equals(EscalationType.L1)) {
1589
                    abmRoles.getL1().add(name);
1590
                } else if (position.getEscalationType().equals(EscalationType.L2)) {
1591
                    abmRoles.getL2().add(name);
1592
                }
1593
 
1594
            }
1595
        }
1596
 
1597
        Set<CustomRetailer> allCrList = new HashSet<>();
1598
        for (List<CustomRetailer> cr : positionIdRetailerMap.values()) {
1599
            allCrList.addAll(cr);
1600
        }
1601
 
1602
        Map<Integer, FofoStore> fofoStoresMap = fofoStoreRepository.selectActiveStores().stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
1603
 
1604
        Map<Integer, FofoAbmReportingModel> partnerIdAbmHeadersMap = new HashMap<>();
1605
 
1606
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
1607
        for (Map.Entry<Integer, CustomRetailer> customRetailerEntry : customRetailerMap.entrySet()) {
1608
 
1609
            CustomRetailer customRetailer = customRetailerEntry.getValue();
1610
 
1611
            String code = customRetailer.getCode();
1612
            // String storeName = "SmartDukaan-" +
1613
            // fofoStore.getCode().replaceAll("[a-zA-Z]", "");
1614
            String businessName = customRetailer.getBusinessName();
1615
            try {
1616
                String l2Manager = StringUtils.join(new HashSet(partnerEmailABMMap.get(customRetailer.getEmail()).getL2()), ", ");
1617
                String l1Manager = StringUtils.join(new HashSet(partnerEmailABMMap.get(customRetailer.getEmail()).getL1()), ", ");
1618
 
1619
                if (StringUtils.isEmpty(l1Manager)) {
1620
                    l2Manager = StringUtils.join(new HashSet(partnerEmailABMMap.get(customRetailer.getEmail()).getL2()), ", ");
1621
                }
1622
 
1623
                FofoAbmReportingModel reportingModel = new FofoAbmReportingModel();
1624
                reportingModel.setBusinessName(businessName);
1625
                reportingModel.setCode(code);
1626
                reportingModel.setFofoId(customRetailer.getPartnerId());
1627
                reportingModel.setL1Manager(l2Manager);
1628
                reportingModel.setL2Manager(l1Manager);
1629
                partnerIdAbmHeadersMap.put(customRetailer.getPartnerId(), reportingModel);
1630
            } catch (Exception e) {
1631
                LOGGER.warn("Could not find partner with email - {}", customRetailer.getEmail());
1632
            }
1633
        }
1634
        return partnerIdAbmHeadersMap;
1635
 
1636
    }
1637
 
1638
 
33161 ranu 1639
    private class RBMRoles {
1640
 
1641
        private List<String> l1;
1642
        private List<String> l2;
1643
        private List<String> l3;
1644
        private List<String> l4;
1645
 
1646
        public RBMRoles() {
1647
            l1 = new ArrayList<>();
1648
            l2 = new ArrayList<>();
1649
            l3 = new ArrayList<>();
1650
            l4 = new ArrayList<>();
1651
        }
1652
 
1653
        public List<String> getL1() {
1654
            return l1;
1655
        }
1656
 
1657
        public List<String> getL2() {
1658
            return l2;
1659
        }
1660
 
1661
        public List<String> getL3() {
1662
            return l3;
1663
        }
1664
 
1665
        public List<String> getL4() {
1666
            return l4;
1667
        }
1668
 
1669
        @Override
1670
        public String toString() {
1671
            return "RBMRoles [l1=" + l1 + ", l2=" + l2 + ", l3=" + l3 + ", l4=" + l4 + "]";
1672
        }
1673
 
1674
    }
1675
 
31762 tejbeer 1676
    @Override
33161 ranu 1677
    @Cacheable(value = "partnerRBMHeader", cacheManager = "oneDayCacheManager")
33244 ranu 1678
    public Map<Integer, FofoRBMReportingModel> getPartnerIdRBMHeaders() throws ProfitMandiBusinessException {
33161 ranu 1679
        Map<String, RBMRoles> partnerEmailRbmMap = new HashMap<>();
1680
 
1681
        List<Position> positions = positionRepository.selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_RBM);
1682
        Map<Integer, AuthUser> authUsersMap = authRepository.selectAllActiveUser().stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
1683
        Map<Integer, List<CustomRetailer>> positionIdRetailerMap = this.getPositionCustomRetailerMap(positions);
1684
        for (Position position : positions) {
1685
            List<CustomRetailer> crList = positionIdRetailerMap.get(position.getId());
1686
            if (crList == null)
1687
                continue;
1688
            for (CustomRetailer cr : crList) {
1689
                if (!partnerEmailRbmMap.containsKey(cr.getEmail())) {
1690
                    partnerEmailRbmMap.put(cr.getEmail(), new RBMRoles());
1691
                }
1692
                RBMRoles rbmRole = partnerEmailRbmMap.get(cr.getEmail());
1693
                AuthUser authUser = authUsersMap.get(position.getAuthUserId());
1694
                if (authUser == null) {
1695
                    continue;
1696
                }
1697
                String name = authUser.getFirstName() + " " + authUser.getLastName();
1698
                if (position.getEscalationType().equals(EscalationType.L1)) {
1699
                    rbmRole.getL1().add(name);
1700
                } else if (position.getEscalationType().equals(EscalationType.L2)) {
1701
                    rbmRole.getL2().add(name);
1702
                }
1703
 
1704
            }
1705
        }
1706
 
1707
        Set<CustomRetailer> allCrList = new HashSet<>();
1708
        for (List<CustomRetailer> cr : positionIdRetailerMap.values()) {
1709
            allCrList.addAll(cr);
1710
        }
1711
 
1712
 
1713
        Map<Integer, FofoRBMReportingModel> partnerIdRbmHeadersMap = new HashMap<>();
1714
 
33377 amit.gupta 1715
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
1716
        for (Map.Entry<Integer, CustomRetailer> customRetailerEntry : customRetailerMap.entrySet()) {
1717
 
1718
            CustomRetailer customRetailer = customRetailerEntry.getValue();
1719
 
1720
            String code = customRetailer.getCode();
33161 ranu 1721
            // String storeName = "SmartDukaan-" +
1722
            // fofoStore.getCode().replaceAll("[a-zA-Z]", "");
33377 amit.gupta 1723
            String businessName = customRetailer.getBusinessName();
33161 ranu 1724
            try {
33377 amit.gupta 1725
                String L2User = StringUtils.join(partnerEmailRbmMap.get(customRetailer.getEmail()).getL2(), ", ");
1726
                String L1USer = StringUtils.join(partnerEmailRbmMap.get(customRetailer.getEmail()).getL1(), ", ");
33161 ranu 1727
 
1728
                FofoRBMReportingModel reportingModel = new FofoRBMReportingModel();
1729
                reportingModel.setBusinessName(businessName);
1730
                reportingModel.setCode(code);
33377 amit.gupta 1731
                reportingModel.setFofoId(customRetailer.getPartnerId());
35180 amit 1732
                reportingModel.setL1Manager(L1USer);
1733
                reportingModel.setL2Manager(L2User);
33377 amit.gupta 1734
                partnerIdRbmHeadersMap.put(customRetailer.getPartnerId(), reportingModel);
33161 ranu 1735
            } catch (Exception e) {
33377 amit.gupta 1736
                LOGGER.warn("Could not find partner with email - {}", customRetailer.getEmail());
33161 ranu 1737
            }
1738
        }
1739
        return partnerIdRbmHeadersMap;
1740
 
1741
    }
1742
 
1743
    @Override
31762 tejbeer 1744
    public Map<Integer, TicketCategory> getSubCategoryIdAndCategoryMap(List<Integer> subCategoryIds) {
1745
        Map<Integer, TicketCategory> subCategoryIdAndCategoryMap = new HashMap<>();
35592 amit 1746
        if (subCategoryIds == null || subCategoryIds.isEmpty()) {
1747
            return subCategoryIdAndCategoryMap;
1748
        }
31762 tejbeer 1749
 
1750
        List<TicketSubCategory> ticketSubCategories = ticketSubCategoryRepository.selectByIds(subCategoryIds);
1751
 
35592 amit 1752
        // OPTIMIZED: Batch fetch all categories instead of N+1 queries
1753
        List<Integer> categoryIds = ticketSubCategories.stream()
1754
                .map(TicketSubCategory::getCategoryId)
1755
                .distinct()
1756
                .collect(Collectors.toList());
1757
        Map<Integer, TicketCategory> categoryMap = ticketCategoryRepository.selectAll(categoryIds).stream()
1758
                .collect(Collectors.toMap(TicketCategory::getId, tc -> tc, (a, b) -> a));
1759
 
31762 tejbeer 1760
        for (TicketSubCategory ticketSubCategory : ticketSubCategories) {
35592 amit 1761
            subCategoryIdAndCategoryMap.put(ticketSubCategory.getId(), categoryMap.get(ticketSubCategory.getCategoryId()));
31762 tejbeer 1762
        }
1763
        return subCategoryIdAndCategoryMap;
1764
    }
1765
 
35394 amit 1766
    @Override
1767
    public Map<Integer, Map<String, Integer>> getBmAsmRbmAuthUserIdsByFofoIds(Set<Integer> fofoIds) throws ProfitMandiBusinessException {
1768
        Map<Integer, Map<String, Integer>> result = new HashMap<>();
1769
 
1770
        if (fofoIds == null || fofoIds.isEmpty()) {
1771
            return result;
1772
        }
1773
 
1774
        // Initialize result map with empty values for each fofoId
1775
        for (Integer fofoId : fofoIds) {
1776
            Map<String, Integer> roleMap = new HashMap<>();
1777
            roleMap.put("BM", 0);
1778
            roleMap.put("ASM", 0);
1779
            roleMap.put("RBM", 0);
1780
            result.put(fofoId, roleMap);
1781
        }
1782
 
1783
        // Fetch positions by category + escalation type (same for all fofoIds)
1784
        List<Position> bmPositions = positionRepository.selectPositionbyCategoryIdAndEscalationType(
1785
                ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L2);
1786
        List<Position> asmPositions = positionRepository.selectPositionbyCategoryIdAndEscalationType(
1787
                ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L1);
1788
        List<Position> rbmPositions = positionRepository.selectPositionbyCategoryIdAndEscalationType(
1789
                ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L1);
1790
 
1791
        // Batch fetch all partner regions for all fofoIds
1792
        List<Integer> fofoIdList = new ArrayList<>(fofoIds);
1793
        fofoIdList.add(0); // Include global entries
1794
        List<PartnerRegion> allPartnerRegions = partnerRegionRepository.selectByfofoIds(fofoIdList);
1795
 
1796
        // Build fofoId -> regionIds map
1797
        Map<Integer, Set<Integer>> fofoRegionMap = new HashMap<>();
1798
        for (Integer fofoId : fofoIds) {
1799
            fofoRegionMap.put(fofoId, new HashSet<>());
1800
            fofoRegionMap.get(fofoId).add(ALL_PARTNERS_REGION); // Add all partners region
1801
        }
1802
        for (PartnerRegion pr : allPartnerRegions) {
1803
            int fofoId = pr.getFofoId();
1804
            if (fofoId == 0) {
1805
                // Global entry applies to all fofoIds
1806
                for (Integer fid : fofoIds) {
1807
                    fofoRegionMap.get(fid).add(pr.getRegionId());
1808
                }
1809
            } else if (fofoIds.contains(fofoId)) {
1810
                fofoRegionMap.get(fofoId).add(pr.getRegionId());
1811
            }
1812
        }
1813
 
1814
        // Collect all unique region IDs and position IDs for batch query
1815
        Set<Integer> allRegionIds = fofoRegionMap.values().stream()
1816
                .flatMap(Set::stream).collect(Collectors.toSet());
1817
        Set<Integer> allPositionIds = new HashSet<>();
1818
        bmPositions.forEach(p -> allPositionIds.add(p.getId()));
1819
        asmPositions.forEach(p -> allPositionIds.add(p.getId()));
1820
        rbmPositions.forEach(p -> allPositionIds.add(p.getId()));
1821
 
1822
        // Batch fetch all partner positions
1823
        List<PartnerPosition> allPartnerPositions = partnerPositionRepository.selectByRegionIdAndPostionId(
1824
                new ArrayList<>(allRegionIds), new ArrayList<>(allPositionIds));
1825
 
1826
        // Build positionId -> set of (regionId, partnerId) for matching
1827
        Map<Integer, List<PartnerPosition>> positionIdToPartnerPositions = allPartnerPositions.stream()
1828
                .collect(Collectors.groupingBy(PartnerPosition::getPositionId));
1829
 
1830
        // Collect all auth user IDs we need
1831
        Set<Integer> allAuthUserIds = new HashSet<>();
1832
        bmPositions.forEach(p -> allAuthUserIds.add(p.getAuthUserId()));
1833
        asmPositions.forEach(p -> allAuthUserIds.add(p.getAuthUserId()));
1834
        rbmPositions.forEach(p -> allAuthUserIds.add(p.getAuthUserId()));
1835
 
1836
        // Batch fetch all auth users
1837
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(new ArrayList<>(allAuthUserIds))
1838
                .stream().filter(AuthUser::isActive)
1839
                .collect(Collectors.toMap(AuthUser::getId, au -> au, (a, b) -> a));
1840
 
1841
        // Build position ID sets for fast lookup
1842
        Set<Integer> bmPositionIds = bmPositions.stream().map(Position::getId).collect(Collectors.toSet());
1843
        Set<Integer> asmPositionIds = asmPositions.stream().map(Position::getId).collect(Collectors.toSet());
1844
        Set<Integer> rbmPositionIds = rbmPositions.stream().map(Position::getId).collect(Collectors.toSet());
1845
 
1846
        // Map position ID to auth user ID
1847
        Map<Integer, Integer> positionToAuthUser = new HashMap<>();
1848
        bmPositions.forEach(p -> positionToAuthUser.put(p.getId(), p.getAuthUserId()));
1849
        asmPositions.forEach(p -> positionToAuthUser.put(p.getId(), p.getAuthUserId()));
1850
        rbmPositions.forEach(p -> positionToAuthUser.put(p.getId(), p.getAuthUserId()));
1851
 
1852
        // For each fofoId, find matching positions
1853
        for (Integer fofoId : fofoIds) {
1854
            Set<Integer> regionIds = fofoRegionMap.get(fofoId);
1855
 
1856
            // Find position IDs that match this fofoId's regions (partnerId = 0 or fofoId)
1857
            Set<Integer> matchingPositionIds = new HashSet<>();
1858
            for (PartnerPosition pp : allPartnerPositions) {
1859
                if (regionIds.contains(pp.getRegionId()) &&
1860
                    (pp.getFofoId() == 0 || pp.getFofoId() == fofoId)) {
1861
                    matchingPositionIds.add(pp.getPositionId());
1862
                }
1863
            }
1864
 
1865
            // Find first active auth user for each role
1866
            Map<String, Integer> roleMap = result.get(fofoId);
1867
 
1868
            for (Integer positionId : matchingPositionIds) {
1869
                Integer authUserId = positionToAuthUser.get(positionId);
1870
                if (authUserId != null && authUserMap.containsKey(authUserId)) {
1871
                    if (bmPositionIds.contains(positionId) && roleMap.get("BM") == 0) {
1872
                        roleMap.put("BM", authUserId);
1873
                    } else if (asmPositionIds.contains(positionId) && roleMap.get("ASM") == 0) {
1874
                        roleMap.put("ASM", authUserId);
1875
                    } else if (rbmPositionIds.contains(positionId) && roleMap.get("RBM") == 0) {
1876
                        roleMap.put("RBM", authUserId);
1877
                    }
1878
                }
1879
            }
1880
        }
1881
 
1882
        return result;
1883
    }
1884
 
35626 amit 1885
    @Override
36972 ranu 1886
    public Map<Integer, Integer> getAuthUserIdsWithoutTicketAssigneeByFofoIds(int categoryId, EscalationType escalationType, Set<Integer> fofoIds) throws ProfitMandiBusinessException {
1887
        Map<Integer, Integer> result = new HashMap<>();
1888
        if (fofoIds == null || fofoIds.isEmpty()) {
1889
            return result;
1890
        }
1891
        for (Integer fofoId : fofoIds) {
1892
            result.put(fofoId, 0);
1893
        }
1894
 
1895
        List<Position> positions = positionRepository.selectPositionbyCategoryIdAndEscalationType(categoryId, escalationType);
1896
        if (positions.isEmpty()) {
1897
            return result;
1898
        }
1899
        Set<Integer> positionIds = positions.stream().map(Position::getId).collect(Collectors.toSet());
1900
        Map<Integer, Integer> positionToAuthUser = new HashMap<>();
1901
        positions.forEach(p -> positionToAuthUser.put(p.getId(), p.getAuthUserId()));
1902
 
1903
        List<Integer> fofoIdList = new ArrayList<>(fofoIds);
1904
        fofoIdList.add(0);
1905
        List<PartnerRegion> allPartnerRegions = partnerRegionRepository.selectByfofoIds(fofoIdList);
1906
 
1907
        Map<Integer, Set<Integer>> fofoRegionMap = new HashMap<>();
1908
        for (Integer fofoId : fofoIds) {
1909
            Set<Integer> regions = new HashSet<>();
1910
            regions.add(ALL_PARTNERS_REGION);
1911
            fofoRegionMap.put(fofoId, regions);
1912
        }
1913
        for (PartnerRegion pr : allPartnerRegions) {
1914
            int fofoId = pr.getFofoId();
1915
            if (fofoId == 0) {
1916
                for (Integer fid : fofoIds) {
1917
                    fofoRegionMap.get(fid).add(pr.getRegionId());
1918
                }
1919
            } else if (fofoIds.contains(fofoId)) {
1920
                fofoRegionMap.get(fofoId).add(pr.getRegionId());
1921
            }
1922
        }
1923
 
1924
        Set<Integer> allRegionIds = fofoRegionMap.values().stream()
1925
                .flatMap(Set::stream).collect(Collectors.toSet());
1926
        List<PartnerPosition> allPartnerPositions = partnerPositionRepository.selectByRegionIdAndPostionId(
1927
                new ArrayList<>(allRegionIds), new ArrayList<>(positionIds));
1928
 
1929
        Set<Integer> allAuthUserIds = positions.stream().map(Position::getAuthUserId).collect(Collectors.toSet());
1930
        Set<Integer> activeAuthUserIds = authRepository.selectByIds(new ArrayList<>(allAuthUserIds))
1931
                .stream().filter(AuthUser::isActive).map(AuthUser::getId).collect(Collectors.toSet());
1932
 
1933
        for (Integer fofoId : fofoIds) {
1934
            Set<Integer> regionIds = fofoRegionMap.get(fofoId);
1935
            for (PartnerPosition pp : allPartnerPositions) {
1936
                if (!regionIds.contains(pp.getRegionId())) continue;
1937
                if (pp.getFofoId() != 0 && pp.getFofoId() != fofoId) continue;
1938
                Integer authUserId = positionToAuthUser.get(pp.getPositionId());
1939
                if (authUserId != null && activeAuthUserIds.contains(authUserId)) {
1940
                    result.put(fofoId, authUserId);
1941
                    break;
1942
                }
1943
            }
1944
        }
1945
        return result;
1946
    }
1947
 
1948
    @Override
35635 ranu 1949
    public Map<Integer, Boolean> getUnreadStatusForTickets(List<Ticket> tickets, int userId, TicketReadStatus.UserType userType) {
35626 amit 1950
        Map<Integer, Boolean> unreadMap = new HashMap<>();
1951
        if (tickets == null || tickets.isEmpty()) {
1952
            return unreadMap;
1953
        }
1954
 
1955
        List<Integer> ticketIds = tickets.stream().map(Ticket::getId).collect(Collectors.toList());
1956
        List<TicketReadStatus> readStatuses = ticketReadStatusRepository.selectByTicketIdsAndUser(ticketIds, userId, userType);
1957
        Map<Integer, Integer> ticketLastReadMap = readStatuses.stream()
1958
                .collect(Collectors.toMap(TicketReadStatus::getTicketId, TicketReadStatus::getLastReadActivityId));
1959
 
1960
        // Get last activities for all tickets to check who created them
1961
        Map<Integer, Activity> lastActivityMap = getLastActivitiesForTickets(ticketIds);
1962
 
1963
        for (Ticket ticket : tickets) {
1964
            int lastActivityId = ticket.getLastActivityId();
1965
            int lastReadActivityId = ticketLastReadMap.getOrDefault(ticket.getId(), 0);
1966
 
1967
            if (lastActivityId <= lastReadActivityId) {
1968
                unreadMap.put(ticket.getId(), false);
1969
                continue;
1970
            }
1971
 
1972
            // Check if the current user created the last activity (exclude own updates)
1973
            Activity lastActivity = lastActivityMap.get(ticket.getId());
1974
            if (lastActivity != null) {
35635 ranu 1975
                if (userType == TicketReadStatus.UserType.AUTH_USER && lastActivity.getCreatedBy() == userId) {
35626 amit 1976
                    unreadMap.put(ticket.getId(), false);
1977
                    continue;
1978
                }
35635 ranu 1979
                if (userType == TicketReadStatus.UserType.PARTNER && lastActivity.getCreatedBy() == 0
35626 amit 1980
                        && lastActivity.getType() == ActivityType.COMMUNICATION_IN) {
1981
                    unreadMap.put(ticket.getId(), false);
1982
                    continue;
1983
                }
1984
                // For partners: only show as unread if activity type is external communication or resolved
35635 ranu 1985
                if (userType == TicketReadStatus.UserType.PARTNER) {
35626 amit 1986
                    boolean isRelevantForPartner = ActivityType.PARTNER_ACTIVITIES.contains(lastActivity.getType());
1987
                    unreadMap.put(ticket.getId(), isRelevantForPartner);
1988
                    continue;
1989
                }
1990
            }
1991
 
1992
            unreadMap.put(ticket.getId(), true);
1993
        }
1994
        return unreadMap;
1995
    }
1996
 
1997
    @Override
35635 ranu 1998
    public void markTicketAsRead(int ticketId, int userId, TicketReadStatus.UserType userType) {
35626 amit 1999
        Ticket ticket = ticketRepository.selectById(ticketId);
2000
        if (ticket == null) {
2001
            return;
2002
        }
2003
        TicketReadStatus readStatus = new TicketReadStatus();
2004
        readStatus.setTicketId(ticketId);
2005
        readStatus.setUserId(userId);
2006
        readStatus.setUserType(userType);
2007
        readStatus.setLastReadActivityId(ticket.getLastActivityId());
2008
        ticketReadStatusRepository.upsert(readStatus);
2009
    }
2010
 
2011
    @Override
2012
    public Map<Integer, Activity> getLastActivitiesForTickets(List<Integer> ticketIds) {
2013
        Map<Integer, Activity> lastActivityMap = new HashMap<>();
2014
        if (ticketIds == null || ticketIds.isEmpty()) {
2015
            return lastActivityMap;
2016
        }
2017
        List<Activity> allActivities = activityRepository.selectAll(ticketIds);
2018
        // Group by ticketId and get the last one (highest id)
2019
        Map<Integer, List<Activity>> groupedByTicket = allActivities.stream()
2020
                .collect(Collectors.groupingBy(Activity::getTicketId));
2021
        for (Map.Entry<Integer, List<Activity>> entry : groupedByTicket.entrySet()) {
2022
            Activity lastActivity = entry.getValue().stream()
2023
                    .max(Comparator.comparingInt(Activity::getId))
2024
                    .orElse(null);
2025
            if (lastActivity != null) {
2026
                lastActivityMap.put(entry.getKey(), lastActivity);
2027
            }
2028
        }
2029
        return lastActivityMap;
2030
    }
2031
 
2032
    @Override
35639 amit 2033
    public Map<Integer, Activity> getLastMessageActivitiesForTickets(List<Integer> ticketIds) {
2034
        Map<Integer, Activity> lastMessageMap = new HashMap<>();
2035
        if (ticketIds == null || ticketIds.isEmpty()) {
2036
            return lastMessageMap;
2037
        }
2038
        Set<ActivityType> messageTypes = EnumSet.of(
2039
                ActivityType.COMMUNICATION_IN, ActivityType.COMMUNICATION_OUT,
2040
                ActivityType.COMMUNICATION_INTERNAL, ActivityType.OPENED);
2041
        List<Activity> allActivities = activityRepository.selectAll(ticketIds);
2042
        Map<Integer, List<Activity>> groupedByTicket = allActivities.stream()
2043
                .filter(a -> messageTypes.contains(a.getType()))
2044
                .collect(Collectors.groupingBy(Activity::getTicketId));
2045
        for (Map.Entry<Integer, List<Activity>> entry : groupedByTicket.entrySet()) {
2046
            Activity lastMessage = entry.getValue().stream()
2047
                    .max(Comparator.comparingInt(Activity::getId))
2048
                    .orElse(null);
2049
            if (lastMessage != null) {
2050
                lastMessageMap.put(entry.getKey(), lastMessage);
2051
            }
2052
        }
2053
        return lastMessageMap;
2054
    }
2055
 
2056
    @Override
35626 amit 2057
    public void notifyPartnerOfExternalCommunication(Ticket ticket, Activity activity) {
2058
        try {
2059
            CustomRetailer partner = retailerService.getFofoRetailer(ticket.getFofoId());
2060
            if (partner == null || partner.getEmail() == null) {
2061
                return;
2062
            }
2063
 
2064
            TicketSubCategory ticketSubCategory = ticketSubCategoryRepository.selectById(ticket.getSubCategoryId());
2065
            TicketCategory ticketCategory = ticketCategoryRepository.selectById(ticketSubCategory.getCategoryId());
2066
 
2067
            Map<String, Object> model = new HashMap<>();
2068
            model.put("ticketId", ticket.getId());
2069
            model.put("partnerName", partner.getBusinessName());
2070
            model.put("categoryName", ticketCategory.getName());
2071
            model.put("subCategoryName", ticketSubCategory.getName());
2072
            model.put("activityMessage", activity.getMessage());
2073
 
2074
            emailService.sendMailWithAttachments(
2075
                    "Update on Your Support Ticket #" + ticket.getId(),
2076
                    "partner-ticket-update.vm",
2077
                    model,
2078
                    new String[]{partner.getEmail()},
2079
                    null,
2080
                    null);
2081
        } catch (Exception e) {
2082
            LOGGER.error("Failed to send partner notification email for ticket {}", ticket.getId(), e);
2083
        }
2084
    }
2085
 
24383 amit.gupta 2086
}