Subversion Repositories SmartDukaan

Rev

Rev 37731 | 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
 
37866 ranu 842
    /**
843
     * Email mapping scoped to a caller-supplied category list. Mirrors
844
     * {@link #getAuthUserPartnerEmailMapping()}'s shape and filters, but doesn't
845
     * hard-code the Sales/RBM/ABM subset — v2 callers (React admin) pass the full
846
     * HO roster they want to serve. Uncached because the key would have to include
847
     * the category list and would miss cache for every call anyway.
848
     */
31762 tejbeer 849
    @Override
37866 ranu 850
    public Map<String, Set<String>> getAuthUserPartnerEmailMappingByCategoryIds(List<Integer> categoryIds) throws ProfitMandiBusinessException {
851
        Map<String, Set<String>> storeGuyMap = new HashMap<>();
852
        if (categoryIds == null || categoryIds.isEmpty()) {
853
            return storeGuyMap;
854
        }
855
        Set<Integer> activeFofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId()).collect(Collectors.toSet());
856
 
857
        List<Position> categoryPositions = positionRepository.selectPositionByCategoryIds(categoryIds);
858
        Map<Integer, Position> positionsMap = categoryPositions.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
859
 
860
        Set<Integer> authUserIds = categoryPositions.stream().map(Position::getAuthUserId).collect(Collectors.toSet());
861
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(new ArrayList<>(authUserIds)).stream()
862
                .collect(Collectors.toMap(AuthUser::getId, x -> x));
863
 
864
        Map<Integer, List<CustomRetailer>> positonPartnerMap = this.getPositionCustomRetailerMap(categoryPositions);
865
        for (Map.Entry<Integer, List<CustomRetailer>> positionPartnerEntry : positonPartnerMap.entrySet()) {
866
            int authUserId = positionsMap.get(positionPartnerEntry.getKey()).getAuthUserId();
867
            Set<String> partnerEmails = positionPartnerEntry.getValue().stream().filter(x -> activeFofoIds.contains(x.getPartnerId())).map(x -> x.getEmail()).collect(Collectors.toSet());
868
            AuthUser authUser = authUserMap.get(authUserId);
869
            if (authUser != null && authUser.isActive()) {
870
                if (!storeGuyMap.containsKey(authUser.getEmailId())) {
871
                    storeGuyMap.put(authUser.getEmailId(), partnerEmails);
872
                } else {
873
                    storeGuyMap.get(authUser.getEmailId()).addAll(partnerEmails);
874
                }
875
            }
876
        }
877
        return storeGuyMap;
878
    }
879
 
880
    @Override
31762 tejbeer 881
    @Cacheable(value = "authUserEmailPartnerIdMapping", cacheManager = "thirtyMinsTimeOutCacheManager")
33244 ranu 882
    public Map<String, Set<Integer>> getAuthUserPartnerIdMapping() throws ProfitMandiBusinessException {
31762 tejbeer 883
        Map<String, Set<Integer>> storeGuyMap = new HashMap<>();
884
        Set<Integer> activeFofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId()).collect(Collectors.toSet());
35443 amit 885
 
886
        // Batch fetch positions by category IDs instead of multiple calls
887
        List<Position> categoryPositions = positionRepository.selectPositionByCategoryIds(Arrays.asList(
888
                ProfitMandiConstants.TICKET_CATEGORY_SALES,
889
                ProfitMandiConstants.TICKET_CATEGORY_RBM,
890
                ProfitMandiConstants.TICKET_CATEGORY_ABM,
891
                ProfitMandiConstants.TICKET_CATEGORY_BUSINESSINTELLIGENT,
892
                ProfitMandiConstants.TICKET_CATEGORY_TRAINING));
31762 tejbeer 893
        Map<Integer, Position> positionsMap = categoryPositions.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
31161 tejbeer 894
 
35443 amit 895
        // Batch fetch all AuthUsers upfront to avoid N+1 queries
896
        Set<Integer> authUserIds = categoryPositions.stream().map(Position::getAuthUserId).collect(Collectors.toSet());
897
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(new ArrayList<>(authUserIds)).stream()
898
                .collect(Collectors.toMap(AuthUser::getId, x -> x));
899
 
31762 tejbeer 900
        Map<Integer, List<CustomRetailer>> positonPartnerMap = this.getPositionCustomRetailerMap(categoryPositions);
901
        for (Map.Entry<Integer, List<CustomRetailer>> positionPartnerEntry : positonPartnerMap.entrySet()) {
902
            int authUserId = positionsMap.get(positionPartnerEntry.getKey()).getAuthUserId();
903
            Set<Integer> partnerIds = positionPartnerEntry.getValue().stream().filter(x -> activeFofoIds.contains(x.getPartnerId())).map(x -> x.getPartnerId()).collect(Collectors.toSet());
35443 amit 904
            AuthUser authUser = authUserMap.get(authUserId);
905
            if (authUser != null && authUser.isActive()) {
31762 tejbeer 906
                if (!storeGuyMap.containsKey(authUser.getEmailId())) {
907
                    storeGuyMap.put(authUser.getEmailId(), partnerIds);
908
                } else {
909
                    storeGuyMap.get(authUser.getEmailId()).addAll(partnerIds);
910
                }
911
            }
912
        }
913
        return storeGuyMap;
914
    }
31472 tejbeer 915
 
31762 tejbeer 916
    @Override
35920 ranu 917
    @Cacheable(value = "authUserEmailInactivePartnerIdMapping", cacheManager = "thirtyMinsTimeOutCacheManager")
918
    public Map<String, Set<Integer>> getAuthUserInactivePartnerIdMapping() throws ProfitMandiBusinessException {
919
        Map<String, Set<Integer>> storeGuyMap = new HashMap<>();
920
        Set<Integer> activeFofoIds = fofoStoreRepository.selectInActiveStore().stream().map(x -> x.getId()).collect(Collectors.toSet());
921
 
922
        // Batch fetch positions by category IDs instead of multiple calls
923
        List<Position> categoryPositions = positionRepository.selectPositionByCategoryIds(Arrays.asList(
924
                ProfitMandiConstants.TICKET_CATEGORY_SALES,
925
                ProfitMandiConstants.TICKET_CATEGORY_RBM,
926
                ProfitMandiConstants.TICKET_CATEGORY_ABM,
927
                ProfitMandiConstants.TICKET_CATEGORY_BUSINESSINTELLIGENT,
928
                ProfitMandiConstants.TICKET_CATEGORY_TRAINING));
929
        Map<Integer, Position> positionsMap = categoryPositions.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
930
 
931
        // Batch fetch all AuthUsers upfront to avoid N+1 queries
932
        Set<Integer> authUserIds = categoryPositions.stream().map(Position::getAuthUserId).collect(Collectors.toSet());
933
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(new ArrayList<>(authUserIds)).stream()
934
                .collect(Collectors.toMap(AuthUser::getId, x -> x));
935
 
936
        Map<Integer, List<CustomRetailer>> positonPartnerMap = this.getPositionCustomRetailerMap(categoryPositions);
937
        for (Map.Entry<Integer, List<CustomRetailer>> positionPartnerEntry : positonPartnerMap.entrySet()) {
938
            int authUserId = positionsMap.get(positionPartnerEntry.getKey()).getAuthUserId();
939
            Set<Integer> partnerIds = positionPartnerEntry.getValue().stream().filter(x -> activeFofoIds.contains(x.getPartnerId())).map(x -> x.getPartnerId()).collect(Collectors.toSet());
940
            AuthUser authUser = authUserMap.get(authUserId);
941
            if (authUser != null && authUser.isActive()) {
942
                if (!storeGuyMap.containsKey(authUser.getEmailId())) {
943
                    storeGuyMap.put(authUser.getEmailId(), partnerIds);
944
                } else {
945
                    storeGuyMap.get(authUser.getEmailId()).addAll(partnerIds);
946
                }
947
            }
948
        }
949
        return storeGuyMap;
950
    }
951
 
952
    @Override
31762 tejbeer 953
    @Cacheable(value = "authUserPartnerEmailPartnerIdMapping", cacheManager = "thirtyMinsTimeOutCacheManager")
33244 ranu 954
    public Map<String, Set<Integer>> getAuthUserPartnerIdMappingByCategoryIds(List<Integer> categoryIds, boolean activeOnly) throws ProfitMandiBusinessException {
31762 tejbeer 955
        Map<String, Set<Integer>> authUserPartnerMap = new HashMap<>();
956
        Set<Integer> activeFofoIds;
957
        if (activeOnly) {
958
            activeFofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId()).collect(Collectors.toSet());
26298 tejbeer 959
 
31762 tejbeer 960
        } else {
961
            activeFofoIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId()).collect(Collectors.toSet());
26298 tejbeer 962
 
31762 tejbeer 963
        }
26298 tejbeer 964
 
31762 tejbeer 965
        List<Position> categoryPositions = positionRepository.selectPositionByCategoryIds(categoryIds);
966
        Map<Integer, Position> positionsMap = categoryPositions.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
26298 tejbeer 967
 
35454 amit 968
        // OPTIMIZED: Batch fetch all AuthUsers instead of N+1 queries
969
        List<Integer> authUserIds = categoryPositions.stream()
970
                .map(Position::getAuthUserId)
971
                .filter(id -> id != null && id > 0)
