Subversion Repositories SmartDukaan

Rev

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