Subversion Repositories SmartDukaan

Rev

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