Subversion Repositories SmartDukaan

Rev

Rev 35443 | Rev 35562 | 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()
531
                .map(Ticket::getL1AuthUser)
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
 
31762 tejbeer 545
    @Override
546
    public Map<Integer, TicketSubCategory> getSubCategoryIdAndSubCategoryMap(List<Integer> subCategoryIds) {
547
        Map<Integer, TicketSubCategory> subCategoryIdAndSubCategoryMap = new HashMap<>();
548
        subCategoryIdAndSubCategoryMap = ticketSubCategoryRepository.selectByIds(subCategoryIds).stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
549
        return subCategoryIdAndSubCategoryMap;
550
    }
31152 tejbeer 551
 
31762 tejbeer 552
    @Override
33244 ranu 553
    public Map<Integer, CustomRetailer> getPartnerByFofoIds(List<Ticket> tickets) throws ProfitMandiBusinessException {
31762 tejbeer 554
        List<Integer> fofoIds = new ArrayList<>();
555
        LOGGER.info(tickets);
556
        if (tickets == null) {
557
            return null;
558
        }
559
        for (Ticket ticket : tickets) {
560
            fofoIds.add(ticket.getFofoId());
561
        }
25721 tejbeer 562
 
31762 tejbeer 563
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
25721 tejbeer 564
 
31762 tejbeer 565
        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));
566
        return fofoIdsAndCustomRetailer;
567
    }
25799 tejbeer 568
 
31762 tejbeer 569
    @Override
570
    public List<TicketCategory> getAllTicketCategotyFromSubCategory() {
25721 tejbeer 571
 
31830 amit.gupta 572
        Collection<TicketSubCategory> ticketSubCategories = ticketSubCategoryRepository.getTicketSubCategoryMap().values();
573
        return new ArrayList<>(ticketSubCategories.stream().map(x -> x.getTicketCategory()).collect(Collectors.toSet()));
31762 tejbeer 574
    }
25799 tejbeer 575
 
31762 tejbeer 576
    @Override
577
    public Map<Integer, AuthUser> getAuthUserIdAndAuthUserMapUsingPositions(List<Position> positions) {
35454 amit 578
        if (positions == null || positions.isEmpty()) {
579
            return new HashMap<>();
31762 tejbeer 580
        }
35454 amit 581
        // OPTIMIZED: Batch fetch all AuthUsers instead of N+1 queries
582
        List<Integer> authUserIds = positions.stream()
583
                .map(Position::getAuthUserId)
584
                .filter(id -> id != null && id > 0)
585
                .distinct()
586
                .collect(Collectors.toList());
587
        return authRepository.selectByIds(authUserIds).stream()
588
                .collect(Collectors.toMap(AuthUser::getId, au -> au, (a, b) -> a));
31762 tejbeer 589
    }
25721 tejbeer 590
 
31762 tejbeer 591
    @Override
592
    public Map<Integer, TicketCategory> getCategoryIdAndCategoryUsingPositions(List<Position> positions) {
35454 amit 593
        if (positions == null || positions.isEmpty()) {
594
            return new HashMap<>();
31762 tejbeer 595
        }
35454 amit 596
        // OPTIMIZED: Batch fetch all categories instead of N+1 queries
597
        List<Integer> categoryIds = positions.stream()
598
                .map(Position::getCategoryId)
599
                .filter(id -> id != null && id > 0)
600
                .distinct()
601
                .collect(Collectors.toList());
602
        return ticketCategoryRepository.selectAll(categoryIds).stream()
603
                .collect(Collectors.toMap(TicketCategory::getId, tc -> tc, (a, b) -> a));
31762 tejbeer 604
    }
29318 tejbeer 605
 
31762 tejbeer 606
    @Override
607
    public Map<Integer, Region> getRegionIdAndRegionMap(List<Position> positions) {
35454 amit 608
        if (positions == null || positions.isEmpty()) {
609
            return new HashMap<>();
31762 tejbeer 610
        }
35454 amit 611
        // OPTIMIZED: Batch fetch all regions instead of N+1 queries
612
        Set<Integer> regionIds = positions.stream()
613
                .map(Position::getRegionId)
614
                .filter(id -> id != null && id > 0)
615
                .collect(Collectors.toSet());
616
        return regionRepository.selectAll().stream()
617
                .filter(r -> regionIds.contains(r.getId()))
618
                .collect(Collectors.toMap(Region::getId, r -> r, (a, b) -> a));
31762 tejbeer 619
    }
29318 tejbeer 620
 
31762 tejbeer 621
    private void sendAssignedTicketMail(AuthUser authUserTo, List<AuthUser> authUsersCc, Ticket ticket, boolean isEscalated, List<Activity> activities) throws ProfitMandiBusinessException {
622
        try {
623
            String[] ccTo = authUsersCc.stream().filter(x -> x != null).map(x -> x.getEmailId()).toArray(String[]::new);
25721 tejbeer 624
 
31762 tejbeer 625
            String messageFormat = null;
626
            if (isEscalated) {
627
                messageFormat = ESCALATED_TICKET;
628
            } else {
629
                messageFormat = ASSIGNED_TICKET;
630
            }
631
            String message = String.format(messageFormat, authUserTo.getName(), ticket.getId(), activities.get(0).getMessage(), retailerService.getFofoRetailer(ticket.getFofoId()).getBusinessName());
632
            Utils.sendMailWithAttachments(mailSender, authUserTo.getEmailId(), ccTo, ASSINMENT_SUBJECT, message, null);
633
        } catch (Exception e) {
634
            e.printStackTrace();
635
            throw new ProfitMandiBusinessException("Ticket Assingment", authUserTo.getEmailId(), "Could not send ticket assignment mail");
636
        }
637
    }
26298 tejbeer 638
 
31762 tejbeer 639
    @Override
33244 ranu 640
    public Map<Integer, List<CustomRetailer>> getPositionCustomRetailerMap(List<Position> positions) throws ProfitMandiBusinessException {
31762 tejbeer 641
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
642
        Map<Integer, List<CustomRetailer>> positionRetailerMap = new HashMap<>();
35443 amit 643
 
644
        // Batch fetch all PartnerPositions upfront to avoid N+1 queries
645
        List<Integer> positionIds = positions.stream().map(Position::getId).collect(Collectors.toList());
646
        Map<Integer, List<Integer>> positionIdToFofoIdsMap = partnerPositionRepository.selectByPositionIds(positionIds)
647
                .stream()
648
                .collect(Collectors.groupingBy(
649
                        pp -> pp.getPositionId(),
650
                        Collectors.mapping(pp -> pp.getFofoId(), Collectors.toList())
651
                ));
652
 
653
        // Collect all region IDs that might need lookup (positions with fofoId=0)
654
        Set<Integer> regionIdsNeedingLookup = new HashSet<>();
31762 tejbeer 655
        for (Position position : positions) {
35443 amit 656
            List<Integer> fofoIds = positionIdToFofoIdsMap.get(position.getId());
657
            if (fofoIds != null && fofoIds.contains(0)) {
658
                regionIdsNeedingLookup.add(position.getRegionId());
659
            }
660
        }
26978 tejbeer 661
 
35443 amit 662
        // Batch fetch all PartnerRegions for regions needing lookup
663
        Map<Integer, List<Integer>> regionIdToFofoIdsMap = new HashMap<>();
664
        if (!regionIdsNeedingLookup.isEmpty()) {
665
            regionIdToFofoIdsMap = partnerRegionRepository.selectAllByRegionIds(new ArrayList<>(regionIdsNeedingLookup))
666
                    .stream()
667
                    .collect(Collectors.groupingBy(
668
                            pr -> pr.getRegionId(),
669
                            Collectors.mapping(pr -> pr.getFofoId(), Collectors.toList())
670
                    ));
671
        }
26978 tejbeer 672
 
35443 amit 673
        // Build the result map using pre-fetched data
674
        for (Position position : positions) {
675
            List<Integer> fofoIds = positionIdToFofoIdsMap.get(position.getId());
676
            if (fofoIds == null || fofoIds.isEmpty()) {
677
                continue;
678
            }
679
 
680
            if (fofoIds.contains(0)) {
681
                // Need region-based lookup
682
                fofoIds = regionIdToFofoIdsMap.get(position.getRegionId());
683
                if (fofoIds == null || fofoIds.contains(0)) {
684
                    fofoIds = new ArrayList<>(customRetailerMap.keySet());
31762 tejbeer 685
                }
35443 amit 686
            }
26978 tejbeer 687
 
35443 amit 688
            positionRetailerMap.put(position.getId(),
689
                    fofoIds.stream()
690
                            .map(customRetailerMap::get)
691
                            .filter(x -> x != null)
692
                            .collect(Collectors.toList()));
31762 tejbeer 693
        }
694
        return positionRetailerMap;
695
    }