972
                .distinct()
973
                .collect(Collectors.toList());
974
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(authUserIds).stream()
975
                .collect(Collectors.toMap(AuthUser::getId, au -> au, (a, b) -> a));
976
 
31762 tejbeer 977
        Map<Integer, List<CustomRetailer>> positonPartnerMap = this.getPositionCustomRetailerMap(categoryPositions);
978
        for (Map.Entry<Integer, List<CustomRetailer>> positionPartnerEntry : positonPartnerMap.entrySet()) {
979
            int authUserId = positionsMap.get(positionPartnerEntry.getKey()).getAuthUserId();
980
            Set<Integer> partnerIds = positionPartnerEntry.getValue().stream().filter(x -> activeFofoIds.contains(x.getPartnerId())).map(x -> x.getPartnerId()).collect(Collectors.toSet());
35454 amit 981
            AuthUser authUser = authUserMap.get(authUserId);
982
            if (authUser != null && authUser.isActive()) {
31762 tejbeer 983
                if (!authUserPartnerMap.containsKey(authUser.getEmailId())) {
984
                    authUserPartnerMap.put(authUser.getEmailId(), partnerIds);
985
                } else {
986
                    authUserPartnerMap.get(authUser.getEmailId()).addAll(partnerIds);
987
                }
988
            }
989
        }
990
        return authUserPartnerMap;
991
    }
26298 tejbeer 992
 
31762 tejbeer 993
    @Override
34082 ranu 994
    public Map<Integer, List<Integer>> authUserpartnerIdMap(int authId, int categoryId) {
995
        Session session = sessionFactory.getCurrentSession();
996
 
34084 ranu 997
        Map<Integer, List<Integer>> authUserpartnerIdMap = new HashMap<>();
34082 ranu 998
 
34158 tejus.loha 999
        List<Position> authPositions = positionRepository.selectPositionbyCategoryIdAndAuthId(categoryId, authId);
34082 ranu 1000
 
35454 amit 1001
        // OPTIMIZED: Batch fetch all PartnerPositions instead of N+1 queries
1002
        List<Integer> positionIds = authPositions.stream()
1003
                .map(Position::getId)
34084 ranu 1004
                .collect(Collectors.toList());
35454 amit 1005
        List<PartnerPosition> partnerPositions = partnerPositionRepository.selectByPositionIds(positionIds);
34082 ranu 1006
 
34084 ranu 1007
        if (partnerPositions.stream().anyMatch(partnerPosition -> partnerPosition.getFofoId() == 0)) {
1008
            List<FofoStore> activeFofoStores = fofoStoreRepository.selectActiveStores();
1009
 
1010
            List<Integer> fofoStoreIds = activeFofoStores.stream()
1011
                    .map(FofoStore::getId) // Extract the IDs of FofoStores
1012
                    .collect(Collectors.toList());
1013
 
1014
            authUserpartnerIdMap.put(authId, fofoStoreIds);
1015
 
34158 tejus.loha 1016
        } else {
34084 ranu 1017
            final TypedQuery<AuthUserPartnerMapModel> typedQuerySimilar = session
1018
                    .createNamedQuery("Position.Auth_User_Partner_Maping", AuthUserPartnerMapModel.class);
1019
 
1020
            typedQuerySimilar.setParameter("authId", authId);
1021
            typedQuerySimilar.setParameter("categoryId", categoryId);
1022
 
1023
            List<AuthUserPartnerMapModel> authUserPartnerMapModels = typedQuerySimilar.getResultList();
1024
 
1025
            authUserpartnerIdMap = authUserPartnerMapModels.stream()
1026
                    .collect(Collectors.groupingBy(
1027
                            AuthUserPartnerMapModel::getAuthId,
1028
                            Collectors.mapping(AuthUserPartnerMapModel::getFofoId, Collectors.toList())
1029
                    ));
1030
 
1031
        }
1032
 
34082 ranu 1033
        LOGGER.info("partnerusermap {}", authUserpartnerIdMap);
1034
        return authUserpartnerIdMap;
1035
    }
1036
 
1037
    @Override
33244 ranu 1038
    public List<String> getAuthUserByPartnerId(int fofoId) throws ProfitMandiBusinessException {
26298 tejbeer 1039
 
31762 tejbeer 1040
        List<String> emails = new ArrayList<>();
1041
        List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId()).collect(Collectors.toList());
26298 tejbeer 1042
 
31762 tejbeer 1043
        regionIds.add(5);// All partners Id;
26298 tejbeer 1044
 
32493 amit.gupta 1045
        List<Integer> partnerPositionIds = partnerPositionRepository.selectByRegionIdAndPartnerId(regionIds, Arrays.asList(fofoId, 0)).stream().map(x -> x.getPositionId()).collect(Collectors.toList());
26448 amit.gupta 1046
 
31762 tejbeer 1047
        LOGGER.info("partnerPositionIds" + partnerPositionIds);
27205 amit.gupta 1048
 
35394 amit 1049
        List<Position> positions = positionRepository.selectByIds(partnerPositionIds);
27548 tejbeer 1050
 
34905 ranu 1051
        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 1052
 
31762 tejbeer 1053
        if (!positions.isEmpty()) {
35454 amit 1054
            // OPTIMIZED: Batch fetch all AuthUsers instead of N+1 queries
1055
            List<Integer> authUserIds = positions.stream()
1056
                    .map(Position::getAuthUserId)
1057
                    .filter(id -> id != null && id > 0)
1058
                    .distinct()
1059
                    .collect(Collectors.toList());
1060
            Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(authUserIds).stream()
1061
                    .collect(Collectors.toMap(AuthUser::getId, au -> au, (a, b) -> a));
1062
 
31762 tejbeer 1063
            for (Position partnerPostionId : positions) {
35454 amit 1064
                AuthUser authUser = authUserMap.get(partnerPostionId.getAuthUserId());
31762 tejbeer 1065
                LOGGER.info("authUser" + authUser);
35454 amit 1066
                if (authUser != null) {
1067
                    emails.add(authUser.getEmailId());
1068
                }
31762 tejbeer 1069
            }
1070
        }
27548 tejbeer 1071
 
31762 tejbeer 1072
        return emails;
1073
    }
27548 tejbeer 1074
 
31762 tejbeer 1075
    @Override
33244 ranu 1076
    public Map<EscalationType, String> getAuthUserAndEsclationTypeByPartnerId(int fofoId) throws ProfitMandiBusinessException {
27548 tejbeer 1077
 
31762 tejbeer 1078
        List<String> emails = new ArrayList<>();
1079
        Map<EscalationType, String> emailEsclationTypeMap = new HashMap<>();
1080
        List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId()).collect(Collectors.toList());
27548 tejbeer 1081
 
31762 tejbeer 1082
        regionIds.add(5);// All partners Id;
1083
        List<Integer> fofoIds = new ArrayList<>();
1084
        fofoIds.add(fofoId);
1085
        fofoIds.add(0);
27548 tejbeer 1086
 
33074 amit.gupta 1087
        //LOGGER.info("fofoIds" + fofoIds);
32493 amit.gupta 1088
        List<Integer> partnerPositionIds = partnerPositionRepository.selectByRegionIdAndPartnerId(regionIds, fofoIds).stream().map(x -> x.getPositionId()).collect(Collectors.toList());
27548 tejbeer 1089
 
33074 amit.gupta 1090
        //LOGGER.info("partnerPositionIds" + partnerPositionIds);
28377 tejbeer 1091
 
35454 amit 1092
        // OPTIMIZED: Batch fetch all positions instead of N+1 queries
1093
        List<Position> positions = positionRepository.selectByIds(partnerPositionIds).stream()
1094
                .filter(p -> p.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES)
1095
                .collect(Collectors.toList());
28377 tejbeer 1096
 
35454 amit 1097
        if (!positions.isEmpty()) {
1098
            // OPTIMIZED: Batch fetch all AuthUsers instead of N+1 queries
1099
            List<Integer> authUserIds = positions.stream()
1100
                    .map(Position::getAuthUserId)
1101
                    .filter(id -> id != null && id > 0)
1102
                    .distinct()
1103
                    .collect(Collectors.toList());
1104
            Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(authUserIds).stream()
1105
                    .collect(Collectors.toMap(AuthUser::getId, au -> au, (a, b) -> a));
1106
 
1107
            for (Position position : positions) {
1108
                AuthUser authUser = authUserMap.get(position.getAuthUserId());
33074 amit.gupta 1109
                //LOGGER.info("authUser" + authUser);
35454 amit 1110
                if (authUser != null) {
1111
                    emailEsclationTypeMap.put(position.getEscalationType(), authUser.getEmailId());
1112
                }
31762 tejbeer 1113
            }
1114
        }
28377 tejbeer 1115
 
33074 amit.gupta 1116
        //LOGGER.info("emailEsclationTypeMap" + emailEsclationTypeMap);
28377 tejbeer 1117
 
31762 tejbeer 1118
        return emailEsclationTypeMap;
1119
    }
31020 tejbeer 1120
 
31762 tejbeer 1121
    @Override
1122
    @Cacheable(value = "authUserIdPartnerIdMapping", cacheManager = "thirtyMinsTimeOutCacheManager")
33244 ranu 1123
    public Map<Integer, List<Integer>> getAuthUserIdPartnerIdMapping() throws ProfitMandiBusinessException {
36802 ranu 1124
        return buildAuthUserIdPartnerIdMapping(true);
1125
    }
