Subversion Repositories SmartDukaan

Rev

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