Subversion Repositories SmartDukaan

Rev

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