1126
 
1127
    @Override
1128
    @Cacheable(value = "authUserIdAllPartnerIdMapping", cacheManager = "thirtyMinsTimeOutCacheManager")
1129
    public Map<Integer, List<Integer>> getAuthUserIdAllPartnerIdMapping() throws ProfitMandiBusinessException {
1130
        return buildAuthUserIdPartnerIdMapping(false);
1131
    }
1132
 
1133
    private Map<Integer, List<Integer>> buildAuthUserIdPartnerIdMapping(boolean activeOnly) throws ProfitMandiBusinessException {
31762 tejbeer 1134
        Map<Integer, List<Integer>> storeGuyMap = new HashMap<>();
36802 ranu 1135
        Set<Integer> fofoIdsScope = (activeOnly
1136
                ? fofoStoreRepository.selectActiveStores()
1137
                : fofoStoreRepository.selectAllFranchiseStores())
1138
                .stream().map(x -> x.getId()).collect(Collectors.toSet());
31020 tejbeer 1139
 
34077 tejus.loha 1140
        List<Position> categoryPositions = positionRepository.selectAllPosition();
31020 tejbeer 1141
 
31762 tejbeer 1142
        Map<Integer, Position> positionsMap = categoryPositions.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
29229 tejbeer 1143
 
35454 amit 1144
        // OPTIMIZED: Batch fetch all AuthUsers instead of N+1 queries
1145
        List<Integer> authUserIds = categoryPositions.stream()
1146
                .map(Position::getAuthUserId)
1147
                .filter(id -> id != null && id > 0)
1148
                .distinct()
1149
                .collect(Collectors.toList());
1150
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(authUserIds).stream()
1151
                .collect(Collectors.toMap(AuthUser::getId, au -> au, (a, b) -> a));
1152
 
31762 tejbeer 1153
        Map<Integer, List<CustomRetailer>> positonPartnerMap = this.getPositionCustomRetailerMap(categoryPositions);
1154
        for (Map.Entry<Integer, List<CustomRetailer>> positionPartnerEntry : positonPartnerMap.entrySet()) {
1155
            int authUserId = positionsMap.get(positionPartnerEntry.getKey()).getAuthUserId();
36802 ranu 1156
            List<Integer> partnerIds = positionPartnerEntry.getValue().stream().filter(x -> fofoIdsScope.contains(x.getPartnerId())).map(x -> x.getPartnerId()).collect(Collectors.toList());
35454 amit 1157
            AuthUser authUser = authUserMap.get(authUserId);
31762 tejbeer 1158
            if (authUser != null && authUser.isActive()) {
1159
                if (!storeGuyMap.containsKey(authUserId)) {
1160
                    storeGuyMap.put(authUserId, partnerIds);
1161
                } else {
1162
                    storeGuyMap.get(authUserId).addAll(partnerIds);
1163
                }
1164
            }
1165
        }
1166
        storeGuyMap.keySet().stream().forEach(x -> {
1167
            List<Integer> fofoIds = storeGuyMap.get(x);
1168
            storeGuyMap.put(x, fofoIds.stream().distinct().collect(Collectors.toList()));
1169
        });
1170
        return storeGuyMap;
1171
    }
28908 tejbeer 1172
 
31762 tejbeer 1173
    @Override
1174
    @Cacheable(value = "L1L2Mapping", cacheManager = "thirtyMinsTimeOutCacheManager")
33244 ranu 1175
    public Map<Integer, List<Integer>> getL2L1Mapping() throws ProfitMandiBusinessException {
31762 tejbeer 1176
        List<Position> l1SalesPositions = positionRepository.selectPositionbyCategoryIdAndEscalationType(
1177
                ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L1);
1178
        List<Position> l2SalesPositions = positionRepository.selectPositionbyCategoryIdAndEscalationType(
1179
                ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L2);
28908 tejbeer 1180
 
33074 amit.gupta 1181
        //LOGGER.info("position" + l1SalesPositions);
31762 tejbeer 1182
        Map<Integer, List<Integer>> authUserPartnerListMap = this.getAuthUserIdPartnerIdMapping();
33074 amit.gupta 1183
        //LOGGER.info("map" + authUserPartnerListMap);
28908 tejbeer 1184
 
31762 tejbeer 1185
        Map<Integer, List<Integer>> l2l1ListMap = new HashMap<>();
29318 tejbeer 1186
 
31762 tejbeer 1187
        for (Position l2SalePosition : l2SalesPositions) {
1188
            int l2AuthUserId = l2SalePosition.getAuthUserId();
1189
            if (authUserPartnerListMap.containsKey(l2SalePosition.getAuthUserId())) {
1190
                List<Integer> mappedL1AuthUsers = new ArrayList<>();
1191
                l2l1ListMap.put(l2AuthUserId, mappedL1AuthUsers);
1192
                List<Integer> l2FofoIds = authUserPartnerListMap.get(l2AuthUserId);
1193
                for (Position l1SalePosition : l1SalesPositions) {
1194
                    int l1AuthUserId = l1SalePosition.getAuthUserId();
1195
                    if (authUserPartnerListMap.containsKey(l1AuthUserId)) {
1196
                        List<Integer> l1FofoIds = authUserPartnerListMap.get(l1SalePosition.getAuthUserId());
1197
                        if (l2FofoIds.containsAll(l1FofoIds)) {
1198
                            mappedL1AuthUsers.add(l1AuthUserId);
1199
                        }
1200
                    }
28856 manish 1201
 
31762 tejbeer 1202
                }
1203
            }
29296 manish 1204
 
31762 tejbeer 1205
        }
29296 manish 1206
 
31762 tejbeer 1207
        return l2l1ListMap;
1208
    }
29296 manish 1209
 
31762 tejbeer 1210
    @Override
1211
    public Map<Integer, List<AuthUser>> getAssignedAuthList(List<Ticket> tickets) {
1212
        if (tickets.size() == 0) {
1213
            return new HashMap<>();
1214
        }
1215
        List<TicketAssigned> ticketAssignedList = ticketAssignedRepository.selectByTicketIds(tickets.stream().map(x -> x.getId()).collect(Collectors.toList()));
1216
        List<Integer> authUserIds = ticketAssignedList.stream().map(x -> x.getAssineeId()).distinct().collect(Collectors.toList());
35394 amit 1217
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(authUserIds).stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
31762 tejbeer 1218
        return ticketAssignedList.stream().collect(Collectors.groupingBy(x -> x.getTicketId(), Collectors.mapping(x -> authUserMap.get(x.getAssineeId()), Collectors.toList())));
1219
    }
28908 tejbeer 1220
 
31762 tejbeer 1221
    @Override
33244 ranu 1222
    public Map<EscalationType, AuthUser> getAuthUserAndEsclationByPartnerId(int fofoId) throws ProfitMandiBusinessException {
31762 tejbeer 1223
        Map<EscalationType, AuthUser> authuserEsclationTypeMap = new HashMap<>();
1224
        List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId()).collect(Collectors.toList());
28908 tejbeer 1225
 
35592 amit 1226
        regionIds.add(ALL_PARTNERS_REGION);// All partners Id;
31762 tejbeer 1227
        List<Integer> fofoIds = new ArrayList<>();
1228
        fofoIds.add(fofoId);
1229
        fofoIds.add(0);
28908 tejbeer 1230
 
32493 amit.gupta 1231
        List<Integer> partnerPositionIds = partnerPositionRepository.selectByRegionIdAndPartnerId(regionIds, fofoIds).stream().map(x -> x.getPositionId()).collect(Collectors.toList());
28908 tejbeer 1232
 
35592 amit 1233
        if (partnerPositionIds.isEmpty()) {
1234
            return authuserEsclationTypeMap;
1235
        }
30003 tejbeer 1236
 
35592 amit 1237
        // OPTIMIZED: Batch fetch all positions instead of N+1 queries
1238
        List<Position> salesPositions = positionRepository.selectByIds(partnerPositionIds).stream()
1239
                .filter(p -> p.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES)
1240
                .collect(Collectors.toList());
30003 tejbeer 1241
 
35592 amit 1242
        if (salesPositions.isEmpty()) {
1243
            return authuserEsclationTypeMap;
1244
        }
30003 tejbeer 1245
 
35592 amit 1246
        // OPTIMIZED: Batch fetch all AuthUsers instead of N+1 queries
1247
        List<Integer> authUserIds = salesPositions.stream()
1248
                .map(Position::getAuthUserId)
1249
                .filter(id -> id != null && id > 0)
1250
                .distinct()
1251
                .collect(Collectors.toList());
1252
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(authUserIds).stream()
1253
                .collect(Collectors.toMap(AuthUser::getId, au -> au, (a, b) -> a));
1254
 
1255
        for (Position position : salesPositions) {
1256
            AuthUser authUser = authUserMap.get(position.getAuthUserId());
1257
            if (authUser != null) {
31762 tejbeer 1258
                authuserEsclationTypeMap.put(position.getEscalationType(), authUser);
1259
            }
1260
        }
30003 tejbeer 1261
 
31762 tejbeer 1262
        return authuserEsclationTypeMap;
1263
    }
30044 tejbeer 1264
 
31762 tejbeer 1265
    @Override
