Subversion Repositories SmartDukaan

Rev

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