26978 tejbeer 696
 
31762 tejbeer 697
    @Override
33244 ranu 698
    public Map<Integer, List<CustomRetailer>> getRegionPartners(List<Position> positions) throws ProfitMandiBusinessException {
31762 tejbeer 699
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
700
        Map<Integer, List<CustomRetailer>> positionIdAndpartnerRegionMap = new HashedMap<>();
26978 tejbeer 701
 
35443 amit 702
        // Batch fetch all PartnerRegions upfront to avoid N+1 queries
703
        List<Integer> regionIds = positions.stream().map(Position::getRegionId).distinct().collect(Collectors.toList());
704
        Map<Integer, List<Integer>> regionIdToFofoIdsMap = partnerRegionRepository.selectAllByRegionIds(regionIds)
705
                .stream()
706
                .collect(Collectors.groupingBy(
707
                        pr -> pr.getRegionId(),
708
                        Collectors.mapping(pr -> pr.getFofoId(), Collectors.toList())
709
                ));
26978 tejbeer 710
 
35443 amit 711
        // Fetch all store IDs once in case any region has fofoId=0
712
        List<Integer> allStoreIds = null;
26978 tejbeer 713
 
35443 amit 714
        for (Position position : positions) {
715
            List<Integer> fofoIds = regionIdToFofoIdsMap.get(position.getRegionId());
716
            if (fofoIds == null || fofoIds.isEmpty()) {
717
                continue;
31762 tejbeer 718
            }
26978 tejbeer 719
 
35443 amit 720
            if (fofoIds.contains(0)) {
721
                if (allStoreIds == null) {
722
                    allStoreIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId()).collect(Collectors.toList());
723
                }
724
                fofoIds = allStoreIds;
725
            }
726
 
727
            Map<Integer, CustomRetailer> fofoRetailers = fofoIds.stream()
728
                    .map(customRetailerMap::get)
729
                    .filter(x -> x != null)
730
                    .collect(Collectors.toMap(x -> x.getPartnerId(), x -> x, (a, b) -> a));
731
            positionIdAndpartnerRegionMap.put(position.getRegionId(), new ArrayList<>(fofoRetailers.values()));
31762 tejbeer 732
        }
26978 tejbeer 733
 
31762 tejbeer 734
        return positionIdAndpartnerRegionMap;
735
    }
26978 tejbeer 736
 
31762 tejbeer 737
    @Override
738
    @Cacheable(value = "authUserEmailMapping", cacheManager = "thirtyMinsTimeOutCacheManager")
33244 ranu 739
    public Map<String, Set<String>> getAuthUserPartnerEmailMapping() throws ProfitMandiBusinessException {
31762 tejbeer 740
        Map<String, Set<String>> storeGuyMap = new HashMap<>();
741
        Set<Integer> activeFofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId()).collect(Collectors.toSet());
35443 amit 742
 
743
        // Batch fetch positions by category IDs instead of multiple calls
744
        List<Position> categoryPositions = positionRepository.selectPositionByCategoryIds(Arrays.asList(
745
                ProfitMandiConstants.TICKET_CATEGORY_SALES,
746
                ProfitMandiConstants.TICKET_CATEGORY_RBM,
747
                ProfitMandiConstants.TICKET_CATEGORY_ABM));
31762 tejbeer 748
        Map<Integer, Position> positionsMap = categoryPositions.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
29229 tejbeer 749
 
35443 amit 750
        // Batch fetch all AuthUsers upfront to avoid N+1 queries
751
        Set<Integer> authUserIds = categoryPositions.stream().map(Position::getAuthUserId).collect(Collectors.toSet());
752
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(new ArrayList<>(authUserIds)).stream()
753
                .collect(Collectors.toMap(AuthUser::getId, x -> x));
754
 
31762 tejbeer 755
        Map<Integer, List<CustomRetailer>> positonPartnerMap = this.getPositionCustomRetailerMap(categoryPositions);
756
        for (Map.Entry<Integer, List<CustomRetailer>> positionPartnerEntry : positonPartnerMap.entrySet()) {
757
            int authUserId = positionsMap.get(positionPartnerEntry.getKey()).getAuthUserId();
758
            Set<String> partnerEmails = positionPartnerEntry.getValue().stream().filter(x -> activeFofoIds.contains(x.getPartnerId())).map(x -> x.getEmail()).collect(Collectors.toSet());
35443 amit 759
            AuthUser authUser = authUserMap.get(authUserId);
760
            if (authUser != null && authUser.isActive()) {
31762 tejbeer 761
                if (!storeGuyMap.containsKey(authUser.getEmailId())) {
762
                    storeGuyMap.put(authUser.getEmailId(), partnerEmails);
763
                } else {
764
                    storeGuyMap.get(authUser.getEmailId()).addAll(partnerEmails);
765
                }
766
            }
767
        }
768
        return storeGuyMap;
769
    }
29229 tejbeer 770
 
31762 tejbeer 771
    @Override
772
    @Cacheable(value = "authUserEmailPartnerIdMapping", cacheManager = "thirtyMinsTimeOutCacheManager")
33244 ranu 773
    public Map<String, Set<Integer>> getAuthUserPartnerIdMapping() throws ProfitMandiBusinessException {
31762 tejbeer 774
        Map<String, Set<Integer>> storeGuyMap = new HashMap<>();
775
        Set<Integer> activeFofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId()).collect(Collectors.toSet());
35443 amit 776
 
777
        // Batch fetch positions by category IDs instead of multiple calls
778
        List<Position> categoryPositions = positionRepository.selectPositionByCategoryIds(Arrays.asList(
779
                ProfitMandiConstants.TICKET_CATEGORY_SALES,
780
                ProfitMandiConstants.TICKET_CATEGORY_RBM,
781
                ProfitMandiConstants.TICKET_CATEGORY_ABM,
782
                ProfitMandiConstants.TICKET_CATEGORY_BUSINESSINTELLIGENT,
783
                ProfitMandiConstants.TICKET_CATEGORY_TRAINING));
31762 tejbeer 784
        Map<Integer, Position> positionsMap = categoryPositions.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
31161 tejbeer 785
 
35443 amit 786
        // Batch fetch all AuthUsers upfront to avoid N+1 queries
787
        Set<Integer> authUserIds = categoryPositions.stream().map(Position::getAuthUserId).collect(Collectors.toSet());
788
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(new ArrayList<>(authUserIds)).stream()
789
                .collect(Collectors.toMap(AuthUser::getId, x -> x));
790
 
31762 tejbeer 791
        Map<Integer, List<CustomRetailer>> positonPartnerMap = this.getPositionCustomRetailerMap(categoryPositions);
792
        for (Map.Entry<Integer, List<CustomRetailer>> positionPartnerEntry : positonPartnerMap.entrySet()) {
793
            int authUserId = positionsMap.get(positionPartnerEntry.getKey()).getAuthUserId();
794
            Set<Integer> partnerIds = positionPartnerEntry.getValue().stream().filter(x -> activeFofoIds.contains(x.getPartnerId())).map(x -> x.getPartnerId()).collect(Collectors.toSet());
35443 amit 795
            AuthUser authUser = authUserMap.get(authUserId);
796
            if (authUser != null && authUser.isActive()) {
31762 tejbeer 797
                if (!storeGuyMap.containsKey(authUser.getEmailId())) {
798
                    storeGuyMap.put(authUser.getEmailId(), partnerIds);
799
                } else {
800
                    storeGuyMap.get(authUser.getEmailId()).addAll(partnerIds);
801
                }
802
            }
803
        }
804
        return storeGuyMap;
805
    }
31472 tejbeer 806
 
31762 tejbeer 807
    @Override
808
    @Cacheable(value = "authUserPartnerEmailPartnerIdMapping", cacheManager = "thirtyMinsTimeOutCacheManager")
33244 ranu 809
    public Map<String, Set<Integer>> getAuthUserPartnerIdMappingByCategoryIds(List<Integer> categoryIds, boolean activeOnly) throws ProfitMandiBusinessException {
31762 tejbeer 810
        Map<String, Set<Integer>> authUserPartnerMap = new HashMap<>();
811
        Set<Integer> activeFofoIds;
812
        if (activeOnly) {
813
            activeFofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId()).collect(Collectors.toSet());
26298 tejbeer 814
 
31762 tejbeer 815
        } else {
816
            activeFofoIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId()).collect(Collectors.toSet());
