Subversion Repositories SmartDukaan

Rev

Rev 37022 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
33917 ranu 1
package com.spice.profitmandi.service;
2
 
35631 ranu 3
import com.spice.profitmandi.common.enumuration.ActivationType;
4
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
5
import com.spice.profitmandi.common.model.CustomRetailer;
33917 ranu 6
import com.spice.profitmandi.common.model.ProfitMandiConstants;
35631 ranu 7
import com.spice.profitmandi.dao.entity.auth.AuthUser;
8
import com.spice.profitmandi.dao.entity.auth.PartnerCollectionRemark;
9
import com.spice.profitmandi.dao.entity.auth.RbmCallSequenceLog;
35761 ranu 10
import com.spice.profitmandi.dao.entity.cs.AgentCallLog;
35631 ranu 11
import com.spice.profitmandi.dao.entity.cs.Position;
12
import com.spice.profitmandi.dao.entity.cs.Ticket;
13
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
34397 ranu 14
import com.spice.profitmandi.dao.entity.fofo.MonthlyTarget;
35759 ranu 15
import com.spice.profitmandi.dao.entity.fofo.RetailerContact;
33985 ranu 16
import com.spice.profitmandi.dao.entity.inventory.RbmAchievements;
33926 ranu 17
import com.spice.profitmandi.dao.entity.inventory.RbmTargets;
35759 ranu 18
import com.spice.profitmandi.dao.entity.user.Address;
35631 ranu 19
import com.spice.profitmandi.dao.enumuration.auth.CollectionRemark;
20
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
33917 ranu 21
import com.spice.profitmandi.dao.model.*;
35631 ranu 22
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
23
import com.spice.profitmandi.dao.repository.auth.PartnerCollectionRemarkRepository;
24
import com.spice.profitmandi.dao.repository.auth.RbmCallSequenceLogRepository;
33985 ranu 25
import com.spice.profitmandi.dao.repository.catalog.RbmAchievementsRepository;
33926 ranu 26
import com.spice.profitmandi.dao.repository.catalog.RbmTargetsRepository;
35631 ranu 27
import com.spice.profitmandi.dao.repository.cs.CsService;
28
import com.spice.profitmandi.dao.repository.cs.PositionRepository;
29
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
35759 ranu 30
import com.spice.profitmandi.dao.repository.dtr.RetailerContactRepository;
34397 ranu 31
import com.spice.profitmandi.dao.repository.fofo.MonthlyTargetRepository;
34880 ranu 32
import com.spice.profitmandi.dao.repository.logistics.PublicHolidaysRepository;
35631 ranu 33
import com.spice.profitmandi.dao.repository.transaction.LoanRepository;
34397 ranu 34
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
35759 ranu 35
import com.spice.profitmandi.dao.repository.user.AddressRepository;
35631 ranu 36
import com.spice.profitmandi.service.user.RetailerService;
33917 ranu 37
import org.apache.logging.log4j.LogManager;
38
import org.apache.logging.log4j.Logger;
39
import org.hibernate.Session;
40
import org.hibernate.SessionFactory;
41
import org.hibernate.query.NativeQuery;
42
import org.springframework.beans.factory.annotation.Autowired;
36334 ranu 43
import org.springframework.cache.annotation.Cacheable;
33917 ranu 44
import org.springframework.stereotype.Component;
45
 
46
import javax.persistence.TypedQuery;
34880 ranu 47
import java.time.*;
35631 ranu 48
import java.time.format.DateTimeFormatter;
34880 ranu 49
import java.time.temporal.ChronoUnit;
35631 ranu 50
import java.util.*;
33997 ranu 51
import java.util.stream.Collectors;
33917 ranu 52
 