35394 amit 1266
    public Map<Integer, Map<EscalationType, AuthUser>> getAuthUserAndEsclationByPartnerIds(Set<Integer> fofoIds) throws ProfitMandiBusinessException {
1267
        Map<Integer, Map<EscalationType, AuthUser>> result = new HashMap<>();
1268
 
1269
        if (fofoIds == null || fofoIds.isEmpty()) {
1270
            return result;
1271
        }
1272
 
1273
        // Initialize result map
1274
        for (Integer fofoId : fofoIds) {
1275
            result.put(fofoId, new HashMap<>());
1276
        }
1277
 
1278
        // Batch fetch all partner regions
1279
        List<Integer> fofoIdListWithZero = new ArrayList<>(fofoIds);
1280
        fofoIdListWithZero.add(0);
1281
        List<PartnerRegion> allPartnerRegions = partnerRegionRepository.selectByfofoIds(fofoIdListWithZero);
1282
 
1283
        // Build fofoId -> regionIds map
1284
        Map<Integer, Set<Integer>> fofoRegionMap = new HashMap<>();
1285
        for (Integer fofoId : fofoIds) {
1286
            fofoRegionMap.put(fofoId, new HashSet<>());
1287
            fofoRegionMap.get(fofoId).add(ALL_PARTNERS_REGION);
1288
        }
1289
        for (PartnerRegion pr : allPartnerRegions) {
1290
            int prFofoId = pr.getFofoId();
1291
            if (prFofoId == 0) {
1292
                for (Integer fid : fofoIds) {
1293
                    fofoRegionMap.get(fid).add(pr.getRegionId());
1294
                }
1295
            } else if (fofoIds.contains(prFofoId)) {
1296
                fofoRegionMap.get(prFofoId).add(pr.getRegionId());
1297
            }
1298
        }
1299
 
1300
        // Collect all region IDs
1301
        Set<Integer> allRegionIds = fofoRegionMap.values().stream()
1302
                .flatMap(Set::stream).collect(Collectors.toSet());
1303
 
1304
        // Batch fetch all partner positions
1305
        List<PartnerPosition> allPartnerPositions = partnerPositionRepository.selectByRegionIdAndPartnerId(
1306
                new ArrayList<>(allRegionIds), fofoIdListWithZero);
1307
 
1308
        // Collect all position IDs
1309
        Set<Integer> allPositionIds = allPartnerPositions.stream()
1310
                .map(PartnerPosition::getPositionId).collect(Collectors.toSet());
1311
 
1312
        // Batch fetch all positions for SALES category
1313
        List<Position> salesPositions = positionRepository.selectPositionbyCategoryIdAndEscalationType(
1314
                ProfitMandiConstants.TICKET_CATEGORY_SALES, null);
1315
        Map<Integer, Position> positionMap = salesPositions.stream()
1316
                .filter(p -> allPositionIds.contains(p.getId()))
1317
                .collect(Collectors.toMap(Position::getId, p -> p, (a, b) -> a));
1318
 
1319
        // Collect all auth user IDs and batch fetch
1320
        Set<Integer> authUserIds = positionMap.values().stream()
1321
                .map(Position::getAuthUserId).collect(Collectors.toSet());
1322
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(new ArrayList<>(authUserIds))
1323
                .stream().collect(Collectors.toMap(AuthUser::getId, au -> au, (a, b) -> a));
1324
 
1325
        // For each fofoId, find matching positions and build result
1326
        for (Integer fofoId : fofoIds) {
1327
            Set<Integer> regionIds = fofoRegionMap.get(fofoId);
1328
            Map<EscalationType, AuthUser> escalationMap = result.get(fofoId);
1329
 
1330
            for (PartnerPosition pp : allPartnerPositions) {
1331
                if (regionIds.contains(pp.getRegionId()) &&
1332
                    (pp.getFofoId() == 0 || pp.getFofoId() == fofoId)) {
1333
                    Position position = positionMap.get(pp.getPositionId());
1334
                    if (position != null) {
1335
                        AuthUser authUser = authUserMap.get(position.getAuthUserId());
1336
                        if (authUser != null) {
1337
                            escalationMap.put(position.getEscalationType(), authUser);
1338
                        }
1339
                    }
1340
                }
1341
            }
1342
        }
1343
 
1344
        return result;
1345
    }
1346
 
1347
    @Override
33244 ranu 1348
    public List<AuthUser> getAuthUserIdByPartnerId(int fofoId) throws ProfitMandiBusinessException {
33041 ranu 1349
        return this.getAuthUserIdByPartnerId(fofoId, EscalationType.escalations.toArray(new EscalationType[0]));
1350
    }
1351
 
1352
    @Override
33244 ranu 1353
    public List<AuthUser> getAuthUserIdByPartnerId(int fofoId, EscalationType... escalationTypes) throws ProfitMandiBusinessException {
31762 tejbeer 1354
        List<AuthUser> authUsers = new ArrayList<>();
1355
        List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId()).collect(Collectors.toList());
30044 tejbeer 1356
 
31762 tejbeer 1357
        regionIds.add(5);// All partners Id;
1358
        List<Integer> fofoIds = new ArrayList<>();
1359
        fofoIds.add(fofoId);
1360
        fofoIds.add(0);
30044 tejbeer 1361
 
33074 amit.gupta 1362
        //LOGGER.info("fofoIds" + fofoIds);
32493 amit.gupta 1363
        List<Integer> partnerPositionIds = partnerPositionRepository.selectByRegionIdAndPartnerId(regionIds, fofoIds).stream().map(x -> x.getPositionId()).collect(Collectors.toList());
30003 tejbeer 1364
 
33074 amit.gupta 1365
        //LOGGER.info("partnerPositionIds" + partnerPositionIds);
34905 ranu 1366
        List<Integer> allowedTicketCategoryIds = Arrays.asList(ProfitMandiConstants.TICKET_CATEGORY_SALES, ProfitMandiConstants.TICKET_CATEGORY_RBM,ProfitMandiConstants.TICKET_CATEGORY_ABM);
30003 tejbeer 1367
 
30044 tejbeer 1368
 
35394 amit 1369
        List<Position> escalationBasedPositions = positionRepository.selectByIds(partnerPositionIds).stream().filter(x -> allowedTicketCategoryIds.contains(x.getCategoryId()) &&
33041 ranu 1370
                Arrays.stream(escalationTypes)
1371
                        .anyMatch(y -> y.equals(x.getEscalationType()))).collect(Collectors.toList());
30003 tejbeer 1372
 
33041 ranu 1373
        List<Integer> authUserIds = escalationBasedPositions.stream().map(x -> x.getAuthUserId()).collect(Collectors.toList());
30003 tejbeer 1374
 
35394 amit 1375
        return authRepository.selectByIds(authUserIds);
30003 tejbeer 1376
 
31762 tejbeer 1377
    }
30044 tejbeer 1378
 
31762 tejbeer 1379
    @Override
37357 amit 1380
    public List<AuthUser> getAuthUsersByPartnerIdAndCategory(int fofoId, int categoryId, EscalationType... escalationTypes) throws ProfitMandiBusinessException {
1381
        List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId()).collect(Collectors.toList());
1382
        regionIds.add(ALL_PARTNERS_REGION);
1383
 
1384
        List<Integer> partnerPositionIds = partnerPositionRepository.selectByRegionIdAndPartnerId(regionIds, Arrays.asList(fofoId, 0))
1385
                .stream().map(x -> x.getPositionId()).distinct().collect(Collectors.toList());
1386
        if (partnerPositionIds.isEmpty()) {
1387
            return new ArrayList<>();
1388
        }
1389
 
1390
        List<EscalationType> escalations = (escalationTypes == null || escalationTypes.length == 0)
1391
                ? EscalationType.escalations : Arrays.asList(escalationTypes);
1392
 
1393
        List<Integer> authUserIds = positionRepository.selectByIds(partnerPositionIds).stream()
1394
                .filter(x -> x.getCategoryId() == categoryId)
1395
                .filter(x -> escalations.contains(x.getEscalationType()))
1396
                .map(x -> x.getAuthUserId())
1397
                .filter(x -> x > 0)
1398
                .distinct().collect(Collectors.toList());
1399
        LOGGER.info("fofoId {}, categoryId {}, escalations {}, authUserIds {}", fofoId, categoryId, escalations, authUserIds);
1400
        if (authUserIds.isEmpty()) {
1401
            return new ArrayList<>();
1402
        }
1403
 
1404
        return authRepository.selectByIds(authUserIds).stream()
1405
                .filter(x -> Boolean.TRUE.equals(x.getActive()))
1406
                .collect(Collectors.toList());
1407
    }
1408
 
1409
    @Override
31762 tejbeer 1410
    public List<AuthUser> getAuthUserIds(int categoryId, List<EscalationType> escalationType) {
30044 tejbeer 1411
 
31762 tejbeer 1412
        List<Position> positions = positionRepository.selectPositionbyCategoryIdAndEscalationTypes(categoryId, escalationType);
1413
        List<Integer> authIds = positions.stream().map(x -> x.getAuthUserId()).distinct().collect(Collectors.toList());
30003 tejbeer 1414
 
33074 amit.gupta 1415
        //LOGGER.info("authIds" + authIds);
35058 amit 1416
        List<AuthUser> authUsers = null;
1417
        if (authIds.size() > 0) {
35394 amit 1418
            authUsers = authRepository.selectByIds(authIds);
35058 amit 1419
        } else {
1420
            authUsers = new ArrayList<>();
1421
        }
30003 tejbeer 1422
 
31762 tejbeer 1423
        LOGGER.info("authUsers" + authUsers);
1424
        return authUsers;
1425
    }