26298 tejbeer 817
 
31762 tejbeer 818
        }
26298 tejbeer 819
 
31762 tejbeer 820
        List<Position> categoryPositions = positionRepository.selectPositionByCategoryIds(categoryIds);
821
        Map<Integer, Position> positionsMap = categoryPositions.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
26298 tejbeer 822
 
35454 amit 823
        // OPTIMIZED: Batch fetch all AuthUsers instead of N+1 queries
824
        List<Integer> authUserIds = categoryPositions.stream()
825
                .map(Position::getAuthUserId)
826
                .filter(id -> id != null && id > 0)
827
                .distinct()
828
                .collect(Collectors.toList());
829
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(authUserIds).stream()
830
                .collect(Collectors.toMap(AuthUser::getId, au -> au, (a, b) -> a));
831
 
31762 tejbeer 832
        Map<Integer, List<CustomRetailer>> positonPartnerMap = this.getPositionCustomRetailerMap(categoryPositions);
833
        for (Map.Entry<Integer, List<CustomRetailer>> positionPartnerEntry : positonPartnerMap.entrySet()) {
834
            int authUserId = positionsMap.get(positionPartnerEntry.getKey()).getAuthUserId();
835
            Set<Integer> partnerIds = positionPartnerEntry.getValue().stream().filter(x -> activeFofoIds.contains(x.getPartnerId())).map(x -> x.getPartnerId()).collect(Collectors.toSet());
35454 amit 836
            AuthUser authUser = authUserMap.get(authUserId);
837
            if (authUser != null && authUser.isActive()) {
31762 tejbeer 838
                if (!authUserPartnerMap.containsKey(authUser.getEmailId())) {
839
                    authUserPartnerMap.put(authUser.getEmailId(), partnerIds);
840
                } else {
841
                    authUserPartnerMap.get(authUser.getEmailId()).addAll(partnerIds);
842
                }
843
            }
844
        }
845
        return authUserPartnerMap;
846
    }
26298 tejbeer 847
 
31762 tejbeer 848
    @Override
34082 ranu 849
    public Map<Integer, List<Integer>> authUserpartnerIdMap(int authId, int categoryId) {
850
        Session session = sessionFactory.getCurrentSession();
851
 
34084 ranu 852
        Map<Integer, List<Integer>> authUserpartnerIdMap = new HashMap<>();
34082 ranu 853
 
34158 tejus.loha 854
        List<Position> authPositions = positionRepository.selectPositionbyCategoryIdAndAuthId(categoryId, authId);
34082 ranu 855
 
35454 amit 856
        // OPTIMIZED: Batch fetch all PartnerPositions instead of N+1 queries
857
        List<Integer> positionIds = authPositions.stream()
858
                .map(Position::getId)
34084 ranu 859
                .collect(Collectors.toList());
35454 amit 860
        List<PartnerPosition> partnerPositions = partnerPositionRepository.selectByPositionIds(positionIds);
34082 ranu 861
 
34084 ranu 862
        if (partnerPositions.stream().anyMatch(partnerPosition -> partnerPosition.getFofoId() == 0)) {
863
            List<FofoStore> activeFofoStores = fofoStoreRepository.selectActiveStores();
864
 
865
            List<Integer> fofoStoreIds = activeFofoStores.stream()
866
                    .map(FofoStore::getId) // Extract the IDs of FofoStores
867
                    .collect(Collectors.toList());
868
 
869
            authUserpartnerIdMap.put(authId, fofoStoreIds);
870
 
34158 tejus.loha 871
        } else {
34084 ranu 872
            final TypedQuery<AuthUserPartnerMapModel> typedQuerySimilar = session
873
                    .createNamedQuery("Position.Auth_User_Partner_Maping", AuthUserPartnerMapModel.class);
874
 
875
            typedQuerySimilar.setParameter("authId", authId);
876
            typedQuerySimilar.setParameter("categoryId", categoryId);
877
 
878
            List<AuthUserPartnerMapModel> authUserPartnerMapModels = typedQuerySimilar.getResultList();
879
 
880
            authUserpartnerIdMap = authUserPartnerMapModels.stream()
881
                    .collect(Collectors.groupingBy(
882
                            AuthUserPartnerMapModel::getAuthId,
883
                            Collectors.mapping(AuthUserPartnerMapModel::getFofoId, Collectors.toList())
884
                    ));
885
 
886
        }
887
 
34082 ranu 888
        LOGGER.info("partnerusermap {}", authUserpartnerIdMap);
889
        return authUserpartnerIdMap;
890
    }
891
 
892
    @Override
33244 ranu 893
    public List<String> getAuthUserByPartnerId(int fofoId) throws ProfitMandiBusinessException {
26298 tejbeer 894
 
31762 tejbeer 895
        List<String> emails = new ArrayList<>();
896
        List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId()).collect(Collectors.toList());
26298 tejbeer 897
 
31762 tejbeer 898
        regionIds.add(5);// All partners Id;
26298 tejbeer 899
 
32493 amit.gupta 900
        List<Integer> partnerPositionIds = partnerPositionRepository.selectByRegionIdAndPartnerId(regionIds, Arrays.asList(fofoId, 0)).stream().map(x -> x.getPositionId()).collect(Collectors.toList());
26448 amit.gupta 901
 
31762 tejbeer 902
        LOGGER.info("partnerPositionIds" + partnerPositionIds);
27205 amit.gupta 903
 
35394 amit 904
        List<Position> positions = positionRepository.selectByIds(partnerPositionIds);
27548 tejbeer 905
 
34905 ranu 906
        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 907
 
31762 tejbeer 908
        if (!positions.isEmpty()) {
35454 amit 909
            // OPTIMIZED: Batch fetch all AuthUsers instead of N+1 queries
910
            List<Integer> authUserIds = positions.stream()
911
                    .map(Position::getAuthUserId)
912
                    .filter(id -> id != null && id > 0)
913
                    .distinct()
914
                    .collect(Collectors.toList());
915
            Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(authUserIds).stream()
916
                    .collect(Collectors.toMap(AuthUser::getId, au -> au, (a, b) -> a));
917
 
31762 tejbeer 918
            for (Position partnerPostionId : positions) {
35454 amit 919
                AuthUser authUser = authUserMap.get(partnerPostionId.getAuthUserId());
31762 tejbeer 920
                LOGGER.info("authUser" + authUser);
35454 amit 921
                if (authUser != null) {
922
                    emails.add(authUser.getEmailId());
923
                }
31762 tejbeer 924
            }
925
        }
27548 tejbeer 926
 
31762 tejbeer 927
        return emails;
928
    }
27548 tejbeer 929
 
31762 tejbeer 930
    @Override
33244 ranu 931
    public Map<EscalationType, String> getAuthUserAndEsclationTypeByPartnerId(int fofoId) throws ProfitMandiBusinessException {
27548 tejbeer 932
 
31762 tejbeer 933
        List<String> emails = new ArrayList<>();
934
        Map<EscalationType, String> emailEsclationTypeMap = new HashMap<>();
935
        List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId()).collect(Collectors.toList());
27548 tejbeer 936
 
31762 tejbeer 937
        regionIds.add(5);// All partners Id;
938
        List<Integer> fofoIds = new ArrayList<>();
939
        fofoIds.add(fofoId);
940
        fofoIds.add(0);
27548 tejbeer 941
 
33074 amit.gupta 942
        //LOGGER.info("fofoIds" + fofoIds);
32493 amit.gupta 943
        List<Integer> partnerPositionIds = partnerPositionRepository.selectByRegionIdAndPartnerId(regionIds, fofoIds).stream().map(x -> x.getPositionId()).collect(Collectors.toList());
27548 tejbeer 944
 
33074 amit.gupta 945
        //LOGGER.info("partnerPositionIds" + partnerPositionIds);
28377 tejbeer 946
 
35454 amit 947
        // OPTIMIZED: Batch fetch all positions instead of N+1 queries
948
        List<Position> positions = positionRepository.selectByIds(partnerPositionIds).stream()
949
                .filter(p -> p.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES)
950
                .collect(Collectors.toList());
28377 tejbeer 951
 
