Subversion Repositories SmartDukaan

Rev

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

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