Subversion Repositories SmartDukaan

Rev

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

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