35454 amit 952
        if (!positions.isEmpty()) {
953
            // OPTIMIZED: Batch fetch all AuthUsers instead of N+1 queries
954
            List<Integer> authUserIds = positions.stream()
955
                    .map(Position::getAuthUserId)
956
                    .filter(id -> id != null && id > 0)
957
                    .distinct()
958
                    .collect(Collectors.toList());
959
            Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(authUserIds).stream()
960
                    .collect(Collectors.toMap(AuthUser::getId, au -> au, (a, b) -> a));
961
 
962
            for (Position position : positions) {
963
                AuthUser authUser = authUserMap.get(position.getAuthUserId());
33074 amit.gupta 964
                //LOGGER.info("authUser" + authUser);
35454 amit 965
                if (authUser != null) {
966
                    emailEsclationTypeMap.put(position.getEscalationType(), authUser.getEmailId());
967
                }
31762 tejbeer 968
            }
969
        }
28377 tejbeer 970
 
33074 amit.gupta 971
        //LOGGER.info("emailEsclationTypeMap" + emailEsclationTypeMap);
28377 tejbeer 972
 
31762 tejbeer 973
        return emailEsclationTypeMap;
974
    }
31020 tejbeer 975
 
31762 tejbeer 976
    @Override
977
    @Cacheable(value = "authUserIdPartnerIdMapping", cacheManager = "thirtyMinsTimeOutCacheManager")
33244 ranu 978
    public Map<Integer, List<Integer>> getAuthUserIdPartnerIdMapping() throws ProfitMandiBusinessException {
31762 tejbeer 979
        Map<Integer, List<Integer>> storeGuyMap = new HashMap<>();
980
        Set<Integer> activeFofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId()).collect(Collectors.toSet());
31020 tejbeer 981
 
34077 tejus.loha 982
        List<Position> categoryPositions = positionRepository.selectAllPosition();
31020 tejbeer 983
 
31762 tejbeer 984
        Map<Integer, Position> positionsMap = categoryPositions.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
29229 tejbeer 985
 
35454 amit 986
        // OPTIMIZED: Batch fetch all AuthUsers instead of N+1 queries
987
        List<Integer> authUserIds = categoryPositions.stream()
988
                .map(Position::getAuthUserId)
989
                .filter(id -> id != null && id > 0)
990
                .distinct()
991
                .collect(Collectors.toList());
992
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(authUserIds).stream()
993
                .collect(Collectors.toMap(AuthUser::getId, au -> au, (a, b) -> a));
994
 
31762 tejbeer 995
        Map<Integer, List<CustomRetailer>> positonPartnerMap = this.getPositionCustomRetailerMap(categoryPositions);
996
        for (Map.Entry<Integer, List<CustomRetailer>> positionPartnerEntry : positonPartnerMap.entrySet()) {
997
            int authUserId = positionsMap.get(positionPartnerEntry.getKey()).getAuthUserId();
998
            List<Integer> partnerIds = positionPartnerEntry.getValue().stream().filter(x -> activeFofoIds.contains(x.getPartnerId())).map(x -> x.getPartnerId()).collect(Collectors.toList());
35454 amit 999
            AuthUser authUser = authUserMap.get(authUserId);
31762 tejbeer 1000
            if (authUser != null && authUser.isActive()) {
1001
                if (!storeGuyMap.containsKey(authUserId)) {
1002
                    storeGuyMap.put(authUserId, partnerIds);
1003
                } else {
1004
                    storeGuyMap.get(authUserId).addAll(partnerIds);
1005
                }
1006
            }
1007
        }
1008
        storeGuyMap.keySet().stream().forEach(x -> {
1009
            List<Integer> fofoIds = storeGuyMap.get(x);
1010
            storeGuyMap.put(x, fofoIds.stream().distinct().collect(Collectors.toList()));
1011
        });
1012
        return storeGuyMap;
1013
    }
28908 tejbeer 1014
 
31762 tejbeer 1015
    @Override
1016
    @Cacheable(value = "L1L2Mapping", cacheManager = "thirtyMinsTimeOutCacheManager")
33244 ranu 1017
    public Map<Integer, List<Integer>> getL2L1Mapping() throws ProfitMandiBusinessException {
31762 tejbeer 1018
        List<Position> l1SalesPositions = positionRepository.selectPositionbyCategoryIdAndEscalationType(
1019
                ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L1);
1020
        List<Position> l2SalesPositions = positionRepository.selectPositionbyCategoryIdAndEscalationType(
1021
                ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L2);
28908 tejbeer 1022
 
33074 amit.gupta 1023
        //LOGGER.info("position" + l1SalesPositions);
31762 tejbeer 1024
        Map<Integer, List<Integer>> authUserPartnerListMap = this.getAuthUserIdPartnerIdMapping();
33074 amit.gupta 1025
        //LOGGER.info("map" + authUserPartnerListMap);
28908 tejbeer 1026
 
31762 tejbeer 1027
        Map<Integer, List<Integer>> l2l1ListMap = new HashMap<>();
29318 tejbeer 1028
 
31762 tejbeer 1029
        for (Position l2SalePosition : l2SalesPositions) {
1030
            int l2AuthUserId = l2SalePosition.getAuthUserId();
1031
            if (authUserPartnerListMap.containsKey(l2SalePosition.getAuthUserId())) {
1032
                List<Integer> mappedL1AuthUsers = new ArrayList<>();
1033
                l2l1ListMap.put(l2AuthUserId, mappedL1AuthUsers);
1034
                List<Integer> l2FofoIds = authUserPartnerListMap.get(l2AuthUserId);
1035
                for (Position l1SalePosition : l1SalesPositions) {
1036
                    int l1AuthUserId = l1SalePosition.getAuthUserId();
1037
                    if (authUserPartnerListMap.containsKey(l1AuthUserId)) {
1038
                        List<Integer> l1FofoIds = authUserPartnerListMap.get(l1SalePosition.getAuthUserId());
1039
                        if (l2FofoIds.containsAll(l1FofoIds)) {
1040
                            mappedL1AuthUsers.add(l1AuthUserId);
1041
                        }
1042
                    }
28856 manish 1043
 
31762 tejbeer 1044
                }
1045
            }
29296 manish 1046
 
31762 tejbeer 1047
        }
29296 manish 1048
 
31762 tejbeer 1049
        return l2l1ListMap;
1050
    }
29296 manish 1051
 
31762 tejbeer 1052
    @Override
1053
    public Map<Integer, List<AuthUser>> getAssignedAuthList(List<Ticket> tickets) {
1054
        if (tickets.size() == 0) {
1055
            return new HashMap<>();
1056
        }
1057
        List<TicketAssigned> ticketAssignedList = ticketAssignedRepository.selectByTicketIds(tickets.stream().map(x -> x.getId()).collect(Collectors.toList()));
1058
        List<Integer> authUserIds = ticketAssignedList.stream().map(x -> x.getAssineeId()).distinct().collect(Collectors.toList());
35394 amit 1059
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(authUserIds).stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
31762 tejbeer 1060
        return ticketAssignedList.stream().collect(Collectors.groupingBy(x -> x.getTicketId(), Collectors.mapping(x -> authUserMap.get(x.getAssineeId()), Collectors.toList())));
1061
    }
28908 tejbeer 1062
 
31762 tejbeer 1063
    @Override
33244 ranu 1064
    public Map<EscalationType, AuthUser> getAuthUserAndEsclationByPartnerId(int fofoId) throws ProfitMandiBusinessException {
31762 tejbeer 1065
        Map<EscalationType, AuthUser> authuserEsclationTypeMap = new HashMap<>();
1066
        List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId()).collect(Collectors.toList());
28908 tejbeer 1067
 
31762 tejbeer 1068
        regionIds.add(5);// All partners Id;
1069
        List<Integer> fofoIds = new ArrayList<>();
1070
        fofoIds.add(fofoId);
1071
        fofoIds.add(0);
28908 tejbeer 1072
 
32877 amit.gupta 1073
        //LOGGER.info("fofoIds" + fofoIds);
32493 amit.gupta 1074
        List<Integer> partnerPositionIds = partnerPositionRepository.selectByRegionIdAndPartnerId(regionIds, fofoIds).stream().map(x -> x.getPositionId()).collect(Collectors.toList());
28908 tejbeer 1075
 
32877 amit.gupta 1076
        //LOGGER.info("partnerPositionIds" + partnerPositionIds);
30003 tejbeer 1077
 
