Subversion Repositories SmartDukaan

Rev

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

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