Subversion Repositories SmartDukaan

Rev

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