31762 tejbeer 1078
        for (Integer partnerPostionId : partnerPositionIds) {
1079
            Position position = positionRepository.selectByIdAndCategoryId(partnerPostionId, ProfitMandiConstants.TICKET_CATEGORY_SALES);
32877 amit.gupta 1080
            //LOGGER.info("position" + position);
31762 tejbeer 1081
            if (position != null) {
30003 tejbeer 1082
 
31762 tejbeer 1083
                AuthUser authUser = authRepository.selectById(position.getAuthUserId());
32877 amit.gupta 1084
                //LOGGER.info("authUser" + authUser);
30003 tejbeer 1085
 
31762 tejbeer 1086
                authuserEsclationTypeMap.put(position.getEscalationType(), authUser);
1087
            }
1088
        }
30003 tejbeer 1089
 
32877 amit.gupta 1090
        //LOGGER.info("emailEsclationTypeMap" + authuserEsclationTypeMap);
30003 tejbeer 1091
 
31762 tejbeer 1092
        return authuserEsclationTypeMap;
1093
    }
30044 tejbeer 1094
 
31762 tejbeer 1095
    @Override
35394 amit 1096
    public Map<Integer, Map<EscalationType, AuthUser>> getAuthUserAndEsclationByPartnerIds(Set<Integer> fofoIds) throws ProfitMandiBusinessException {
1097
        Map<Integer, Map<EscalationType, AuthUser>> result = new HashMap<>();
1098
 
1099
        if (fofoIds == null || fofoIds.isEmpty()) {
1100
            return result;
1101
        }
1102
 
1103
        // Initialize result map
1104
        for (Integer fofoId : fofoIds) {
1105
            result.put(fofoId, new HashMap<>());
1106
        }
1107
 
1108
        // Batch fetch all partner regions
1109
        List<Integer> fofoIdListWithZero = new ArrayList<>(fofoIds);
1110
        fofoIdListWithZero.add(0);
1111
        List<PartnerRegion> allPartnerRegions = partnerRegionRepository.selectByfofoIds(fofoIdListWithZero);
1112
 
1113
        // Build fofoId -> regionIds map
1114
        Map<Integer, Set<Integer>> fofoRegionMap = new HashMap<>();
1115
        for (Integer fofoId : fofoIds) {
1116
            fofoRegionMap.put(fofoId, new HashSet<>());
1117
            fofoRegionMap.get(fofoId).add(ALL_PARTNERS_REGION);
1118
        }
1119
        for (PartnerRegion pr : allPartnerRegions) {
1120
            int prFofoId = pr.getFofoId();
1121
            if (prFofoId == 0) {
1122
                for (Integer fid : fofoIds) {
1123
                    fofoRegionMap.get(fid).add(pr.getRegionId());
1124
                }
1125
            } else if (fofoIds.contains(prFofoId)) {
1126
                fofoRegionMap.get(prFofoId).add(pr.getRegionId());
1127
            }
1128
        }
1129
 
1130
        // Collect all region IDs
1131
        Set<Integer> allRegionIds = fofoRegionMap.values().stream()
1132
                .flatMap(Set::stream).collect(Collectors.toSet());
1133
 
1134
        // Batch fetch all partner positions
1135
        List<PartnerPosition> allPartnerPositions = partnerPositionRepository.selectByRegionIdAndPartnerId(
1136
                new ArrayList<>(allRegionIds), fofoIdListWithZero);
1137
 
1138
        // Collect all position IDs
1139
        Set<Integer> allPositionIds = allPartnerPositions.stream()
1140
                .map(PartnerPosition::getPositionId).collect(Collectors.toSet());
1141
 
1142
        // Batch fetch all positions for SALES category
1143
        List<Position> salesPositions = positionRepository.selectPositionbyCategoryIdAndEscalationType(
1144
                ProfitMandiConstants.TICKET_CATEGORY_SALES, null);
1145
        Map<Integer, Position> positionMap = salesPositions.stream()
1146
                .filter(p -> allPositionIds.contains(p.getId()))
1147
                .collect(Collectors.toMap(Position::getId, p -> p, (a, b) -> a));
1148
 
1149
        // Collect all auth user IDs and batch fetch
1150
        Set<Integer> authUserIds = positionMap.values().stream()
1151
                .map(Position::getAuthUserId).collect(Collectors.toSet());
1152
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(new ArrayList<>(authUserIds))
1153
                .stream().collect(Collectors.toMap(AuthUser::getId, au -> au, (a, b) -> a));
1154
 
1155
        // For each fofoId, find matching positions and build result
1156
        for (Integer fofoId : fofoIds) {
1157
            Set<Integer> regionIds = fofoRegionMap.get(fofoId);
1158
            Map<EscalationType, AuthUser> escalationMap = result.get(fofoId);
1159
 
1160
            for (PartnerPosition pp : allPartnerPositions) {
1161
                if (regionIds.contains(pp.getRegionId()) &&
1162
                    (pp.getFofoId() == 0 || pp.getFofoId() == fofoId)) {
1163
                    Position position = positionMap.get(pp.getPositionId());
1164
                    if (position != null) {
1165
                        AuthUser authUser = authUserMap.get(position.getAuthUserId());
1166
                        if (authUser != null) {
1167
                            escalationMap.put(position.getEscalationType(), authUser);
1168
                        }
1169
                    }
1170
                }
1171
            }
1172
        }
1173
 
1174
        return result;
1175
    }
1176
 
1177
    @Override
33244 ranu 1178
    public List<AuthUser> getAuthUserIdByPartnerId(int fofoId) throws ProfitMandiBusinessException {
33041 ranu 1179
        return this.getAuthUserIdByPartnerId(fofoId, EscalationType.escalations.toArray(new EscalationType[0]));
1180
    }
1181
 
1182
    @Override
33244 ranu 1183
    public List<AuthUser> getAuthUserIdByPartnerId(int fofoId, EscalationType... escalationTypes) throws ProfitMandiBusinessException {
31762 tejbeer 1184
        List<AuthUser> authUsers = new ArrayList<>();
1185
        List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId()).collect(Collectors.toList());
30044 tejbeer 1186
 
31762 tejbeer 1187
        regionIds.add(5);// All partners Id;
1188
        List<Integer> fofoIds = new ArrayList<>();
1189
        fofoIds.add(fofoId);
1190
        fofoIds.add(0);
30044 tejbeer 1191
 
33074 amit.gupta 1192
        //LOGGER.info("fofoIds" + fofoIds);
32493 amit.gupta 1193
        List<Integer> partnerPositionIds = partnerPositionRepository.selectByRegionIdAndPartnerId(regionIds, fofoIds).stream().map(x -> x.getPositionId()).collect(Collectors.toList());
30003 tejbeer 1194
 
33074 amit.gupta 1195
        //LOGGER.info("partnerPositionIds" + partnerPositionIds);
34905 ranu 1196
        List<Integer> allowedTicketCategoryIds = Arrays.asList(ProfitMandiConstants.TICKET_CATEGORY_SALES, ProfitMandiConstants.TICKET_CATEGORY_RBM,ProfitMandiConstants.TICKET_CATEGORY_ABM);
30003 tejbeer 1197
 
30044 tejbeer 1198
 
35394 amit 1199
        List<Position> escalationBasedPositions = positionRepository.selectByIds(partnerPositionIds).stream().filter(x -> allowedTicketCategoryIds.contains(x.getCategoryId()) &&
33041 ranu 1200
                Arrays.stream(escalationTypes)
1201
                        .anyMatch(y -> y.equals(x.getEscalationType()))).collect(Collectors.toList());
30003 tejbeer 1202
 
33041 ranu 1203
        List<Integer> authUserIds = escalationBasedPositions.stream().map(x -> x.getAuthUserId()).collect(Collectors.toList());
30003 tejbeer 1204
 
35394 amit 1205
        return authRepository.selectByIds(authUserIds);
30003 tejbeer 1206
 
31762 tejbeer 1207
    }
30044 tejbeer 1208
 
31762 tejbeer 1209
    @Override
1210
    public List<AuthUser> getAuthUserIds(int categoryId, List<EscalationType> escalationType) {
30044 tejbeer 1211
 
31762 tejbeer 1212
        List<Position> positions = positionRepository.selectPositionbyCategoryIdAndEscalationTypes(categoryId, escalationType);
1213
        List<Integer> authIds = positions.stream().map(x -> x.getAuthUserId()).distinct().collect(Collectors.toList());
30003 tejbeer 1214
 
33074 amit.gupta 1215
        //LOGGER.info("authIds" + authIds);
35058 amit 1216
        List<AuthUser> authUsers = null;
1217
        if (authIds.size() > 0) {
35394 amit 1218
            authUsers = authRepository.selectByIds(authIds);
35058 amit 1219
        } else {
1220
            authUsers = new ArrayList<>();
1221
        }
30003 tejbeer 1222
 
31762 tejbeer 1223
        LOGGER.info("authUsers" + authUsers);
1224
        return authUsers;
1225
    }
