Subversion Repositories SmartDukaan

Rev

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