1426
 
1427
    @Override
1428
    public List<AuthUser> getAuthUserByCategoryId(int categoryId, EscalationType escalationType) {
1429
 
1430
        List<Position> positions = positionRepository.selectPositionbyCategoryIdAndEscalationType(categoryId, escalationType);
1431
        List<Integer> authIds = positions.stream().map(x -> x.getAuthUserId()).distinct().collect(Collectors.toList());
1432
 
1433
        LOGGER.info("authIds" + authIds);
1434
        List<AuthUser> authUsers = new ArrayList<>();
1435
        if (!authIds.isEmpty()) {
35394 amit 1436
            authUsers = authRepository.selectByIds(authIds);
31762 tejbeer 1437
        }
1438
 
1439
        LOGGER.info("authUsers" + authUsers);
1440
        return authUsers;
1441
    }
1442
 
1443
    @Override
1444
    @Cacheable(value = "authUserByCategoryId", cacheManager = "thirtyMinsTimeOutCacheManager")
1445
    public List<AuthUser> getAuthUserByCategoryId(int categoryId) {
1446
        List<Position> positions = positionRepository.selectPositionByCategoryId(categoryId);
1447
        List<Integer> authIds = positions.stream().map(x -> x.getAuthUserId()).distinct().collect(Collectors.toList());
1448
 
1449
        LOGGER.info("authIds" + authIds);
1450
 
35394 amit 1451
        List<AuthUser> authUsers = authRepository.selectByIds(authIds).stream().filter(x -> x.getActive()).collect(Collectors.toList());
31762 tejbeer 1452
 
1453
        LOGGER.info("authUsers" + authUsers);
1454
        return authUsers;
1455
    }
1456
 
34380 amit.gupta 1457
    private class SaleRoles1 {
31762 tejbeer 1458
 
1459
        private List<String> l1;
1460
        private List<String> l2;
1461
        private List<String> l3;
1462
        private List<String> l4;
1463
 
34380 amit.gupta 1464
        public SaleRoles1() {
31762 tejbeer 1465
            l1 = new ArrayList<>();
1466
            l2 = new ArrayList<>();
1467
            l3 = new ArrayList<>();
1468
            l4 = new ArrayList<>();
1469
        }
1470
 
1471
        public List<String> getL1() {
1472
            return l1;
1473
        }
1474
 
1475
        public List<String> getL2() {
1476
            return l2;
1477
        }
1478
 
1479
        public List<String> getL3() {
1480
            return l3;
1481
        }
1482
 
1483
        public List<String> getL4() {
1484
            return l4;
1485
        }
1486
 
1487
        @Override
1488
        public String toString() {
1489
            return "SaleRoles [l1=" + l1 + ", l2=" + l2 + ", l3=" + l3 + ", l4=" + l4 + "]";
1490
        }
1491
 
1492
    }
1493
 
33161 ranu 1494
 
31762 tejbeer 1495
    @Override
1496
    @Cacheable(value = "partnerSaleHeader", cacheManager = "oneDayCacheManager")
33244 ranu 1497
    public Map<Integer, FofoReportingModel> getPartnerIdSalesHeaders() throws ProfitMandiBusinessException {
34380 amit.gupta 1498
        Map<String, SaleRoles1> partnerEmailSalesMap = new HashMap<>();
31762 tejbeer 1499
 
1500
        List<Position> positions = positionRepository.selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_SALES);
1501
        Map<Integer, AuthUser> authUsersMap = authRepository.selectAllActiveUser().stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
1502
        Map<Integer, List<CustomRetailer>> positionIdRetailerMap = this.getPositionCustomRetailerMap(positions);
1503
        for (Position position : positions) {
1504
            List<CustomRetailer> crList = positionIdRetailerMap.get(position.getId());
1505
            if (crList == null)
1506
                continue;
1507
            for (CustomRetailer cr : crList) {
1508
                if (!partnerEmailSalesMap.containsKey(cr.getEmail())) {
34380 amit.gupta 1509
                    partnerEmailSalesMap.put(cr.getEmail(), new SaleRoles1());
31762 tejbeer 1510
                }
34380 amit.gupta 1511
                SaleRoles1 saleRoles1 = partnerEmailSalesMap.get(cr.getEmail());
31762 tejbeer 1512
                AuthUser authUser = authUsersMap.get(position.getAuthUserId());
1513
                if (authUser == null) {
1514
                    continue;
1515
                }
1516
                String name = authUser.getFirstName() + " " + authUser.getLastName();
1517
                if (position.getEscalationType().equals(EscalationType.L1)) {
34380 amit.gupta 1518
                    saleRoles1.getL1().add(name);
31762 tejbeer 1519
                } else if (position.getEscalationType().equals(EscalationType.L2)) {
34380 amit.gupta 1520
                    saleRoles1.getL2().add(name);
31762 tejbeer 1521
                }
1522
 
1523
            }
1524
        }
1525
 
1526
        Set<CustomRetailer> allCrList = new HashSet<>();
1527
        for (List<CustomRetailer> cr : positionIdRetailerMap.values()) {
1528
            allCrList.addAll(cr);
1529
        }
1530
 
1531
        Map<Integer, FofoStore> fofoStoresMap = fofoStoreRepository.selectActiveStores().stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
1532
 
1533
        Map<Integer, FofoReportingModel> partnerIdSalesHeadersMap = new HashMap<>();
1534
 
33378 ranu 1535
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
1536
        for (Map.Entry<Integer, CustomRetailer> customRetailerEntry : customRetailerMap.entrySet()) {
1537
 
1538
            CustomRetailer customRetailer = customRetailerEntry.getValue();
1539
 
1540
            String code = customRetailer.getCode();
31762 tejbeer 1541
            // String storeName = "SmartDukaan-" +
1542
            // fofoStore.getCode().replaceAll("[a-zA-Z]", "");
33378 ranu 1543
            String businessName = customRetailer.getBusinessName();
31762 tejbeer 1544
            try {
37351 ranu 1545
                String stateManager = StringUtils.join(new HashSet(partnerEmailSalesMap.get(customRetailer.getEmail()).getL4()), ", ");
34158 tejus.loha 1546
                String territoryManager = StringUtils.join(new HashSet(partnerEmailSalesMap.get(customRetailer.getEmail()).getL1()), ", ");
37351 ranu 1547
                String salesL2Manager = StringUtils.join(new HashSet(partnerEmailSalesMap.get(customRetailer.getEmail()).getL2()), ", ");
31762 tejbeer 1548
 
1549
                FofoReportingModel reportingModel = new FofoReportingModel();
1550
                reportingModel.setBusinessName(businessName);
1551
                reportingModel.setCode(code);
33378 ranu 1552
                reportingModel.setFofoId(customRetailer.getPartnerId());
31762 tejbeer 1553
                reportingModel.setRegionalManager(stateManager);
1554
                reportingModel.setTerritoryManager(territoryManager);
37351 ranu 1555
                reportingModel.setSalesL2Manager(salesL2Manager);
33378 ranu 1556
                partnerIdSalesHeadersMap.put(customRetailer.getPartnerId(), reportingModel);
31762 tejbeer 1557
            } catch (Exception e) {
33378 ranu 1558
                LOGGER.warn("Could not find partner with email - {}", customRetailer.getEmail());
31762 tejbeer 1559
            }
1560
        }
1561
        return partnerIdSalesHeadersMap;
1562
 
1563
    }
1564
 
33161 ranu 1565
 
34905 ranu 1566
    private class ABMRoles {
1567
 
1568
        private List<String> l1;
1569
        private List<String> l2;
1570
        private List<String> l3;
1571
        private List<String> l4;
1572
 
1573
        public ABMRoles() {
1574
            l1 = new ArrayList<>();
1575
            l2 = new ArrayList<>();
1576
            l3 = new ArrayList<>();
1577
            l4 = new ArrayList<>();
1578
        }
1579
 
1580
        public List<String> getL1() {
1581
            return l1;
1582
        }
1583
 
1584
        public List<String> getL2() {
1585
            return l2;
1586
        }
1587
 
1588
        public List<String> getL3() {
1589
            return l3;
1590
        }
1591
 
1592
        public List<String> getL4() {
1593
            return l4;
1594
        }
1595
 
1596
        @Override
1597
        public String toString() {
1598
            return "SaleRoles [l1=" + l1 + ", l2=" + l2 + ", l3=" + l3 + ", l4=" + l4 + "]";
1599
        }
1600
 
1601
    }
1602
 
1603
 
1604
    @Override
1605
    @Cacheable(value = "partnerABMHeader", cacheManager = "oneDayCacheManager")
1606
    public Map<Integer, FofoAbmReportingModel> getPartnerIdABMHeaders() throws ProfitMandiBusinessException {
1607
        Map<String, ABMRoles> partnerEmailABMMap = new HashMap<>();
1608
 
1609
        List<Position> positions = positionRepository.selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_ABM);
1610
        Map<Integer, AuthUser> authUsersMap = authRepository.selectAllActiveUser().stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
