Subversion Repositories SmartDukaan

Rev

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