Subversion Repositories SmartDukaan

Rev

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

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