1611
        Map<Integer, List<CustomRetailer>> positionIdRetailerMap = this.getPositionCustomRetailerMap(positions);
1612
        for (Position position : positions) {
1613
            List<CustomRetailer> crList = positionIdRetailerMap.get(position.getId());
1614
            if (crList == null)
1615
                continue;
1616
            for (CustomRetailer cr : crList) {
1617
                if (!partnerEmailABMMap.containsKey(cr.getEmail())) {
1618
                    partnerEmailABMMap.put(cr.getEmail(), new ABMRoles());
1619
                }
1620
                ABMRoles abmRoles = partnerEmailABMMap.get(cr.getEmail());
1621
                AuthUser authUser = authUsersMap.get(position.getAuthUserId());
1622
                if (authUser == null) {
1623
                    continue;
1624
                }
1625
                String name = authUser.getFirstName() + " " + authUser.getLastName();
1626
                if (position.getEscalationType().equals(EscalationType.L1)) {
1627
                    abmRoles.getL1().add(name);
1628
                } else if (position.getEscalationType().equals(EscalationType.L2)) {
1629
                    abmRoles.getL2().add(name);
1630
                }
1631
 
1632
            }
1633
        }
1634
 
1635
        Set<CustomRetailer> allCrList = new HashSet<>();
1636
        for (List<CustomRetailer> cr : positionIdRetailerMap.values()) {
1637
            allCrList.addAll(cr);
1638
        }
1639
 
1640
        Map<Integer, FofoStore> fofoStoresMap = fofoStoreRepository.selectActiveStores().stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
1641
 
1642
        Map<Integer, FofoAbmReportingModel> partnerIdAbmHeadersMap = new HashMap<>();
1643
 
1644
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
1645
        for (Map.Entry<Integer, CustomRetailer> customRetailerEntry : customRetailerMap.entrySet()) {
1646
 
1647
            CustomRetailer customRetailer = customRetailerEntry.getValue();
1648
 
1649
            String code = customRetailer.getCode();
1650
            // String storeName = "SmartDukaan-" +
1651
            // fofoStore.getCode().replaceAll("[a-zA-Z]", "");
1652
            String businessName = customRetailer.getBusinessName();
1653
            try {
1654
                String l2Manager = StringUtils.join(new HashSet(partnerEmailABMMap.get(customRetailer.getEmail()).getL2()), ", ");
1655
                String l1Manager = StringUtils.join(new HashSet(partnerEmailABMMap.get(customRetailer.getEmail()).getL1()), ", ");
1656
 
1657
                if (StringUtils.isEmpty(l1Manager)) {
1658
                    l2Manager = StringUtils.join(new HashSet(partnerEmailABMMap.get(customRetailer.getEmail()).getL2()), ", ");
1659
                }
1660
 
1661
                FofoAbmReportingModel reportingModel = new FofoAbmReportingModel();
1662
                reportingModel.setBusinessName(businessName);
1663
                reportingModel.setCode(code);
1664
                reportingModel.setFofoId(customRetailer.getPartnerId());
1665
                reportingModel.setL1Manager(l2Manager);
1666
                reportingModel.setL2Manager(l1Manager);
1667
                partnerIdAbmHeadersMap.put(customRetailer.getPartnerId(), reportingModel);
1668
            } catch (Exception e) {
1669
                LOGGER.warn("Could not find partner with email - {}", customRetailer.getEmail());
1670
            }
1671
        }
1672
        return partnerIdAbmHeadersMap;
1673
 
1674
    }
1675
 
1676
 
33161 ranu 1677
    private class RBMRoles {
1678
 
1679
        private List<String> l1;
1680
        private List<String> l2;
1681
        private List<String> l3;
1682
        private List<String> l4;
1683
 
1684
        public RBMRoles() {
1685
            l1 = new ArrayList<>();
1686
            l2 = new ArrayList<>();
1687
            l3 = new ArrayList<>();
1688
            l4 = new ArrayList<>();
1689
        }
1690
 
1691
        public List<String> getL1() {
1692
            return l1;
1693
        }
1694
 
1695
        public List<String> getL2() {
1696
            return l2;
1697
        }
1698
 
1699
        public List<String> getL3() {
1700
            return l3;
1701
        }
1702
 
1703
        public List<String> getL4() {
1704
            return l4;
1705
        }
1706
 
1707
        @Override
1708
        public String toString() {
1709
            return "RBMRoles [l1=" + l1 + ", l2=" + l2 + ", l3=" + l3 + ", l4=" + l4 + "]";
1710
        }
1711
 
1712
    }
1713
 
31762 tejbeer 1714
    @Override
33161 ranu 1715
    @Cacheable(value = "partnerRBMHeader", cacheManager = "oneDayCacheManager")
33244 ranu 1716
    public Map<Integer, FofoRBMReportingModel> getPartnerIdRBMHeaders() throws ProfitMandiBusinessException {
33161 ranu 1717
        Map<String, RBMRoles> partnerEmailRbmMap = new HashMap<>();
1718
 
1719
        List<Position> positions = positionRepository.selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_RBM);
1720
        Map<Integer, AuthUser> authUsersMap = authRepository.selectAllActiveUser().stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
1721
        Map<Integer, List<CustomRetailer>> positionIdRetailerMap = this.getPositionCustomRetailerMap(positions);
1722
        for (Position position : positions) {
1723
            List<CustomRetailer> crList = positionIdRetailerMap.get(position.getId());
1724
            if (crList == null)
1725
                continue;
1726
            for (CustomRetailer cr : crList) {
1727
                if (!partnerEmailRbmMap.containsKey(cr.getEmail())) {
1728
                    partnerEmailRbmMap.put(cr.getEmail(), new RBMRoles());
1729
                }
1730
                RBMRoles rbmRole = partnerEmailRbmMap.get(cr.getEmail());
1731
                AuthUser authUser = authUsersMap.get(position.getAuthUserId());
1732
                if (authUser == null) {
1733
                    continue;
1734
                }
1735
                String name = authUser.getFirstName() + " " + authUser.getLastName();
1736
                if (position.getEscalationType().equals(EscalationType.L1)) {
1737
                    rbmRole.getL1().add(name);
1738
                } else if (position.getEscalationType().equals(EscalationType.L2)) {
1739
                    rbmRole.getL2().add(name);
1740
                }
1741
 
1742
            }
1743
        }
1744
 
1745
        Set<CustomRetailer> allCrList = new HashSet<>();
1746
        for (List<CustomRetailer> cr : positionIdRetailerMap.values()) {
1747
            allCrList.addAll(cr);
1748
        }
1749
 
1750
 
1751
        Map<Integer, FofoRBMReportingModel> partnerIdRbmHeadersMap = new HashMap<>();
1752
 
33377 amit.gupta 1753
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
1754
        for (Map.Entry<Integer, CustomRetailer> customRetailerEntry : customRetailerMap.entrySet()) {
1755
 
1756
            CustomRetailer customRetailer = customRetailerEntry.getValue();
1757
 
1758
            String code = customRetailer.getCode();
33161 ranu 1759
            // String storeName = "SmartDukaan-" +
1760
            // fofoStore.getCode().replaceAll("[a-zA-Z]", "");
33377 amit.gupta 1761
            String businessName = customRetailer.getBusinessName();
33161 ranu 1762
            try {
33377 amit.gupta 1763
                String L2User = StringUtils.join(partnerEmailRbmMap.get(customRetailer.getEmail()).getL2(), ", ");
1764
                String L1USer = StringUtils.join(partnerEmailRbmMap.get(customRetailer.getEmail()).getL1(), ", ");
33161 ranu 1765
 
1766
                FofoRBMReportingModel reportingModel = new FofoRBMReportingModel();
1767
                reportingModel.setBusinessName(businessName);
1768
                reportingModel.setCode(code);
33377 amit.gupta 1769
                reportingModel.setFofoId(customRetailer.getPartnerId());
35180 amit 1770
                reportingModel.setL1Manager(L1USer);
1771
                reportingModel.setL2Manager(L2User);
33377 amit.gupta 1772
                partnerIdRbmHeadersMap.put(customRetailer.getPartnerId(), reportingModel);
33161 ranu 1773
            } catch (Exception e) {
33377 amit.gupta 1774
                LOGGER.warn("Could not find partner with email - {}", customRetailer.getEmail());
33161 ranu 1775
            }
1776
        }
1777
        return partnerIdRbmHeadersMap;
1778
 
1779
    }
1780
 
1781
    @Override
31762 tejbeer 1782
    public Map<Integer, TicketCategory> getSubCategoryIdAndCategoryMap(List<Integer> subCategoryIds) {
1783
        Map<Integer, TicketCategory> subCategoryIdAndCategoryMap = new HashMap<>();
35592 amit 1784
        if (subCategoryIds == null || subCategoryIds.isEmpty()) {
1785
            return subCategoryIdAndCategoryMap;
1786
        }
31762 tejbeer 1787
 
1788
        List<TicketSubCategory> ticketSubCategories = ticketSubCategoryRepository.selectByIds(subCategoryIds);
1789
 
35592 amit 1790
        // OPTIMIZED: Batch fetch all categories instead of N+1 queries
1791
        List<Integer> categoryIds = ticketSubCategories.stream()
1792
                .map(TicketSubCategory::getCategoryId)
1793
                .distinct()
1794
                .collect(Collectors.toList());
1795
        Map<Integer, TicketCategory> categoryMap = ticketCategoryRepository.selectAll(categoryIds).stream()
1796
                .collect(Collectors.toMap(TicketCategory::getId, tc -> tc, (a, b) -> a));
1797
 
31762 tejbeer 1798
        for (TicketSubCategory ticketSubCategory : ticketSubCategories) {
35592 amit 1799
            subCategoryIdAndCategoryMap.put(ticketSubCategory.getId(), categoryMap.get(ticketSubCategory.getCategoryId()));
31762 tejbeer 1800
        }
1801
        return subCategoryIdAndCategoryMap;
1802
    }