53
@Component
54
public class RbmTargetServiceImpl implements RbmTargetService {
55
    private static final Logger LOGGER = LogManager.getLogger(RbmTargetServiceImpl.class);
56
 
57
    @Autowired
58
    SessionFactory sessionFactory;
59
 
33926 ranu 60
    @Autowired
61
    RbmTargetsRepository rbmTargetsRepository;
33917 ranu 62
 
33985 ranu 63
    @Autowired
64
    RbmAchievementsRepository rbmAchievementsRepository;
65
 
34397 ranu 66
    @Autowired
67
    MonthlyTargetRepository monthlyTargetRepository;
68
 
34880 ranu 69
    @Autowired
70
    PublicHolidaysRepository publicHolidaysRepository;
71
 
35631 ranu 72
    @Autowired
73
    RetailerService retailerService;
74
 
33917 ranu 75
    @Override
76
    public List<WarehouseRbmTargetModel> getWarehouseWiseRbmMonthlyTarget() {
77
        Session session = sessionFactory.getCurrentSession();
78
        final TypedQuery<WarehouseRbmTargetModel> typedQuerySimilar = session.createNamedQuery("RbmTarget.getWarehouseWiseMonthlyTarget", WarehouseRbmTargetModel.class);
79
 
80
        return typedQuerySimilar.getResultList();
81
 
82
    }
83
 
84
    @Override
85
    public List<MTDAchievedTargetModel> getDateWiseAchievedTargetOfRbm(LocalDate startDate, LocalDate endDate) {
86
        Session session = sessionFactory.getCurrentSession();
87
        final TypedQuery<MTDAchievedTargetModel> typedQuerySimilar = session.createNamedQuery("RbmTarget.getRbmAchievedMonthlyTarget", MTDAchievedTargetModel.class);
88
        typedQuerySimilar.setParameter("startDate", startDate);
89
        typedQuerySimilar.setParameter("endDate", endDate);
90
        return typedQuerySimilar.getResultList();
91
 
92
    }
93
 
94
    @Override
34055 ranu 95
    public List<TodayAchievedMovementModel> getMovementWiseAchievementByDate(LocalDate startDate, LocalDate endDate) {
33917 ranu 96
        LOGGER.info("start date {}, end date {}", startDate, endDate);
97
        Session session = sessionFactory.getCurrentSession();
34055 ranu 98
        final TypedQuery<TodayAchievedMovementModel> typedQuerySimilar = session.createNamedQuery("RBMTarget.TodayAchivementByMovement", TodayAchievedMovementModel.class);
33917 ranu 99
        typedQuerySimilar.setParameter("startDate", startDate);
100
        typedQuerySimilar.setParameter("endDate", endDate);
101
        return typedQuerySimilar.getResultList();
102
 
103
    }
104
 
105
    @Override
106
    public List<WarehouseMobileStockByMovementModel> getWarehouseMobileStockByMovement() {
107
        Session session = sessionFactory.getCurrentSession();
108
        final TypedQuery<WarehouseMobileStockByMovementModel> typedQuerySimilar = session.createNamedQuery("WarehouseStock.MovementWiseMobileStock", WarehouseMobileStockByMovementModel.class);
109
 
110
        return typedQuerySimilar.getResultList();
111
 
112
    }
113
 
33991 ranu 114
    @Override
115
    public List<SoldCatalogsReportModel> getCatalogSoldReport(LocalDate startDate, LocalDate endDate) {
116
        Session session = sessionFactory.getCurrentSession();
117
        final TypedQuery<SoldCatalogsReportModel> typedQuerySimilar = session.createNamedQuery("CatalogsReport.SoldCatalogsReport", SoldCatalogsReportModel.class);
118
        typedQuerySimilar.setParameter("startDate", startDate);
119
        typedQuerySimilar.setParameter("endDate", endDate);
120
        return typedQuerySimilar.getResultList();
33917 ranu 121
 
33991 ranu 122
    }
123
 
124
 
33917 ranu 125
    public int getWorkingDaysCount(LocalDate startDate) {
126
        Session session = sessionFactory.getCurrentSession();
127
 
128
        // Convert the LocalDate to a format MySQL can interpret
129
        String startDateString = startDate.toString();
130
 
131
        final NativeQuery<?> nativeQuery = session.createNativeQuery(
132
                "SELECT (DATEDIFF(LAST_DAY(:startDate), :startDate) + 1) " +
133
                        " - (FLOOR((DATEDIFF(LAST_DAY(:startDate), :startDate) + (WEEKDAY(:startDate) + 1)) / 7)) " +
134
                        " - (SELECT COUNT(*) " +
135
                        " FROM logistics.publicholidays " +
136
                        " WHERE date BETWEEN :startDate AND LAST_DAY(:startDate) " +
137
                        " AND WEEKDAY(date) != 6) AS working_days"
138
        );
139
 
140
        // Set the start date parameter for each placeholder
141
        nativeQuery.setParameter("startDate", startDateString);
142
 
143
        Object result = nativeQuery.getSingleResult();
144
        return result != null ? ((Number) result).intValue() : 0;
145
    }
146
 
147
 
35044 ranu 148
 
33917 ranu 149
    @Override
150
    public List<RbmArrViewModel> getRbmTodayArr() throws Exception {
151
        LocalDate todayDate = LocalDate.now();
152
        return getRbmTodayArr(todayDate);
153
    }
154
 
155
    @Override
33997 ranu 156
    public List<RbmTargetAndAchievementsModel> getRbmTargetsAndAchievemnts(LocalDate startDate, LocalDate endDate) {
157
 
34002 ranu 158
        List<RbmTargetsModel> rbmTargetsList = rbmTargetsRepository.selectTargetsModelListByDates(startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
33997 ranu 159
 
160
        LOGGER.info("rbmTargetsList {}", rbmTargetsList);
161
        // Group Targtes by RBM and Warehouse
34002 ranu 162
        Map<String, RbmTargetsModel> targetsMap = rbmTargetsList.stream()
33997 ranu 163
                .collect(Collectors.toMap(
164
                        a -> a.getRbmAuthId() + "-" + a.getWarehouseId(),
165
                        a -> a,
166
                        (a1, a2) -> mergeTargets(a1, a2) // Handle duplicates by merging
167
                ));
168
 
169
 
34002 ranu 170
        List<RbmAchievementsModel> rbmAchievements = rbmAchievementsRepository.selectAchievementsModelListByDates(startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
33997 ranu 171
        LOGGER.info("rbmTargetsList {}", rbmAchievements);
172
        // Group achievements by RBM and Warehouse
34002 ranu 173
        Map<String, RbmAchievementsModel> achievementMap = rbmAchievements.stream()
33997 ranu 174
                .collect(Collectors.toMap(
175
                        a -> a.getRbmAuthId() + "-" + a.getWarehouseId(),
176
                        a -> a,
177
                        (a1, a2) -> mergeAchievements(a1, a2) // Handle duplicates by merging
178
                ));
179
 
180
        return targetsMap.keySet().stream()
181
                .map(key -> {
182
                    String[] parts = key.split("-");
183
                    int rbmAuthId = Integer.parseInt(parts[0]);
184
                    int warehouseId = Integer.parseInt(parts[1]);
185
 
34002 ranu 186
                    RbmTargetsModel target = targetsMap.get(key);
187
                    RbmAchievementsModel achievement = achievementMap.getOrDefault(key, new RbmAchievementsModel());
33997 ranu 188
 
189
                    RbmTargetAndAchievementsModel model = new RbmTargetAndAchievementsModel();
190
                    model.setAuthId(rbmAuthId);
191
                    model.setRbmName(target.getRbmName());
192
                    model.setWarehouseName(ProfitMandiConstants.WAREHOUSE_MAP.getOrDefault(warehouseId, "Unknown"));
193
 
194
                    // Set target values
34006 ranu 195
                    model.setHidTarget((long) target.getHidTarget());
34098 ranu 196
                    model.setRunningTarget((long) target.getRunningTarget());
34006 ranu 197
                    model.setFastMovingTarget((long) target.getFastMovingTarget());
198
                    model.setSlowMovingTarget((long) target.getSlowMovingTarget());
199
                    model.setOtherMovingTarget((long) target.getOtherTarget());
33997 ranu 200
 
201
                    // Set achievement values
34006 ranu 202
                    model.setAchievedHid((long) achievement.getAchievedHidTarget());
34098 ranu 203
                    model.setAchievedRunning((long) achievement.getAchievedRunningTarget());
34006 ranu 204
                    model.setAchievedFastMoving((long) achievement.getAchievedFastMovingTarget());
205
                    model.setAchievedSlowMoving((long) achievement.getAchievedSlowMovingTarget());
206
                    model.setAchievedOtherMoving((long) achievement.getAchievedOtherTarget());
33997 ranu 207
 
208
                    model.setTotalTarget(
34006 ranu 209
                            (long) target.getHidTarget() +
34098 ranu 210
                                    (long) target.getRunningTarget() +
34006 ranu 211
                                    (long) target.getFastMovingTarget() +
212
                                    (long) target.getSlowMovingTarget() +
213
                                    (long) target.getOtherTarget()
33997 ranu 214
                    );
215
                    model.setTotalAchievemnt(
34006 ranu 216
                            (long) achievement.getAchievedHidTarget() +
34098 ranu 217
                                    (long) achievement.getAchievedRunningTarget() +
34006 ranu 218
                                    (long) achievement.getAchievedFastMovingTarget() +
219
                                    (long) achievement.getAchievedSlowMovingTarget() +
220
                                    (long) achievement.getAchievedOtherTarget()
33997 ranu 221
                    );
222
 
223
                    return model;
224
                })
225
                .collect(Collectors.toList());
226
 
227
    }
228
 
34002 ranu 229
    private RbmTargetsModel mergeTargets(RbmTargetsModel a1, RbmTargetsModel a2) {
33997 ranu 230
 
231
        // Merge logic for achievements (aggregate the target and achieved values)
34006 ranu 232
        a1.setHidTarget((a1.getHidTarget()) +
233
                (a2.getHidTarget()));
33997 ranu 234
 
34006 ranu 235
        a1.setFastMovingTarget((a1.getFastMovingTarget()) +
236
                (a2.getFastMovingTarget()));
33997 ranu 237
 
34006 ranu 238
        a1.setSlowMovingTarget((a1.getSlowMovingTarget()) +
239
                (a2.getSlowMovingTarget()));
33997 ranu 240
 
34098 ranu 241
        a1.setRunningTarget((a1.getRunningTarget()) +
242
                (a2.getRunningTarget()));
33997 ranu 243
 
34006 ranu 244
        a1.setOtherTarget((a1.getOtherTarget()) +
245
                (a2.getOtherTarget()));
33997 ranu 246
        return a1;
247
    }
248
 
34002 ranu 249
    private RbmAchievementsModel mergeAchievements(RbmAchievementsModel a1, RbmAchievementsModel a2) {
33997 ranu 250
        // Merge logic for achievements (aggregate the target and achieved values)
34006 ranu 251
        a1.setAchievedHidTarget((a1.getAchievedHidTarget()) +
252
                (a2.getAchievedHidTarget()));
33997 ranu 253
 
34098 ranu 254
        a1.setAchievedRunningTarget((a1.getAchievedRunningTarget()) +
255
                (a2.getAchievedRunningTarget()));
33997 ranu 256
 
34006 ranu 257
        a1.setAchievedFastMovingTarget((a1.getAchievedFastMovingTarget()) +
258
                (a2.getAchievedFastMovingTarget()));
33997 ranu 259
 
34006 ranu 260
        a1.setAchievedSlowMovingTarget((a1.getAchievedSlowMovingTarget()) +
261
                (a2.getAchievedSlowMovingTarget()));
33997 ranu 262
 
34006 ranu 263
        a1.setAchievedOtherTarget((a1.getAchievedOtherTarget()) +
264
                (a2.getAchievedOtherTarget()));
33997 ranu 265
 
266
        return a1;
267
    }
34002 ranu 268
 
33997 ranu 269
    @Override
33917 ranu 270
    public List<RbmArrViewModel> getRbmTodayArr(LocalDate todayDate) throws Exception {
271
 
272
        LocalDate startDateOfMonthDay1 = LocalDate.now().withDayOfMonth(1);
273
 
34289 ranu 274
        List<WarehouseRbmTargetModel> warehouseRbmTargetModelList = this.getWarehouseWiseRbmMonthlyTarget();
275
        List<WarehouseRbmTargetModel> warehouseRbmTargetModels = warehouseRbmTargetModelList.stream().filter(x -> x.getMonthlyTarget() > 0).collect(Collectors.toList());
276
        LOGGER.info("warehouseRbmTargetModels {}", warehouseRbmTargetModels);
277
        List<TodayAchievedMovementModel> todayAchievedMovementModels = getMovementWiseAchievementByDate(todayDate, todayDate.plusDays(1));
33917 ranu 278
 
279
        List<MTDAchievedTargetModel> mtdAchievedTargetModels = getDateWiseAchievedTargetOfRbm(startDateOfMonthDay1, todayDate);
280
 
35044 ranu 281
        int remainingWorkingDaysCount = (int) getRemainingDaysInMonth(todayDate);
33917 ranu 282
 
33926 ranu 283
        List<RbmTargets> todayRbmTargetsList = rbmTargetsRepository.selectTargetsByDates(todayDate.atStartOfDay(), todayDate.atTime(LocalTime.MAX));
33917 ranu 284
 
33926 ranu 285
        LOGGER.info("todayRbmTargetsList {}", todayRbmTargetsList);
33917 ranu 286
 
287
        List<RbmArrViewModel> rbmArrViewModels = new ArrayList<>();
288
 
34028 ranu 289
        if (!todayRbmTargetsList.isEmpty()) {
33917 ranu 290
 
35454 amit 291
            // OPTIMIZED: Pre-build maps for O(1) lookup instead of O(n) filter in each iteration
292
            // Map key: "authId-warehouseId"
293
            Map<String, Double> mtdAchievedMap = mtdAchievedTargetModels.stream()
294
                    .collect(Collectors.groupingBy(
295
                            x -> x.getAuthId() + "-" + x.getWarehouseId(),
296
                            Collectors.summingDouble(MTDAchievedTargetModel::getAcheivedMonthlyTarget)
297
                    ));
298
 
299
            Map<String, TodayAchievedMovementModel> todayAchievedMap = todayAchievedMovementModels.stream()
300
                    .collect(Collectors.toMap(
301
                            x -> x.getAuthId() + "-" + x.getWarehouseId(),
302
                            x -> x,
303
                            (a, b) -> a
304
                    ));
305
 
306
            Map<String, RbmTargets> todayRbmTargetsMap = todayRbmTargetsList.stream()
307
                    .collect(Collectors.toMap(
308
                            x -> x.getRbmAuthId() + "-" + x.getWarehouseId(),
309
                            x -> x,
310
                            (a, b) -> a
311
                    ));
312
 
34028 ranu 313
            for (WarehouseRbmTargetModel rbmTarget : warehouseRbmTargetModels) {
33917 ranu 314
 
35454 amit 315
                String lookupKey = rbmTarget.getAuthId() + "-" + rbmTarget.getWarehouseId();
316
 
34028 ranu 317
                float monthlyTarget = rbmTarget.getMonthlyTarget();
35454 amit 318
                float achievedSoFar = mtdAchievedMap.getOrDefault(lookupKey, 0.0).floatValue();
33917 ranu 319
 
34028 ranu 320
                float remainingTarget = monthlyTarget - achievedSoFar;
33953 ranu 321
 
34028 ranu 322
                float todayTarget = (remainingWorkingDaysCount > 0 && remainingTarget > 0) ? remainingTarget / remainingWorkingDaysCount : 0;
323
 
33926 ranu 324
                String warehouseName = ProfitMandiConstants.WAREHOUSE_MAP.getOrDefault(rbmTarget.getWarehouseId(), "Unknown");
33917 ranu 325
 
34288 ranu 326
                LOGGER.info("rbmTarget ==== {}", rbmTarget);
34281 ranu 327
 
35454 amit 328
                TodayAchievedMovementModel todayAchievedMovementModel = todayAchievedMap.get(lookupKey);
34283 ranu 329
 
35454 amit 330
                RbmTargets todayRbmTargets = todayRbmTargetsMap.get(lookupKey);
34285 ranu 331
 
35454 amit 332
                if (todayRbmTargets != null) {
34034 ranu 333
                    LOGGER.info("todayRbmTargets {}", todayRbmTargets);
334
                    RbmArrViewModel viewModel = new RbmArrViewModel();
33917 ranu 335
 
34034 ranu 336
                    viewModel.setAuthId(rbmTarget.getAuthId());
337
                    viewModel.setRbmName(rbmTarget.getRbmName());
338
                    viewModel.setWarehouseName(warehouseName);
339
                    viewModel.setTodayTarget(Math.round(todayTarget));
340
                    viewModel.setMonthlyTarget(Math.round(monthlyTarget));
341
                    viewModel.setMtdAchievedTarget(Math.round(achievedSoFar));
33926 ranu 342
 
34034 ranu 343
                    viewModel.setTodayHidTarget(Math.round((todayRbmTargets.getHidTarget())));
344
                    viewModel.setTodayFastMovingTarget(Math.round(todayRbmTargets.getFastMovingTarget()));
34098 ranu 345
                    viewModel.setTodaySlowMovingTarget(Math.round(todayRbmTargets.getSlowMovingtarget()));
346
                    viewModel.setTodayRunningTarget(Math.round(todayRbmTargets.getRunningtarget()));
34034 ranu 347
                    viewModel.setTodayOtherMovingTarget(Math.round(todayRbmTargets.getOtherTarget()));
33926 ranu 348
 
34283 ranu 349
                    if (todayAchievedMovementModel != null) {
350
                        viewModel.setTodayAchievedHidTarget(Math.round(todayAchievedMovementModel.getHidBilled()));
351
                        viewModel.setTodayAchievedFastMovingTarget(Math.round(todayAchievedMovementModel.getFastMovingBilled()));
352
                        viewModel.setTodayAchievedSlowMovingTarget(Math.round(todayAchievedMovementModel.getSlowMovinBilled()));
353
                        viewModel.setTodayAchievedRunningTarget(Math.round(todayAchievedMovementModel.getRunningBilled()));
354
                        viewModel.setTodayAchievedOtherMovingTarget(Math.round(todayAchievedMovementModel.getOtherBilled()));
355
                        viewModel.setTotalAchievedTarget(Math.round(todayAchievedMovementModel.getHidBilled() + todayAchievedMovementModel.getFastMovingBilled() + todayAchievedMovementModel.getSlowMovinBilled() + todayAchievedMovementModel.getRunningBilled() + todayAchievedMovementModel.getOtherBilled()));
356
                    } else {
357
                        viewModel.setTodayAchievedHidTarget(0);
358
                        viewModel.setTodayAchievedFastMovingTarget(0);
359
                        viewModel.setTodayAchievedSlowMovingTarget(0);
360
                        viewModel.setTodayAchievedRunningTarget(0);
361
                        viewModel.setTodayAchievedOtherMovingTarget(0);
362
                        viewModel.setTotalAchievedTarget(0);
363
                    }
34034 ranu 364
                    rbmArrViewModels.add(viewModel);
365
                } else {
366
                    LOGGER.info("No matching RbmTargets found for AuthId: {} and rbmname {} and WarehouseId: {}", rbmTarget.getAuthId(), rbmTarget.getRbmName(), rbmTarget.getWarehouseId());
367
                }
33917 ranu 368
 
34034 ranu 369
 
370
 
34028 ranu 371
            }
33917 ranu 372
        }
373
 
374
        LOGGER.info("rbmArrViewModels {}", rbmArrViewModels);
375
        return rbmArrViewModels;
376
    }
377
 
33926 ranu 378
    @Override
379
    public void setMovementWiseRbmTargets() {
380
        LocalDate todayDate = LocalDate.now();
33917 ranu 381
 
33926 ranu 382
        LocalDate startDateOfMonthDay1 = LocalDate.now().withDayOfMonth(1);
383
 
384
        List<WarehouseRbmTargetModel> warehouseRbmTargetModels = this.getWarehouseWiseRbmMonthlyTarget();
385
 
386
        List<MTDAchievedTargetModel> mtdAchievedTargetModels = getDateWiseAchievedTargetOfRbm(startDateOfMonthDay1, todayDate);
387
 
388
 
35044 ranu 389
        int remainingWorkingDaysCount = (int) getRemainingDaysInMonth(todayDate);
33926 ranu 390
 
391
        List<WarehouseMobileStockByMovementModel> warehouseMobileStockByMovementModels = getWarehouseMobileStockByMovement();
392
 
35454 amit 393
        // OPTIMIZED: Pre-build maps for O(1) lookup instead of O(n) filter in each iteration
394
        Map<String, Double> mtdAchievedMap = mtdAchievedTargetModels.stream()
395
                .collect(Collectors.groupingBy(
396
                        x -> x.getAuthId() + "-" + x.getWarehouseId(),
397
                        Collectors.summingDouble(MTDAchievedTargetModel::getAcheivedMonthlyTarget)
398
                ));
399
 
400
        Map<Integer, WarehouseMobileStockByMovementModel> warehouseStockMap = warehouseMobileStockByMovementModels.stream()
401
                .collect(Collectors.toMap(
402
                        WarehouseMobileStockByMovementModel::getWarehouseId,
403
                        x -> x,
404
                        (a, b) -> a
405
                ));
406
 
33926 ranu 407
        for (WarehouseRbmTargetModel rbmTarget : warehouseRbmTargetModels) {
408
 
35454 amit 409
            String lookupKey = rbmTarget.getAuthId() + "-" + rbmTarget.getWarehouseId();
410
 
33926 ranu 411
            float monthlyTarget = rbmTarget.getMonthlyTarget();
35454 amit 412
            float achievedSoFar = mtdAchievedMap.getOrDefault(lookupKey, 0.0).floatValue();
33926 ranu 413
 
414
 
415
            float remainingTarget = monthlyTarget - achievedSoFar;
33953 ranu 416
            LOGGER.info("remainingTarget {}", remainingTarget);
33926 ranu 417
 
33953 ranu 418
            float todayTarget = (remainingWorkingDaysCount > 0 && remainingTarget > 0) ? remainingTarget / remainingWorkingDaysCount : 0;
419
            LOGGER.info("todayTarget {}", todayTarget);
420
 
33926 ranu 421
            // Get the warehouse stock data
35454 amit 422
            WarehouseMobileStockByMovementModel warehouseMobileStockByMovementModel = warehouseStockMap.get(rbmTarget.getWarehouseId());
33926 ranu 423
 
424
 
425
            if (warehouseMobileStockByMovementModel != null) {
426
 
427
                // Total stock value for this warehouse
428
                float totalStockValue = warehouseMobileStockByMovementModel.getTotalAvailabilityPrice();
429
 
430
                // Calculate target allocation based on stock value proportion
431
                float hidTarget = (warehouseMobileStockByMovementModel.getTotalHidCatalogPrice() / totalStockValue) * todayTarget;
432
                float fastMovingTarget = (warehouseMobileStockByMovementModel.getTotalFastMovingCatalogPrice() / totalStockValue) * todayTarget;
433
                float slowMovingTarget = (warehouseMobileStockByMovementModel.getTotalSlowMovingCatalogPrice() / totalStockValue) * todayTarget;
34098 ranu 434
                float runningTarget = (warehouseMobileStockByMovementModel.getTotalRunningCatalogPrice() / totalStockValue) * todayTarget;
33926 ranu 435
                float otherTarget = (warehouseMobileStockByMovementModel.getTotalOtherCategoryCatalogPrice() / totalStockValue) * todayTarget;
436
 
437
                RbmTargets rbmTargets = new RbmTargets();
438
                rbmTargets.setWarehouseId(rbmTarget.getWarehouseId());
439
                rbmTargets.setRbmAuthId(rbmTarget.getAuthId());
440
                rbmTargets.setRbmName(rbmTarget.getRbmName());
34098 ranu 441
                rbmTargets.setRunningtarget(runningTarget);
33926 ranu 442
                rbmTargets.setHidTarget(hidTarget);
443
                rbmTargets.setFastMovingTarget(fastMovingTarget);
34098 ranu 444
                rbmTargets.setSlowMovingtarget(slowMovingTarget);
33926 ranu 445
                rbmTargets.setOtherTarget(otherTarget);
446
                rbmTargets.setCreateTimestamp(LocalDateTime.now());
447
 
448
                rbmTargetsRepository.persist(rbmTargets);
449
 
450
            }
451
        }
452
 
453
    }
454
 
455
 
33985 ranu 456
    @Override
457
    public void setMovementWiseRbmAchievement() {
458
        LocalDate todayDate = LocalDate.now();
459
 
34055 ranu 460
        List<TodayAchievedMovementModel> todayAchievedMovementModels = getMovementWiseAchievementByDate(todayDate, todayDate.plusDays(1));
33985 ranu 461
 
462
 
463
        for (TodayAchievedMovementModel achievement : todayAchievedMovementModels) {
464
 
465
            RbmAchievements rbmAchievements = new RbmAchievements();
466
 
467
            rbmAchievements.setRbmAuthId(achievement.getAuthId());
468
            rbmAchievements.setRbmName(achievement.getRbmName());
469
            rbmAchievements.setWarehouseId(achievement.getWarehouseId());
470
            rbmAchievements.setAchievedHidTarget(achievement.getHidBilled());
471
            rbmAchievements.setAchievedFastMovingTarget(achievement.getFastMovingBilled());
34098 ranu 472
            rbmAchievements.setAchievedSlowMovingTarget(achievement.getSlowMovinBilled());
473
            rbmAchievements.setAchievedRunningTarget(achievement.getRunningBilled());
34012 ranu 474
            rbmAchievements.setAchievedOtherTarget(achievement.getOtherBilled());
33985 ranu 475
            rbmAchievements.setCreateTimestamp(LocalDateTime.now());
476
 
477
            rbmAchievementsRepository.persist(rbmAchievements);
478
 
479
        }
480
 
481
    }
482
 
34055 ranu 483
    @Override
484
    public List<Sold15daysOldAgingModel> getAgingSale(LocalDate startDate, LocalDate endDate) {
485
        Session session = sessionFactory.getCurrentSession();
486
        final TypedQuery<Sold15daysOldAgingModel> typedQuerySimilar = session.createNamedQuery("Aging.SoldAgingModel", Sold15daysOldAgingModel.class);
34056 ranu 487
        typedQuerySimilar.setParameter("startDate", startDate);
488
        typedQuerySimilar.setParameter("endDate", endDate);
34055 ranu 489
        return typedQuerySimilar.getResultList();
33985 ranu 490
 
34055 ranu 491
    }
492
 
34103 ranu 493
    @Override
494
    public List<RbmBilledFofoIdsModel> getDateWiseBilledFofoIdByRbm(LocalDate startDate, LocalDate endDate) {
495
        Session session = sessionFactory.getCurrentSession();
496
        final TypedQuery<RbmBilledFofoIdsModel> typedQuerySimilar = session.createNamedQuery("RBM.RbmBilledFofoId", RbmBilledFofoIdsModel.class);
497
        typedQuerySimilar.setParameter("startDate", startDate);
498
        typedQuerySimilar.setParameter("endDate", endDate);
499
        return typedQuerySimilar.getResultList();
35453 amit 500
    }
34103 ranu 501
 
35453 amit 502
    @Override
36296 amit 503
    @Cacheable(value = "rbmWeeklyBilling",
36329 amit 504
            cacheManager = "fiveMintimeoutCacheManager",
505
            sync = true)
35453 amit 506
    public List<RbmWeeklyBillingModel> getWeeklyBillingDataForMonth(LocalDate monthStart, LocalDate monthEnd) {
507
        Session session = sessionFactory.getCurrentSession();
508
        final TypedQuery<RbmWeeklyBillingModel> typedQuery = session.createNamedQuery("RBM.WeeklyBilling", RbmWeeklyBillingModel.class);
509
        typedQuery.setParameter("startDate", monthStart);
510
        typedQuery.setParameter("endDate", monthEnd);
511
        return typedQuery.getResultList();
34103 ranu 512
    }
513
 
34055 ranu 514
    public List<Our15DaysOldAgingStock> our15DaysAgingStock() {
515
        Session session = sessionFactory.getCurrentSession();
516
        final TypedQuery<Our15DaysOldAgingStock> typedQuerySimilar = session.createNamedQuery("Aging.15DaysOurStock", Our15DaysOldAgingStock.class);
517
        return typedQuerySimilar.getResultList();
36334 ranu 518
    }
34055 ranu 519
 
36334 ranu 520
    @Override
521
    public List<WarehouseAgingStockModel> getWarehouseWiseAgingStock() {
522
        Session session = sessionFactory.getCurrentSession();
523
        final TypedQuery<WarehouseAgingStockModel> typedQuery = session.createNamedQuery("Aging.15DaysWarehouseWiseStock", WarehouseAgingStockModel.class);
524
        return typedQuery.getResultList();
34055 ranu 525
    }
526
 
34397 ranu 527
    @Autowired
528
    OrderRepository orderRepository;
34055 ranu 529
 
34397 ranu 530
    @Override
34641 ranu 531
    public double calculateFofoIdTodayTarget(int fofoId, double secondryMtd,LocalDate date) {
34397 ranu 532
 
533
        MonthlyTarget monthlyTarget = monthlyTargetRepository.selectByDateAndFofoId(YearMonth.now(), fofoId);
34404 ranu 534
        if (monthlyTarget == null) {
535
            // Log or handle as needed
536
            return 0; // or -1 or some fallback
537
        }
34397 ranu 538
 
539
        double remainingTarget = monthlyTarget.getPurchaseTarget() - secondryMtd;
34880 ranu 540
//        double remainingWorkingDays = getWorkingDaysCount(date);
541
        double remainingWorkingDays = (double) getRemainingDaysInMonth(date);
34397 ranu 542
 
543
 
34716 ranu 544
 
34397 ranu 545
        if (remainingWorkingDays == 0) return remainingTarget; // Last day
34716 ranu 546
        LOGGER.info("remainingWorkingDays {}", remainingWorkingDays);
547
        LOGGER.info("remainingTarget {}", remainingTarget);
34397 ranu 548
 
549
        return (int) Math.ceil(remainingTarget / remainingWorkingDays);
550
    }
551
 
34880 ranu 552
    @Override
553
    public long getRemainingDaysInMonth(LocalDate date) {
554
        LocalDate lastDayOfMonth = YearMonth.from(date).atEndOfMonth();
34397 ranu 555
 
34880 ranu 556
        long totalDays = ChronoUnit.DAYS.between(date, lastDayOfMonth) + 1;
34397 ranu 557
 
34880 ranu 558
        // Count Sundays manually
559
        long sundayCount = 0;
560
        LocalDate current = date;
561
        while (!current.isAfter(lastDayOfMonth)) {
562
            if (current.getDayOfWeek() == DayOfWeek.SUNDAY) {
563
                sundayCount++;
564
            }
565
            current = current.plusDays(1);
566
        }
567
 
568
        // Public holidays in the range
569
        long publicHolidays = publicHolidaysRepository
570
                .selectAllBetweenDates(date, lastDayOfMonth)
571
                .size();
572
 
573
        long remainingDays = totalDays - sundayCount - publicHolidays;
574
 
575
        LOGGER.info("remainingDays {}", remainingDays);
576
        LOGGER.info("totalDays {}", totalDays);
577
        LOGGER.info("sundays {}", sundayCount);
578
        LOGGER.info("publicHolidays {}", publicHolidays);
579
 
580
        return remainingDays;
581
    }
582
 
35631 ranu 583
    @Autowired
584
    PositionRepository positionRepository;
34880 ranu 585
 
35631 ranu 586
    @Autowired
587
    CsService csService;
34880 ranu 588
 
35631 ranu 589
    @Autowired
590
    FofoStoreRepository fofoStoreRepository;
591
 
592
    @Autowired
593
    AuthRepository authRepository;
594
 
595
    @Autowired
596
    LoanRepository loanRepository;
597
 
598
    @Autowired
599
    PartnerCollectionService partnerCollectionService;
600
 
601
    @Autowired
602
    PartnerCollectionRemarkRepository partnerCollectionRemarkRepository;
603
 
604
    @Autowired
605
    RbmCallSequenceLogRepository rbmCallSequenceLogRepository;
606
 
607
    @Autowired
608
    com.spice.profitmandi.dao.repository.cs.TicketRepository ticketRepository;
609
 
35702 ranu 610
    @Autowired
611
    com.spice.profitmandi.dao.repository.cs.AgentCallLogRepository agentCallLogRepository;
612
 
35759 ranu 613
    @Autowired
614
    RetailerContactRepository retailerContactRepository;
615
 
616
    @Autowired
617
    AddressRepository addressRepository;
618
 
36225 ranu 619
    @Autowired
620
    com.spice.profitmandi.dao.repository.cs.PartnerPositionRepository partnerPositionRepository;
621
 
35631 ranu 622
    @Override
623
    public List<RbmCallTargetModel> getRbmCallTargetModels() throws Exception {
36234 ranu 624
        return getRbmCallTargetModels(LocalDate.now());
625
    }
626
 
37010 ranu 627
    // Matches "No Answer", "NO_ANSWER", "no-answer", "noanswer", etc.
628
    private static boolean isNoAnswerStatus(String status) {
629
        if (status == null) return false;
630
        String s = status.trim().toLowerCase().replace('_', ' ').replace('-', ' ').replaceAll("\\s+", " ");
631
        return s.equals("no answer") || s.equals("noanswer");
632
    }
633
 
634
    @Override
635
    public List<OutOfSequenceDetailModel> getOutOfSequenceDetails(int authId) {
636
 
637
        LocalDate today = LocalDate.now();
638
        LocalDateTime start = today.atStartOfDay();
639
        LocalDateTime end = today.plusDays(1).atStartOfDay();
640
 
641
        List<RbmCallSequenceLog> logs =
642
                rbmCallSequenceLogRepository.selectByAuthIdAndDateRange(authId, start, end);
643
 
644
        Map<Integer, RbmCallSequenceLog> uniqueOosLogsByFofoId = new LinkedHashMap<>();
645
 
646
        for (RbmCallSequenceLog log : logs) {
647
            if (log.isOutOfSequence()) {
648
                // Keep only the first occurrence per fofoId (latest entry since ordered by id DESC)
649
                uniqueOosLogsByFofoId.putIfAbsent(log.getFofoId(), log);
650
            }
651
        }
652
 
653
        if (uniqueOosLogsByFofoId.isEmpty()) {
654
            return Collections.emptyList();
655
        }
656
 
657
        Set<Integer> fofoIds = uniqueOosLogsByFofoId.keySet();
658
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
659
        try {
660
            retailerMap = retailerService.getFofoRetailers(new ArrayList<>(fofoIds));
661
        } catch (ProfitMandiBusinessException e) {
662
            LOGGER.error("Error fetching fofo stores", e);
663
        }
664
 
665
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
666
        List<OutOfSequenceDetailModel> result = new ArrayList<>();
667
 
668
        for (RbmCallSequenceLog log : uniqueOosLogsByFofoId.values()) {
669
            CustomRetailer retailer = retailerMap.get(log.getFofoId());
670
            String partyName = retailer != null
671
                    ? retailer.getBusinessName()
672
                    : "Unknown (" + log.getFofoId() + ")";
673
            String code = retailer != null
674
                    ? retailer.getCode()
675
                    : "-";
676
 
677
            String time = log.getCreateTimestamp() != null
678
                    ? log.getCreateTimestamp().format(timeFormatter)
679
                    : "-";
680
 
681
            result.add(new OutOfSequenceDetailModel(partyName, code, time));
682
        }
683
 
684
        return result;
685
    }
686
 
687
    @Override
688
    public List<CalledPartnerDetailModel> getCalledPartnerDetails(int authId) throws ProfitMandiBusinessException {
689
        return getCalledPartnerDetails(authId, LocalDate.now());
690
    }
691
 
692
    @Override
693
    public List<CalledPartnerDetailModel> getCalledPartnerDetails(int authId, LocalDate date) throws ProfitMandiBusinessException {
694
        // Get all call logs for this auth user on this date
695
        LOGGER.info("getCalledPartnerDetails: authId={}, date={}", authId, date);
696
        List<AgentCallLog> callLogs = agentCallLogRepository.findByAuthIdAndDate(authId, date);
697
        LOGGER.info("Found {} call logs for authId={} on date={}", callLogs.size(), authId, date);
698
 
699
        if (callLogs.isEmpty()) {
700
            return Collections.emptyList();
701
        }
702
 
703
        // Build a map of normalized customer number -> fofoId
704
        Map<String, Integer> customerToFofoIdMap = new HashMap<>();
705
        Set<String> normalizedNumbers = new HashSet<>();
706
 
707
        for (AgentCallLog callLog : callLogs) {
708
            String customerNumber = callLog.getCustomerNumber();
709
            if (customerNumber != null) {
710
                String normalized = customerNumber.startsWith("+91") ? customerNumber.substring(3) : customerNumber;
711
                normalizedNumbers.add(normalized);
712
            }
713
        }
714
 
715
        // For each normalized number, find fofoId from retailer_contact first, then address
716
        for (String mobile : normalizedNumbers) {
717
            Integer fofoId = findFofoIdByMobile(mobile);
718
            if (fofoId != null) {
719
                customerToFofoIdMap.put(mobile, fofoId);
720
            }
721
        }
722
 
723
        // Get unique fofoIds for retailer lookup
724
        Set<Integer> fofoIds = new HashSet<>(customerToFofoIdMap.values());
725
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
726
        if (!fofoIds.isEmpty()) {
727
            try {
728
                retailerMap = retailerService.getFofoRetailers(new ArrayList<>(fofoIds));
729
            } catch (ProfitMandiBusinessException e) {
730
                LOGGER.error("Error fetching fofo stores", e);
731
            }
732
        }
733
 
734
        // Get today's remarks for these fofoIds
735
        Map<Integer, List<PartnerCollectionRemark>> fofoRemarkMap = new HashMap<>();
736
        if (!fofoIds.isEmpty()) {
737
            List<PartnerCollectionRemark> todayRemarks = partnerCollectionRemarkRepository
738
                    .selectAllByFofoIdsOnDate(new ArrayList<>(fofoIds), date);
739
            for (PartnerCollectionRemark remark : todayRemarks) {
740
                fofoRemarkMap.computeIfAbsent(remark.getFofoId(), k -> new ArrayList<>()).add(remark);
741
            }
742
        }
743
 
744
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
745
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
746
        List<CalledPartnerDetailModel> result = new ArrayList<>();
747
 
748
        for (com.spice.profitmandi.dao.entity.cs.AgentCallLog callLog : callLogs) {
749
            String customerNumber = callLog.getCustomerNumber();
750
            if (customerNumber == null) {
751
                continue;
752
            }
753
 
754
            String normalized = customerNumber.startsWith("+91") ? customerNumber.substring(3) : customerNumber;
755
            Integer fofoId = customerToFofoIdMap.get(normalized);
756
 
757
            String partyName = "Unknown";
758
            String code = "-";
759
 
760
            if (fofoId != null) {
761
                CustomRetailer retailer = retailerMap.get(fofoId);
762
                if (retailer != null) {
763
                    partyName = retailer.getBusinessName();
764
                    code = retailer.getCode();
765
                } else {
766
                    partyName = "Unknown (" + fofoId + ")";
767
                }
768
            } else {
769
                partyName = "Unknown (" + normalized + ")";
770
            }
771
 
772
            // Get remark if available
773
            String remarkValue = "-";
774
            String messageValue = "-";
775
            String remarkTime = "-";
776
 
777
            if (fofoId != null && fofoRemarkMap.containsKey(fofoId)) {
778
                List<PartnerCollectionRemark> remarks = fofoRemarkMap.get(fofoId);
779
                if (!remarks.isEmpty()) {
780
                    PartnerCollectionRemark remark = remarks.get(0);
781
                    remarkValue = remark.getRemark() != null ? remark.getRemark().getValue() : "-";
782
                    messageValue = remark.getMessage() != null ? remark.getMessage() : "-";
783
                    remarkTime = remark.getCreateTimestamp() != null ? remark.getCreateTimestamp().format(timeFormatter) : "-";
784
                }
785
            }
786
 
787
            // Build call log data
788
            String recordingUrl = callLog.getRecordingUrl();
789
            String callStatus = callLog.getCallStatus();
790
            String callDuration = callLog.getCallDuration();
791
            String callDateTime = null;
792
            if (callLog.getCallDate() != null && callLog.getCallTime() != null) {
793
                LocalDateTime callDateTimeObj = LocalDateTime.of(callLog.getCallDate(), callLog.getCallTime());
794
                callDateTime = callDateTimeObj.format(dateTimeFormatter);
795
            }
796
 
797
            result.add(new CalledPartnerDetailModel(partyName, code, remarkValue, messageValue, remarkTime,
798
                    recordingUrl, callStatus, callDuration, callDateTime));
799
        }
800
 
801
        return result;
802
    }
803
 
804
    private Integer findFofoIdByMobile(String mobile) {
805
        // First check retailer_contact
806
        List<RetailerContact> contacts = retailerContactRepository.selectByMobile(mobile);
807
        if (contacts != null && !contacts.isEmpty()) {
808
            return contacts.get(0).getFofoId();
809
        }
810
 
811
        // Fallback to user.address
812
        List<Address> addresses = addressRepository.selectAllByPhoneNumber(mobile);
813
        if (addresses != null && !addresses.isEmpty()) {
814
            return addresses.get(0).getRetaierId();
815
        }
816
 
817
        return null;
818
    }
819
 
820
    private List<CalledPartnerDetailModel> buildCalledPartnerResult(List<PartnerCollectionRemark> allRemarks) {
821
        if (allRemarks.isEmpty()) {
822
            return Collections.emptyList();
823
        }
824
 
825
        // Get unique fofoIds for retailer lookup
826
        Set<Integer> fofoIds = allRemarks.stream()
827
                .map(PartnerCollectionRemark::getFofoId)
828
                .collect(Collectors.toSet());
829
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
830
        try {
831
            retailerMap = retailerService.getFofoRetailers(new ArrayList<>(fofoIds));
832
        } catch (ProfitMandiBusinessException e) {
833
            LOGGER.error("Error fetching fofo stores", e);
834
        }
835
 
836
        // Fetch call logs for remarks that have agentCallLogId
837
        Map<Long, com.spice.profitmandi.dao.entity.cs.AgentCallLog> callLogMap = new HashMap<>();
838
        try {
839
            List<Long> callLogIds = allRemarks.stream()
840
                    .filter(r -> r.getAgentCallLogId() > 0)
841
                    .map(PartnerCollectionRemark::getAgentCallLogId)
842
                    .collect(Collectors.toList());
843
 
844
            if (!callLogIds.isEmpty()) {
845
                List<com.spice.profitmandi.dao.entity.cs.AgentCallLog> callLogs = agentCallLogRepository.findByIds(callLogIds);
846
                if (callLogs != null) {
847
                    callLogMap = callLogs.stream()
848
                            .collect(Collectors.toMap(com.spice.profitmandi.dao.entity.cs.AgentCallLog::getId, c -> c, (a, b) -> a));
849
                }
850
            }
851
        } catch (Exception e) {
852
            LOGGER.error("Error fetching call logs by ids", e);
853
        }
854
 
855
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
856
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
857
        List<CalledPartnerDetailModel> result = new ArrayList<>();
858
 
859
        for (PartnerCollectionRemark remark : allRemarks) {
860
            CustomRetailer retailer = retailerMap.get(remark.getFofoId());
861
            String partyName = retailer != null
862
                    ? retailer.getBusinessName()
863
                    : "Unknown (" + remark.getFofoId() + ")";
864
            String code = retailer != null
865
                    ? retailer.getCode()
866
                    : "-";
867
 
868
            String remarkValue = remark.getRemark() != null
869
                    ? remark.getRemark().getValue()
870
                    : "-";
871
 
872
            String messageValue = remark.getMessage() != null
873
                    ? remark.getMessage()
874
                    : "-";
875
 
876
            String time = remark.getCreateTimestamp() != null
877
                    ? remark.getCreateTimestamp().format(timeFormatter)
878
                    : "-";
879
 
880
            // Get call log data if available
881
            String recordingUrl = null;
882
            String callStatus = null;
883
            String callDuration = null;
884
            String callDateTime = null;
885
 
886
            try {
887
                if (remark.getAgentCallLogId() > 0 && callLogMap.containsKey(remark.getAgentCallLogId())) {
888
                    com.spice.profitmandi.dao.entity.cs.AgentCallLog callLog = callLogMap.get(remark.getAgentCallLogId());
889
                    recordingUrl = callLog.getRecordingUrl();
890
                    callStatus = callLog.getCallStatus();
891
                    callDuration = callLog.getCallDuration();
892
                    if (callLog.getCallDate() != null && callLog.getCallTime() != null) {
893
                        LocalDateTime callDateTimeObj = LocalDateTime.of(callLog.getCallDate(), callLog.getCallTime());
894
                        callDateTime = callDateTimeObj.format(dateTimeFormatter);
895
                    }
896
                }
897
            } catch (Exception e) {
898
                LOGGER.error("Error processing call log for remark id: {}", remark.getId(), e);
899
            }
900
 
901
            result.add(new CalledPartnerDetailModel(partyName, code, remarkValue, messageValue, time,
902
                    recordingUrl, callStatus, callDuration, callDateTime));
903
        }
904
 
905
        return result;
906
    }
907
 
908
    @Override
909
    public List<List<String>> getRbmCallTargetRawDataByAuthId(int authId) throws Exception {
910
        List<List<String>> rows = new ArrayList<>();
911
 
912
        // Get auth user
913
        List<AuthUser> authUsers = authRepository.selectByIds(Collections.singletonList(authId));
914
        if (authUsers.isEmpty()) {
915
            return rows;
916
        }
917
        AuthUser authUser = authUsers.get(0);
918
 
919
        // Get positions to determine if L2
920
        List<Position> positions = positionRepository.selectPositionByAuthIds(Collections.singletonList(authId));
921
        boolean isL2 = positions.stream()
922
                .anyMatch(p -> ProfitMandiConstants.TICKET_CATEGORY_RBM == p.getCategoryId()
923
                        && EscalationType.L2.equals(p.getEscalationType()));
924
 
925
        LocalDateTime startDate = LocalDate.now().atStartOfDay();
926
        LocalDate firstOfMonth = LocalDate.now().withDayOfMonth(1);
927
        LocalDate endOfMonth = LocalDate.now().withDayOfMonth(LocalDate.now().lengthOfMonth()).plusDays(1);
928
 
929
        // Get fofo IDs from mtdBillingData (same source as Partner Count in getRbmCallTargetModels)
930
        List<RbmWeeklyBillingModel> mtdBillingData = getWeeklyBillingDataForMonth(firstOfMonth, endOfMonth);
931
 
932
        List<Integer> fofoIdList;
933
        if (isL2) {
37145 ranu 934
            // L2: get fofo IDs from escalated tickets (same as getRbmCallTargetModels).
935
            // selectOpenEscalatedTicketsByAuthIds already filters to tickets where authId is the
936
            // current assignee AND the ticket has moved past L1 — no post-filter needed.
37010 ranu 937
            List<Ticket> escalatedTickets = ticketRepository.selectOpenEscalatedTicketsByAuthIds(Collections.singletonList(authId));
938
            fofoIdList = escalatedTickets.stream()
939
                    .map(Ticket::getFofoId)
940
                    .distinct()
941
                    .collect(Collectors.toList());
942
        } else {
943
            // L1: get fofo IDs from mtdBillingData with isTargetedPartner (same as Partner Count)
944
            fofoIdList = mtdBillingData.stream()
945
                    .filter(RbmWeeklyBillingModel::isTargetedPartner)
946
                    .filter(m -> m.getAuthId() == authId)
947
                    .map(RbmWeeklyBillingModel::getFofoId)
948
                    .distinct()
949
                    .collect(Collectors.toList());
950
        }
951
 
952
        if (fofoIdList.isEmpty()) {
953
            return rows;
954
        }
955
 
956
        // MTD billed fofoIds for zero billing check
957
        Set<Integer> mtdBilledFofoIds = mtdBillingData.stream()
958
                .filter(RbmWeeklyBillingModel::isMtdBilled)
959
                .map(RbmWeeklyBillingModel::getFofoId)
960
                .collect(Collectors.toSet());
961
 
962
        // Collection rank map for status calculation
963
        Map<Integer, Integer> collectionRankMap = new HashMap<>();
964
        try {
965
            collectionRankMap = partnerCollectionService.getCollectionRankMap(fofoIdList, startDate);
966
        } catch (ProfitMandiBusinessException e) {
967
            LOGGER.error("Error fetching collection rank map", e);
968
        }
969
 
970
        // Resolve partner names/codes
971
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
972
        if (!fofoIdList.isEmpty()) {
973
            try {
974
                retailerMap = retailerService.getFofoRetailers(fofoIdList);
975
            } catch (ProfitMandiBusinessException e) {
976
                LOGGER.error("Error fetching fofo retailers for raw data", e);
977
            }
978
        }
979
 
980
        String rbmName = authUser.getFullName() + (isL2 ? " (L2)" : "");
981
 
982
        // Build rows for ALL partners (same count as Partner Count)
983
        for (Integer fofoId : fofoIdList) {
984
            // Default to rank 5 (Normal) for partners without collection plan
985
            int rank = collectionRankMap.getOrDefault(fofoId, 5);
986
            boolean hasZeroBilling = !mtdBilledFofoIds.contains(fofoId);
987
 
988
            // Status assignment with same priority as getRbmCallTargetModels
989
            String status;
990
            if (rank == 1) {
991
                status = "Plan Today";
992
            } else if (rank == 2) {
993
                status = "Carry Forward";
994
            } else if (hasZeroBilling) {
995
                status = "Zero Billing";
996
            } else if (rank == 3) {
997
                status = "Untouched";
998
            } else if (rank == 4) {
999
                status = "Future Plan";
1000
            } else {
1001
                status = "Normal";
1002
            }
1003
 
1004
            CustomRetailer retailer = retailerMap.get(fofoId);
1005
            String partnerName = retailer != null ? retailer.getBusinessName() : "Unknown (" + fofoId + ")";
1006
            String partnerCode = retailer != null ? retailer.getCode() : "-";
1007
 
1008
            rows.add(Arrays.asList(partnerName, partnerCode, status, rbmName));
1009
        }
1010
 
1011
        return rows;
1012
    }
1013
 
1014
    @Override
1015
    public List<List<String>> getAllRbmCallTargetRawData() throws Exception {
1016
        List<List<String>> rows = new ArrayList<>();
1017
 
1018
        // Get all L1 RBM positions (rows are emitted per L1 RBM).
1019
        // Call-log lookup happens against ALL callers via findAllByDate — so an L2/L3 or admin call
1020
        // still counts as "tried" for the partner.
1021
        List<Position> allRbmPositions = positionRepository
1022
                .selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_RBM).stream()
1023
                .filter(x -> EscalationType.L1.equals(x.getEscalationType()))
1024
                .collect(Collectors.toList());
1025
 
1026
        List<Integer> l1AuthIds = allRbmPositions.stream()
1027
                .map(Position::getAuthUserId).distinct().collect(Collectors.toList());
1028
 
1029
        if (l1AuthIds.isEmpty()) {
1030
            return rows;
1031
        }
1032
 
1033
        // Get auth user map
1034
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(l1AuthIds).stream()
1035
                .collect(Collectors.toMap(AuthUser::getId, au -> au));
1036
 
1037
        // Positions per auth user (needed early to build L1 partner assignments below)
1038
        Map<Integer, List<Position>> positionsByAuthId = positionRepository.selectPositionByAuthIds(l1AuthIds).stream()
1039
                .collect(Collectors.groupingBy(Position::getAuthUserId));
1040
 
1041
        // Build L1 partner assignments from partner_position — SAME source the UI summary uses for
1042
        // Calling Target. storeGuyMap (email-based CS mapping) was returning smaller/different lists
1043
        // for users who are also L2, causing summary=43 but download=3 for Ebadullah.
1044
        Map<Integer, Integer> l1PositionIdToAuthId = new HashMap<>();
1045
        for (int rbmAuthId : l1AuthIds) {
1046
            List<Position> positions = positionsByAuthId.getOrDefault(rbmAuthId, Collections.emptyList());
1047
            for (Position p : positions) {
1048
                if (ProfitMandiConstants.TICKET_CATEGORY_RBM == p.getCategoryId()
1049
                        && EscalationType.L1.equals(p.getEscalationType())) {
1050
                    l1PositionIdToAuthId.put(p.getId(), rbmAuthId);
1051
                }
1052
            }
1053
        }
1054
 
1055
        Map<Integer, List<Integer>> rbmToFofoIdsMap = new HashMap<>();
1056
        Set<Integer> allFofoIds = new HashSet<>();
1057
        if (!l1PositionIdToAuthId.isEmpty()) {
1058
            List<com.spice.profitmandi.dao.entity.cs.PartnerPosition> allL1PPs =
1059
                    partnerPositionRepository.selectByPositionIds(new ArrayList<>(l1PositionIdToAuthId.keySet()));
1060
            // Group by owning RBM; keep partners distinct within each RBM.
1061
            Map<Integer, Set<Integer>> perRbmSets = new HashMap<>();
1062
            for (com.spice.profitmandi.dao.entity.cs.PartnerPosition pp : allL1PPs) {
1063
                Integer ownerAuthId = l1PositionIdToAuthId.get(pp.getPositionId());
1064
                if (ownerAuthId == null) continue;
1065
                perRbmSets.computeIfAbsent(ownerAuthId, k -> new HashSet<>()).add(pp.getFofoId());
1066
                allFofoIds.add(pp.getFofoId());
1067
            }
1068
            for (Map.Entry<Integer, Set<Integer>> e : perRbmSets.entrySet()) {
1069
                rbmToFofoIdsMap.put(e.getKey(), new ArrayList<>(e.getValue()));
1070
            }
1071
        }
1072
 
1073
        if (allFofoIds.isEmpty()) {
1074
            return rows;
1075
        }
1076
 
1077
        // Get fofo stores for filtering and name resolution
1078
        Map<Integer, FofoStore> fofoStoresMap = new HashMap<>();
1079
        try {
1080
            fofoStoresMap = fofoStoreRepository.selectByRetailerIds(new ArrayList<>(allFofoIds)).stream()
1081
                    .collect(Collectors.toMap(FofoStore::getId, x -> x, (a, b) -> a));
1082
        } catch (ProfitMandiBusinessException e) {
1083
            LOGGER.error("Error fetching fofo stores for all raw data", e);
1084
        }
1085
 
1086
        // Batch fetch collection rank map
1087
        LocalDateTime startDate = LocalDate.now().atStartOfDay();
1088
        Map<Integer, Integer> allCollectionRankMap = new HashMap<>();
1089
        try {
1090
            allCollectionRankMap = partnerCollectionService.getCollectionRankMap(new ArrayList<>(allFofoIds), startDate);
1091
        } catch (ProfitMandiBusinessException e) {
1092
            LOGGER.error("Error fetching collection rank map for all raw data", e);
1093
        }
1094
 
1095
        // MTD billing data
1096
        LocalDate firstOfMonth = LocalDate.now().withDayOfMonth(1);
1097
        LocalDate endOfMonth = LocalDate.now().withDayOfMonth(LocalDate.now().lengthOfMonth()).plusDays(1);
1098
        List<RbmWeeklyBillingModel> mtdBillingData = getWeeklyBillingDataForMonth(firstOfMonth, endOfMonth);
1099
        Set<Integer> allMtdBilledFofoIds = mtdBillingData.stream()
1100
                .filter(RbmWeeklyBillingModel::isMtdBilled)
1101
                .map(RbmWeeklyBillingModel::getFofoId)
1102
                .collect(Collectors.toSet());
1103
 
1104
        // Batch fetch partner collection remarks for escalation filtering
1105
        Map<Integer, PartnerCollectionRemark> allPartnerCollectionRemarks = new HashMap<>();
1106
        if (!allFofoIds.isEmpty()) {
1107
            List<Integer> allRemarkIds = partnerCollectionRemarkRepository.selectMaxRemarkId(new ArrayList<>(allFofoIds));
1108
            if (!allRemarkIds.isEmpty()) {
1109
                allPartnerCollectionRemarks = partnerCollectionRemarkRepository.selectByIds(allRemarkIds).stream()
1110
                        .collect(Collectors.toMap(PartnerCollectionRemark::getFofoId, x -> x, (a, b) -> a));
1111
            }
1112
        }
1113
 
1114
        // Resolve partner names/codes in batch
1115
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
1116
        try {
1117
            retailerMap = retailerService.getFofoRetailers(new ArrayList<>(allFofoIds));
1118
        } catch (ProfitMandiBusinessException e) {
1119
            LOGGER.error("Error fetching fofo retailers for all raw data", e);
1120
        }
1121
 
1122
        // Batch-fetch EVERY call log for today (across all callers, not just RBMs) and build a
1123
        // fofoId -> latest AgentCallLog map. We use findAllByDate here so that calls placed by
1124
        // admins, escalation agents, or anyone whose authId isn't in the RBM position table are
1125
        // still surfaced. Downstream we only read this map for fofoIds we actually emit, so
1126
        // extra entries are harmless.
37013 ranu 1127
        // Group ALL today's call logs by fofoId so we can apply the Tried rule per partner
1128
        // (uses customerStatus + persistence, same as the summary's Tried metric).
1129
        Map<Integer, List<AgentCallLog>> callsByFofoId = new HashMap<>();
37010 ranu 1130
        try {
1131
            List<AgentCallLog> todayCallLogs = agentCallLogRepository.findAllByDate(LocalDate.now());
1132
            Set<String> normalizedMobiles = new HashSet<>();
1133
            for (AgentCallLog log : todayCallLogs) {
1134
                if (log.getCustomerNumber() != null) {
1135
                    String n = log.getCustomerNumber();
1136
                    normalizedMobiles.add(n.startsWith("+91") ? n.substring(3) : n);
1137
                }
1138
            }
1139
            Map<String, Integer> mobileToFofoIdMap = buildMobileToFofoIdMap(normalizedMobiles);
1140
            for (AgentCallLog log : todayCallLogs) {
1141
                if (log.getCustomerNumber() == null) continue;
1142
                String n = log.getCustomerNumber();
1143
                String normalized = n.startsWith("+91") ? n.substring(3) : n;
1144
                Integer fofoId = mobileToFofoIdMap.get(normalized);
1145
                if (fofoId == null) continue;
37013 ranu 1146
                callsByFofoId.computeIfAbsent(fofoId, k -> new ArrayList<>()).add(log);
37010 ranu 1147
            }
1148
        } catch (Exception e) {
37013 ranu 1149
            LOGGER.error("Error building call logs map for all raw data", e);
37010 ranu 1150
        }
1151
 
1152
        // Process each L1 RBM
1153
        // Note: no cross-RBM dedup — a partner assigned to multiple RBMs appears once per RBM,
1154
        // matching the UI summary counts so row totals per RBM equal that RBM's "Calling Target".
1155
        for (int rbmAuthId : l1AuthIds) {
1156
            AuthUser authUser = authUserMap.get(rbmAuthId);
1157
            if (authUser == null) {
1158
                continue;
1159
            }
1160
 
1161
            List<Integer> fofoIdList = rbmToFofoIdsMap.getOrDefault(rbmAuthId, Collections.emptyList());
1162
            if (fofoIdList.isEmpty()) {
1163
                continue; // No L1 partner assignments for this RBM
1164
            }
1165
 
1166
            // Filter escalated partners for L1 RBMs
1167
            List<Position> positions = positionsByAuthId.getOrDefault(rbmAuthId, Collections.emptyList());
1168
            boolean isRBMAndL1 = positions.stream()
1169
                    .anyMatch(position ->
1170
                            ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId()
1171
                                    && EscalationType.L1.equals(position.getEscalationType()));
1172
 
1173
            List<Integer> fofoIds = fofoIdList;
1174
            if (isRBMAndL1) {
1175
                Map<Integer, PartnerCollectionRemark> partnerRemarks = new HashMap<>();
1176
                for (Integer fofoId : fofoIdList) {
1177
                    if (allPartnerCollectionRemarks.containsKey(fofoId)) {
1178
                        partnerRemarks.put(fofoId, allPartnerCollectionRemarks.get(fofoId));
1179
                    }
1180
                }
1181
                Map<Integer, PartnerCollectionRemark> finalPartnerRemarks = partnerRemarks;
1182
                fofoIds = fofoIdList.stream()
1183
                        .filter(fofoId -> {
1184
                            if (!finalPartnerRemarks.containsKey(fofoId)) return true;
1185
                            PartnerCollectionRemark pcr = finalPartnerRemarks.get(fofoId);
1186
                            return !(CollectionRemark.RBM_L2_ESCALATION.equals(pcr.getRemark())
1187
                                    || CollectionRemark.SALES_ESCALATION.equals(pcr.getRemark()));
1188
                        })
1189
                        .collect(Collectors.toList());
1190
            }
1191
 
1192
            // Filter to only external, ACTIVE or REVIVAL stores
1193
            Map<Integer, FofoStore> finalFofoStoresMap = fofoStoresMap;
1194
            List<Integer> validFofoIds = fofoIds.stream()
1195
                    .filter(fofoId -> {
1196
                        FofoStore store = finalFofoStoresMap.get(fofoId);
1197
                        if (store == null || store.isInternal()) return false;
1198
                        return ActivationType.ACTIVE.equals(store.getActivationType())
1199
                                || ActivationType.REVIVAL.equals(store.getActivationType());
1200
                    })
1201
                    .collect(Collectors.toList());
1202
 
1203
            String rbmName = authUser.getFullName();
1204
 
1205
            // Categorize each partner and add a row per RBM assignment.
1206
            for (Integer fofoId : validFofoIds) {
1207
                int rank = allCollectionRankMap.getOrDefault(fofoId, 5);
1208
                boolean hasZeroBilling = !allMtdBilledFofoIds.contains(fofoId);
1209
 
1210
                String status;
1211
                if (rank == 1) {
1212
                    status = "Plan Today";
1213
                } else if (rank == 2) {
1214
                    status = "Carry Forward";
1215
                } else if (hasZeroBilling) {
1216
                    status = "Zero Billing";
1217
                } else if (rank == 3) {
1218
                    status = "Untouched";
1219
                } else {
1220
                    continue; // Skip Future Plan and Normal — only include calling target parties
1221
                }
1222
 
1223
                CustomRetailer retailer = retailerMap.get(fofoId);
1224
                String partnerName = retailer != null ? retailer.getBusinessName() : "Unknown (" + fofoId + ")";
1225
                String partnerCode = retailer != null ? retailer.getCode() : "-";
1226
 
37013 ranu 1227
                // Show the latest customerStatus from today's call logs for this partner.
1228
                // "Did Not Try" only when there is no call log at all today.
1229
                List<AgentCallLog> partnerCalls = callsByFofoId.getOrDefault(fofoId, Collections.emptyList());
37010 ranu 1230
                String latestCallStatus = "Did Not Try";
37013 ranu 1231
                if (!partnerCalls.isEmpty()) {
1232
                    AgentCallLog latest = null;
1233
                    for (AgentCallLog l : partnerCalls) {
1234
                        if (latest == null || (l.getId() != null && latest.getId() != null && l.getId() > latest.getId())) {
1235
                            latest = l;
1236
                        }
1237
                    }
1238
                    if (latest != null && latest.getCustomerStatus() != null && !latest.getCustomerStatus().isEmpty()) {
1239
                        latestCallStatus = latest.getCustomerStatus();
1240
                    }
37010 ranu 1241
                }
1242
 
1243
                rows.add(Arrays.asList(partnerName, partnerCode, status, rbmName, latestCallStatus));
1244
            }
1245
        }
1246
 
1247
        return rows;
1248
    }
1249
 
1250
    /**
1251
     * Get count of distinct partners called today based on call logs.
1252
     * Maps customerNumber from call log to fofoId using retailer_contact and address.
1253
     * If same fofoId is called multiple times, counts only once.
1254
     * Numbers without fofoId mapping are also counted (by distinct customer number).
1255
     *
1256
     * @param authId the RBM auth ID
1257
     * @return count of distinct partners/numbers called today
1258
     */
1259
    public long getCalledCountFromCallLogs(long authId) {
1260
        return getCalledCountFromCallLogs(authId, LocalDate.now());
1261
    }
1262
 
1263
    public long getCalledCountFromCallLogs(long authId, LocalDate date) {
1264
        return getCallStats(authId, date)[0];
1265
    }
1266
 
1267
    /**
1268
     * Batch-builds a mobile (normalized, +91 stripped) -> fofoId mapping for all the given mobiles
1269
     * in just two queries (retailer_contact, then address fallback for unmapped numbers).
1270
     * Replaces the previous per-call-log findFofoIdByMobile() N+1 lookups.
1271
     */
1272
    private Map<String, Integer> buildMobileToFofoIdMap(Set<String> normalizedMobiles) {
1273
        Map<String, Integer> result = new HashMap<>();
1274
        if (normalizedMobiles == null || normalizedMobiles.isEmpty()) {
1275
            return result;
1276
        }
1277
        List<String> mobilesList = new ArrayList<>(normalizedMobiles);
1278
 
1279
        // First pass: retailer_contact
1280
        List<RetailerContact> contacts = retailerContactRepository.selectByMobiles(mobilesList);
1281
        for (RetailerContact rc : contacts) {
1282
            // Keep the first fofoId we see per mobile (matches old single-mobile behavior of get(0))
1283
            result.putIfAbsent(rc.getMobile(), rc.getFofoId());
1284
        }
1285
 
1286
        // Second pass: address fallback for mobiles not yet mapped
1287
        List<String> unmapped = mobilesList.stream()
1288
                .filter(m -> !result.containsKey(m))
1289
                .collect(Collectors.toList());
1290
        if (!unmapped.isEmpty()) {
1291
            List<Address> addresses = addressRepository.selectAllByPhoneNumbers(unmapped);
1292
            for (Address addr : addresses) {
1293
                result.putIfAbsent(addr.getPhoneNumber(), addr.getRetaierId());
1294
            }
1295
        }
1296
        return result;
1297
    }
1298
 
1299
    /**
1300
     * In-memory variant of getCallStats() that uses pre-fetched call logs and mobile→fofoId mapping.
1301
     * Used by the batch-fetched RBM Call Target loop to avoid N+1 query patterns.
1302
     */
1303
    private long[] getCallStatsFromLogs(List<AgentCallLog> callLogs, Map<String, Integer> mobileToFofoIdMap) {
1304
        if (callLogs == null || callLogs.isEmpty()) {
1305
            return new long[]{0, 0, 0};
1306
        }
1307
 
1308
        Set<Integer> calledFofoIds = new HashSet<>();
1309
        Set<String> calledNumbersWithoutFofoId = new HashSet<>();
1310
        long totalRecordingCalls = 0;
1311
        Set<String> uniqueRecordingNumbers = new HashSet<>();
1312
 
1313
        for (AgentCallLog callLog : callLogs) {
1314
            String customerNumber = callLog.getCustomerNumber();
1315
            if (customerNumber != null) {
1316
                String normalized = customerNumber.startsWith("+91") ? customerNumber.substring(3) : customerNumber;
1317
                Integer fofoId = mobileToFofoIdMap.get(normalized);
1318
                if (fofoId != null) {
1319
                    calledFofoIds.add(fofoId);
1320
                } else {
1321
                    calledNumbersWithoutFofoId.add(normalized);
1322
                }
1323
 
1324
                if (callLog.getRecordingUrl() != null && !callLog.getRecordingUrl().isEmpty()
1325
                        && !"None".equalsIgnoreCase(callLog.getRecordingUrl())) {
1326
                    totalRecordingCalls++;
1327
                    uniqueRecordingNumbers.add(normalized);
1328
                }
1329
            }
1330
        }
1331
 
1332
        long calledCount = calledFofoIds.size() + calledNumbersWithoutFofoId.size();
1333
        return new long[]{calledCount, totalRecordingCalls, uniqueRecordingNumbers.size()};
1334
    }
1335
 
37022 ranu 1336
    // Same rule as computeUniqueTriedCount but restricted to fofoIds in the target set.
1337
    // Used to compute "TGT Calls" — how many of THIS RBM's Calling Target partners were
1338
    // actually engaged today. Off-target activity is silently excluded.
1339
    private long computeUniqueTriedCountForTargets(List<AgentCallLog> callLogs,
1340
                                                   Map<String, Integer> mobileToFofoIdMap,
1341
                                                   Set<Integer> targetFofoIds) {
1342
        if (callLogs == null || callLogs.isEmpty()) return 0L;
1343
        if (targetFofoIds == null || targetFofoIds.isEmpty()) return 0L;
1344
        Map<Integer, List<AgentCallLog>> byFofoId = new HashMap<>();
1345
        for (AgentCallLog log : callLogs) {
1346
            String num = log.getCustomerNumber();
1347
            if (num == null) continue;
1348
            String normalized = num.startsWith("+91") ? num.substring(3) : num;
1349
            Integer fofoId = mobileToFofoIdMap != null ? mobileToFofoIdMap.get(normalized) : null;
1350
            if (fofoId == null) continue;
1351
            if (!targetFofoIds.contains(fofoId)) continue; // off-target, skip
1352
            byFofoId.computeIfAbsent(fofoId, k -> new ArrayList<>()).add(log);
1353
        }
1354
        long count = 0L;
1355
        for (List<AgentCallLog> logs : byFofoId.values()) {
1356
            boolean hasNonMissed = false;
1357
            for (AgentCallLog l : logs) {
1358
                if (!isMissedCustomerStatus(l.getCustomerStatus())) {
1359
                    hasNonMissed = true;
1360
                    break;
1361
                }
1362
            }
1363
            if (hasNonMissed) count++;
1364
            else if (logs.size() >= 3) count++;
1365
        }
1366
        return count;
1367
    }
1368
 
37012 ranu 1369
    // Matches "Missed", "MISSED", "No Answer", "NO_ANSWER", "no-answer" etc.
1370
    // Kommuno currently emits "Missed" — kept liberal so we're covered if the tag changes.
1371
    private static boolean isMissedCustomerStatus(String status) {
1372
        if (status == null) return false;
1373
        String s = status.trim().toLowerCase().replace('_', ' ').replace('-', ' ').replaceAll("\\s+", " ");
1374
        return s.equals("missed") || s.equals("no answer") || s.equals("noanswer");
1375
    }
1376
 
37013 ranu 1377
 
36234 ranu 1378
    public List<RbmCallTargetModel> getRbmCallTargetModels(LocalDate queryDate) throws Exception {
35631 ranu 1379
        long methodStart = System.currentTimeMillis();
1380
        List<RbmCallTargetModel> rbmCallTargetModels = new ArrayList<>();
1381
 
1382
        // Get all RBM positions (L1 and L2)
1383
        long start = System.currentTimeMillis();
1384
        List<Position> allRbmPositions = positionRepository
1385
                .selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_RBM).stream()
36210 ranu 1386
                .filter(x -> Arrays.asList(EscalationType.L1, EscalationType.L2, EscalationType.L3).contains(x.getEscalationType()))
35631 ranu 1387
                .collect(Collectors.toList());
1388
 
36210 ranu 1389
        // Separate L1, L2 and L3 auth IDs
35631 ranu 1390
        List<Integer> l1AuthIds = allRbmPositions.stream()
1391
                .filter(p -> EscalationType.L1.equals(p.getEscalationType()))
1392
                .map(Position::getAuthUserId).distinct().collect(Collectors.toList());
1393
        List<Integer> l2AuthIds = allRbmPositions.stream()
1394
                .filter(p -> EscalationType.L2.equals(p.getEscalationType()))
1395
                .map(Position::getAuthUserId).distinct().collect(Collectors.toList());
36210 ranu 1396
        List<Integer> l3AuthIds = allRbmPositions.stream()
1397
                .filter(p -> EscalationType.L3.equals(p.getEscalationType()))
1398
                .map(Position::getAuthUserId).distinct().collect(Collectors.toList());
35631 ranu 1399
 
1400
        // Union of all auth IDs for batch fetching
1401
        List<Integer> rbmPositionsAuthIds = allRbmPositions.stream()
1402
                .map(Position::getAuthUserId).distinct().collect(Collectors.toList());
36210 ranu 1403
        LOGGER.info("RBM Call Target - RBM positions fetch: {}ms, L1: {}, L2: {}, L3: {}", System.currentTimeMillis() - start, l1AuthIds.size(), l2AuthIds.size(), l3AuthIds.size());
35631 ranu 1404
 
1405
        start = System.currentTimeMillis();
1406
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1407
        LOGGER.info("RBM Call Target - StoreGuyMap fetch: {}ms", System.currentTimeMillis() - start);
1408
 
36234 ranu 1409
        LocalDateTime startDate = queryDate.atStartOfDay();
1410
        LocalDate firstOfMonth = queryDate.withDayOfMonth(1);
1411
        LocalDate endOfMonth = queryDate.withDayOfMonth(queryDate.lengthOfMonth()).plusDays(1);
35631 ranu 1412
 
1413
        // Get auth user map
1414
        start = System.currentTimeMillis();
1415
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(rbmPositionsAuthIds).stream()
1416
                .collect(Collectors.toMap(AuthUser::getId, au -> au));
1417
        LOGGER.info("RBM Call Target - AuthUser fetch: {}ms", System.currentTimeMillis() - start);
1418
 
1419
        // Batch fetch positions by auth IDs (to check if RBM is L1)
1420
        start = System.currentTimeMillis();
1421
        Map<Integer, List<Position>> positionsByAuthId = positionRepository.selectPositionByAuthIds(rbmPositionsAuthIds).stream()
1422
                .collect(Collectors.groupingBy(Position::getAuthUserId));
1423
        LOGGER.info("RBM Call Target - Positions by AuthId fetch: {}ms", System.currentTimeMillis() - start);
1424
 
1425
        // Get all fofo IDs for all RBMs
1426
        Set<Integer> allFofoIds = new HashSet<>();
1427
        Map<Integer, List<Integer>> rbmToFofoIdsMap = new HashMap<>();
1428
        for (int rbmAuthId : rbmPositionsAuthIds) {
1429
            AuthUser au = authUserMap.get(rbmAuthId);
1430
            if (au != null && storeGuyMap.containsKey(au.getEmailId())) {
1431
                List<Integer> fofoIds = new ArrayList<>(storeGuyMap.get(au.getEmailId()));
1432
                allFofoIds.addAll(fofoIds);
1433
                rbmToFofoIdsMap.put(rbmAuthId, fofoIds);
1434
            }
1435
        }
35816 ranu 1436
        // Initialize L2 calling list map - will be populated after fetching remarks
35631 ranu 1437
        Map<Integer, List<Integer>> l2AuthIdToFofoIds = new HashMap<>();
35816 ranu 1438
        for (int l2AuthId : l2AuthIds) {
1439
            l2AuthIdToFofoIds.put(l2AuthId, new ArrayList<>());
35631 ranu 1440
        }
36210 ranu 1441
        // Initialize L3 calling list map - will be populated after fetching remarks
1442
        Map<Integer, List<Integer>> l3AuthIdToFofoIds = new HashMap<>();
1443
        for (int l3AuthId : l3AuthIds) {
1444
            l3AuthIdToFofoIds.put(l3AuthId, new ArrayList<>());
1445
        }
35631 ranu 1446
        LOGGER.info("RBM Call Target - Total fofo IDs to process: {}", allFofoIds.size());
1447
 
1448
        // Get only needed fofo stores (OPTIMIZED - was fetching ALL stores before)
1449
        start = System.currentTimeMillis();
1450
        Map<Integer, FofoStore> fofoStoresMap = new HashMap<>();
1451
        if (!allFofoIds.isEmpty()) {
1452
            try {
1453
                fofoStoresMap = fofoStoreRepository.selectByRetailerIds(new ArrayList<>(allFofoIds)).stream()
1454
                        .collect(Collectors.toMap(FofoStore::getId, x -> x, (a, b) -> a));
1455
            } catch (ProfitMandiBusinessException e) {
1456
                LOGGER.error("Error fetching fofo stores", e);
1457
            }
1458
        }
1459
        LOGGER.info("RBM Call Target - FofoStores fetch (only needed): {}ms, count: {}", System.currentTimeMillis() - start, fofoStoresMap.size());
1460
 
1461
        // Batch fetch max remark ids for all fofoIds (for escalation filtering)
1462
        start = System.currentTimeMillis();
1463
        Map<Integer, PartnerCollectionRemark> allPartnerCollectionRemarks = new HashMap<>();
1464
        if (!allFofoIds.isEmpty()) {
1465
            List<Integer> allRemarkIds = partnerCollectionRemarkRepository.selectMaxRemarkId(new ArrayList<>(allFofoIds));
1466
            if (!allRemarkIds.isEmpty()) {
1467
                allPartnerCollectionRemarks = partnerCollectionRemarkRepository.selectByIds(allRemarkIds).stream()
1468
                        .collect(Collectors.toMap(PartnerCollectionRemark::getFofoId, x -> x, (a, b) -> a));
1469
            }
1470
        }
1471
        LOGGER.info("RBM Call Target - PartnerCollectionRemarks fetch: {}ms", System.currentTimeMillis() - start);
1472
 
35816 ranu 1473
        // Populate L2 calling list based on partners whose latest remark is RBM_L2_ESCALATION
1474
        // Find the L1 who has the partner and add to that L1's manager (L2) calling list
1475
        for (Map.Entry<Integer, PartnerCollectionRemark> entry : allPartnerCollectionRemarks.entrySet()) {
1476
            Integer fofoId = entry.getKey();
1477
            PartnerCollectionRemark remark = entry.getValue();
1478
 
1479
            if (CollectionRemark.RBM_L2_ESCALATION.equals(remark.getRemark())) {
1480
                // Find which L1 RBM has this partner assigned
1481
                for (int l1AuthId : l1AuthIds) {
1482
                    List<Integer> l1FofoIds = rbmToFofoIdsMap.getOrDefault(l1AuthId, Collections.emptyList());
1483
                    if (l1FofoIds.contains(fofoId)) {
1484
                        // Get L1's manager (L2)
1485
                        AuthUser l1User = authUserMap.get(l1AuthId);
1486
                        if (l1User != null && l2AuthIdToFofoIds.containsKey(l1User.getManagerId())) {
1487
                            int l2ManagerId = l1User.getManagerId();
1488
                            l2AuthIdToFofoIds.get(l2ManagerId).add(fofoId);
1489
                        }
1490
                        break; // Found the L1 for this fofoId
1491
                    }
1492
                }
1493
            }
1494
        }
1495
        LOGGER.info("RBM Call Target - L2 calling lists populated from RBM_L2_ESCALATION remarks");
1496
 
36210 ranu 1497
        // Populate L3 calling list based on partners whose latest remark is RBM_L3_ESCALATION
36212 ranu 1498
        // Find the L1 who originally has the partner, then:
1499
        // Case 1: L1 -> L3 directly (if L1's manager IS L3)
1500
        // Case 2: L1 -> L2 -> L3 (if L1's manager is L2, then L2's manager is L3)
36210 ranu 1501
        for (Map.Entry<Integer, PartnerCollectionRemark> entry : allPartnerCollectionRemarks.entrySet()) {
1502
            Integer fofoId = entry.getKey();
1503
            PartnerCollectionRemark remark = entry.getValue();
1504
 
1505
            if (CollectionRemark.RBM_L3_ESCALATION.equals(remark.getRemark())) {
1506
                // Find which L1 RBM originally has this partner assigned
1507
                for (int l1AuthId : l1AuthIds) {
1508
                    List<Integer> l1FofoIds = rbmToFofoIdsMap.getOrDefault(l1AuthId, Collections.emptyList());
1509
                    if (l1FofoIds.contains(fofoId)) {
1510
                        AuthUser l1User = authUserMap.get(l1AuthId);
1511
                        if (l1User != null) {
36212 ranu 1512
                            int l1ManagerId = l1User.getManagerId();
1513
                            // Case 1: L1's manager IS L3 directly (L1 → L3, no L2 in between)
1514
                            if (l3AuthIdToFofoIds.containsKey(l1ManagerId)) {
1515
                                l3AuthIdToFofoIds.get(l1ManagerId).add(fofoId);
1516
                                LOGGER.debug("L3 Calling List (direct): fofoId={} -> L1={} -> L3={}",
1517
                                        fofoId, l1AuthId, l1ManagerId);
1518
                            } else {
1519
                                // Case 2: L1 -> L2 -> L3
1520
                                AuthUser l2User = authUserMap.get(l1ManagerId);
1521
                                if (l2User != null && l3AuthIdToFofoIds.containsKey(l2User.getManagerId())) {
1522
                                    int l3ManagerId = l2User.getManagerId();
1523
                                    l3AuthIdToFofoIds.get(l3ManagerId).add(fofoId);
1524
                                    LOGGER.debug("L3 Calling List: fofoId={} -> L1={} -> L2={} -> L3={}",
1525
                                            fofoId, l1AuthId, l1ManagerId, l3ManagerId);
1526
                                }
36210 ranu 1527
                            }
1528
                        }
1529
                        break; // Found the L1 for this fofoId
1530
                    }
1531
                }
1532
            }
1533
        }
1534
        LOGGER.info("RBM Call Target - L3 calling lists populated from RBM_L3_ESCALATION remarks");
1535
 
35631 ranu 1536
        // Batch fetch collection RANK map for all fofoIds (OPTIMIZED - only fetches rank, not full model)
1537
        start = System.currentTimeMillis();
1538
        Map<Integer, Integer> allCollectionRankMap = new HashMap<>();
1539
        if (!allFofoIds.isEmpty()) {
1540
            try {
1541
                allCollectionRankMap = partnerCollectionService.getCollectionRankMap(new ArrayList<>(allFofoIds), startDate);
1542
            } catch (ProfitMandiBusinessException e) {
1543
                LOGGER.error("Error fetching collection rank map for all fofoIds", e);
1544
            }
1545
        }
1546
        LOGGER.info("RBM Call Target - CollectionRankMap fetch (OPTIMIZED): {}ms", System.currentTimeMillis() - start);
1547
 
35669 ranu 1548
        // Get MTD billing data for zero billing calculation and partner counts
35631 ranu 1549
        start = System.currentTimeMillis();
1550
        List<RbmWeeklyBillingModel> mtdBillingData = getWeeklyBillingDataForMonth(firstOfMonth, endOfMonth);
1551
        Set<Integer> allMtdBilledFofoIds = mtdBillingData.stream()
1552
                .filter(RbmWeeklyBillingModel::isMtdBilled)
1553
                .map(RbmWeeklyBillingModel::getFofoId)
1554
                .collect(Collectors.toSet());
35669 ranu 1555
        // Build partner count and fofoIds per RBM from mtdBillingData (same source as Today ARR page)
1556
        Map<Integer, Set<Integer>> mtdFofoIdsByAuthId = mtdBillingData.stream()
1557
                .filter(RbmWeeklyBillingModel::isTargetedPartner)
1558
                .collect(Collectors.groupingBy(RbmWeeklyBillingModel::getAuthId,
1559
                        Collectors.mapping(RbmWeeklyBillingModel::getFofoId, Collectors.toSet())));
35631 ranu 1560
        LOGGER.info("RBM Call Target - MTD Billing fetch: {}ms", System.currentTimeMillis() - start);
1561
 
1562
        // Batch fetch today's remarks for all auth IDs (to calculate Value Achieved)
1563
        start = System.currentTimeMillis();
1564
        Map<Integer, List<PartnerCollectionRemark>> remarksByAuthId = partnerCollectionRemarkRepository
1565
                .selectAllByAuthIdsOnDate(rbmPositionsAuthIds, LocalDate.now()).stream()
1566
                .collect(Collectors.groupingBy(PartnerCollectionRemark::getAuthId));
1567
        LOGGER.info("RBM Call Target - Today Remarks fetch: {}ms", System.currentTimeMillis() - start);
1568
 
1569
        // Batch fetch today's out-of-sequence logs for all RBMs
1570
        start = System.currentTimeMillis();
1571
        LocalDateTime todayStart = LocalDate.now().atStartOfDay();
1572
        LocalDateTime todayEnd = LocalDate.now().plusDays(1).atStartOfDay();
1573
        List<RbmCallSequenceLog> outOfSequenceLogs = rbmCallSequenceLogRepository.selectOutOfSequenceByDateRange(todayStart, todayEnd);
1574
        Map<Integer, Long> outOfSequenceCountByAuthId = outOfSequenceLogs.stream()
35654 ranu 1575
                .collect(Collectors.groupingBy(RbmCallSequenceLog::getAuthId,
1576
                        Collectors.mapping(RbmCallSequenceLog::getFofoId, Collectors.collectingAndThen(Collectors.toSet(), s -> (long) s.size()))));
35631 ranu 1577
        LOGGER.info("RBM Call Target - Out of Sequence fetch: {}ms", System.currentTimeMillis() - start);
1578
 
36284 ranu 1579
        // BATCH FETCH: All call logs for all RBMs (L1 + L2 + L3) in a single query.
1580
        // Replaces the previous N+1 pattern where getCallStats() was called per RBM.
1581
        start = System.currentTimeMillis();
1582
        List<AgentCallLog> allCallLogs = agentCallLogRepository.findByAuthIdsAndDate(rbmPositionsAuthIds, queryDate);
1583
        Map<Long, List<AgentCallLog>> callLogsByAuthId = allCallLogs.stream()
1584
                .collect(Collectors.groupingBy(AgentCallLog::getAuthId));
1585
        LOGGER.info("RBM Call Target - Call logs batch fetch: {}ms ({} logs across {} RBMs)",
1586
                System.currentTimeMillis() - start, allCallLogs.size(), callLogsByAuthId.size());
1587
 
1588
        // BATCH FETCH: Build a single mobile -> fofoId map from all unique customer numbers across all call logs.
1589
        // Replaces the previous N+1 pattern where findFofoIdByMobile() was called per call log entry.
1590
        start = System.currentTimeMillis();
1591
        Set<String> allNormalizedMobiles = new HashSet<>();
1592
        for (AgentCallLog callLog : allCallLogs) {
1593
            String customerNumber = callLog.getCustomerNumber();
1594
            if (customerNumber != null) {
1595
                String normalized = customerNumber.startsWith("+91") ? customerNumber.substring(3) : customerNumber;
1596
                allNormalizedMobiles.add(normalized);
1597
            }
1598
        }
1599
        Map<String, Integer> mobileToFofoIdMap = buildMobileToFofoIdMap(allNormalizedMobiles);
1600
        LOGGER.info("RBM Call Target - Mobile→FofoId batch fetch: {}ms ({} unique mobiles, {} mapped)",
1601
                System.currentTimeMillis() - start, allNormalizedMobiles.size(), mobileToFofoIdMap.size());
1602
 
36225 ranu 1603
        // Identify users who are both L1 and L2 — they will be shown only as L2
1604
        Set<Integer> l2AuthIdSet = new HashSet<>(l2AuthIds);
1605
 
1606
        // Process L1 RBMs (skip users who are also L2 — their data will be merged into L2 model)
35631 ranu 1607
        for (int rbmAuthId : l1AuthIds) {
36225 ranu 1608
            if (l2AuthIdSet.contains(rbmAuthId)) {
1609
                continue; // Will be handled in L2 processing with merged L1 data
1610
            }
35631 ranu 1611
            AuthUser authUser = authUserMap.get(rbmAuthId);
1612
            if (authUser == null || !storeGuyMap.containsKey(authUser.getEmailId())) {
1613
                continue;
1614
            }
1615
 
1616
            List<Integer> fofoIdList = rbmToFofoIdsMap.getOrDefault(rbmAuthId, Collections.emptyList());
1617
 
1618
            // Check if RBM is L1 (same logic as getSummaryModel)
1619
            List<Position> positions = positionsByAuthId.getOrDefault(authUser.getId(), Collections.emptyList());
1620
            boolean isRBMAndL1 = positions.stream()
1621
                    .anyMatch(position ->
1622
                            ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId()
1623
                                    && EscalationType.L1.equals(position.getEscalationType()));
1624
 
1625
            // Filter escalated partners for L1 RBMs (same logic as getSummaryModel)
1626
            List<Integer> fofoIds = fofoIdList;
1627
            if (isRBMAndL1) {
1628
                Map<Integer, PartnerCollectionRemark> partnerCollectionRemarks = new HashMap<>();
1629
                for (Integer fofoId : fofoIdList) {
1630
                    if (allPartnerCollectionRemarks.containsKey(fofoId)) {
1631
                        partnerCollectionRemarks.put(fofoId, allPartnerCollectionRemarks.get(fofoId));
1632
                    }
1633
                }
1634
                fofoIds = partnerCollectionRemarks.entrySet().stream()
1635
                        .filter(entry -> {
1636
                            PartnerCollectionRemark pcrMap = entry.getValue();
1637
                            return !(CollectionRemark.RBM_L2_ESCALATION.equals(pcrMap.getRemark())
1638
                                    || CollectionRemark.SALES_ESCALATION.equals(pcrMap.getRemark()));
1639
                        })
1640
                        .map(Map.Entry::getKey)
1641
                        .collect(Collectors.toList());
1642
            }
1643
 
36181 ranu 1644
            // Filter to only external, ACTIVE or REVIVAL stores (collection plan not required)
35631 ranu 1645
            Map<Integer, Integer> finalAllCollectionRankMap = allCollectionRankMap;
1646
            Map<Integer, FofoStore> finalFofoStoresMap = fofoStoresMap;
1647
            List<Integer> validFofoIds = fofoIds.stream()
1648
                    .filter(fofoId -> {
1649
                        FofoStore store = finalFofoStoresMap.get(fofoId);
1650
                        if (store == null || store.isInternal()) {
1651
                            return false;
1652
                        }
36181 ranu 1653
                        // Only include ACTIVE or REVIVAL partners (not Low Sale, not Disputed, not Billing Pending)
1654
                        return ActivationType.ACTIVE.equals(store.getActivationType())
1655
                                || ActivationType.REVIVAL.equals(store.getActivationType());
35631 ranu 1656
                    })
1657
                    .collect(Collectors.toList());
1658
 
1659
            if (validFofoIds.isEmpty()) {
1660
                continue;
1661
            }
1662
 
1663
            RbmCallTargetModel targetModel = new RbmCallTargetModel();
1664
            targetModel.setAuthId(rbmAuthId);
1665
            targetModel.setRbmName(authUser.getFullName());
35669 ranu 1666
            // Use partner count from mtdBillingData (same source as Today ARR page)
1667
            Set<Integer> mtdFofoIds = mtdFofoIdsByAuthId.getOrDefault(rbmAuthId, Collections.emptySet());
1668
            targetModel.setPartnerCount(mtdFofoIds.size());
35631 ranu 1669
 
1670
            // Categorize each partner - each partner belongs to ONE category only
35665 ranu 1671
            // Priority: PlanToday > CarryForward > ZeroBilling > Untouched > FuturePlan > Normal
36181 ranu 1672
            // Revival is counted separately (just for display, doesn't affect categorization)
35631 ranu 1673
            Set<Integer> planTodayPartners = new HashSet<>();
1674
            Set<Integer> carryForwardPartners = new HashSet<>();
1675
            Set<Integer> untouchedPartners = new HashSet<>();
1676
            Set<Integer> zeroBillingPartners = new HashSet<>();
1677
            Set<Integer> futurePlanPartners = new HashSet<>();
1678
            Set<Integer> normalPartners = new HashSet<>();
36181 ranu 1679
            Set<Integer> revivalPartners = new HashSet<>();
35631 ranu 1680
 
1681
            for (Integer fofoId : validFofoIds) {
1682
                // Get collection plan rank (from optimized rank map)
1683
                int rank = allCollectionRankMap.getOrDefault(fofoId, 5); // default to Normal if no plan
1684
 
1685
                // Check if partner has zero billing in MTD
1686
                boolean hasZeroBilling = !allMtdBilledFofoIds.contains(fofoId);
1687
 
36181 ranu 1688
                // Count REVIVAL partners separately (just for display, doesn't affect categorization)
1689
                FofoStore store = finalFofoStoresMap.get(fofoId);
1690
                if (store != null && ActivationType.REVIVAL.equals(store.getActivationType())) {
1691
                    revivalPartners.add(fofoId);
1692
                }
1693
 
35631 ranu 1694
                // Assign to category based on priority
1695
                if (rank == 1) {
1696
                    planTodayPartners.add(fofoId);
1697
                } else if (rank == 2) {
1698
                    carryForwardPartners.add(fofoId);
35665 ranu 1699
                } else if (hasZeroBilling) {
1700
                    zeroBillingPartners.add(fofoId);
35631 ranu 1701
                } else if (rank == 3) {
1702
                    untouchedPartners.add(fofoId);
1703
                } else if (rank == 4) {
1704
                    futurePlanPartners.add(fofoId);
1705
                } else {
1706
                    normalPartners.add(fofoId);
1707
                }
1708
            }
1709
 
1710
            // Set counts
1711
            targetModel.setCreditCollection(0); // Credit collection is handled in separate list
1712
            targetModel.setPlanToday(planTodayPartners.size());
1713
            targetModel.setCarryForward(carryForwardPartners.size());
1714
            targetModel.setUntouched(untouchedPartners.size());
1715
            targetModel.setZeroBilling(zeroBillingPartners.size());
1716
            targetModel.setFuturePlan(futurePlanPartners.size());
1717
            targetModel.setNormal(normalPartners.size());
36181 ranu 1718
            targetModel.setRevival(revivalPartners.size());
35631 ranu 1719
 
1720
            // Today Target = PlanToday + CarryForward + ZeroBilling + Untouched
1721
            // These are mutually exclusive now, so we can sum them
1722
            long todayTarget = planTodayPartners.size() +
1723
                    carryForwardPartners.size() + zeroBillingPartners.size() + untouchedPartners.size();
1724
            targetModel.setTodayTargetOfCall(todayTarget);
1725
 
1726
            // Create set of partners in Today Target categories
1727
            Set<Integer> todayTargetPartners = new HashSet<>();
1728
            todayTargetPartners.addAll(planTodayPartners);
1729
            todayTargetPartners.addAll(carryForwardPartners);
1730
            todayTargetPartners.addAll(zeroBillingPartners);
1731
            todayTargetPartners.addAll(untouchedPartners);
1732
 
36284 ranu 1733
            // Value Achieved = All distinct partners called today (from pre-fetched call logs)
37010 ranu 1734
            List<AgentCallLog> l1Logs = callLogsByAuthId.get((long) rbmAuthId);
1735
            long[] callStats = getCallStatsFromLogs(l1Logs, mobileToFofoIdMap);
36276 ranu 1736
            targetModel.setValueTargetAchieved(callStats[0]);
1737
            targetModel.setTotalRecordingCalls(callStats[1]);
1738
            targetModel.setUniqueRecordingCalls(callStats[2]);
37022 ranu 1739
            targetModel.setTriedUniqueCalls(computeUniqueTriedCount(l1Logs, mobileToFofoIdMap));
1740
            targetModel.setTgtCalls(computeUniqueTriedCountForTargets(l1Logs, mobileToFofoIdMap, todayTargetPartners));
35631 ranu 1741
 
37012 ranu 1742
            // Keep todayRemarks for movedToFuture calculation
35843 ranu 1743
            List<PartnerCollectionRemark> todayRemarks = remarksByAuthId.getOrDefault(rbmAuthId, Collections.emptyList());
1744
 
35631 ranu 1745
            // Moved to Future = Partners in Future Plan category who have a remark today
1746
            // These are partners who were contacted today but moved to a future date
1747
            Set<Integer> todayRemarkedFofoIds = todayRemarks.stream()
1748
                    .map(PartnerCollectionRemark::getFofoId)
1749
                    .collect(Collectors.toSet());
1750
            long movedToFuture = futurePlanPartners.stream()
1751
                    .filter(todayRemarkedFofoIds::contains)
1752
                    .count();
1753
            targetModel.setMovedToFuture(movedToFuture);
1754
 
1755
            // Set out of sequence count for this RBM
1756
            targetModel.setOutOfSequenceCount(outOfSequenceCountByAuthId.getOrDefault(rbmAuthId, 0L));
1757
 
1758
            rbmCallTargetModels.add(targetModel);
1759
        }
1760
 
1761
        // Process L2 RBMs (escalated ticket logic with categorization)
36225 ranu 1762
        // For users who are both L1 and L2, merge their L1 calling target into L2 model
35631 ranu 1763
        for (int l2AuthId : l2AuthIds) {
1764
            AuthUser authUser = authUserMap.get(l2AuthId);
1765
            if (authUser == null) {
1766
                continue;
1767
            }
1768
 
1769
            List<Integer> l2FofoIdList = l2AuthIdToFofoIds.getOrDefault(l2AuthId, Collections.emptyList());
1770
 
35816 ranu 1771
            // For L2, use unique fofoIds with RBM_L2_ESCALATION remark as target
35662 ranu 1772
            Set<Integer> l2TargetFofoIds = new HashSet<>(l2FofoIdList);
35631 ranu 1773
 
37022 ranu 1774
            // Collected from the L1-merge branch below when the user is also L1. Used later
1775
            // for the TGT Calls scope: L2 escalation + L1 target buckets.
1776
            Set<Integer> l1MergedTargetPartners = new HashSet<>();
1777
 
35631 ranu 1778
            RbmCallTargetModel l2Model = new RbmCallTargetModel();
1779
            l2Model.setAuthId(l2AuthId);
1780
            l2Model.setRbmName(authUser.getFullName() + " (L2)");
1781
            l2Model.setL2Position(true);
35816 ranu 1782
            l2Model.setL2CallingList(l2TargetFofoIds.size());
36228 ranu 1783
            // Partner count: if user is also L1, use L1 partner count (MTD targeted partners)
1784
            if (l1AuthIds.contains(l2AuthId)) {
1785
                Set<Integer> mtdFofoIds = mtdFofoIdsByAuthId.getOrDefault(l2AuthId, Collections.emptySet());
1786
                l2Model.setPartnerCount(mtdFofoIds.size());
1787
            } else {
1788
                List<Integer> l2AssignedFofoIds = rbmToFofoIdsMap.getOrDefault(l2AuthId, Collections.emptyList());
1789
                l2Model.setPartnerCount(l2AssignedFofoIds.size());
1790
            }
35631 ranu 1791
 
36229 ranu 1792
            // If user is also L1, calculate full L1 breakdown and merge into L2 model
36225 ranu 1793
            if (l1AuthIds.contains(l2AuthId) && storeGuyMap.containsKey(authUser.getEmailId())) {
36229 ranu 1794
                // Get only L1 RBM position partners (not L2 partners) from partner_position
36225 ranu 1795
                List<Position> positions = positionsByAuthId.getOrDefault(l2AuthId, Collections.emptyList());
36229 ranu 1796
                Set<Integer> l1RbmPositionIds = positions.stream()
1797
                        .filter(p -> ProfitMandiConstants.TICKET_CATEGORY_RBM == p.getCategoryId()
1798
                                && EscalationType.L1.equals(p.getEscalationType()))
1799
                        .map(Position::getId)
1800
                        .collect(Collectors.toSet());
1801
                // Fetch partner_position for only L1 RBM positions of this user
1802
                List<Integer> fofoIdList = partnerPositionRepository
1803
                        .selectByPositionIds(new ArrayList<>(l1RbmPositionIds)).stream()
1804
                        .map(pp -> pp.getFofoId())
1805
                        .distinct()
1806
                        .collect(Collectors.toList());
1807
                boolean isRBMAndL1 = !l1RbmPositionIds.isEmpty();
36225 ranu 1808
                List<Integer> l1FofoIds = new ArrayList<>(fofoIdList);
1809
                if (isRBMAndL1) {
1810
                    Map<Integer, PartnerCollectionRemark> partnerCollectionRemarks = new HashMap<>();
1811
                    for (Integer fofoId : fofoIdList) {
1812
                        if (allPartnerCollectionRemarks.containsKey(fofoId)) {
1813
                            partnerCollectionRemarks.put(fofoId, allPartnerCollectionRemarks.get(fofoId));
1814
                        }
1815
                    }
1816
                    l1FofoIds = partnerCollectionRemarks.entrySet().stream()
1817
                            .filter(entry -> {
1818
                                PartnerCollectionRemark pcrMap = entry.getValue();
1819
                                return !(CollectionRemark.RBM_L2_ESCALATION.equals(pcrMap.getRemark())
1820
                                        || CollectionRemark.SALES_ESCALATION.equals(pcrMap.getRemark()));
1821
                            })
1822
                            .map(Map.Entry::getKey)
1823
                            .collect(Collectors.toList());
1824
                }
1825
                Map<Integer, FofoStore> finalFofoStoresMap2 = fofoStoresMap;
1826
                List<Integer> validL1FofoIds = l1FofoIds.stream()
1827
                        .filter(fofoId -> {
1828
                            FofoStore store = finalFofoStoresMap2.get(fofoId);
1829
                            if (store == null || store.isInternal()) return false;
1830
                            return ActivationType.ACTIVE.equals(store.getActivationType())
1831
                                    || ActivationType.REVIVAL.equals(store.getActivationType());
1832
                        })
1833
                        .collect(Collectors.toList());
35631 ranu 1834
 
36229 ranu 1835
                // Categorize L1 partners — same logic as L1 processing
1836
                Set<Integer> planTodayPartners = new HashSet<>();
1837
                Set<Integer> carryForwardPartners = new HashSet<>();
1838
                Set<Integer> untouchedPartners = new HashSet<>();
1839
                Set<Integer> zeroBillingPartners = new HashSet<>();
1840
                Set<Integer> futurePlanPartners = new HashSet<>();
1841
                Set<Integer> normalPartners = new HashSet<>();
1842
                Set<Integer> revivalPartners = new HashSet<>();
1843
 
36225 ranu 1844
                for (Integer fofoId : validL1FofoIds) {
1845
                    int rank = allCollectionRankMap.getOrDefault(fofoId, 5);
1846
                    boolean hasZeroBilling = !allMtdBilledFofoIds.contains(fofoId);
36229 ranu 1847
                    FofoStore store = finalFofoStoresMap2.get(fofoId);
1848
                    if (store != null && ActivationType.REVIVAL.equals(store.getActivationType())) {
1849
                        revivalPartners.add(fofoId);
36225 ranu 1850
                    }
36229 ranu 1851
                    if (rank == 1) {
1852
                        planTodayPartners.add(fofoId);
1853
                    } else if (rank == 2) {
1854
                        carryForwardPartners.add(fofoId);
1855
                    } else if (hasZeroBilling) {
1856
                        zeroBillingPartners.add(fofoId);
1857
                    } else if (rank == 3) {
1858
                        untouchedPartners.add(fofoId);
1859
                    } else if (rank == 4) {
1860
                        futurePlanPartners.add(fofoId);
1861
                    } else {
1862
                        normalPartners.add(fofoId);
1863
                    }
36225 ranu 1864
                }
36229 ranu 1865
 
1866
                // Set L1 breakdown fields on L2 model
1867
                l2Model.setPlanToday(planTodayPartners.size());
1868
                l2Model.setCarryForward(carryForwardPartners.size());
1869
                l2Model.setZeroBilling(zeroBillingPartners.size());
1870
                l2Model.setUntouched(untouchedPartners.size());
1871
                l2Model.setFuturePlan(futurePlanPartners.size());
1872
                l2Model.setNormal(normalPartners.size());
1873
                l2Model.setRevival(revivalPartners.size());
1874
 
1875
                long l1OwnTarget = planTodayPartners.size() + carryForwardPartners.size()
1876
                        + zeroBillingPartners.size() + untouchedPartners.size();
1877
 
37022 ranu 1878
                // Feed the L1 target sets up to the outer scope so TGT Calls can include them.
1879
                l1MergedTargetPartners.addAll(planTodayPartners);
1880
                l1MergedTargetPartners.addAll(carryForwardPartners);
1881
                l1MergedTargetPartners.addAll(zeroBillingPartners);
1882
                l1MergedTargetPartners.addAll(untouchedPartners);
1883
 
36229 ranu 1884
                // Today Target = own L1 target + L2 escalation
1885
                l2Model.setTodayTargetOfCall(l2TargetFofoIds.size() + l1OwnTarget);
1886
 
1887
                // Moved to Future from L1 partners
1888
                List<PartnerCollectionRemark> todayRemarks = remarksByAuthId.getOrDefault(l2AuthId, Collections.emptyList());
1889
                Set<Integer> todayRemarkedFofoIds = todayRemarks.stream()
1890
                        .map(PartnerCollectionRemark::getFofoId)
1891
                        .collect(Collectors.toSet());
1892
                long movedToFuture = futurePlanPartners.stream()
1893
                        .filter(todayRemarkedFofoIds::contains)
1894
                        .count();
1895
                l2Model.setMovedToFuture(movedToFuture);
1896
            } else {
1897
                // Pure L2 (not also L1) — target is only L2 escalation
1898
                l2Model.setTodayTargetOfCall(l2TargetFofoIds.size());
36225 ranu 1899
            }
1900
 
36284 ranu 1901
            // Value Achieved = All distinct partners called today (from pre-fetched call logs)
37010 ranu 1902
            List<AgentCallLog> l2Logs = callLogsByAuthId.get((long) l2AuthId);
1903
            long[] l2CallStats = getCallStatsFromLogs(l2Logs, mobileToFofoIdMap);
36276 ranu 1904
            l2Model.setValueTargetAchieved(l2CallStats[0]);
1905
            l2Model.setTotalRecordingCalls(l2CallStats[1]);
1906
            l2Model.setUniqueRecordingCalls(l2CallStats[2]);
37022 ranu 1907
            l2Model.setTriedUniqueCalls(computeUniqueTriedCount(l2Logs, mobileToFofoIdMap));
35631 ranu 1908
 
37022 ranu 1909
            // TGT Calls scope: L2 escalation + (if user is also L1) the L1 target buckets.
1910
            Set<Integer> l2TgtSet = new HashSet<>(l2TargetFofoIds);
1911
            l2TgtSet.addAll(l1MergedTargetPartners);
1912
            l2Model.setTgtCalls(computeUniqueTriedCountForTargets(l2Logs, mobileToFofoIdMap, l2TgtSet));
1913
 
35631 ranu 1914
            l2Model.setOutOfSequenceCount(outOfSequenceCountByAuthId.getOrDefault(l2AuthId, 0L));
1915
            rbmCallTargetModels.add(l2Model);
1916
        }
1917
 
36210 ranu 1918
        // Process L3 RBMs (escalated ticket logic with categorization)
1919
        for (int l3AuthId : l3AuthIds) {
1920
            AuthUser authUser = authUserMap.get(l3AuthId);
1921
            if (authUser == null) {
1922
                continue;
1923
            }
1924
 
1925
            List<Integer> l3FofoIdList = l3AuthIdToFofoIds.getOrDefault(l3AuthId, Collections.emptyList());
1926
 
1927
            // For L3, use unique fofoIds with RBM_L3_ESCALATION remark as target
1928
            Set<Integer> l3TargetFofoIds = new HashSet<>(l3FofoIdList);
1929
 
1930
            RbmCallTargetModel l3Model = new RbmCallTargetModel();
1931
            l3Model.setAuthId(l3AuthId);
1932
            l3Model.setRbmName(authUser.getFullName() + " (L3)");
1933
            l3Model.setL3Position(true);
1934
            l3Model.setL3CallingList(l3TargetFofoIds.size());
36359 ranu 1935
            // Partner count = total assigned partners (excluding internal)
1936
            Map<Integer, FofoStore> finalFofoStoresMapL3 = fofoStoresMap;
36210 ranu 1937
            List<Integer> l3AssignedFofoIds = rbmToFofoIdsMap.getOrDefault(l3AuthId, Collections.emptyList());
36359 ranu 1938
            long l3ExternalPartnerCount = l3AssignedFofoIds.stream()
1939
                    .filter(fofoId -> {
1940
                        FofoStore store = finalFofoStoresMapL3.get(fofoId);
1941
                        return store != null && !store.isInternal();
1942
                    })
1943
                    .count();
1944
            l3Model.setPartnerCount(l3ExternalPartnerCount);
36210 ranu 1945
 
1946
            // L3 Target = partners with RBM_L3_ESCALATION as latest remark
1947
            l3Model.setTodayTargetOfCall(l3TargetFofoIds.size());
1948
 
36284 ranu 1949
            // Value Achieved = All distinct partners called today (from pre-fetched call logs)
37010 ranu 1950
            List<AgentCallLog> l3Logs = callLogsByAuthId.get((long) l3AuthId);
1951
            long[] l3CallStats = getCallStatsFromLogs(l3Logs, mobileToFofoIdMap);
36276 ranu 1952
            l3Model.setValueTargetAchieved(l3CallStats[0]);
1953
            l3Model.setTotalRecordingCalls(l3CallStats[1]);
1954
            l3Model.setUniqueRecordingCalls(l3CallStats[2]);
37022 ranu 1955
            l3Model.setTriedUniqueCalls(computeUniqueTriedCount(l3Logs, mobileToFofoIdMap));
1956
            // L3 TGT Calls scope: L3 escalation partners.
1957
            l3Model.setTgtCalls(computeUniqueTriedCountForTargets(l3Logs, mobileToFofoIdMap, l3TargetFofoIds));
36210 ranu 1958
 
1959
            l3Model.setOutOfSequenceCount(outOfSequenceCountByAuthId.getOrDefault(l3AuthId, 0L));
1960
            rbmCallTargetModels.add(l3Model);
1961
        }
1962
 
36225 ranu 1963
        // Group models by escalation level
36210 ranu 1964
        Map<Integer, RbmCallTargetModel> l3ModelsByAuthId = new HashMap<>();
35631 ranu 1965
        Map<Integer, RbmCallTargetModel> l2ModelsByAuthId = new HashMap<>();
1966
        Map<Integer, RbmCallTargetModel> l1ModelsByAuthId = new HashMap<>();
1967
        for (RbmCallTargetModel m : rbmCallTargetModels) {
36210 ranu 1968
            if (m.isL3Position()) {
1969
                l3ModelsByAuthId.put(m.getAuthId(), m);
1970
            } else if (m.isL2Position()) {
35631 ranu 1971
                l2ModelsByAuthId.put(m.getAuthId(), m);
1972
            } else {
1973
                l1ModelsByAuthId.put(m.getAuthId(), m);
1974
            }
1975
        }
1976
 
36225 ranu 1977
        // Build partner-based hierarchy using partner_position table
1978
        // Map positionId -> Position for quick lookup
1979
        Map<Integer, Position> positionByIdMap = allRbmPositions.stream()
1980
                .collect(Collectors.toMap(Position::getId, p -> p, (a, b) -> a));
1981
 
1982
        // Get all RBM position IDs and fetch their partner assignments
1983
        List<Integer> allRbmPositionIds = allRbmPositions.stream()
1984
                .map(Position::getId).collect(Collectors.toList());
1985
        List<com.spice.profitmandi.dao.entity.cs.PartnerPosition> allPartnerPositions =
1986
                partnerPositionRepository.selectByPositionIds(allRbmPositionIds);
1987
 
1988
        // Build partnerId -> map of escalationType -> Set<authUserIds>
1989
        // This tells us for each partner, who is their L1, L2, L3
1990
        Map<Integer, Map<EscalationType, Set<Integer>>> partnerToAuthByLevel = new HashMap<>();
1991
        for (com.spice.profitmandi.dao.entity.cs.PartnerPosition pp : allPartnerPositions) {
1992
            Position pos = positionByIdMap.get(pp.getPositionId());
1993
            if (pos != null && pos.getEscalationType() != null) {
1994
                partnerToAuthByLevel
1995
                        .computeIfAbsent(pp.getFofoId(), k -> new HashMap<>())
1996
                        .computeIfAbsent(pos.getEscalationType(), k -> new HashSet<>())
1997
                        .add(pos.getAuthUserId());
1998
            }
1999
        }
2000
 
2001
        // Build L2 -> L1 team map based on shared partners
2002
        // If an L1 and L2 share partners (L1 at L1 level, L2 at L2 level), that L1 belongs under that L2
2003
        Map<Integer, List<RbmCallTargetModel>> l2TeamMap = new LinkedHashMap<>();
2004
        for (RbmCallTargetModel l2Model : l2ModelsByAuthId.values()) {
2005
            l2TeamMap.put(l2Model.getAuthId(), new ArrayList<>());
2006
        }
2007
 
2008
        // Build L3 -> L2 team map based on shared partners
36210 ranu 2009
        Map<Integer, List<RbmCallTargetModel>> l3TeamMap = new LinkedHashMap<>();
2010
        for (RbmCallTargetModel l3Model : l3ModelsByAuthId.values()) {
2011
            l3TeamMap.put(l3Model.getAuthId(), new ArrayList<>());
2012
        }
2013
 
36225 ranu 2014
        // For each L1, find which L2 shares the most partners -> that's their L2
2015
        Set<Integer> addedL1AuthIds = new HashSet<>();
2016
        for (RbmCallTargetModel l1Model : l1ModelsByAuthId.values()) {
2017
            Map<Integer, Integer> l2SharedCount = new HashMap<>(); // l2AuthId -> shared partner count
2018
            for (Map.Entry<Integer, Map<EscalationType, Set<Integer>>> entry : partnerToAuthByLevel.entrySet()) {
2019
                Map<EscalationType, Set<Integer>> levelMap = entry.getValue();
2020
                Set<Integer> l1IdsForPartner = levelMap.getOrDefault(EscalationType.L1, Collections.emptySet());
2021
                Set<Integer> l2AuthIdsForPartner = levelMap.getOrDefault(EscalationType.L2, Collections.emptySet());
2022
                if (l1IdsForPartner.contains(l1Model.getAuthId())) {
2023
                    for (int l2Id : l2AuthIdsForPartner) {
2024
                        if (l2ModelsByAuthId.containsKey(l2Id) && l2Id != l1Model.getAuthId()) {
2025
                            l2SharedCount.merge(l2Id, 1, Integer::sum);
2026
                        }
2027
                    }
2028
                }
2029
            }
2030
            // Assign L1 to the L2 with most shared partners
2031
            if (!l2SharedCount.isEmpty()) {
2032
                int bestL2 = l2SharedCount.entrySet().stream()
2033
                        .max(Map.Entry.comparingByValue()).get().getKey();
2034
                l2TeamMap.get(bestL2).add(l1Model);
2035
                addedL1AuthIds.add(l1Model.getAuthId());
2036
            }
2037
        }
2038
 
2039
        // For each L2, find which L3 shares the most partners -> that's their L3
36210 ranu 2040
        Set<Integer> addedL2AuthIds = new HashSet<>();
2041
        for (RbmCallTargetModel l2Model : l2ModelsByAuthId.values()) {
36225 ranu 2042
            Map<Integer, Integer> l3SharedCount = new HashMap<>();
2043
            for (Map.Entry<Integer, Map<EscalationType, Set<Integer>>> entry : partnerToAuthByLevel.entrySet()) {
2044
                Map<EscalationType, Set<Integer>> levelMap = entry.getValue();
2045
                Set<Integer> l2AuthIdsForPartner = levelMap.getOrDefault(EscalationType.L2, Collections.emptySet());
2046
                Set<Integer> l3AuthIdsForPartner = levelMap.getOrDefault(EscalationType.L3, Collections.emptySet());
2047
                if (l2AuthIdsForPartner.contains(l2Model.getAuthId())) {
2048
                    for (int l3Id : l3AuthIdsForPartner) {
2049
                        if (l3ModelsByAuthId.containsKey(l3Id)) {
2050
                            l3SharedCount.merge(l3Id, 1, Integer::sum);
2051
                        }
2052
                    }
2053
                }
2054
            }
2055
            if (!l3SharedCount.isEmpty()) {
2056
                int bestL3 = l3SharedCount.entrySet().stream()
2057
                        .max(Map.Entry.comparingByValue()).get().getKey();
2058
                l3TeamMap.get(bestL3).add(l2Model);
36210 ranu 2059
                addedL2AuthIds.add(l2Model.getAuthId());
2060
            }
2061
        }
2062
 
36225 ranu 2063
        // For L1s not mapped to any L2, check if they map directly to an L3 via shared partners
2064
        Map<Integer, List<RbmCallTargetModel>> l3DirectL1Map = new LinkedHashMap<>();
2065
        for (RbmCallTargetModel l3Model : l3ModelsByAuthId.values()) {
2066
            l3DirectL1Map.put(l3Model.getAuthId(), new ArrayList<>());
35631 ranu 2067
        }
2068
        for (RbmCallTargetModel l1Model : l1ModelsByAuthId.values()) {
36225 ranu 2069
            if (addedL1AuthIds.contains(l1Model.getAuthId())) continue;
2070
            Map<Integer, Integer> l3SharedCount = new HashMap<>();
2071
            for (Map.Entry<Integer, Map<EscalationType, Set<Integer>>> entry : partnerToAuthByLevel.entrySet()) {
2072
                Map<EscalationType, Set<Integer>> levelMap = entry.getValue();
2073
                Set<Integer> l1IdsForPartner = levelMap.getOrDefault(EscalationType.L1, Collections.emptySet());
2074
                Set<Integer> l3AuthIdsForPartner = levelMap.getOrDefault(EscalationType.L3, Collections.emptySet());
2075
                if (l1IdsForPartner.contains(l1Model.getAuthId())) {
2076
                    for (int l3Id : l3AuthIdsForPartner) {
2077
                        if (l3ModelsByAuthId.containsKey(l3Id)) {
2078
                            l3SharedCount.merge(l3Id, 1, Integer::sum);
2079
                        }
2080
                    }
2081
                }
2082
            }
2083
            if (!l3SharedCount.isEmpty()) {
2084
                int bestL3 = l3SharedCount.entrySet().stream()
2085
                        .max(Map.Entry.comparingByValue()).get().getKey();
2086
                l3DirectL1Map.get(bestL3).add(l1Model);
35631 ranu 2087
                addedL1AuthIds.add(l1Model.getAuthId());
2088
            }
2089
        }
2090
 
36225 ranu 2091
        // Build sorted result: L3 -> L2 -> L1 (with direct L1s under L3 if no L2)
35631 ranu 2092
        List<RbmCallTargetModel> sortedModels = new ArrayList<>();
2093
 
36210 ranu 2094
        List<RbmCallTargetModel> l3Sorted = new ArrayList<>(l3ModelsByAuthId.values());
2095
        l3Sorted.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
35631 ranu 2096
 
36210 ranu 2097
        for (RbmCallTargetModel l3Model : l3Sorted) {
2098
            sortedModels.add(l3Model);
2099
            List<RbmCallTargetModel> l2Team = l3TeamMap.getOrDefault(l3Model.getAuthId(), Collections.emptyList());
2100
            l2Team.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
2101
            for (RbmCallTargetModel l2Model : l2Team) {
2102
                sortedModels.add(l2Model);
2103
                List<RbmCallTargetModel> l1Team = l2TeamMap.getOrDefault(l2Model.getAuthId(), Collections.emptyList());
2104
                l1Team.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
2105
                sortedModels.addAll(l1Team);
2106
            }
36225 ranu 2107
            // Add L1s that report directly to this L3 (no L2 in between)
2108
            List<RbmCallTargetModel> directL1Team = l3DirectL1Map.getOrDefault(l3Model.getAuthId(), Collections.emptyList());
2109
            directL1Team.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
2110
            sortedModels.addAll(directL1Team);
36210 ranu 2111
        }
2112
 
36225 ranu 2113
        // Add L2s not mapped to any L3
36210 ranu 2114
        List<RbmCallTargetModel> unmappedL2 = new ArrayList<>();
2115
        for (RbmCallTargetModel l2Model : l2ModelsByAuthId.values()) {
2116
            if (!addedL2AuthIds.contains(l2Model.getAuthId())) {
2117
                unmappedL2.add(l2Model);
2118
            }
2119
        }
2120
        unmappedL2.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
2121
        for (RbmCallTargetModel l2Model : unmappedL2) {
35631 ranu 2122
            sortedModels.add(l2Model);
2123
            List<RbmCallTargetModel> team = l2TeamMap.getOrDefault(l2Model.getAuthId(), Collections.emptyList());
2124
            team.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
2125
            sortedModels.addAll(team);
2126
        }
2127
 
36225 ranu 2128
        // Add any L1s not mapped to any L2 or L3
35631 ranu 2129
        List<RbmCallTargetModel> unmappedL1 = new ArrayList<>();
2130
        for (RbmCallTargetModel m : l1ModelsByAuthId.values()) {
2131
            if (!addedL1AuthIds.contains(m.getAuthId())) {
2132
                unmappedL1.add(m);
2133
            }
2134
        }
2135
        unmappedL1.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
2136
        sortedModels.addAll(unmappedL1);
2137
 
2138
        LOGGER.info("RBM Call Target - TOTAL TIME: {}ms, RBM count: {}", System.currentTimeMillis() - methodStart, sortedModels.size());
2139
        return sortedModels;
2140
    }
2141
 
35843 ranu 2142
    /**
37011 ranu 2143
     * Rule: count each distinct customer number this RBM attempted today, based on
37012 ranu 2144
     * the vendor-reported customer-side outcome (AgentCallLog.customerStatus):
2145
     *   - If ANY call to this number has customerStatus that is not "Missed"
2146
     *     → count as 1 (customer was reached at some point).
2147
     *   - Else (every call to this number was Missed) → count only if attempts >= 3
37011 ranu 2148
     *     (persistence credit).
37012 ranu 2149
     * null/empty customerStatus is treated as "not Missed" (favours counting when
2150
     * the vendor didn't classify the outcome).
35843 ranu 2151
     */
37022 ranu 2152
    private long computeUniqueTriedCount(List<AgentCallLog> callLogs,
2153
                                         Map<String, Integer> mobileToFofoIdMap) {
37010 ranu 2154
        if (callLogs == null || callLogs.isEmpty()) return 0L;
37022 ranu 2155
        // Group by fofoId (not raw number) — numbers that don't resolve to a partner via
2156
        // retailer_contact/address are skipped. Once a number gets added to retailer_contact
2157
        // it'll automatically resolve and start counting on the next page load.
2158
        Map<Integer, List<AgentCallLog>> byFofoId = new HashMap<>();
37010 ranu 2159
        for (AgentCallLog log : callLogs) {
2160
            String num = log.getCustomerNumber();
2161
            if (num == null) continue;
2162
            String normalized = num.startsWith("+91") ? num.substring(3) : num;
37022 ranu 2163
            Integer fofoId = mobileToFofoIdMap != null ? mobileToFofoIdMap.get(normalized) : null;
2164
            if (fofoId == null) continue; // unknown number — excluded from Tried
2165
            byFofoId.computeIfAbsent(fofoId, k -> new ArrayList<>()).add(log);
36284 ranu 2166
        }
37010 ranu 2167
        long count = 0L;
37022 ranu 2168
        for (List<AgentCallLog> logs : byFofoId.values()) {
37012 ranu 2169
            boolean hasNonMissed = false;
2170
            for (AgentCallLog l : logs) {
2171
                if (!isMissedCustomerStatus(l.getCustomerStatus())) {
2172
                    hasNonMissed = true;
37010 ranu 2173
                    break;
36284 ranu 2174
                }
2175
            }
37012 ranu 2176
            if (hasNonMissed) count++;
2177
            else if (logs.size() >= 3) count++;
36284 ranu 2178
        }
37010 ranu 2179
        return count;
36284 ranu 2180
    }
2181
 
2182
    /**
36276 ranu 2183
     * Returns call stats: [0] = called count, [1] = total recording calls, [2] = unique recording calls
2184
     */
2185
    public long[] getCallStats(long authId, LocalDate date) {
36234 ranu 2186
        List<AgentCallLog> callLogs = agentCallLogRepository.findByAuthIdAndDate(authId, date);
2187
 
35843 ranu 2188
        if (callLogs == null || callLogs.isEmpty()) {
36276 ranu 2189
            return new long[]{0, 0, 0};
35843 ranu 2190
        }
2191
 
2192
        Set<Integer> calledFofoIds = new HashSet<>();
2193
        Set<String> calledNumbersWithoutFofoId = new HashSet<>();
36276 ranu 2194
        long totalRecordingCalls = 0;
2195
        Set<String> uniqueRecordingNumbers = new HashSet<>();
35843 ranu 2196
 
2197
        for (AgentCallLog callLog : callLogs) {
2198
            String customerNumber = callLog.getCustomerNumber();
2199
            if (customerNumber != null) {
2200
                // Normalize the phone number (remove +91 prefix if present)
2201
                String normalized = customerNumber.startsWith("+91") ? customerNumber.substring(3) : customerNumber;
2202
 
2203
                // Find fofoId from retailer_contact or address
2204
                Integer fofoId = findFofoIdByMobile(normalized);
2205
                if (fofoId != null) {
2206
                    calledFofoIds.add(fofoId);
2207
                } else {
2208
                    // Number not found in retailer_contact or address, count by distinct number
2209
                    calledNumbersWithoutFofoId.add(normalized);
2210
                }
36276 ranu 2211
 
2212
                // Count calls with recordings
2213
                if (callLog.getRecordingUrl() != null && !callLog.getRecordingUrl().isEmpty()
2214
                        && !"None".equalsIgnoreCase(callLog.getRecordingUrl())) {
2215
                    totalRecordingCalls++;
2216
                    uniqueRecordingNumbers.add(normalized);
2217
                }
35843 ranu 2218
            }
2219
        }
2220
 
2221
        // Total called = distinct fofoIds + distinct numbers without fofoId mapping
36276 ranu 2222
        long calledCount = calledFofoIds.size() + calledNumbersWithoutFofoId.size();
2223
        return new long[]{calledCount, totalRecordingCalls, uniqueRecordingNumbers.size()};
35843 ranu 2224
    }
2225
 
35852 ranu 2226
    @Override
2227
    public List<List<String>> getAllCallDataByDate(LocalDate date) throws Exception {
2228
        List<List<String>> rows = new ArrayList<>();
2229
 
2230
        // Add header row
2231
        rows.add(Arrays.asList("RBM Name", "Partner Name", "Code", "Remark", "Call Status", "Call Duration", "Call Date Time", "Recording URL"));
2232
 
2233
        // Get all call logs for the date
2234
        List<AgentCallLog> allCallLogs = agentCallLogRepository.findAllByDate(date);
2235
        LOGGER.info("getAllCallDataByDate: Found {} call logs for date {}", allCallLogs.size(), date);
2236
 
2237
        if (allCallLogs.isEmpty()) {
2238
            return rows;
2239
        }
2240
 
2241
        // Get unique authIds from call logs
2242
        Set<Long> authIds = allCallLogs.stream()
2243
                .map(AgentCallLog::getAuthId)
2244
                .collect(Collectors.toSet());
2245
 
2246
        // Get auth users for RBM names
2247
        List<Integer> authIdInts = authIds.stream().map(Long::intValue).collect(Collectors.toList());
2248
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(authIdInts).stream()
2249
                .collect(Collectors.toMap(AuthUser::getId, au -> au, (a, b) -> a));
2250
 
2251
        // Build a map of normalized customer number -> fofoId
2252
        Map<String, Integer> customerToFofoIdMap = new HashMap<>();
2253
        Set<String> normalizedNumbers = new HashSet<>();
2254
 
2255
        for (AgentCallLog callLog : allCallLogs) {
2256
            String customerNumber = callLog.getCustomerNumber();
2257
            if (customerNumber != null) {
2258
                String normalized = customerNumber.startsWith("+91") ? customerNumber.substring(3) : customerNumber;
2259
                normalizedNumbers.add(normalized);
2260
            }
2261
        }
2262
 
2263
        // For each normalized number, find fofoId
2264
        for (String mobile : normalizedNumbers) {
2265
            Integer fofoId = findFofoIdByMobile(mobile);
2266
            if (fofoId != null) {
2267
                customerToFofoIdMap.put(mobile, fofoId);
2268
            }
2269
        }
2270
 
2271
        // Get unique fofoIds for retailer lookup
2272
        Set<Integer> fofoIds = new HashSet<>(customerToFofoIdMap.values());
2273
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
2274
        if (!fofoIds.isEmpty()) {
2275
            try {
2276
                retailerMap = retailerService.getFofoRetailers(new ArrayList<>(fofoIds));
2277
            } catch (ProfitMandiBusinessException e) {
2278
                LOGGER.error("Error fetching fofo stores", e);
2279
            }
2280
        }
2281
 
2282
        // Get remarks for these fofoIds on this date
2283
        Map<Integer, List<PartnerCollectionRemark>> fofoRemarkMap = new HashMap<>();
2284
        if (!fofoIds.isEmpty()) {
2285
            List<PartnerCollectionRemark> dateRemarks = partnerCollectionRemarkRepository
2286
                    .selectAllByFofoIdsOnDate(new ArrayList<>(fofoIds), date);
2287
            for (PartnerCollectionRemark remark : dateRemarks) {
2288
                fofoRemarkMap.computeIfAbsent(remark.getFofoId(), k -> new ArrayList<>()).add(remark);
2289
            }
2290
        }
2291
 
2292
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
2293
 
2294
        // Build rows
2295
        for (AgentCallLog callLog : allCallLogs) {
2296
            String customerNumber = callLog.getCustomerNumber();
2297
            if (customerNumber == null) {
2298
                continue;
2299
            }
2300
 
2301
            // Get RBM Name
2302
            AuthUser authUser = authUserMap.get((int) callLog.getAuthId());
2303
            String rbmName = authUser != null ? authUser.getFullName() : "Unknown";
2304
 
2305
            String normalized = customerNumber.startsWith("+91") ? customerNumber.substring(3) : customerNumber;
2306
            Integer fofoId = customerToFofoIdMap.get(normalized);
2307
 
2308
            String partyName = "Unknown";
2309
            String code = "-";
2310
 
2311
            if (fofoId != null) {
2312
                CustomRetailer retailer = retailerMap.get(fofoId);
2313
                if (retailer != null) {
2314
                    partyName = retailer.getBusinessName();
2315
                    code = retailer.getCode();
2316
                } else {
2317
                    partyName = "Unknown (" + fofoId + ")";
2318
                }
2319
            } else {
2320
                partyName = "Unknown (" + normalized + ")";
2321
            }
2322
 
2323
            // Get remark if available
2324
            String remarkValue = "-";
2325
            if (fofoId != null && fofoRemarkMap.containsKey(fofoId)) {
2326
                List<PartnerCollectionRemark> remarks = fofoRemarkMap.get(fofoId);
2327
                if (!remarks.isEmpty()) {
2328
                    PartnerCollectionRemark remark = remarks.get(0);
2329
                    remarkValue = remark.getRemark() != null ? remark.getRemark().getValue() : "-";
2330
                    if (remark.getMessage() != null && !remark.getMessage().isEmpty()) {
2331
                        remarkValue = remarkValue + " - " + remark.getMessage();
2332
                    }
2333
                }
2334
            }
2335
 
2336
            // Call status from customerStatus field
2337
            String callStatus = callLog.getCustomerStatus() != null ? callLog.getCustomerStatus() : "-";
2338
            String callDuration = callLog.getCallDuration() != null ? callLog.getCallDuration() : "-";
2339
 
2340
            String callDateTime = "-";
2341
            if (callLog.getCallDate() != null && callLog.getCallTime() != null) {
2342
                LocalDateTime callDateTimeObj = LocalDateTime.of(callLog.getCallDate(), callLog.getCallTime());
2343
                callDateTime = callDateTimeObj.format(dateTimeFormatter);
2344
            }
2345
 
2346
            String recordingUrl = callLog.getRecordingUrl() != null ? callLog.getRecordingUrl() : "-";
2347
 
2348
            rows.add(Arrays.asList(rbmName, partyName, code, remarkValue, callStatus, callDuration, callDateTime, recordingUrl));
2349
        }
2350
 
2351
        return rows;
2352
    }
2353
 
33917 ranu 2354
}