1226
 
1227
    @Override
1228
    public List<AuthUser> getAuthUserByCategoryId(int categoryId, EscalationType escalationType) {
1229
 
1230
        List<Position> positions = positionRepository.selectPositionbyCategoryIdAndEscalationType(categoryId, escalationType);
1231
        List<Integer> authIds = positions.stream().map(x -> x.getAuthUserId()).distinct().collect(Collectors.toList());
1232
 
1233
        LOGGER.info("authIds" + authIds);
1234
        List<AuthUser> authUsers = new ArrayList<>();
1235
        if (!authIds.isEmpty()) {
35394 amit 1236
            authUsers = authRepository.selectByIds(authIds);
31762 tejbeer 1237
        }
1238
 
1239
        LOGGER.info("authUsers" + authUsers);
1240
        return authUsers;
1241
    }
1242
 
1243
    @Override
1244
    @Cacheable(value = "authUserByCategoryId", cacheManager = "thirtyMinsTimeOutCacheManager")
1245
    public List<AuthUser> getAuthUserByCategoryId(int categoryId) {
1246
        List<Position> positions = positionRepository.selectPositionByCategoryId(categoryId);
1247
        List<Integer> authIds = positions.stream().map(x -> x.getAuthUserId()).distinct().collect(Collectors.toList());
1248
 
1249
        LOGGER.info("authIds" + authIds);
1250
 
35394 amit 1251
        List<AuthUser> authUsers = authRepository.selectByIds(authIds).stream().filter(x -> x.getActive()).collect(Collectors.toList());
31762 tejbeer 1252
 
1253
        LOGGER.info("authUsers" + authUsers);
1254
        return authUsers;
1255
    }
1256
 
34380 amit.gupta 1257
    private class SaleRoles1 {
31762 tejbeer 1258
 
1259
        private List<String> l1;
1260
        private List<String> l2;
1261
        private List<String> l3;
1262
        private List<String> l4;
1263
 
34380 amit.gupta 1264
        public SaleRoles1() {
31762 tejbeer 1265
            l1 = new ArrayList<>();
1266
            l2 = new ArrayList<>();
1267
            l3 = new ArrayList<>();
1268
            l4 = new ArrayList<>();
1269
        }
1270
 
1271
        public List<String> getL1() {
1272
            return l1;
1273
        }
1274
 
1275
        public List<String> getL2() {
1276
            return l2;
1277
        }
1278
 
1279
        public List<String> getL3() {
1280
            return l3;
1281
        }
1282
 
1283
        public List<String> getL4() {
1284
            return l4;
1285
        }
1286
 
1287
        @Override
1288
        public String toString() {
1289
            return "SaleRoles [l1=" + l1 + ", l2=" + l2 + ", l3=" + l3 + ", l4=" + l4 + "]";
1290
        }
1291
 
1292
    }
1293
 
33161 ranu 1294
 
31762 tejbeer 1295
    @Override
1296
    @Cacheable(value = "partnerSaleHeader", cacheManager = "oneDayCacheManager")
33244 ranu 1297
    public Map<Integer, FofoReportingModel> getPartnerIdSalesHeaders() throws ProfitMandiBusinessException {
34380 amit.gupta 1298
        Map<String, SaleRoles1> partnerEmailSalesMap = new HashMap<>();
31762 tejbeer 1299
 
1300
        List<Position> positions = positionRepository.selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_SALES);
1301
        Map<Integer, AuthUser> authUsersMap = authRepository.selectAllActiveUser().stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
1302
        Map<Integer, List<CustomRetailer>> positionIdRetailerMap = this.getPositionCustomRetailerMap(positions);
1303
        for (Position position : positions) {
1304
            List<CustomRetailer> crList = positionIdRetailerMap.get(position.getId());
1305
            if (crList == null)
1306
                continue;
1307
            for (CustomRetailer cr : crList) {
1308
                if (!partnerEmailSalesMap.containsKey(cr.getEmail())) {
34380 amit.gupta 1309
                    partnerEmailSalesMap.put(cr.getEmail(), new SaleRoles1());
31762 tejbeer 1310
                }
34380 amit.gupta 1311
                SaleRoles1 saleRoles1 = partnerEmailSalesMap.get(cr.getEmail());
31762 tejbeer 1312
                AuthUser authUser = authUsersMap.get(position.getAuthUserId());
1313
                if (authUser == null) {
1314
                    continue;
1315
                }
1316
                String name = authUser.getFirstName() + " " + authUser.getLastName();
1317
                if (position.getEscalationType().equals(EscalationType.L1)) {
34380 amit.gupta 1318
                    saleRoles1.getL1().add(name);
31762 tejbeer 1319
                } else if (position.getEscalationType().equals(EscalationType.L2)) {
34380 amit.gupta 1320
                    saleRoles1.getL2().add(name);
31762 tejbeer 1321
                }
1322
 
1323
            }
1324
        }
1325
 
1326
        Set<CustomRetailer> allCrList = new HashSet<>();
1327
        for (List<CustomRetailer> cr : positionIdRetailerMap.values()) {
1328
            allCrList.addAll(cr);
1329
        }
1330
 
1331
        Map<Integer, FofoStore> fofoStoresMap = fofoStoreRepository.selectActiveStores().stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
1332
 
1333
        Map<Integer, FofoReportingModel> partnerIdSalesHeadersMap = new HashMap<>();
1334
 
33378 ranu 1335
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
1336
        for (Map.Entry<Integer, CustomRetailer> customRetailerEntry : customRetailerMap.entrySet()) {
1337
 
1338
            CustomRetailer customRetailer = customRetailerEntry.getValue();
1339
 
1340
            String code = customRetailer.getCode();
31762 tejbeer 1341
            // String storeName = "SmartDukaan-" +
1342
            // fofoStore.getCode().replaceAll("[a-zA-Z]", "");
33378 ranu 1343
            String businessName = customRetailer.getBusinessName();
31762 tejbeer 1344
            try {
34158 tejus.loha 1345
                String stateManager = StringUtils.join(new HashSet(partnerEmailSalesMap.get(customRetailer.getEmail()).getL2()), ", ");
1346
                String territoryManager = StringUtils.join(new HashSet(partnerEmailSalesMap.get(customRetailer.getEmail()).getL1()), ", ");
31762 tejbeer 1347
 
1348
                FofoReportingModel reportingModel = new FofoReportingModel();
1349
                reportingModel.setBusinessName(businessName);
1350
                reportingModel.setCode(code);
33378 ranu 1351
                reportingModel.setFofoId(customRetailer.getPartnerId());
31762 tejbeer 1352
                reportingModel.setRegionalManager(stateManager);
1353
                reportingModel.setTerritoryManager(territoryManager);
33378 ranu 1354
                partnerIdSalesHeadersMap.put(customRetailer.getPartnerId(), reportingModel);
31762 tejbeer 1355
            } catch (Exception e) {
33378 ranu 1356
                LOGGER.warn("Could not find partner with email - {}", customRetailer.getEmail());
31762 tejbeer 1357
            }
1358
        }
1359
        return partnerIdSalesHeadersMap;
1360
 
1361
    }
1362
 
33161 ranu 1363
 
34905 ranu 1364
    private class ABMRoles {
1365
 
1366
        private List<String> l1;
1367
        private List<String> l2;
1368
        private List<String> l3;
1369
        private List<String> l4;
1370
 
1371
        public ABMRoles() {
1372
            l1 = new ArrayList<>();
1373
            l2 = new ArrayList<>();
1374
            l3 = new ArrayList<>();
1375
            l4 = new ArrayList<>();
1376
        }
1377
 
1378
        public List<String> getL1() {
1379
            return l1;
1380
        }
1381
 
1382
        public List<String> getL2() {
1383
            return l2;
1384
        }
1385
 
1386
        public List<String> getL3() {
1387
            return l3;
1388
        }
1389
 
1390
        public List<String> getL4() {
1391
            return l4;
1392
        }
1393
 
1394
        @Override
1395
        public String toString() {
1396
            return "SaleRoles [l1=" + l1 + ", l2=" + l2 + ", l3=" + l3 + ", l4=" + l4 + "]";
1397
        }
1398
 
1399
    }