1803
 
35394 amit 1804
    @Override
1805
    public Map<Integer, Map<String, Integer>> getBmAsmRbmAuthUserIdsByFofoIds(Set<Integer> fofoIds) throws ProfitMandiBusinessException {
1806
        Map<Integer, Map<String, Integer>> result = new HashMap<>();
1807
 
1808
        if (fofoIds == null || fofoIds.isEmpty()) {
1809
            return result;
1810
        }
1811
 
1812
        // Initialize result map with empty values for each fofoId
1813
        for (Integer fofoId : fofoIds) {
1814
            Map<String, Integer> roleMap = new HashMap<>();
1815
            roleMap.put("BM", 0);
1816
            roleMap.put("ASM", 0);
1817
            roleMap.put("RBM", 0);
1818
            result.put(fofoId, roleMap);
1819
        }
1820
 
1821
        // Fetch positions by category + escalation type (same for all fofoIds)
1822
        List<Position> bmPositions = positionRepository.selectPositionbyCategoryIdAndEscalationType(
1823
                ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L2);
1824
        List<Position> asmPositions = positionRepository.selectPositionbyCategoryIdAndEscalationType(
1825
                ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L1);
1826
        List<Position> rbmPositions = positionRepository.selectPositionbyCategoryIdAndEscalationType(
1827
                ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L1);
1828
 
1829
        // Batch fetch all partner regions for all fofoIds
1830
        List<Integer> fofoIdList = new ArrayList<>(fofoIds);
1831
        fofoIdList.add(0); // Include global entries
1832
        List<PartnerRegion> allPartnerRegions = partnerRegionRepository.selectByfofoIds(fofoIdList);
1833
 
1834
        // Build fofoId -> regionIds map
1835
        Map<Integer, Set<Integer>> fofoRegionMap = new HashMap<>();
1836
        for (Integer fofoId : fofoIds) {
1837
            fofoRegionMap.put(fofoId, new HashSet<>());
1838
            fofoRegionMap.get(fofoId).add(ALL_PARTNERS_REGION); // Add all partners region
1839
        }
1840
        for (PartnerRegion pr : allPartnerRegions) {
1841
            int fofoId = pr.getFofoId();
1842
            if (fofoId == 0) {
1843
                // Global entry applies to all fofoIds
1844
                for (Integer fid : fofoIds) {
1845
                    fofoRegionMap.get(fid).add(pr.getRegionId());
1846
                }
1847
            } else if (fofoIds.contains(fofoId)) {
1848
                fofoRegionMap.get(fofoId).add(pr.getRegionId());
1849
            }
1850
        }
1851
 
1852
        // Collect all unique region IDs and position IDs for batch query
1853
        Set<Integer> allRegionIds = fofoRegionMap.values().stream()
1854
                .flatMap(Set::stream).collect(Collectors.toSet());
1855
        Set<Integer> allPositionIds = new HashSet<>();
1856
        bmPositions.forEach(p -> allPositionIds.add(p.getId()));
1857
        asmPositions.forEach(p -> allPositionIds.add(p.getId()));
1858
        rbmPositions.forEach(p -> allPositionIds.add(p.getId()));
1859
 
1860
        // Batch fetch all partner positions
1861
        List<PartnerPosition> allPartnerPositions = partnerPositionRepository.selectByRegionIdAndPostionId(
1862
                new ArrayList<>(allRegionIds), new ArrayList<>(allPositionIds));
1863
 
1864
        // Build positionId -> set of (regionId, partnerId) for matching
1865
        Map<Integer, List<PartnerPosition>> positionIdToPartnerPositions = allPartnerPositions.stream()
1866
                .collect(Collectors.groupingBy(PartnerPosition::getPositionId));
1867
 
1868
        // Collect all auth user IDs we need
1869
        Set<Integer> allAuthUserIds = new HashSet<>();
1870
        bmPositions.forEach(p -> allAuthUserIds.add(p.getAuthUserId()));
1871
        asmPositions.forEach(p -> allAuthUserIds.add(p.getAuthUserId()));
1872
        rbmPositions.forEach(p -> allAuthUserIds.add(p.getAuthUserId()));
1873
 
1874
        // Batch fetch all auth users
1875
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(new ArrayList<>(allAuthUserIds))
1876
                .stream().filter(AuthUser::isActive)
1877
                .collect(Collectors.toMap(AuthUser::getId, au -> au, (a, b) -> a));
1878
 
1879
        // Build position ID sets for fast lookup
1880
        Set<Integer> bmPositionIds = bmPositions.stream().map(Position::getId).collect(Collectors.toSet());
1881
        Set<Integer> asmPositionIds = asmPositions.stream().map(Position::getId).collect(Collectors.toSet());
1882
        Set<Integer> rbmPositionIds = rbmPositions.stream().map(Position::getId).collect(Collectors.toSet());
1883
 
1884
        // Map position ID to auth user ID
1885
        Map<Integer, Integer> positionToAuthUser = new HashMap<>();
1886
        bmPositions.forEach(p -> positionToAuthUser.put(p.getId(), p.getAuthUserId()));
1887
        asmPositions.forEach(p -> positionToAuthUser.put(p.getId(), p.getAuthUserId()));
1888
        rbmPositions.forEach(p -> positionToAuthUser.put(p.getId(), p.getAuthUserId()));
1889
 
1890
        // For each fofoId, find matching positions
1891
        for (Integer fofoId : fofoIds) {
1892
            Set<Integer> regionIds = fofoRegionMap.get(fofoId);
1893
 
1894
            // Find position IDs that match this fofoId's regions (partnerId = 0 or fofoId)
1895
            Set<Integer> matchingPositionIds = new HashSet<>();
1896
            for (PartnerPosition pp : allPartnerPositions) {
1897
                if (regionIds.contains(pp.getRegionId()) &&
1898
                    (pp.getFofoId() == 0 || pp.getFofoId() == fofoId)) {
1899
                    matchingPositionIds.add(pp.getPositionId());
1900
                }
1901
            }
1902
 
1903
            // Find first active auth user for each role
1904
            Map<String, Integer> roleMap = result.get(fofoId);
1905
 
1906
            for (Integer positionId : matchingPositionIds) {
1907
                Integer authUserId = positionToAuthUser.get(positionId);
1908
                if (authUserId != null && authUserMap.containsKey(authUserId)) {
1909
                    if (bmPositionIds.contains(positionId) && roleMap.get("BM") == 0) {
1910
                        roleMap.put("BM", authUserId);
1911
                    } else if (asmPositionIds.contains(positionId) && roleMap.get("ASM") == 0) {
1912
                        roleMap.put("ASM", authUserId);
1913
                    } else if (rbmPositionIds.contains(positionId) && roleMap.get("RBM") == 0) {
1914
                        roleMap.put("RBM", authUserId);
1915
                    }
1916
                }
1917
            }
1918
        }
1919
 
1920
        return result;
1921
    }
1922
 
35626 amit 1923
    @Override