1400
 
1401
 
1402
    @Override
1403
    @Cacheable(value = "partnerABMHeader", cacheManager = "oneDayCacheManager")
1404
    public Map<Integer, FofoAbmReportingModel> getPartnerIdABMHeaders() throws ProfitMandiBusinessException {
1405
        Map<String, ABMRoles> partnerEmailABMMap = new HashMap<>();
1406
 
1407
        List<Position> positions = positionRepository.selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_ABM);
1408
        Map<Integer, AuthUser> authUsersMap = authRepository.selectAllActiveUser().stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
1409
        Map<Integer, List<CustomRetailer>> positionIdRetailerMap = this.getPositionCustomRetailerMap(positions);
1410
        for (Position position : positions) {
1411
            List<CustomRetailer> crList = positionIdRetailerMap.get(position.getId());
1412
            if (crList == null)
1413
                continue;
1414
            for (CustomRetailer cr : crList) {
1415
                if (!partnerEmailABMMap.containsKey(cr.getEmail())) {
1416
                    partnerEmailABMMap.put(cr.getEmail(), new ABMRoles());
1417
                }
1418
                ABMRoles abmRoles = partnerEmailABMMap.get(cr.getEmail());
1419
                AuthUser authUser = authUsersMap.get(position.getAuthUserId());
1420
                if (authUser == null) {
1421
                    continue;
1422
                }
1423
                String name = authUser.getFirstName() + " " + authUser.getLastName();
1424
                if (position.getEscalationType().equals(EscalationType.L1)) {
1425
                    abmRoles.getL1().add(name);
1426
                } else if (position.getEscalationType().equals(EscalationType.L2)) {
1427
                    abmRoles.getL2().add(name);
1428
                }
1429
 
1430
            }
1431
        }
1432
 
1433
        Set<CustomRetailer> allCrList = new HashSet<>();
1434
        for (List<CustomRetailer> cr : positionIdRetailerMap.values()) {
1435
            allCrList.addAll(cr);
1436
        }
1437
 
1438
        Map<Integer, FofoStore> fofoStoresMap = fofoStoreRepository.selectActiveStores().stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
1439
 
1440
        Map<Integer, FofoAbmReportingModel> partnerIdAbmHeadersMap = new HashMap<>();
1441
 
1442
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
1443
        for (Map.Entry<Integer, CustomRetailer> customRetailerEntry : customRetailerMap.entrySet()) {
1444
 
1445
            CustomRetailer customRetailer = customRetailerEntry.getValue();
1446
 
1447
            String code = customRetailer.getCode();
1448
            // String storeName = "SmartDukaan-" +
1449
            // fofoStore.getCode().replaceAll("[a-zA-Z]", "");
1450
            String businessName = customRetailer.getBusinessName();
1451
            try {
1452
                String l2Manager = StringUtils.join(new HashSet(partnerEmailABMMap.get(customRetailer.getEmail()).getL2()), ", ");
1453
                String l1Manager = StringUtils.join(new HashSet(partnerEmailABMMap.get(customRetailer.getEmail()).getL1()), ", ");
1454
 
1455
                if (StringUtils.isEmpty(l1Manager)) {
1456
                    l2Manager = StringUtils.join(new HashSet(partnerEmailABMMap.get(customRetailer.getEmail()).getL2()), ", ");
1457
                }
1458
 
1459
                FofoAbmReportingModel reportingModel = new FofoAbmReportingModel();
1460
                reportingModel.setBusinessName(businessName);
1461
                reportingModel.setCode(code);
1462
                reportingModel.setFofoId(customRetailer.getPartnerId());
1463
                reportingModel.setL1Manager(l2Manager);
1464
                reportingModel.setL2Manager(l1Manager);
1465
                partnerIdAbmHeadersMap.put(customRetailer.getPartnerId(), reportingModel);
1466
            } catch (Exception e) {
1467
                LOGGER.warn("Could not find partner with email - {}", customRetailer.getEmail());
1468
            }
1469
        }
1470
        return partnerIdAbmHeadersMap;
1471
 
1472
    }
1473
 
1474
 
33161 ranu 1475
    private class RBMRoles {
1476
 
1477
        private List<String> l1;
1478
        private List<String> l2;
1479
        private List<String> l3;
1480
        private List<String> l4;
1481
 
1482
        public RBMRoles() {
1483
            l1 = new ArrayList<>();
1484
            l2 = new ArrayList<>();
1485
            l3 = new ArrayList<>();
1486
            l4 = new ArrayList<>();
1487
        }
1488
 
1489
        public List<String> getL1() {
1490
            return l1;
1491
        }
1492
 
1493
        public List<String> getL2() {
1494
            return l2;
1495
        }
1496
 
1497
        public List<String> getL3() {
1498
            return l3;
1499
        }
1500
 
1501
        public List<String> getL4() {
1502
            return l4;
1503
        }
1504
 
1505
        @Override
1506
        public String toString() {
1507
            return "RBMRoles [l1=" + l1 + ", l2=" + l2 + ", l3=" + l3 + ", l4=" + l4 + "]";
1508
        }
1509
 
1510
    }
1511
 
31762 tejbeer 1512
    @Override
33161 ranu 1513
    @Cacheable(value = "partnerRBMHeader", cacheManager = "oneDayCacheManager")
33244 ranu 1514
    public Map<Integer, FofoRBMReportingModel> getPartnerIdRBMHeaders() throws ProfitMandiBusinessException {
33161 ranu 1515
        Map<String, RBMRoles> partnerEmailRbmMap = new HashMap<>();
1516
 
1517
        List<Position> positions = positionRepository.selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_RBM);
1518
        Map<Integer, AuthUser> authUsersMap = authRepository.selectAllActiveUser().stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
1519
        Map<Integer, List<CustomRetailer>> positionIdRetailerMap = this.getPositionCustomRetailerMap(positions);
1520
        for (Position position : positions) {
1521
            List<CustomRetailer> crList = positionIdRetailerMap.get(position.getId());
1522
            if (crList == null)
1523
                continue;
1524
            for (CustomRetailer cr : crList) {
1525
                if (!partnerEmailRbmMap.containsKey(cr.getEmail())) {
1526
                    partnerEmailRbmMap.put(cr.getEmail(), new RBMRoles());
1527
                }
1528
                RBMRoles rbmRole = partnerEmailRbmMap.get(cr.getEmail());
1529
                AuthUser authUser = authUsersMap.get(position.getAuthUserId());
1530
                if (authUser == null) {
1531
                    continue;
1532
                }
1533
                String name = authUser.getFirstName() + " " + authUser.getLastName();
1534
                if (position.getEscalationType().equals(EscalationType.L1)) {
1535
                    rbmRole.getL1().add(name);
1536
                } else if (position.getEscalationType().equals(EscalationType.L2)) {
1537
                    rbmRole.getL2().add(name);
1538
                }
1539
 
1540
            }
1541
        }
1542
 
1543
        Set<CustomRetailer> allCrList = new HashSet<>();
1544
        for (List<CustomRetailer> cr : positionIdRetailerMap.values()) {
1545
            allCrList.addAll(cr);
1546
        }
1547
 
1548
 
1549
        Map<Integer, FofoRBMReportingModel> partnerIdRbmHeadersMap = new HashMap<>();
1550
 
33377 amit.gupta 1551
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
1552
        for (Map.Entry<Integer, CustomRetailer> customRetailerEntry : customRetailerMap.entrySet()) {
1553
 
1554
            CustomRetailer customRetailer = customRetailerEntry.getValue();
1555
 
1556
            String code = customRetailer.getCode();
33161 ranu 1557
            // String storeName = "SmartDukaan-" +
1558
            // fofoStore.getCode().replaceAll("[a-zA-Z]", "");
33377 amit.gupta 1559
            String businessName = customRetailer.getBusinessName();
33161 ranu 1560
            try {
33377 amit.gupta 1561
                String L2User = StringUtils.join(partnerEmailRbmMap.get(customRetailer.getEmail()).getL2(), ", ");
1562
                String L1USer = StringUtils.join(partnerEmailRbmMap.get(customRetailer.getEmail()).getL1(), ", ");
33161 ranu 1563
 
1564
                FofoRBMReportingModel reportingModel = new FofoRBMReportingModel();
1565
                reportingModel.setBusinessName(businessName);
1566
                reportingModel.setCode(code);
33377 amit.gupta 1567
                reportingModel.setFofoId(customRetailer.getPartnerId());
35180 amit 1568
                reportingModel.setL1Manager(L1USer);
1569
                reportingModel.setL2Manager(L2User);
33377 amit.gupta 1570
                partnerIdRbmHeadersMap.put(customRetailer.getPartnerId(), reportingModel);
33161 ranu 1571
            } catch (Exception e) {
33377 amit.gupta 1572
                LOGGER.warn("Could not find partner with email - {}", customRetailer.getEmail());
33161 ranu 1573
            }
1574
        }
1575
        return partnerIdRbmHeadersMap;
1576
 
1577
    }
1578
 
1579
    @Override
31762 tejbeer 1580
    public Map<Integer, TicketCategory> getSubCategoryIdAndCategoryMap(List<Integer> subCategoryIds) {
1581
        Map<Integer, TicketCategory> subCategoryIdAndCategoryMap = new HashMap<>();
1582
 
1583
        List<TicketSubCategory> ticketSubCategories = ticketSubCategoryRepository.selectByIds(subCategoryIds);
1584
 
1585
        for (TicketSubCategory ticketSubCategory : ticketSubCategories) {
1586
 
1587
            TicketCategory ticketCategory = ticketCategoryRepository.selectById(ticketSubCategory.getCategoryId());
1588
 
1589
            subCategoryIdAndCategoryMap.put(ticketSubCategory.getId(), ticketCategory);
1590
 
1591
        }
1592
        return subCategoryIdAndCategoryMap;
1593
    }
1594
 
35394 amit 1595
    @Override
1596
    public Map<Integer, Map<String, Integer>> getBmAsmRbmAuthUserIdsByFofoIds(Set<Integer> fofoIds) throws ProfitMandiBusinessException {
1597
        Map<Integer, Map<String, Integer>> result = new HashMap<>();
1598
 
1599
        if (fofoIds == null || fofoIds.isEmpty()) {
1600
            return result;
1601
        }
1602
 
1603
        // Initialize result map with empty values for each fofoId
1604
        for (Integer fofoId : fofoIds) {
1605
            Map<String, Integer> roleMap = new HashMap<>();
1606
            roleMap.put("BM", 0);
1607
            roleMap.put("ASM", 0);
1608
            roleMap.put("RBM", 0);
1609
            result.put(fofoId, roleMap);
1610
        }
1611
 
1612
        // Fetch positions by category + escalation type (same for all fofoIds)
1613
        List<Position> bmPositions = positionRepository.selectPositionbyCategoryIdAndEscalationType(
1614
                ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L2);
1615
        List<Position> asmPositions = positionRepository.selectPositionbyCategoryIdAndEscalationType(
1616
                ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L1);
1617
        List<Position> rbmPositions = positionRepository.selectPositionbyCategoryIdAndEscalationType(
1618
                ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L1);
1619
 
1620
        // Batch fetch all partner regions for all fofoIds
1621
        List<Integer> fofoIdList = new ArrayList<>(fofoIds);
1622
        fofoIdList.add(0); // Include global entries
1623
        List<PartnerRegion> allPartnerRegions = partnerRegionRepository.selectByfofoIds(fofoIdList);
1624
 
1625
        // Build fofoId -> regionIds map
1626
        Map<Integer, Set<Integer>> fofoRegionMap = new HashMap<>();
1627
        for (Integer fofoId : fofoIds) {
1628
            fofoRegionMap.put(fofoId, new HashSet<>());
1629
            fofoRegionMap.get(fofoId).add(ALL_PARTNERS_REGION); // Add all partners region
1630
        }
1631
        for (PartnerRegion pr : allPartnerRegions) {
1632
            int fofoId = pr.getFofoId();
1633
            if (fofoId == 0) {
1634
                // Global entry applies to all fofoIds
1635
                for (Integer fid : fofoIds) {
1636
                    fofoRegionMap.get(fid).add(pr.getRegionId());
1637
                }
1638
            } else if (fofoIds.contains(fofoId)) {
1639
                fofoRegionMap.get(fofoId).add(pr.getRegionId());
1640
            }
1641
        }
1642
 
1643
        // Collect all unique region IDs and position IDs for batch query
1644
        Set<Integer> allRegionIds = fofoRegionMap.values().stream()
1645
                .flatMap(Set::stream).collect(Collectors.toSet());
1646
        Set<Integer> allPositionIds = new HashSet<>();
1647
        bmPositions.forEach(p -> allPositionIds.add(p.getId()));
1648
        asmPositions.forEach(p -> allPositionIds.add(p.getId()));
1649
        rbmPositions.forEach(p -> allPositionIds.add(p.getId()));
1650
 
1651
        // Batch fetch all partner positions
1652
        List<PartnerPosition> allPartnerPositions = partnerPositionRepository.selectByRegionIdAndPostionId(
1653
                new ArrayList<>(allRegionIds), new ArrayList<>(allPositionIds));
1654
 
1655
        // Build positionId -> set of (regionId, partnerId) for matching
1656
        Map<Integer, List<PartnerPosition>> positionIdToPartnerPositions = allPartnerPositions.stream()
1657
                .collect(Collectors.groupingBy(PartnerPosition::getPositionId));
1658
 
1659
        // Collect all auth user IDs we need
1660
        Set<Integer> allAuthUserIds = new HashSet<>();
1661
        bmPositions.forEach(p -> allAuthUserIds.add(p.getAuthUserId()));
1662
        asmPositions.forEach(p -> allAuthUserIds.add(p.getAuthUserId()));
1663
        rbmPositions.forEach(p -> allAuthUserIds.add(p.getAuthUserId()));
1664
 
1665
        // Batch fetch all auth users
1666
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(new ArrayList<>(allAuthUserIds))
1667
                .stream().filter(AuthUser::isActive)
1668
                .collect(Collectors.toMap(AuthUser::getId, au -> au, (a, b) -> a));
1669
 
1670
        // Build position ID sets for fast lookup
1671
        Set<Integer> bmPositionIds = bmPositions.stream().map(Position::getId).collect(Collectors.toSet());
1672
        Set<Integer> asmPositionIds = asmPositions.stream().map(Position::getId).collect(Collectors.toSet());
1673
        Set<Integer> rbmPositionIds = rbmPositions.stream().map(Position::getId).collect(Collectors.toSet());
1674
 
1675
        // Map position ID to auth user ID
1676
        Map<Integer, Integer> positionToAuthUser = new HashMap<>();
1677
        bmPositions.forEach(p -> positionToAuthUser.put(p.getId(), p.getAuthUserId()));
1678
        asmPositions.forEach(p -> positionToAuthUser.put(p.getId(), p.getAuthUserId()));
1679
        rbmPositions.forEach(p -> positionToAuthUser.put(p.getId(), p.getAuthUserId()));
1680
 
1681
        // For each fofoId, find matching positions
1682
        for (Integer fofoId : fofoIds) {
1683
            Set<Integer> regionIds = fofoRegionMap.get(fofoId);
1684
 
1685
            // Find position IDs that match this fofoId's regions (partnerId = 0 or fofoId)
1686
            Set<Integer> matchingPositionIds = new HashSet<>();
1687
            for (PartnerPosition pp : allPartnerPositions) {
1688
                if (regionIds.contains(pp.getRegionId()) &&
1689
                    (pp.getFofoId() == 0 || pp.getFofoId() == fofoId)) {
1690
                    matchingPositionIds.add(pp.getPositionId());
1691
                }
1692
            }
1693
 
1694
            // Find first active auth user for each role
1695
            Map<String, Integer> roleMap = result.get(fofoId);
1696
 
1697
            for (Integer positionId : matchingPositionIds) {
1698
                Integer authUserId = positionToAuthUser.get(positionId);
1699
                if (authUserId != null && authUserMap.containsKey(authUserId)) {
1700
                    if (bmPositionIds.contains(positionId) && roleMap.get("BM") == 0) {
1701
                        roleMap.put("BM", authUserId);
1702
                    } else if (asmPositionIds.contains(positionId) && roleMap.get("ASM") == 0) {
1703
                        roleMap.put("ASM", authUserId);
1704
                    } else if (rbmPositionIds.contains(positionId) && roleMap.get("RBM") == 0) {
1705
                        roleMap.put("RBM", authUserId);
1706
                    }
1707
                }
1708
            }
1709
        }
1710
 
1711
        return result;
1712
    }
1713
 
24383 amit.gupta 1714
}