36972 ranu 1924
    public Map<Integer, Integer> getAuthUserIdsWithoutTicketAssigneeByFofoIds(int categoryId, EscalationType escalationType, Set<Integer> fofoIds) throws ProfitMandiBusinessException {
1925
        Map<Integer, Integer> result = new HashMap<>();
1926
        if (fofoIds == null || fofoIds.isEmpty()) {
1927
            return result;
1928
        }
1929
        for (Integer fofoId : fofoIds) {
1930
            result.put(fofoId, 0);
1931
        }
1932
 
1933
        List<Position> positions = positionRepository.selectPositionbyCategoryIdAndEscalationType(categoryId, escalationType);
1934
        if (positions.isEmpty()) {
1935
            return result;
1936
        }
1937
        Set<Integer> positionIds = positions.stream().map(Position::getId).collect(Collectors.toSet());
1938
        Map<Integer, Integer> positionToAuthUser = new HashMap<>();
1939
        positions.forEach(p -> positionToAuthUser.put(p.getId(), p.getAuthUserId()));
1940
 
1941
        List<Integer> fofoIdList = new ArrayList<>(fofoIds);
1942
        fofoIdList.add(0);
1943
        List<PartnerRegion> allPartnerRegions = partnerRegionRepository.selectByfofoIds(fofoIdList);
1944
 
1945
        Map<Integer, Set<Integer>> fofoRegionMap = new HashMap<>();
1946
        for (Integer fofoId : fofoIds) {
1947
            Set<Integer> regions = new HashSet<>();
1948
            regions.add(ALL_PARTNERS_REGION);
1949
            fofoRegionMap.put(fofoId, regions);
1950
        }
1951
        for (PartnerRegion pr : allPartnerRegions) {
1952
            int fofoId = pr.getFofoId();
1953
            if (fofoId == 0) {
1954
                for (Integer fid : fofoIds) {
1955
                    fofoRegionMap.get(fid).add(pr.getRegionId());
1956
                }
1957
            } else if (fofoIds.contains(fofoId)) {
1958
                fofoRegionMap.get(fofoId).add(pr.getRegionId());
1959
            }
1960
        }
1961
 
1962
        Set<Integer> allRegionIds = fofoRegionMap.values().stream()
1963
                .flatMap(Set::stream).collect(Collectors.toSet());
1964
        List<PartnerPosition> allPartnerPositions = partnerPositionRepository.selectByRegionIdAndPostionId(
1965
                new ArrayList<>(allRegionIds), new ArrayList<>(positionIds));
1966
 
1967
        Set<Integer> allAuthUserIds = positions.stream().map(Position::getAuthUserId).collect(Collectors.toSet());
1968
        Set<Integer> activeAuthUserIds = authRepository.selectByIds(new ArrayList<>(allAuthUserIds))
1969
                .stream().filter(AuthUser::isActive).map(AuthUser::getId).collect(Collectors.toSet());
1970
 
1971
        for (Integer fofoId : fofoIds) {
1972
            Set<Integer> regionIds = fofoRegionMap.get(fofoId);
1973
            for (PartnerPosition pp : allPartnerPositions) {
1974
                if (!regionIds.contains(pp.getRegionId())) continue;
1975
                if (pp.getFofoId() != 0 && pp.getFofoId() != fofoId) continue;
1976
                Integer authUserId = positionToAuthUser.get(pp.getPositionId());
1977
                if (authUserId != null && activeAuthUserIds.contains(authUserId)) {
1978
                    result.put(fofoId, authUserId);
1979
                    break;
1980
                }
1981
            }
1982
        }
1983
        return result;
1984
    }
1985
 
1986
    @Override
35635 ranu 1987
    public Map<Integer, Boolean> getUnreadStatusForTickets(List<Ticket> tickets, int userId, TicketReadStatus.UserType userType) {
35626 amit 1988
        Map<Integer, Boolean> unreadMap = new HashMap<>();
1989
        if (tickets == null || tickets.isEmpty()) {
1990
            return unreadMap;
1991
        }
1992
 
1993
        List<Integer> ticketIds = tickets.stream().map(Ticket::getId).collect(Collectors.toList());
1994
        List<TicketReadStatus> readStatuses = ticketReadStatusRepository.selectByTicketIdsAndUser(ticketIds, userId, userType);
1995
        Map<Integer, Integer> ticketLastReadMap = readStatuses.stream()
1996
                .collect(Collectors.toMap(TicketReadStatus::getTicketId, TicketReadStatus::getLastReadActivityId));
1997
 
1998
        // Get last activities for all tickets to check who created them
1999
        Map<Integer, Activity> lastActivityMap = getLastActivitiesForTickets(ticketIds);
2000
 
2001
        for (Ticket ticket : tickets) {
2002
            int lastActivityId = ticket.getLastActivityId();
2003
            int lastReadActivityId = ticketLastReadMap.getOrDefault(ticket.getId(), 0);
2004
 
2005
            if (lastActivityId <= lastReadActivityId) {
2006
                unreadMap.put(ticket.getId(), false);
2007
                continue;
2008
            }
2009
 
2010
            // Check if the current user created the last activity (exclude own updates)
2011
            Activity lastActivity = lastActivityMap.get(ticket.getId());
2012
            if (lastActivity != null) {
35635 ranu 2013
                if (userType == TicketReadStatus.UserType.AUTH_USER && lastActivity.getCreatedBy() == userId) {
35626 amit 2014
                    unreadMap.put(ticket.getId(), false);
2015
                    continue;
2016
                }
35635 ranu 2017
                if (userType == TicketReadStatus.UserType.PARTNER && lastActivity.getCreatedBy() == 0
35626 amit 2018
                        && lastActivity.getType() == ActivityType.COMMUNICATION_IN) {
2019
                    unreadMap.put(ticket.getId(), false);
2020
                    continue;
2021
                }
2022
                // For partners: only show as unread if activity type is external communication or resolved
35635 ranu 2023
                if (userType == TicketReadStatus.UserType.PARTNER) {
35626 amit 2024
                    boolean isRelevantForPartner = ActivityType.PARTNER_ACTIVITIES.contains(lastActivity.getType());
2025
                    unreadMap.put(ticket.getId(), isRelevantForPartner);
2026
                    continue;
2027
                }
2028
            }
2029
 
2030
            unreadMap.put(ticket.getId(), true);
2031
        }
2032
        return unreadMap;
2033
    }
2034
 
2035
    @Override
35635 ranu 2036
    public void markTicketAsRead(int ticketId, int userId, TicketReadStatus.UserType userType) {
35626 amit 2037
        Ticket ticket = ticketRepository.selectById(ticketId);
2038
        if (ticket == null) {
2039
            return;
2040
        }
2041
        TicketReadStatus readStatus = new TicketReadStatus();
2042
        readStatus.setTicketId(ticketId);
2043
        readStatus.setUserId(userId);
2044
        readStatus.setUserType(userType);
2045
        readStatus.setLastReadActivityId(ticket.getLastActivityId());
2046
        ticketReadStatusRepository.upsert(readStatus);
2047
    }
2048
 
2049
    @Override
2050
    public Map<Integer, Activity> getLastActivitiesForTickets(List<Integer> ticketIds) {
2051
        Map<Integer, Activity> lastActivityMap = new HashMap<>();
2052
        if (ticketIds == null || ticketIds.isEmpty()) {
2053
            return lastActivityMap;
2054
        }
2055
        List<Activity> allActivities = activityRepository.selectAll(ticketIds);
2056
        // Group by ticketId and get the last one (highest id)
2057
        Map<Integer, List<Activity>> groupedByTicket = allActivities.stream()
2058
                .collect(Collectors.groupingBy(Activity::getTicketId));
2059
        for (Map.Entry<Integer, List<Activity>> entry : groupedByTicket.entrySet()) {
2060
            Activity lastActivity = entry.getValue().stream()
2061
                    .max(Comparator.comparingInt(Activity::getId))
2062
                    .orElse(null);
2063
            if (lastActivity != null) {
2064
                lastActivityMap.put(entry.getKey(), lastActivity);
2065
            }
2066
        }
2067
        return lastActivityMap;
2068
    }
2069
 
2070
    @Override
35639 amit 2071
    public Map<Integer, Activity> getLastMessageActivitiesForTickets(List<Integer> ticketIds) {
2072
        Map<Integer, Activity> lastMessageMap = new HashMap<>();
2073
        if (ticketIds == null || ticketIds.isEmpty()) {
2074
            return lastMessageMap;
2075
        }
2076
        Set<ActivityType> messageTypes = EnumSet.of(
2077
                ActivityType.COMMUNICATION_IN, ActivityType.COMMUNICATION_OUT,
2078
                ActivityType.COMMUNICATION_INTERNAL, ActivityType.OPENED);
2079
        List<Activity> allActivities = activityRepository.selectAll(ticketIds);
2080
        Map<Integer, List<Activity>> groupedByTicket = allActivities.stream()
2081
                .filter(a -> messageTypes.contains(a.getType()))
2082
                .collect(Collectors.groupingBy(Activity::getTicketId));
2083
        for (Map.Entry<Integer, List<Activity>> entry : groupedByTicket.entrySet()) {
2084
            Activity lastMessage = entry.getValue().stream()
2085
                    .max(Comparator.comparingInt(Activity::getId))
2086
                    .orElse(null);
2087
            if (lastMessage != null) {
2088
                lastMessageMap.put(entry.getKey(), lastMessage);
2089
            }
2090
        }
2091
        return lastMessageMap;
2092
    }
2093
 
2094
    @Override
35626 amit 2095
    public void notifyPartnerOfExternalCommunication(Ticket ticket, Activity activity) {
2096
        try {
2097
            CustomRetailer partner = retailerService.getFofoRetailer(ticket.getFofoId());
2098
            if (partner == null || partner.getEmail() == null) {
2099
                return;
2100
            }
2101
 
2102
            TicketSubCategory ticketSubCategory = ticketSubCategoryRepository.selectById(ticket.getSubCategoryId());
2103
            TicketCategory ticketCategory = ticketCategoryRepository.selectById(ticketSubCategory.getCategoryId());
2104
 
2105
            Map<String, Object> model = new HashMap<>();
2106
            model.put("ticketId", ticket.getId());
2107
            model.put("partnerName", partner.getBusinessName());
2108
            model.put("categoryName", ticketCategory.getName());
2109
            model.put("subCategoryName", ticketSubCategory.getName());
2110
            model.put("activityMessage", activity.getMessage());
2111
 
2112
            emailService.sendMailWithAttachments(
2113
                    "Update on Your Support Ticket #" + ticket.getId(),
2114
                    "partner-ticket-update.vm",
2115
                    model,
2116
                    new String[]{partner.getEmail()},
2117
                    null,
2118
                    null);
2119
        } catch (Exception e) {
2120
            LOGGER.error("Failed to send partner notification email for ticket {}", ticket.getId(), e);
2121
        }
2122
    }
2123
 
24383 amit.gupta 2124
}