Subversion Repositories SmartDukaan

Rev

Rev 37487 | Rev 37505 | 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) {
517
        LocalDateTime dayStart = date.atStartOfDay();
518
        LocalDateTime dayEnd = date.plusDays(1).atStartOfDay();
519
 
520
        // Persisted RBM snapshots for the target date (one row per RBM × warehouse).
521
        List<RbmTargets> todayRbmSnapshots = rbmTargetsRepository.selectTargetsByDates(dayStart, dayEnd);
522
        if (todayRbmSnapshots.isEmpty()) {
523
            LOGGER.warn("setSalesTargetsForDate: no RBM snapshots for {}; run pushRbmTargets first", date);
524
            return;
525
        }
526
 
527
        // Index snapshots by (rbmAuthId, warehouseId) for O(1) roll-up.
528
        // rbm_auth_id → warehouseId → snapshot row.
529
        Map<Integer, Map<Integer, RbmTargets>> byRbmByWh = new HashMap<>();
530
        for (RbmTargets s : todayRbmSnapshots) {
531
            byRbmByWh.computeIfAbsent(s.getRbmAuthId(), k -> new HashMap<>()).put(s.getWarehouseId(), s);
532
        }
533
        Set<Integer> allSnapshotRbms = byRbmByWh.keySet();
534
 
535
        // Sales roles + their (categoryId, escalationType) mapping — mirrors
536
        // MonitorController /indent/today_po_table_fragment so both places agree.
537
        String[][] roles = {
538
                {"ASM", "4", "L1"}, {"CM", "4", "L2"}, {"DM", "4", "L3"},
539
                {"BM", "4", "L4"}, {"RSM", "4", "L5"}, {"NSM", "4", "L6"}
540
        };
541
 
542
        int written = 0;
543
        // Stamp rows within the target day so date-range queries pick them up
544
        // for the right day, even during backfill of a past date.
545
        LocalDate today = LocalDate.now();
546
        LocalDateTime stamp = date.equals(today) ? LocalDateTime.now() : date.atTime(java.time.LocalTime.NOON);
547
        for (String[] r : roles) {
548
            String role = r[0];
549
            int catId = Integer.parseInt(r[1]);
550
            EscalationType level = EscalationType.valueOf(r[2]);
551
            for (AuthUser sales : csService.getAuthUserByCategoryId(catId, level)) {
552
                if (!sales.isActive()) continue;
553
 
554
                // Downline authIds (includes self; we skip self since Sales users
555
                // aren't RBMs and won't appear in snapshot).
556
                Set<Integer> downline = new HashSet<>();
557
                downline.add(sales.getId());
558
                List<Integer> reportees = authService.getAllReportees(sales.getId());
559
                if (reportees != null) downline.addAll(reportees);
560
                downline.retainAll(allSnapshotRbms);  // keep only RBMs with today's snapshot
561
                if (downline.isEmpty()) continue;      // no RBMs under this Sales person today
562
 
563
                // Aggregate per warehouse across the downline RBMs.
564
                Map<Integer, float[]> perWh = new LinkedHashMap<>();  // wh → [hid, fast, run, slow, other]
565
                for (int rbmAuthId : downline) {
566
                    Map<Integer, RbmTargets> whMap = byRbmByWh.get(rbmAuthId);
567
                    if (whMap == null) continue;
568
                    for (Map.Entry<Integer, RbmTargets> e : whMap.entrySet()) {
569
                        RbmTargets t = e.getValue();
570
                        float[] acc = perWh.computeIfAbsent(e.getKey(), k -> new float[5]);
571
                        acc[0] += t.getHidTarget();
572
                        acc[1] += t.getFastMovingTarget();
573
                        acc[2] += t.getRunningtarget();
574
                        acc[3] += t.getSlowMovingtarget();
575
                        acc[4] += t.getOtherTarget();
576
                    }
577
                }
578
 
579
                for (Map.Entry<Integer, float[]> e : perWh.entrySet()) {
580
                    float[] acc = e.getValue();
581
                    SalesTargets st = new SalesTargets();
582
                    st.setSalesAuthId(sales.getId());
583
                    st.setSalesName(sales.getFullName());
584
                    st.setRole(role);
585
                    st.setWarehouseId(e.getKey());
586
                    st.setHidTarget(acc[0]);
587
                    st.setFastMovingTarget(acc[1]);
588
                    st.setRunningTarget(acc[2]);
589
                    st.setSlowMovingTarget(acc[3]);
590
                    st.setOtherTarget(acc[4]);
591
                    st.setCreateTimestamp(stamp);
592
                    salesTargetsRepository.persist(st);
593
                    written++;
594
                }
595
            }
596
        }
597
        LOGGER.info("setSalesTargetsForDate: wrote {} sales_targets rows for {}", written, date);
598
    }
599
 
600
    @Override
601
    public List<SalesTargets> getSalesTargetsByDates(LocalDate startDate, LocalDate endDate) {
602
        return salesTargetsRepository.selectTargetsByDates(startDate.atStartOfDay(), endDate.atStartOfDay());
603
    }
604
 
605
    @Override
606
    public void setSalesAchievements() {
607
        setSalesAchievementsForDate(LocalDate.now());
608
    }
609
 
610
    @Override
611
    public void setSalesAchievementsForDate(LocalDate date) {
612
        // ACH per (RBM authId × warehouse) for the target date, from the live
613
        // order SQL. Same source used everywhere else.
614
        List<TodayAchievedMovementModel> achModels =
615
                getMovementWiseAchievementByDate(date, date.plusDays(1));
616
        if (achModels.isEmpty()) {
617
            LOGGER.warn("setSalesAchievementsForDate: no orders on {}; nothing to snapshot", date);
618
            return;
619
        }
620
 
621
        // Sales roles + (categoryId, escalationType) — same mapping used elsewhere.
622
        String[][] roles = {
623
                {"ASM", "4", "L1"}, {"CM", "4", "L2"}, {"DM", "4", "L3"},
624
                {"BM", "4", "L4"}, {"RSM", "4", "L5"}, {"NSM", "4", "L6"}
625
        };
626
 
627
        // Stamp within the target date so date-range queries pick these rows
628
        // up for the correct day even during backfill.
629
        LocalDate today = LocalDate.now();
630
        LocalDateTime stamp = date.equals(today) ? LocalDateTime.now() : date.atTime(java.time.LocalTime.NOON);
631
 
632
        int written = 0;
633
        for (String[] r : roles) {
634
            String role = r[0];
635
            int catId = Integer.parseInt(r[1]);
636
            EscalationType level = EscalationType.valueOf(r[2]);
637
            for (AuthUser sales : csService.getAuthUserByCategoryId(catId, level)) {
638
                if (!sales.isActive()) continue;
639
 
640
                // Downline authIds (include self).
641
                Set<Integer> downline = new HashSet<>();
642
                downline.add(sales.getId());
643
                List<Integer> reportees = authService.getAllReportees(sales.getId());
644
                if (reportees != null) downline.addAll(reportees);
645
 
646
                // Aggregate ACH per warehouse across downline RBMs.
647
                Map<Integer, float[]> perWh = new LinkedHashMap<>();  // wh → [hid, fast, run, slow, other]
648
                for (TodayAchievedMovementModel a : achModels) {
649
                    if (!downline.contains(a.getAuthId())) continue;
650
                    float[] acc = perWh.computeIfAbsent(a.getWarehouseId(), k -> new float[5]);
651
                    acc[0] += a.getHidBilled();
652
                    acc[1] += a.getFastMovingBilled();
653
                    acc[2] += a.getRunningBilled() != null ? a.getRunningBilled() : 0f;
654
                    acc[3] += a.getSlowMovinBilled() != null ? a.getSlowMovinBilled() : 0f;
655
                    acc[4] += a.getOtherBilled() != null ? a.getOtherBilled() : 0f;
656
                }
657
                if (perWh.isEmpty()) continue;
658
 
659
                for (Map.Entry<Integer, float[]> e : perWh.entrySet()) {
660
                    float[] acc = e.getValue();
661
                    SalesAchievements sa = new SalesAchievements();
662
                    sa.setSalesAuthId(sales.getId());
663
                    sa.setSalesName(sales.getFullName());
664
                    sa.setRole(role);
665
                    sa.setWarehouseId(e.getKey());
666
                    sa.setAchievedHidTarget(acc[0]);
667
                    sa.setAchievedFastMovingTarget(acc[1]);
668
                    sa.setAchievedRunningTarget(acc[2]);
669
                    sa.setAchievedSlowMovingTarget(acc[3]);
670
                    sa.setAchievedOtherTarget(acc[4]);
671
                    sa.setCreateTimestamp(stamp);
672
                    salesAchievementsRepository.persist(sa);
673
                    written++;
674
                }
675
            }
676
        }
677
        LOGGER.info("setSalesAchievementsForDate: wrote {} sales_achievements rows for {}", written, date);
678
    }
679
 
680
    @Override
33985 ranu 681
    public void setMovementWiseRbmAchievement() {
682
        LocalDate todayDate = LocalDate.now();
683
 
34055 ranu 684
        List<TodayAchievedMovementModel> todayAchievedMovementModels = getMovementWiseAchievementByDate(todayDate, todayDate.plusDays(1));
33985 ranu 685
 
686
 
687
        for (TodayAchievedMovementModel achievement : todayAchievedMovementModels) {
688
 
689
            RbmAchievements rbmAchievements = new RbmAchievements();
690
 
691
            rbmAchievements.setRbmAuthId(achievement.getAuthId());
692
            rbmAchievements.setRbmName(achievement.getRbmName());
693
            rbmAchievements.setWarehouseId(achievement.getWarehouseId());
694
            rbmAchievements.setAchievedHidTarget(achievement.getHidBilled());
695
            rbmAchievements.setAchievedFastMovingTarget(achievement.getFastMovingBilled());
34098 ranu 696
            rbmAchievements.setAchievedSlowMovingTarget(achievement.getSlowMovinBilled());
697
            rbmAchievements.setAchievedRunningTarget(achievement.getRunningBilled());
34012 ranu 698
            rbmAchievements.setAchievedOtherTarget(achievement.getOtherBilled());
33985 ranu 699
            rbmAchievements.setCreateTimestamp(LocalDateTime.now());
700
 
701
            rbmAchievementsRepository.persist(rbmAchievements);
702
 
703
        }
704
 
705
    }
706
 
34055 ranu 707
    @Override
708
    public List<Sold15daysOldAgingModel> getAgingSale(LocalDate startDate, LocalDate endDate) {
709
        Session session = sessionFactory.getCurrentSession();
710
        final TypedQuery<Sold15daysOldAgingModel> typedQuerySimilar = session.createNamedQuery("Aging.SoldAgingModel", Sold15daysOldAgingModel.class);
34056 ranu 711
        typedQuerySimilar.setParameter("startDate", startDate);
712
        typedQuerySimilar.setParameter("endDate", endDate);
34055 ranu 713
        return typedQuerySimilar.getResultList();
33985 ranu 714
 
34055 ranu 715
    }
716
 
34103 ranu 717
    @Override
718
    public List<RbmBilledFofoIdsModel> getDateWiseBilledFofoIdByRbm(LocalDate startDate, LocalDate endDate) {
719
        Session session = sessionFactory.getCurrentSession();
720
        final TypedQuery<RbmBilledFofoIdsModel> typedQuerySimilar = session.createNamedQuery("RBM.RbmBilledFofoId", RbmBilledFofoIdsModel.class);
721
        typedQuerySimilar.setParameter("startDate", startDate);
722
        typedQuerySimilar.setParameter("endDate", endDate);
723
        return typedQuerySimilar.getResultList();
35453 amit 724
    }
34103 ranu 725
 
35453 amit 726
    @Override
36296 amit 727
    @Cacheable(value = "rbmWeeklyBilling",
36329 amit 728
            cacheManager = "fiveMintimeoutCacheManager",
729
            sync = true)
35453 amit 730
    public List<RbmWeeklyBillingModel> getWeeklyBillingDataForMonth(LocalDate monthStart, LocalDate monthEnd) {
731
        Session session = sessionFactory.getCurrentSession();
732
        final TypedQuery<RbmWeeklyBillingModel> typedQuery = session.createNamedQuery("RBM.WeeklyBilling", RbmWeeklyBillingModel.class);
733
        typedQuery.setParameter("startDate", monthStart);
734
        typedQuery.setParameter("endDate", monthEnd);
735
        return typedQuery.getResultList();
34103 ranu 736
    }
737
 
34055 ranu 738
    public List<Our15DaysOldAgingStock> our15DaysAgingStock() {
739
        Session session = sessionFactory.getCurrentSession();
740
        final TypedQuery<Our15DaysOldAgingStock> typedQuerySimilar = session.createNamedQuery("Aging.15DaysOurStock", Our15DaysOldAgingStock.class);
741
        return typedQuerySimilar.getResultList();
36334 ranu 742
    }
34055 ranu 743
 
36334 ranu 744
    @Override
745
    public List<WarehouseAgingStockModel> getWarehouseWiseAgingStock() {
746
        Session session = sessionFactory.getCurrentSession();
747
        final TypedQuery<WarehouseAgingStockModel> typedQuery = session.createNamedQuery("Aging.15DaysWarehouseWiseStock", WarehouseAgingStockModel.class);
748
        return typedQuery.getResultList();
34055 ranu 749
    }
750
 
34397 ranu 751
    @Autowired
752
    OrderRepository orderRepository;
34055 ranu 753
 
34397 ranu 754
    @Override
34641 ranu 755
    public double calculateFofoIdTodayTarget(int fofoId, double secondryMtd,LocalDate date) {
34397 ranu 756
 
757
        MonthlyTarget monthlyTarget = monthlyTargetRepository.selectByDateAndFofoId(YearMonth.now(), fofoId);
34404 ranu 758
        if (monthlyTarget == null) {
759
            // Log or handle as needed
760
            return 0; // or -1 or some fallback
761
        }
34397 ranu 762
 
763
        double remainingTarget = monthlyTarget.getPurchaseTarget() - secondryMtd;
34880 ranu 764
//        double remainingWorkingDays = getWorkingDaysCount(date);
765
        double remainingWorkingDays = (double) getRemainingDaysInMonth(date);
34397 ranu 766
 
767
 
34716 ranu 768
 
34397 ranu 769
        if (remainingWorkingDays == 0) return remainingTarget; // Last day
34716 ranu 770
        LOGGER.info("remainingWorkingDays {}", remainingWorkingDays);
771
        LOGGER.info("remainingTarget {}", remainingTarget);
34397 ranu 772
 
773
        return (int) Math.ceil(remainingTarget / remainingWorkingDays);
774
    }
775
 
34880 ranu 776
    @Override
777
    public long getRemainingDaysInMonth(LocalDate date) {
778
        LocalDate lastDayOfMonth = YearMonth.from(date).atEndOfMonth();
34397 ranu 779
 
34880 ranu 780
        long totalDays = ChronoUnit.DAYS.between(date, lastDayOfMonth) + 1;
34397 ranu 781
 
34880 ranu 782
        // Count Sundays manually
783
        long sundayCount = 0;
784
        LocalDate current = date;
785
        while (!current.isAfter(lastDayOfMonth)) {
786
            if (current.getDayOfWeek() == DayOfWeek.SUNDAY) {
787
                sundayCount++;
788
            }
789
            current = current.plusDays(1);
790
        }
791
 
792
        // Public holidays in the range
793
        long publicHolidays = publicHolidaysRepository
794
                .selectAllBetweenDates(date, lastDayOfMonth)
795
                .size();
796
 
797
        long remainingDays = totalDays - sundayCount - publicHolidays;
798
 
799
        LOGGER.info("remainingDays {}", remainingDays);
800
        LOGGER.info("totalDays {}", totalDays);
801
        LOGGER.info("sundays {}", sundayCount);
802
        LOGGER.info("publicHolidays {}", publicHolidays);
803
 
804
        return remainingDays;
805
    }
806
 
35631 ranu 807
    @Autowired
808
    PositionRepository positionRepository;
34880 ranu 809
 
35631 ranu 810
    @Autowired
811
    CsService csService;
34880 ranu 812
 
35631 ranu 813
    @Autowired
814
    FofoStoreRepository fofoStoreRepository;
815
 
816
    @Autowired
817
    AuthRepository authRepository;
818
 
819
    @Autowired
820
    LoanRepository loanRepository;
821
 
822
    @Autowired
823
    PartnerCollectionService partnerCollectionService;
824
 
825
    @Autowired
826
    PartnerCollectionRemarkRepository partnerCollectionRemarkRepository;
827
 
828
    @Autowired
829
    RbmCallSequenceLogRepository rbmCallSequenceLogRepository;
830
 
831
    @Autowired
832
    com.spice.profitmandi.dao.repository.cs.TicketRepository ticketRepository;
833
 
35702 ranu 834
    @Autowired
835
    com.spice.profitmandi.dao.repository.cs.AgentCallLogRepository agentCallLogRepository;
836
 
35759 ranu 837
    @Autowired
838
    RetailerContactRepository retailerContactRepository;
839
 
840
    @Autowired
841
    AddressRepository addressRepository;
842
 
36225 ranu 843
    @Autowired
844
    com.spice.profitmandi.dao.repository.cs.PartnerPositionRepository partnerPositionRepository;
845
 
35631 ranu 846
    @Override
847
    public List<RbmCallTargetModel> getRbmCallTargetModels() throws Exception {
36234 ranu 848
        return getRbmCallTargetModels(LocalDate.now());
849
    }
850
 
37010 ranu 851
    // Matches "No Answer", "NO_ANSWER", "no-answer", "noanswer", etc.
852
    private static boolean isNoAnswerStatus(String status) {
853
        if (status == null) return false;
854
        String s = status.trim().toLowerCase().replace('_', ' ').replace('-', ' ').replaceAll("\\s+", " ");
855
        return s.equals("no answer") || s.equals("noanswer");
856
    }
857
 
858
    @Override
859
    public List<OutOfSequenceDetailModel> getOutOfSequenceDetails(int authId) {
860
 
861
        LocalDate today = LocalDate.now();
862
        LocalDateTime start = today.atStartOfDay();
863
        LocalDateTime end = today.plusDays(1).atStartOfDay();
864
 
865
        List<RbmCallSequenceLog> logs =
866
                rbmCallSequenceLogRepository.selectByAuthIdAndDateRange(authId, start, end);
867
 
868
        Map<Integer, RbmCallSequenceLog> uniqueOosLogsByFofoId = new LinkedHashMap<>();
869
 
870
        for (RbmCallSequenceLog log : logs) {
871
            if (log.isOutOfSequence()) {
872
                // Keep only the first occurrence per fofoId (latest entry since ordered by id DESC)
873
                uniqueOosLogsByFofoId.putIfAbsent(log.getFofoId(), log);
874
            }
875
        }
876
 
877
        if (uniqueOosLogsByFofoId.isEmpty()) {
878
            return Collections.emptyList();
879
        }
880
 
881
        Set<Integer> fofoIds = uniqueOosLogsByFofoId.keySet();
882
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
883
        try {
884
            retailerMap = retailerService.getFofoRetailers(new ArrayList<>(fofoIds));
885
        } catch (ProfitMandiBusinessException e) {
886
            LOGGER.error("Error fetching fofo stores", e);
887
        }
888
 
889
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
890
        List<OutOfSequenceDetailModel> result = new ArrayList<>();
891
 
892
        for (RbmCallSequenceLog log : uniqueOosLogsByFofoId.values()) {
893
            CustomRetailer retailer = retailerMap.get(log.getFofoId());
894
            String partyName = retailer != null
895
                    ? retailer.getBusinessName()
896
                    : "Unknown (" + log.getFofoId() + ")";
897
            String code = retailer != null
898
                    ? retailer.getCode()
899
                    : "-";
900
 
901
            String time = log.getCreateTimestamp() != null
902
                    ? log.getCreateTimestamp().format(timeFormatter)
903
                    : "-";
904
 
905
            result.add(new OutOfSequenceDetailModel(partyName, code, time));
906
        }
907
 
908
        return result;
909
    }
910
 
911
    @Override
912
    public List<CalledPartnerDetailModel> getCalledPartnerDetails(int authId) throws ProfitMandiBusinessException {
913
        return getCalledPartnerDetails(authId, LocalDate.now());
914
    }
915
 
916
    @Override
917
    public List<CalledPartnerDetailModel> getCalledPartnerDetails(int authId, LocalDate date) throws ProfitMandiBusinessException {
918
        // Get all call logs for this auth user on this date
919
        LOGGER.info("getCalledPartnerDetails: authId={}, date={}", authId, date);
920
        List<AgentCallLog> callLogs = agentCallLogRepository.findByAuthIdAndDate(authId, date);
921
        LOGGER.info("Found {} call logs for authId={} on date={}", callLogs.size(), authId, date);
922
 
923
        if (callLogs.isEmpty()) {
924
            return Collections.emptyList();
925
        }
926
 
927
        // Build a map of normalized customer number -> fofoId
928
        Map<String, Integer> customerToFofoIdMap = new HashMap<>();
929
        Set<String> normalizedNumbers = new HashSet<>();
930
 
931
        for (AgentCallLog callLog : callLogs) {
932
            String customerNumber = callLog.getCustomerNumber();
933
            if (customerNumber != null) {
934
                String normalized = customerNumber.startsWith("+91") ? customerNumber.substring(3) : customerNumber;
935
                normalizedNumbers.add(normalized);
936
            }
937
        }
938
 
939
        // For each normalized number, find fofoId from retailer_contact first, then address
940
        for (String mobile : normalizedNumbers) {
941
            Integer fofoId = findFofoIdByMobile(mobile);
942
            if (fofoId != null) {
943
                customerToFofoIdMap.put(mobile, fofoId);
944
            }
945
        }
946
 
947
        // Get unique fofoIds for retailer lookup
948
        Set<Integer> fofoIds = new HashSet<>(customerToFofoIdMap.values());
949
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
950
        if (!fofoIds.isEmpty()) {
951
            try {
952
                retailerMap = retailerService.getFofoRetailers(new ArrayList<>(fofoIds));
953
            } catch (ProfitMandiBusinessException e) {
954
                LOGGER.error("Error fetching fofo stores", e);
955
            }
956
        }
957
 
958
        // Get today's remarks for these fofoIds
959
        Map<Integer, List<PartnerCollectionRemark>> fofoRemarkMap = new HashMap<>();
960
        if (!fofoIds.isEmpty()) {
961
            List<PartnerCollectionRemark> todayRemarks = partnerCollectionRemarkRepository
962
                    .selectAllByFofoIdsOnDate(new ArrayList<>(fofoIds), date);
963
            for (PartnerCollectionRemark remark : todayRemarks) {
964
                fofoRemarkMap.computeIfAbsent(remark.getFofoId(), k -> new ArrayList<>()).add(remark);
965
            }
966
        }
967
 
968
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
969
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
970
        List<CalledPartnerDetailModel> result = new ArrayList<>();
971
 
972
        for (com.spice.profitmandi.dao.entity.cs.AgentCallLog callLog : callLogs) {
973
            String customerNumber = callLog.getCustomerNumber();
974
            if (customerNumber == null) {
975
                continue;
976
            }
977
 
978
            String normalized = customerNumber.startsWith("+91") ? customerNumber.substring(3) : customerNumber;
979
            Integer fofoId = customerToFofoIdMap.get(normalized);
980
 
981
            String partyName = "Unknown";
982
            String code = "-";
983
 
984
            if (fofoId != null) {
985
                CustomRetailer retailer = retailerMap.get(fofoId);
986
                if (retailer != null) {
987
                    partyName = retailer.getBusinessName();
988
                    code = retailer.getCode();
989
                } else {
990
                    partyName = "Unknown (" + fofoId + ")";
991
                }
992
            } else {
993
                partyName = "Unknown (" + normalized + ")";
994
            }
995
 
996
            // Get remark if available
997
            String remarkValue = "-";
998
            String messageValue = "-";
999
            String remarkTime = "-";
1000
 
1001
            if (fofoId != null && fofoRemarkMap.containsKey(fofoId)) {
1002
                List<PartnerCollectionRemark> remarks = fofoRemarkMap.get(fofoId);
1003
                if (!remarks.isEmpty()) {
1004
                    PartnerCollectionRemark remark = remarks.get(0);
1005
                    remarkValue = remark.getRemark() != null ? remark.getRemark().getValue() : "-";
1006
                    messageValue = remark.getMessage() != null ? remark.getMessage() : "-";
1007
                    remarkTime = remark.getCreateTimestamp() != null ? remark.getCreateTimestamp().format(timeFormatter) : "-";
1008
                }
1009
            }
1010
 
1011
            // Build call log data
1012
            String recordingUrl = callLog.getRecordingUrl();
1013
            String callStatus = callLog.getCallStatus();
1014
            String callDuration = callLog.getCallDuration();
1015
            String callDateTime = null;
1016
            if (callLog.getCallDate() != null && callLog.getCallTime() != null) {
1017
                LocalDateTime callDateTimeObj = LocalDateTime.of(callLog.getCallDate(), callLog.getCallTime());
1018
                callDateTime = callDateTimeObj.format(dateTimeFormatter);
1019
            }
1020
 
1021
            result.add(new CalledPartnerDetailModel(partyName, code, remarkValue, messageValue, remarkTime,
1022
                    recordingUrl, callStatus, callDuration, callDateTime));
1023
        }
1024
 
1025
        return result;
1026
    }
1027
 
1028
    private Integer findFofoIdByMobile(String mobile) {
1029
        // First check retailer_contact
1030
        List<RetailerContact> contacts = retailerContactRepository.selectByMobile(mobile);
1031
        if (contacts != null && !contacts.isEmpty()) {
1032
            return contacts.get(0).getFofoId();
1033
        }
1034
 
1035
        // Fallback to user.address
1036
        List<Address> addresses = addressRepository.selectAllByPhoneNumber(mobile);
1037
        if (addresses != null && !addresses.isEmpty()) {
1038
            return addresses.get(0).getRetaierId();
1039
        }
1040
 
1041
        return null;
1042
    }
1043
 
1044
    private List<CalledPartnerDetailModel> buildCalledPartnerResult(List<PartnerCollectionRemark> allRemarks) {
1045
        if (allRemarks.isEmpty()) {
1046
            return Collections.emptyList();
1047
        }
1048
 
1049
        // Get unique fofoIds for retailer lookup
1050
        Set<Integer> fofoIds = allRemarks.stream()
1051
                .map(PartnerCollectionRemark::getFofoId)
1052
                .collect(Collectors.toSet());
1053
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
1054
        try {
1055
            retailerMap = retailerService.getFofoRetailers(new ArrayList<>(fofoIds));
1056
        } catch (ProfitMandiBusinessException e) {
1057
            LOGGER.error("Error fetching fofo stores", e);
1058
        }
1059
 
1060
        // Fetch call logs for remarks that have agentCallLogId
1061
        Map<Long, com.spice.profitmandi.dao.entity.cs.AgentCallLog> callLogMap = new HashMap<>();
1062
        try {
1063
            List<Long> callLogIds = allRemarks.stream()
1064
                    .filter(r -> r.getAgentCallLogId() > 0)
1065
                    .map(PartnerCollectionRemark::getAgentCallLogId)
1066
                    .collect(Collectors.toList());
1067
 
1068
            if (!callLogIds.isEmpty()) {
1069
                List<com.spice.profitmandi.dao.entity.cs.AgentCallLog> callLogs = agentCallLogRepository.findByIds(callLogIds);
1070
                if (callLogs != null) {
1071
                    callLogMap = callLogs.stream()
1072
                            .collect(Collectors.toMap(com.spice.profitmandi.dao.entity.cs.AgentCallLog::getId, c -> c, (a, b) -> a));
1073
                }
1074
            }
1075
        } catch (Exception e) {
1076
            LOGGER.error("Error fetching call logs by ids", e);
1077
        }
1078
 
1079
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
1080
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
1081
        List<CalledPartnerDetailModel> result = new ArrayList<>();
1082
 
1083
        for (PartnerCollectionRemark remark : allRemarks) {
1084
            CustomRetailer retailer = retailerMap.get(remark.getFofoId());
1085
            String partyName = retailer != null
1086
                    ? retailer.getBusinessName()
1087
                    : "Unknown (" + remark.getFofoId() + ")";
1088
            String code = retailer != null
1089
                    ? retailer.getCode()
1090
                    : "-";
1091
 
1092
            String remarkValue = remark.getRemark() != null
1093
                    ? remark.getRemark().getValue()
1094
                    : "-";
1095
 
1096
            String messageValue = remark.getMessage() != null
1097
                    ? remark.getMessage()
1098
                    : "-";
1099
 
1100
            String time = remark.getCreateTimestamp() != null
1101
                    ? remark.getCreateTimestamp().format(timeFormatter)
1102
                    : "-";
1103
 
1104
            // Get call log data if available
1105
            String recordingUrl = null;
1106
            String callStatus = null;
1107
            String callDuration = null;
1108
            String callDateTime = null;
1109
 
1110
            try {
1111
                if (remark.getAgentCallLogId() > 0 && callLogMap.containsKey(remark.getAgentCallLogId())) {
1112
                    com.spice.profitmandi.dao.entity.cs.AgentCallLog callLog = callLogMap.get(remark.getAgentCallLogId());
1113
                    recordingUrl = callLog.getRecordingUrl();
1114
                    callStatus = callLog.getCallStatus();
1115
                    callDuration = callLog.getCallDuration();
1116
                    if (callLog.getCallDate() != null && callLog.getCallTime() != null) {
1117
                        LocalDateTime callDateTimeObj = LocalDateTime.of(callLog.getCallDate(), callLog.getCallTime());
1118
                        callDateTime = callDateTimeObj.format(dateTimeFormatter);
1119
                    }
1120
                }
1121
            } catch (Exception e) {
1122
                LOGGER.error("Error processing call log for remark id: {}", remark.getId(), e);
1123
            }
1124
 
1125
            result.add(new CalledPartnerDetailModel(partyName, code, remarkValue, messageValue, time,
1126
                    recordingUrl, callStatus, callDuration, callDateTime));
1127
        }
1128
 
1129
        return result;
1130
    }
1131
 
1132
    @Override
1133
    public List<List<String>> getRbmCallTargetRawDataByAuthId(int authId) throws Exception {
1134
        List<List<String>> rows = new ArrayList<>();
1135
 
1136
        // Get auth user
1137
        List<AuthUser> authUsers = authRepository.selectByIds(Collections.singletonList(authId));
1138
        if (authUsers.isEmpty()) {
1139
            return rows;
1140
        }
1141
        AuthUser authUser = authUsers.get(0);
1142
 
1143
        // Get positions to determine if L2
1144
        List<Position> positions = positionRepository.selectPositionByAuthIds(Collections.singletonList(authId));
1145
        boolean isL2 = positions.stream()
1146
                .anyMatch(p -> ProfitMandiConstants.TICKET_CATEGORY_RBM == p.getCategoryId()
1147
                        && EscalationType.L2.equals(p.getEscalationType()));
1148
 
1149
        LocalDateTime startDate = LocalDate.now().atStartOfDay();
1150
        LocalDate firstOfMonth = LocalDate.now().withDayOfMonth(1);
1151
        LocalDate endOfMonth = LocalDate.now().withDayOfMonth(LocalDate.now().lengthOfMonth()).plusDays(1);
1152
 
1153
        // Get fofo IDs from mtdBillingData (same source as Partner Count in getRbmCallTargetModels)
1154
        List<RbmWeeklyBillingModel> mtdBillingData = getWeeklyBillingDataForMonth(firstOfMonth, endOfMonth);
1155
 
1156
        List<Integer> fofoIdList;
1157
        if (isL2) {
37145 ranu 1158
            // L2: get fofo IDs from escalated tickets (same as getRbmCallTargetModels).
1159
            // selectOpenEscalatedTicketsByAuthIds already filters to tickets where authId is the
1160
            // current assignee AND the ticket has moved past L1 — no post-filter needed.
37010 ranu 1161
            List<Ticket> escalatedTickets = ticketRepository.selectOpenEscalatedTicketsByAuthIds(Collections.singletonList(authId));
1162
            fofoIdList = escalatedTickets.stream()
1163
                    .map(Ticket::getFofoId)
1164
                    .distinct()
1165
                    .collect(Collectors.toList());
1166
        } else {
1167
            // L1: get fofo IDs from mtdBillingData with isTargetedPartner (same as Partner Count)
1168
            fofoIdList = mtdBillingData.stream()
1169
                    .filter(RbmWeeklyBillingModel::isTargetedPartner)
1170
                    .filter(m -> m.getAuthId() == authId)
1171
                    .map(RbmWeeklyBillingModel::getFofoId)
1172
                    .distinct()
1173
                    .collect(Collectors.toList());
1174
        }
1175
 
1176
        if (fofoIdList.isEmpty()) {
1177
            return rows;
1178
        }
1179
 
1180
        // MTD billed fofoIds for zero billing check
1181
        Set<Integer> mtdBilledFofoIds = mtdBillingData.stream()
1182
                .filter(RbmWeeklyBillingModel::isMtdBilled)
1183
                .map(RbmWeeklyBillingModel::getFofoId)
1184
                .collect(Collectors.toSet());
1185
 
1186
        // Collection rank map for status calculation
1187
        Map<Integer, Integer> collectionRankMap = new HashMap<>();
1188
        try {
1189
            collectionRankMap = partnerCollectionService.getCollectionRankMap(fofoIdList, startDate);
1190
        } catch (ProfitMandiBusinessException e) {
1191
            LOGGER.error("Error fetching collection rank map", e);
1192
        }
1193
 
1194
        // Resolve partner names/codes
1195
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
1196
        if (!fofoIdList.isEmpty()) {
1197
            try {
1198
                retailerMap = retailerService.getFofoRetailers(fofoIdList);
1199
            } catch (ProfitMandiBusinessException e) {
1200
                LOGGER.error("Error fetching fofo retailers for raw data", e);
1201
            }
1202
        }
1203
 
1204
        String rbmName = authUser.getFullName() + (isL2 ? " (L2)" : "");
1205
 
1206
        // Build rows for ALL partners (same count as Partner Count)
1207
        for (Integer fofoId : fofoIdList) {
1208
            // Default to rank 5 (Normal) for partners without collection plan
1209
            int rank = collectionRankMap.getOrDefault(fofoId, 5);
1210
            boolean hasZeroBilling = !mtdBilledFofoIds.contains(fofoId);
1211
 
1212
            // Status assignment with same priority as getRbmCallTargetModels
1213
            String status;
1214
            if (rank == 1) {
1215
                status = "Plan Today";
1216
            } else if (rank == 2) {
1217
                status = "Carry Forward";
1218
            } else if (hasZeroBilling) {
1219
                status = "Zero Billing";
1220
            } else if (rank == 3) {
1221
                status = "Untouched";
1222
            } else if (rank == 4) {
1223
                status = "Future Plan";
1224
            } else {
1225
                status = "Normal";
1226
            }
1227
 
1228
            CustomRetailer retailer = retailerMap.get(fofoId);
1229
            String partnerName = retailer != null ? retailer.getBusinessName() : "Unknown (" + fofoId + ")";
1230
            String partnerCode = retailer != null ? retailer.getCode() : "-";
1231
 
1232
            rows.add(Arrays.asList(partnerName, partnerCode, status, rbmName));
1233
        }
1234
 
1235
        return rows;
1236
    }
1237
 
1238
    @Override
1239
    public List<List<String>> getAllRbmCallTargetRawData() throws Exception {
1240
        List<List<String>> rows = new ArrayList<>();
1241
 
1242
        // Get all L1 RBM positions (rows are emitted per L1 RBM).
1243
        // Call-log lookup happens against ALL callers via findAllByDate — so an L2/L3 or admin call
1244
        // still counts as "tried" for the partner.
1245
        List<Position> allRbmPositions = positionRepository
1246
                .selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_RBM).stream()
1247
                .filter(x -> EscalationType.L1.equals(x.getEscalationType()))
1248
                .collect(Collectors.toList());
1249
 
1250
        List<Integer> l1AuthIds = allRbmPositions.stream()
1251
                .map(Position::getAuthUserId).distinct().collect(Collectors.toList());
1252
 
1253
        if (l1AuthIds.isEmpty()) {
1254
            return rows;
1255
        }
1256
 
1257
        // Get auth user map
1258
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(l1AuthIds).stream()
1259
                .collect(Collectors.toMap(AuthUser::getId, au -> au));
1260
 
1261
        // Positions per auth user (needed early to build L1 partner assignments below)
1262
        Map<Integer, List<Position>> positionsByAuthId = positionRepository.selectPositionByAuthIds(l1AuthIds).stream()
1263
                .collect(Collectors.groupingBy(Position::getAuthUserId));
1264
 
1265
        // Build L1 partner assignments from partner_position — SAME source the UI summary uses for
1266
        // Calling Target. storeGuyMap (email-based CS mapping) was returning smaller/different lists
1267
        // for users who are also L2, causing summary=43 but download=3 for Ebadullah.
1268
        Map<Integer, Integer> l1PositionIdToAuthId = new HashMap<>();
1269
        for (int rbmAuthId : l1AuthIds) {
1270
            List<Position> positions = positionsByAuthId.getOrDefault(rbmAuthId, Collections.emptyList());
1271
            for (Position p : positions) {
1272
                if (ProfitMandiConstants.TICKET_CATEGORY_RBM == p.getCategoryId()
1273
                        && EscalationType.L1.equals(p.getEscalationType())) {
1274
                    l1PositionIdToAuthId.put(p.getId(), rbmAuthId);
1275
                }
1276
            }
1277
        }
1278
 
1279
        Map<Integer, List<Integer>> rbmToFofoIdsMap = new HashMap<>();
1280
        Set<Integer> allFofoIds = new HashSet<>();
1281
        if (!l1PositionIdToAuthId.isEmpty()) {
1282
            List<com.spice.profitmandi.dao.entity.cs.PartnerPosition> allL1PPs =
1283
                    partnerPositionRepository.selectByPositionIds(new ArrayList<>(l1PositionIdToAuthId.keySet()));
1284
            // Group by owning RBM; keep partners distinct within each RBM.
1285
            Map<Integer, Set<Integer>> perRbmSets = new HashMap<>();
1286
            for (com.spice.profitmandi.dao.entity.cs.PartnerPosition pp : allL1PPs) {
1287
                Integer ownerAuthId = l1PositionIdToAuthId.get(pp.getPositionId());
1288
                if (ownerAuthId == null) continue;
1289
                perRbmSets.computeIfAbsent(ownerAuthId, k -> new HashSet<>()).add(pp.getFofoId());
1290
                allFofoIds.add(pp.getFofoId());
1291
            }
1292
            for (Map.Entry<Integer, Set<Integer>> e : perRbmSets.entrySet()) {
1293
                rbmToFofoIdsMap.put(e.getKey(), new ArrayList<>(e.getValue()));
1294
            }
1295
        }
1296
 
1297
        if (allFofoIds.isEmpty()) {
1298
            return rows;
1299
        }
1300
 
1301
        // Get fofo stores for filtering and name resolution
1302
        Map<Integer, FofoStore> fofoStoresMap = new HashMap<>();
1303
        try {
1304
            fofoStoresMap = fofoStoreRepository.selectByRetailerIds(new ArrayList<>(allFofoIds)).stream()
1305
                    .collect(Collectors.toMap(FofoStore::getId, x -> x, (a, b) -> a));
1306
        } catch (ProfitMandiBusinessException e) {
1307
            LOGGER.error("Error fetching fofo stores for all raw data", e);
1308
        }
1309
 
1310
        // Batch fetch collection rank map
1311
        LocalDateTime startDate = LocalDate.now().atStartOfDay();
1312
        Map<Integer, Integer> allCollectionRankMap = new HashMap<>();
1313
        try {
1314
            allCollectionRankMap = partnerCollectionService.getCollectionRankMap(new ArrayList<>(allFofoIds), startDate);
1315
        } catch (ProfitMandiBusinessException e) {
1316
            LOGGER.error("Error fetching collection rank map for all raw data", e);
1317
        }
1318
 
1319
        // MTD billing data
1320
        LocalDate firstOfMonth = LocalDate.now().withDayOfMonth(1);
1321
        LocalDate endOfMonth = LocalDate.now().withDayOfMonth(LocalDate.now().lengthOfMonth()).plusDays(1);
1322
        List<RbmWeeklyBillingModel> mtdBillingData = getWeeklyBillingDataForMonth(firstOfMonth, endOfMonth);
1323
        Set<Integer> allMtdBilledFofoIds = mtdBillingData.stream()
1324
                .filter(RbmWeeklyBillingModel::isMtdBilled)
1325
                .map(RbmWeeklyBillingModel::getFofoId)
1326
                .collect(Collectors.toSet());
1327
 
1328
        // Batch fetch partner collection remarks for escalation filtering
1329
        Map<Integer, PartnerCollectionRemark> allPartnerCollectionRemarks = new HashMap<>();
1330
        if (!allFofoIds.isEmpty()) {
1331
            List<Integer> allRemarkIds = partnerCollectionRemarkRepository.selectMaxRemarkId(new ArrayList<>(allFofoIds));
1332
            if (!allRemarkIds.isEmpty()) {
1333
                allPartnerCollectionRemarks = partnerCollectionRemarkRepository.selectByIds(allRemarkIds).stream()
1334
                        .collect(Collectors.toMap(PartnerCollectionRemark::getFofoId, x -> x, (a, b) -> a));
1335
            }
1336
        }
1337
 
1338
        // Resolve partner names/codes in batch
1339
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
1340
        try {
1341
            retailerMap = retailerService.getFofoRetailers(new ArrayList<>(allFofoIds));
1342
        } catch (ProfitMandiBusinessException e) {
1343
            LOGGER.error("Error fetching fofo retailers for all raw data", e);
1344
        }
1345
 
1346
        // Batch-fetch EVERY call log for today (across all callers, not just RBMs) and build a
1347
        // fofoId -> latest AgentCallLog map. We use findAllByDate here so that calls placed by
1348
        // admins, escalation agents, or anyone whose authId isn't in the RBM position table are
1349
        // still surfaced. Downstream we only read this map for fofoIds we actually emit, so
1350
        // extra entries are harmless.
37013 ranu 1351
        // Group ALL today's call logs by fofoId so we can apply the Tried rule per partner
1352
        // (uses customerStatus + persistence, same as the summary's Tried metric).
1353
        Map<Integer, List<AgentCallLog>> callsByFofoId = new HashMap<>();
37010 ranu 1354
        try {
1355
            List<AgentCallLog> todayCallLogs = agentCallLogRepository.findAllByDate(LocalDate.now());
1356
            Set<String> normalizedMobiles = new HashSet<>();
1357
            for (AgentCallLog log : todayCallLogs) {
1358
                if (log.getCustomerNumber() != null) {
1359
                    String n = log.getCustomerNumber();
1360
                    normalizedMobiles.add(n.startsWith("+91") ? n.substring(3) : n);
1361
                }
1362
            }
1363
            Map<String, Integer> mobileToFofoIdMap = buildMobileToFofoIdMap(normalizedMobiles);
1364
            for (AgentCallLog log : todayCallLogs) {
1365
                if (log.getCustomerNumber() == null) continue;
1366
                String n = log.getCustomerNumber();
1367
                String normalized = n.startsWith("+91") ? n.substring(3) : n;
1368
                Integer fofoId = mobileToFofoIdMap.get(normalized);
1369
                if (fofoId == null) continue;
37013 ranu 1370
                callsByFofoId.computeIfAbsent(fofoId, k -> new ArrayList<>()).add(log);
37010 ranu 1371
            }
1372
        } catch (Exception e) {
37013 ranu 1373
            LOGGER.error("Error building call logs map for all raw data", e);
37010 ranu 1374
        }
1375
 
1376
        // Process each L1 RBM
1377
        // Note: no cross-RBM dedup — a partner assigned to multiple RBMs appears once per RBM,
1378
        // matching the UI summary counts so row totals per RBM equal that RBM's "Calling Target".
1379
        for (int rbmAuthId : l1AuthIds) {
1380
            AuthUser authUser = authUserMap.get(rbmAuthId);
1381
            if (authUser == null) {
1382
                continue;
1383
            }
1384
 
1385
            List<Integer> fofoIdList = rbmToFofoIdsMap.getOrDefault(rbmAuthId, Collections.emptyList());
1386
            if (fofoIdList.isEmpty()) {
1387
                continue; // No L1 partner assignments for this RBM
1388
            }
1389
 
1390
            // Filter escalated partners for L1 RBMs
1391
            List<Position> positions = positionsByAuthId.getOrDefault(rbmAuthId, Collections.emptyList());
1392
            boolean isRBMAndL1 = positions.stream()
1393
                    .anyMatch(position ->
1394
                            ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId()
1395
                                    && EscalationType.L1.equals(position.getEscalationType()));
1396
 
1397
            List<Integer> fofoIds = fofoIdList;
1398
            if (isRBMAndL1) {
1399
                Map<Integer, PartnerCollectionRemark> partnerRemarks = new HashMap<>();
1400
                for (Integer fofoId : fofoIdList) {
1401
                    if (allPartnerCollectionRemarks.containsKey(fofoId)) {
1402
                        partnerRemarks.put(fofoId, allPartnerCollectionRemarks.get(fofoId));
1403
                    }
1404
                }
1405
                Map<Integer, PartnerCollectionRemark> finalPartnerRemarks = partnerRemarks;
1406
                fofoIds = fofoIdList.stream()
1407
                        .filter(fofoId -> {
1408
                            if (!finalPartnerRemarks.containsKey(fofoId)) return true;
1409
                            PartnerCollectionRemark pcr = finalPartnerRemarks.get(fofoId);
1410
                            return !(CollectionRemark.RBM_L2_ESCALATION.equals(pcr.getRemark())
1411
                                    || CollectionRemark.SALES_ESCALATION.equals(pcr.getRemark()));
1412
                        })
1413
                        .collect(Collectors.toList());
1414
            }
1415
 
1416
            // Filter to only external, ACTIVE or REVIVAL stores
1417
            Map<Integer, FofoStore> finalFofoStoresMap = fofoStoresMap;
1418
            List<Integer> validFofoIds = fofoIds.stream()
1419
                    .filter(fofoId -> {
1420
                        FofoStore store = finalFofoStoresMap.get(fofoId);
1421
                        if (store == null || store.isInternal()) return false;
1422
                        return ActivationType.ACTIVE.equals(store.getActivationType())
1423
                                || ActivationType.REVIVAL.equals(store.getActivationType());
1424
                    })
1425
                    .collect(Collectors.toList());
1426
 
1427
            String rbmName = authUser.getFullName();
1428
 
1429
            // Categorize each partner and add a row per RBM assignment.
1430
            for (Integer fofoId : validFofoIds) {
1431
                int rank = allCollectionRankMap.getOrDefault(fofoId, 5);
1432
                boolean hasZeroBilling = !allMtdBilledFofoIds.contains(fofoId);
1433
 
1434
                String status;
1435
                if (rank == 1) {
1436
                    status = "Plan Today";
1437
                } else if (rank == 2) {
1438
                    status = "Carry Forward";
1439
                } else if (hasZeroBilling) {
1440
                    status = "Zero Billing";
1441
                } else if (rank == 3) {
1442
                    status = "Untouched";
1443
                } else {
1444
                    continue; // Skip Future Plan and Normal — only include calling target parties
1445
                }
1446
 
1447
                CustomRetailer retailer = retailerMap.get(fofoId);
1448
                String partnerName = retailer != null ? retailer.getBusinessName() : "Unknown (" + fofoId + ")";
1449
                String partnerCode = retailer != null ? retailer.getCode() : "-";
1450
 
37013 ranu 1451
                // Show the latest customerStatus from today's call logs for this partner.
1452
                // "Did Not Try" only when there is no call log at all today.
1453
                List<AgentCallLog> partnerCalls = callsByFofoId.getOrDefault(fofoId, Collections.emptyList());
37010 ranu 1454
                String latestCallStatus = "Did Not Try";
37013 ranu 1455
                if (!partnerCalls.isEmpty()) {
1456
                    AgentCallLog latest = null;
1457
                    for (AgentCallLog l : partnerCalls) {
1458
                        if (latest == null || (l.getId() != null && latest.getId() != null && l.getId() > latest.getId())) {
1459
                            latest = l;
1460
                        }
1461
                    }
1462
                    if (latest != null && latest.getCustomerStatus() != null && !latest.getCustomerStatus().isEmpty()) {
1463
                        latestCallStatus = latest.getCustomerStatus();
1464
                    }
37010 ranu 1465
                }
1466
 
1467
                rows.add(Arrays.asList(partnerName, partnerCode, status, rbmName, latestCallStatus));
1468
            }
1469
        }
1470
 
1471
        return rows;
1472
    }
1473
 
1474
    /**
1475
     * Get count of distinct partners called today based on call logs.
1476
     * Maps customerNumber from call log to fofoId using retailer_contact and address.
1477
     * If same fofoId is called multiple times, counts only once.
1478
     * Numbers without fofoId mapping are also counted (by distinct customer number).
1479
     *
1480
     * @param authId the RBM auth ID
1481
     * @return count of distinct partners/numbers called today
1482
     */
1483
    public long getCalledCountFromCallLogs(long authId) {
1484
        return getCalledCountFromCallLogs(authId, LocalDate.now());
1485
    }
1486
 
1487
    public long getCalledCountFromCallLogs(long authId, LocalDate date) {
1488
        return getCallStats(authId, date)[0];
1489
    }
1490
 
1491
    /**
1492
     * Batch-builds a mobile (normalized, +91 stripped) -> fofoId mapping for all the given mobiles
1493
     * in just two queries (retailer_contact, then address fallback for unmapped numbers).
1494
     * Replaces the previous per-call-log findFofoIdByMobile() N+1 lookups.
1495
     */
1496
    private Map<String, Integer> buildMobileToFofoIdMap(Set<String> normalizedMobiles) {
1497
        Map<String, Integer> result = new HashMap<>();
1498
        if (normalizedMobiles == null || normalizedMobiles.isEmpty()) {
1499
            return result;
1500
        }
1501
        List<String> mobilesList = new ArrayList<>(normalizedMobiles);
1502
 
1503
        // First pass: retailer_contact
1504
        List<RetailerContact> contacts = retailerContactRepository.selectByMobiles(mobilesList);
1505
        for (RetailerContact rc : contacts) {
1506
            // Keep the first fofoId we see per mobile (matches old single-mobile behavior of get(0))
1507
            result.putIfAbsent(rc.getMobile(), rc.getFofoId());
1508
        }
1509
 
1510
        // Second pass: address fallback for mobiles not yet mapped
1511
        List<String> unmapped = mobilesList.stream()
1512
                .filter(m -> !result.containsKey(m))
1513
                .collect(Collectors.toList());
1514
        if (!unmapped.isEmpty()) {
1515
            List<Address> addresses = addressRepository.selectAllByPhoneNumbers(unmapped);
1516
            for (Address addr : addresses) {
1517
                result.putIfAbsent(addr.getPhoneNumber(), addr.getRetaierId());
1518
            }
1519
        }
1520
        return result;
1521
    }
1522
 
1523
    /**
1524
     * In-memory variant of getCallStats() that uses pre-fetched call logs and mobile→fofoId mapping.
1525
     * Used by the batch-fetched RBM Call Target loop to avoid N+1 query patterns.
1526
     */
1527
    private long[] getCallStatsFromLogs(List<AgentCallLog> callLogs, Map<String, Integer> mobileToFofoIdMap) {
1528
        if (callLogs == null || callLogs.isEmpty()) {
1529
            return new long[]{0, 0, 0};
1530
        }
1531
 
1532
        Set<Integer> calledFofoIds = new HashSet<>();
1533
        Set<String> calledNumbersWithoutFofoId = new HashSet<>();
1534
        long totalRecordingCalls = 0;
1535
        Set<String> uniqueRecordingNumbers = new HashSet<>();
1536
 
1537
        for (AgentCallLog callLog : callLogs) {
1538
            String customerNumber = callLog.getCustomerNumber();
1539
            if (customerNumber != null) {
1540
                String normalized = customerNumber.startsWith("+91") ? customerNumber.substring(3) : customerNumber;
1541
                Integer fofoId = mobileToFofoIdMap.get(normalized);
1542
                if (fofoId != null) {
1543
                    calledFofoIds.add(fofoId);
1544
                } else {
1545
                    calledNumbersWithoutFofoId.add(normalized);
1546
                }
1547
 
1548
                if (callLog.getRecordingUrl() != null && !callLog.getRecordingUrl().isEmpty()
1549
                        && !"None".equalsIgnoreCase(callLog.getRecordingUrl())) {
1550
                    totalRecordingCalls++;
1551
                    uniqueRecordingNumbers.add(normalized);
1552
                }
1553
            }
1554
        }
1555
 
1556
        long calledCount = calledFofoIds.size() + calledNumbersWithoutFofoId.size();
1557
        return new long[]{calledCount, totalRecordingCalls, uniqueRecordingNumbers.size()};
1558
    }
1559
 
37022 ranu 1560
    // Same rule as computeUniqueTriedCount but restricted to fofoIds in the target set.
1561
    // Used to compute "TGT Calls" — how many of THIS RBM's Calling Target partners were
1562
    // actually engaged today. Off-target activity is silently excluded.
1563
    private long computeUniqueTriedCountForTargets(List<AgentCallLog> callLogs,
1564
                                                   Map<String, Integer> mobileToFofoIdMap,
1565
                                                   Set<Integer> targetFofoIds) {
1566
        if (callLogs == null || callLogs.isEmpty()) return 0L;
1567
        if (targetFofoIds == null || targetFofoIds.isEmpty()) return 0L;
1568
        Map<Integer, List<AgentCallLog>> byFofoId = new HashMap<>();
1569
        for (AgentCallLog log : callLogs) {
1570
            String num = log.getCustomerNumber();
1571
            if (num == null) continue;
1572
            String normalized = num.startsWith("+91") ? num.substring(3) : num;
1573
            Integer fofoId = mobileToFofoIdMap != null ? mobileToFofoIdMap.get(normalized) : null;
1574
            if (fofoId == null) continue;
1575
            if (!targetFofoIds.contains(fofoId)) continue; // off-target, skip
1576
            byFofoId.computeIfAbsent(fofoId, k -> new ArrayList<>()).add(log);
1577
        }
1578
        long count = 0L;
1579
        for (List<AgentCallLog> logs : byFofoId.values()) {
1580
            boolean hasNonMissed = false;
1581
            for (AgentCallLog l : logs) {
1582
                if (!isMissedCustomerStatus(l.getCustomerStatus())) {
1583
                    hasNonMissed = true;
1584
                    break;
1585
                }
1586
            }
1587
            if (hasNonMissed) count++;
1588
            else if (logs.size() >= 3) count++;
1589
        }
1590
        return count;
1591
    }
1592
 
37012 ranu 1593
    // Matches "Missed", "MISSED", "No Answer", "NO_ANSWER", "no-answer" etc.
1594
    // Kommuno currently emits "Missed" — kept liberal so we're covered if the tag changes.
1595
    private static boolean isMissedCustomerStatus(String status) {
1596
        if (status == null) return false;
1597
        String s = status.trim().toLowerCase().replace('_', ' ').replace('-', ' ').replaceAll("\\s+", " ");
1598
        return s.equals("missed") || s.equals("no answer") || s.equals("noanswer");
1599
    }
1600
 
37013 ranu 1601
 
36234 ranu 1602
    public List<RbmCallTargetModel> getRbmCallTargetModels(LocalDate queryDate) throws Exception {
35631 ranu 1603
        long methodStart = System.currentTimeMillis();
1604
        List<RbmCallTargetModel> rbmCallTargetModels = new ArrayList<>();
1605
 
1606
        // Get all RBM positions (L1 and L2)
1607
        long start = System.currentTimeMillis();
1608
        List<Position> allRbmPositions = positionRepository
1609
                .selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_RBM).stream()
36210 ranu 1610
                .filter(x -> Arrays.asList(EscalationType.L1, EscalationType.L2, EscalationType.L3).contains(x.getEscalationType()))
35631 ranu 1611
                .collect(Collectors.toList());
1612
 
36210 ranu 1613
        // Separate L1, L2 and L3 auth IDs
35631 ranu 1614
        List<Integer> l1AuthIds = allRbmPositions.stream()
1615
                .filter(p -> EscalationType.L1.equals(p.getEscalationType()))
1616
                .map(Position::getAuthUserId).distinct().collect(Collectors.toList());
1617
        List<Integer> l2AuthIds = allRbmPositions.stream()
1618
                .filter(p -> EscalationType.L2.equals(p.getEscalationType()))
1619
                .map(Position::getAuthUserId).distinct().collect(Collectors.toList());
36210 ranu 1620
        List<Integer> l3AuthIds = allRbmPositions.stream()
1621
                .filter(p -> EscalationType.L3.equals(p.getEscalationType()))
1622
                .map(Position::getAuthUserId).distinct().collect(Collectors.toList());
35631 ranu 1623
 
1624
        // Union of all auth IDs for batch fetching
1625
        List<Integer> rbmPositionsAuthIds = allRbmPositions.stream()
1626
                .map(Position::getAuthUserId).distinct().collect(Collectors.toList());
36210 ranu 1627
        LOGGER.info("RBM Call Target - RBM positions fetch: {}ms, L1: {}, L2: {}, L3: {}", System.currentTimeMillis() - start, l1AuthIds.size(), l2AuthIds.size(), l3AuthIds.size());
35631 ranu 1628
 
1629
        start = System.currentTimeMillis();
1630
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1631
        LOGGER.info("RBM Call Target - StoreGuyMap fetch: {}ms", System.currentTimeMillis() - start);
1632
 
36234 ranu 1633
        LocalDateTime startDate = queryDate.atStartOfDay();
1634
        LocalDate firstOfMonth = queryDate.withDayOfMonth(1);
1635
        LocalDate endOfMonth = queryDate.withDayOfMonth(queryDate.lengthOfMonth()).plusDays(1);
35631 ranu 1636
 
1637
        // Get auth user map
1638
        start = System.currentTimeMillis();
1639
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(rbmPositionsAuthIds).stream()
1640
                .collect(Collectors.toMap(AuthUser::getId, au -> au));
1641
        LOGGER.info("RBM Call Target - AuthUser fetch: {}ms", System.currentTimeMillis() - start);
1642
 
1643
        // Batch fetch positions by auth IDs (to check if RBM is L1)
1644
        start = System.currentTimeMillis();
1645
        Map<Integer, List<Position>> positionsByAuthId = positionRepository.selectPositionByAuthIds(rbmPositionsAuthIds).stream()
1646
                .collect(Collectors.groupingBy(Position::getAuthUserId));
1647
        LOGGER.info("RBM Call Target - Positions by AuthId fetch: {}ms", System.currentTimeMillis() - start);
1648
 
1649
        // Get all fofo IDs for all RBMs
1650
        Set<Integer> allFofoIds = new HashSet<>();
1651
        Map<Integer, List<Integer>> rbmToFofoIdsMap = new HashMap<>();
1652
        for (int rbmAuthId : rbmPositionsAuthIds) {
1653
            AuthUser au = authUserMap.get(rbmAuthId);
1654
            if (au != null && storeGuyMap.containsKey(au.getEmailId())) {
1655
                List<Integer> fofoIds = new ArrayList<>(storeGuyMap.get(au.getEmailId()));
1656
                allFofoIds.addAll(fofoIds);
1657
                rbmToFofoIdsMap.put(rbmAuthId, fofoIds);
1658
            }
1659
        }
35816 ranu 1660
        // Initialize L2 calling list map - will be populated after fetching remarks
35631 ranu 1661
        Map<Integer, List<Integer>> l2AuthIdToFofoIds = new HashMap<>();
35816 ranu 1662
        for (int l2AuthId : l2AuthIds) {
1663
            l2AuthIdToFofoIds.put(l2AuthId, new ArrayList<>());
35631 ranu 1664
        }
36210 ranu 1665
        // Initialize L3 calling list map - will be populated after fetching remarks
1666
        Map<Integer, List<Integer>> l3AuthIdToFofoIds = new HashMap<>();
1667
        for (int l3AuthId : l3AuthIds) {
1668
            l3AuthIdToFofoIds.put(l3AuthId, new ArrayList<>());
1669
        }
35631 ranu 1670
        LOGGER.info("RBM Call Target - Total fofo IDs to process: {}", allFofoIds.size());
1671
 
1672
        // Get only needed fofo stores (OPTIMIZED - was fetching ALL stores before)
1673
        start = System.currentTimeMillis();
1674
        Map<Integer, FofoStore> fofoStoresMap = new HashMap<>();
1675
        if (!allFofoIds.isEmpty()) {
1676
            try {
1677
                fofoStoresMap = fofoStoreRepository.selectByRetailerIds(new ArrayList<>(allFofoIds)).stream()
1678
                        .collect(Collectors.toMap(FofoStore::getId, x -> x, (a, b) -> a));
1679
            } catch (ProfitMandiBusinessException e) {
1680
                LOGGER.error("Error fetching fofo stores", e);
1681
            }
1682
        }
1683
        LOGGER.info("RBM Call Target - FofoStores fetch (only needed): {}ms, count: {}", System.currentTimeMillis() - start, fofoStoresMap.size());
1684
 
1685
        // Batch fetch max remark ids for all fofoIds (for escalation filtering)
1686
        start = System.currentTimeMillis();
1687
        Map<Integer, PartnerCollectionRemark> allPartnerCollectionRemarks = new HashMap<>();
1688
        if (!allFofoIds.isEmpty()) {
1689
            List<Integer> allRemarkIds = partnerCollectionRemarkRepository.selectMaxRemarkId(new ArrayList<>(allFofoIds));
1690
            if (!allRemarkIds.isEmpty()) {
1691
                allPartnerCollectionRemarks = partnerCollectionRemarkRepository.selectByIds(allRemarkIds).stream()
1692
                        .collect(Collectors.toMap(PartnerCollectionRemark::getFofoId, x -> x, (a, b) -> a));
1693
            }
1694
        }
1695
        LOGGER.info("RBM Call Target - PartnerCollectionRemarks fetch: {}ms", System.currentTimeMillis() - start);
1696
 
35816 ranu 1697
        // Populate L2 calling list based on partners whose latest remark is RBM_L2_ESCALATION
1698
        // Find the L1 who has the partner and add to that L1's manager (L2) calling list
1699
        for (Map.Entry<Integer, PartnerCollectionRemark> entry : allPartnerCollectionRemarks.entrySet()) {
1700
            Integer fofoId = entry.getKey();
1701
            PartnerCollectionRemark remark = entry.getValue();
1702
 
1703
            if (CollectionRemark.RBM_L2_ESCALATION.equals(remark.getRemark())) {
1704
                // Find which L1 RBM has this partner assigned
1705
                for (int l1AuthId : l1AuthIds) {
1706
                    List<Integer> l1FofoIds = rbmToFofoIdsMap.getOrDefault(l1AuthId, Collections.emptyList());
1707
                    if (l1FofoIds.contains(fofoId)) {
1708
                        // Get L1's manager (L2)
1709
                        AuthUser l1User = authUserMap.get(l1AuthId);
1710
                        if (l1User != null && l2AuthIdToFofoIds.containsKey(l1User.getManagerId())) {
1711
                            int l2ManagerId = l1User.getManagerId();
1712
                            l2AuthIdToFofoIds.get(l2ManagerId).add(fofoId);
1713
                        }
1714
                        break; // Found the L1 for this fofoId
1715
                    }
1716
                }
1717
            }
1718
        }
1719
        LOGGER.info("RBM Call Target - L2 calling lists populated from RBM_L2_ESCALATION remarks");
1720
 
36210 ranu 1721
        // Populate L3 calling list based on partners whose latest remark is RBM_L3_ESCALATION
36212 ranu 1722
        // Find the L1 who originally has the partner, then:
1723
        // Case 1: L1 -> L3 directly (if L1's manager IS L3)
1724
        // Case 2: L1 -> L2 -> L3 (if L1's manager is L2, then L2's manager is L3)
36210 ranu 1725
        for (Map.Entry<Integer, PartnerCollectionRemark> entry : allPartnerCollectionRemarks.entrySet()) {
1726
            Integer fofoId = entry.getKey();
1727
            PartnerCollectionRemark remark = entry.getValue();
1728
 
1729
            if (CollectionRemark.RBM_L3_ESCALATION.equals(remark.getRemark())) {
1730
                // Find which L1 RBM originally has this partner assigned
1731
                for (int l1AuthId : l1AuthIds) {
1732
                    List<Integer> l1FofoIds = rbmToFofoIdsMap.getOrDefault(l1AuthId, Collections.emptyList());
1733
                    if (l1FofoIds.contains(fofoId)) {
1734
                        AuthUser l1User = authUserMap.get(l1AuthId);
1735
                        if (l1User != null) {
36212 ranu 1736
                            int l1ManagerId = l1User.getManagerId();
1737
                            // Case 1: L1's manager IS L3 directly (L1 → L3, no L2 in between)
1738
                            if (l3AuthIdToFofoIds.containsKey(l1ManagerId)) {
1739
                                l3AuthIdToFofoIds.get(l1ManagerId).add(fofoId);
1740
                                LOGGER.debug("L3 Calling List (direct): fofoId={} -> L1={} -> L3={}",
1741
                                        fofoId, l1AuthId, l1ManagerId);
1742
                            } else {
1743
                                // Case 2: L1 -> L2 -> L3
1744
                                AuthUser l2User = authUserMap.get(l1ManagerId);
1745
                                if (l2User != null && l3AuthIdToFofoIds.containsKey(l2User.getManagerId())) {
1746
                                    int l3ManagerId = l2User.getManagerId();
1747
                                    l3AuthIdToFofoIds.get(l3ManagerId).add(fofoId);
1748
                                    LOGGER.debug("L3 Calling List: fofoId={} -> L1={} -> L2={} -> L3={}",
1749
                                            fofoId, l1AuthId, l1ManagerId, l3ManagerId);
1750
                                }
36210 ranu 1751
                            }
1752
                        }
1753
                        break; // Found the L1 for this fofoId
1754
                    }
1755
                }
1756
            }
1757
        }
1758
        LOGGER.info("RBM Call Target - L3 calling lists populated from RBM_L3_ESCALATION remarks");
1759
 
35631 ranu 1760
        // Batch fetch collection RANK map for all fofoIds (OPTIMIZED - only fetches rank, not full model)
1761
        start = System.currentTimeMillis();
1762
        Map<Integer, Integer> allCollectionRankMap = new HashMap<>();
1763
        if (!allFofoIds.isEmpty()) {
1764
            try {
1765
                allCollectionRankMap = partnerCollectionService.getCollectionRankMap(new ArrayList<>(allFofoIds), startDate);
1766
            } catch (ProfitMandiBusinessException e) {
1767
                LOGGER.error("Error fetching collection rank map for all fofoIds", e);
1768
            }
1769
        }
1770
        LOGGER.info("RBM Call Target - CollectionRankMap fetch (OPTIMIZED): {}ms", System.currentTimeMillis() - start);
1771
 
35669 ranu 1772
        // Get MTD billing data for zero billing calculation and partner counts
35631 ranu 1773
        start = System.currentTimeMillis();
1774
        List<RbmWeeklyBillingModel> mtdBillingData = getWeeklyBillingDataForMonth(firstOfMonth, endOfMonth);
1775
        Set<Integer> allMtdBilledFofoIds = mtdBillingData.stream()
1776
                .filter(RbmWeeklyBillingModel::isMtdBilled)
1777
                .map(RbmWeeklyBillingModel::getFofoId)
1778
                .collect(Collectors.toSet());
35669 ranu 1779
        // Build partner count and fofoIds per RBM from mtdBillingData (same source as Today ARR page)
1780
        Map<Integer, Set<Integer>> mtdFofoIdsByAuthId = mtdBillingData.stream()
1781
                .filter(RbmWeeklyBillingModel::isTargetedPartner)
1782
                .collect(Collectors.groupingBy(RbmWeeklyBillingModel::getAuthId,
1783
                        Collectors.mapping(RbmWeeklyBillingModel::getFofoId, Collectors.toSet())));
35631 ranu 1784
        LOGGER.info("RBM Call Target - MTD Billing fetch: {}ms", System.currentTimeMillis() - start);
1785
 
1786
        // Batch fetch today's remarks for all auth IDs (to calculate Value Achieved)
1787
        start = System.currentTimeMillis();
1788
        Map<Integer, List<PartnerCollectionRemark>> remarksByAuthId = partnerCollectionRemarkRepository
1789
                .selectAllByAuthIdsOnDate(rbmPositionsAuthIds, LocalDate.now()).stream()
1790
                .collect(Collectors.groupingBy(PartnerCollectionRemark::getAuthId));
1791
        LOGGER.info("RBM Call Target - Today Remarks fetch: {}ms", System.currentTimeMillis() - start);
1792
 
1793
        // Batch fetch today's out-of-sequence logs for all RBMs
1794
        start = System.currentTimeMillis();
1795
        LocalDateTime todayStart = LocalDate.now().atStartOfDay();
1796
        LocalDateTime todayEnd = LocalDate.now().plusDays(1).atStartOfDay();
1797
        List<RbmCallSequenceLog> outOfSequenceLogs = rbmCallSequenceLogRepository.selectOutOfSequenceByDateRange(todayStart, todayEnd);
1798
        Map<Integer, Long> outOfSequenceCountByAuthId = outOfSequenceLogs.stream()
35654 ranu 1799
                .collect(Collectors.groupingBy(RbmCallSequenceLog::getAuthId,
1800
                        Collectors.mapping(RbmCallSequenceLog::getFofoId, Collectors.collectingAndThen(Collectors.toSet(), s -> (long) s.size()))));
35631 ranu 1801
        LOGGER.info("RBM Call Target - Out of Sequence fetch: {}ms", System.currentTimeMillis() - start);
1802
 
36284 ranu 1803
        // BATCH FETCH: All call logs for all RBMs (L1 + L2 + L3) in a single query.
1804
        // Replaces the previous N+1 pattern where getCallStats() was called per RBM.
1805
        start = System.currentTimeMillis();
1806
        List<AgentCallLog> allCallLogs = agentCallLogRepository.findByAuthIdsAndDate(rbmPositionsAuthIds, queryDate);
1807
        Map<Long, List<AgentCallLog>> callLogsByAuthId = allCallLogs.stream()
1808
                .collect(Collectors.groupingBy(AgentCallLog::getAuthId));
1809
        LOGGER.info("RBM Call Target - Call logs batch fetch: {}ms ({} logs across {} RBMs)",
1810
                System.currentTimeMillis() - start, allCallLogs.size(), callLogsByAuthId.size());
1811
 
1812
        // BATCH FETCH: Build a single mobile -> fofoId map from all unique customer numbers across all call logs.
1813
        // Replaces the previous N+1 pattern where findFofoIdByMobile() was called per call log entry.
1814
        start = System.currentTimeMillis();
1815
        Set<String> allNormalizedMobiles = new HashSet<>();
1816
        for (AgentCallLog callLog : allCallLogs) {
1817
            String customerNumber = callLog.getCustomerNumber();
1818
            if (customerNumber != null) {
1819
                String normalized = customerNumber.startsWith("+91") ? customerNumber.substring(3) : customerNumber;
1820
                allNormalizedMobiles.add(normalized);
1821
            }
1822
        }
1823
        Map<String, Integer> mobileToFofoIdMap = buildMobileToFofoIdMap(allNormalizedMobiles);
1824
        LOGGER.info("RBM Call Target - Mobile→FofoId batch fetch: {}ms ({} unique mobiles, {} mapped)",
1825
                System.currentTimeMillis() - start, allNormalizedMobiles.size(), mobileToFofoIdMap.size());
1826
 
36225 ranu 1827
        // Identify users who are both L1 and L2 — they will be shown only as L2
1828
        Set<Integer> l2AuthIdSet = new HashSet<>(l2AuthIds);
1829
 
1830
        // Process L1 RBMs (skip users who are also L2 — their data will be merged into L2 model)
35631 ranu 1831
        for (int rbmAuthId : l1AuthIds) {
36225 ranu 1832
            if (l2AuthIdSet.contains(rbmAuthId)) {
1833
                continue; // Will be handled in L2 processing with merged L1 data
1834
            }
35631 ranu 1835
            AuthUser authUser = authUserMap.get(rbmAuthId);
1836
            if (authUser == null || !storeGuyMap.containsKey(authUser.getEmailId())) {
1837
                continue;
1838
            }
1839
 
1840
            List<Integer> fofoIdList = rbmToFofoIdsMap.getOrDefault(rbmAuthId, Collections.emptyList());
1841
 
1842
            // Check if RBM is L1 (same logic as getSummaryModel)
1843
            List<Position> positions = positionsByAuthId.getOrDefault(authUser.getId(), Collections.emptyList());
1844
            boolean isRBMAndL1 = positions.stream()
1845
                    .anyMatch(position ->
1846
                            ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId()
1847
                                    && EscalationType.L1.equals(position.getEscalationType()));
1848
 
1849
            // Filter escalated partners for L1 RBMs (same logic as getSummaryModel)
1850
            List<Integer> fofoIds = fofoIdList;
1851
            if (isRBMAndL1) {
1852
                Map<Integer, PartnerCollectionRemark> partnerCollectionRemarks = new HashMap<>();
1853
                for (Integer fofoId : fofoIdList) {
1854
                    if (allPartnerCollectionRemarks.containsKey(fofoId)) {
1855
                        partnerCollectionRemarks.put(fofoId, allPartnerCollectionRemarks.get(fofoId));
1856
                    }
1857
                }
1858
                fofoIds = partnerCollectionRemarks.entrySet().stream()
1859
                        .filter(entry -> {
1860
                            PartnerCollectionRemark pcrMap = entry.getValue();
1861
                            return !(CollectionRemark.RBM_L2_ESCALATION.equals(pcrMap.getRemark())
1862
                                    || CollectionRemark.SALES_ESCALATION.equals(pcrMap.getRemark()));
1863
                        })
1864
                        .map(Map.Entry::getKey)
1865
                        .collect(Collectors.toList());
1866
            }
1867
 
36181 ranu 1868
            // Filter to only external, ACTIVE or REVIVAL stores (collection plan not required)
35631 ranu 1869
            Map<Integer, Integer> finalAllCollectionRankMap = allCollectionRankMap;
1870
            Map<Integer, FofoStore> finalFofoStoresMap = fofoStoresMap;
1871
            List<Integer> validFofoIds = fofoIds.stream()
1872
                    .filter(fofoId -> {
1873
                        FofoStore store = finalFofoStoresMap.get(fofoId);
1874
                        if (store == null || store.isInternal()) {
1875
                            return false;
1876
                        }
36181 ranu 1877
                        // Only include ACTIVE or REVIVAL partners (not Low Sale, not Disputed, not Billing Pending)
1878
                        return ActivationType.ACTIVE.equals(store.getActivationType())
1879
                                || ActivationType.REVIVAL.equals(store.getActivationType());
35631 ranu 1880
                    })
1881
                    .collect(Collectors.toList());
1882
 
1883
            if (validFofoIds.isEmpty()) {
1884
                continue;
1885
            }
1886
 
1887
            RbmCallTargetModel targetModel = new RbmCallTargetModel();
1888
            targetModel.setAuthId(rbmAuthId);
1889
            targetModel.setRbmName(authUser.getFullName());
35669 ranu 1890
            // Use partner count from mtdBillingData (same source as Today ARR page)
1891
            Set<Integer> mtdFofoIds = mtdFofoIdsByAuthId.getOrDefault(rbmAuthId, Collections.emptySet());
1892
            targetModel.setPartnerCount(mtdFofoIds.size());
35631 ranu 1893
 
1894
            // Categorize each partner - each partner belongs to ONE category only
35665 ranu 1895
            // Priority: PlanToday > CarryForward > ZeroBilling > Untouched > FuturePlan > Normal
36181 ranu 1896
            // Revival is counted separately (just for display, doesn't affect categorization)
35631 ranu 1897
            Set<Integer> planTodayPartners = new HashSet<>();
1898
            Set<Integer> carryForwardPartners = new HashSet<>();
1899
            Set<Integer> untouchedPartners = new HashSet<>();
1900
            Set<Integer> zeroBillingPartners = new HashSet<>();
1901
            Set<Integer> futurePlanPartners = new HashSet<>();
1902
            Set<Integer> normalPartners = new HashSet<>();
36181 ranu 1903
            Set<Integer> revivalPartners = new HashSet<>();
35631 ranu 1904
 
1905
            for (Integer fofoId : validFofoIds) {
1906
                // Get collection plan rank (from optimized rank map)
1907
                int rank = allCollectionRankMap.getOrDefault(fofoId, 5); // default to Normal if no plan
1908
 
1909
                // Check if partner has zero billing in MTD
1910
                boolean hasZeroBilling = !allMtdBilledFofoIds.contains(fofoId);
1911
 
36181 ranu 1912
                // Count REVIVAL partners separately (just for display, doesn't affect categorization)
1913
                FofoStore store = finalFofoStoresMap.get(fofoId);
1914
                if (store != null && ActivationType.REVIVAL.equals(store.getActivationType())) {
1915
                    revivalPartners.add(fofoId);
1916
                }
1917
 
35631 ranu 1918
                // Assign to category based on priority
1919
                if (rank == 1) {
1920
                    planTodayPartners.add(fofoId);
1921
                } else if (rank == 2) {
1922
                    carryForwardPartners.add(fofoId);
35665 ranu 1923
                } else if (hasZeroBilling) {
1924
                    zeroBillingPartners.add(fofoId);
35631 ranu 1925
                } else if (rank == 3) {
1926
                    untouchedPartners.add(fofoId);
1927
                } else if (rank == 4) {
1928
                    futurePlanPartners.add(fofoId);
1929
                } else {
1930
                    normalPartners.add(fofoId);
1931
                }
1932
            }
1933
 
1934
            // Set counts
1935
            targetModel.setCreditCollection(0); // Credit collection is handled in separate list
1936
            targetModel.setPlanToday(planTodayPartners.size());
1937
            targetModel.setCarryForward(carryForwardPartners.size());
1938
            targetModel.setUntouched(untouchedPartners.size());
1939
            targetModel.setZeroBilling(zeroBillingPartners.size());
1940
            targetModel.setFuturePlan(futurePlanPartners.size());
1941
            targetModel.setNormal(normalPartners.size());
36181 ranu 1942
            targetModel.setRevival(revivalPartners.size());
35631 ranu 1943
 
1944
            // Today Target = PlanToday + CarryForward + ZeroBilling + Untouched
1945
            // These are mutually exclusive now, so we can sum them
1946
            long todayTarget = planTodayPartners.size() +
1947
                    carryForwardPartners.size() + zeroBillingPartners.size() + untouchedPartners.size();
1948
            targetModel.setTodayTargetOfCall(todayTarget);
1949
 
1950
            // Create set of partners in Today Target categories
1951
            Set<Integer> todayTargetPartners = new HashSet<>();
1952
            todayTargetPartners.addAll(planTodayPartners);
1953
            todayTargetPartners.addAll(carryForwardPartners);
1954
            todayTargetPartners.addAll(zeroBillingPartners);
1955
            todayTargetPartners.addAll(untouchedPartners);
1956
 
36284 ranu 1957
            // Value Achieved = All distinct partners called today (from pre-fetched call logs)
37010 ranu 1958
            List<AgentCallLog> l1Logs = callLogsByAuthId.get((long) rbmAuthId);
1959
            long[] callStats = getCallStatsFromLogs(l1Logs, mobileToFofoIdMap);
36276 ranu 1960
            targetModel.setValueTargetAchieved(callStats[0]);
1961
            targetModel.setTotalRecordingCalls(callStats[1]);
1962
            targetModel.setUniqueRecordingCalls(callStats[2]);
37022 ranu 1963
            targetModel.setTriedUniqueCalls(computeUniqueTriedCount(l1Logs, mobileToFofoIdMap));
1964
            targetModel.setTgtCalls(computeUniqueTriedCountForTargets(l1Logs, mobileToFofoIdMap, todayTargetPartners));
35631 ranu 1965
 
37012 ranu 1966
            // Keep todayRemarks for movedToFuture calculation
35843 ranu 1967
            List<PartnerCollectionRemark> todayRemarks = remarksByAuthId.getOrDefault(rbmAuthId, Collections.emptyList());
1968
 
35631 ranu 1969
            // Moved to Future = Partners in Future Plan category who have a remark today
1970
            // These are partners who were contacted today but moved to a future date
1971
            Set<Integer> todayRemarkedFofoIds = todayRemarks.stream()
1972
                    .map(PartnerCollectionRemark::getFofoId)
1973
                    .collect(Collectors.toSet());
1974
            long movedToFuture = futurePlanPartners.stream()
1975
                    .filter(todayRemarkedFofoIds::contains)
1976
                    .count();
1977
            targetModel.setMovedToFuture(movedToFuture);
1978
 
1979
            // Set out of sequence count for this RBM
1980
            targetModel.setOutOfSequenceCount(outOfSequenceCountByAuthId.getOrDefault(rbmAuthId, 0L));
1981
 
1982
            rbmCallTargetModels.add(targetModel);
1983
        }
1984
 
1985
        // Process L2 RBMs (escalated ticket logic with categorization)
36225 ranu 1986
        // For users who are both L1 and L2, merge their L1 calling target into L2 model
35631 ranu 1987
        for (int l2AuthId : l2AuthIds) {
1988
            AuthUser authUser = authUserMap.get(l2AuthId);
1989
            if (authUser == null) {
1990
                continue;
1991
            }
1992
 
1993
            List<Integer> l2FofoIdList = l2AuthIdToFofoIds.getOrDefault(l2AuthId, Collections.emptyList());
1994
 
35816 ranu 1995
            // For L2, use unique fofoIds with RBM_L2_ESCALATION remark as target
35662 ranu 1996
            Set<Integer> l2TargetFofoIds = new HashSet<>(l2FofoIdList);
35631 ranu 1997
 
37022 ranu 1998
            // Collected from the L1-merge branch below when the user is also L1. Used later
1999
            // for the TGT Calls scope: L2 escalation + L1 target buckets.
2000
            Set<Integer> l1MergedTargetPartners = new HashSet<>();
2001
 
35631 ranu 2002
            RbmCallTargetModel l2Model = new RbmCallTargetModel();
2003
            l2Model.setAuthId(l2AuthId);
2004
            l2Model.setRbmName(authUser.getFullName() + " (L2)");
2005
            l2Model.setL2Position(true);
35816 ranu 2006
            l2Model.setL2CallingList(l2TargetFofoIds.size());
36228 ranu 2007
            // Partner count: if user is also L1, use L1 partner count (MTD targeted partners)
2008
            if (l1AuthIds.contains(l2AuthId)) {
2009
                Set<Integer> mtdFofoIds = mtdFofoIdsByAuthId.getOrDefault(l2AuthId, Collections.emptySet());
2010
                l2Model.setPartnerCount(mtdFofoIds.size());
2011
            } else {
2012
                List<Integer> l2AssignedFofoIds = rbmToFofoIdsMap.getOrDefault(l2AuthId, Collections.emptyList());
2013
                l2Model.setPartnerCount(l2AssignedFofoIds.size());
2014
            }
35631 ranu 2015
 
36229 ranu 2016
            // If user is also L1, calculate full L1 breakdown and merge into L2 model
36225 ranu 2017
            if (l1AuthIds.contains(l2AuthId) && storeGuyMap.containsKey(authUser.getEmailId())) {
36229 ranu 2018
                // Get only L1 RBM position partners (not L2 partners) from partner_position
36225 ranu 2019
                List<Position> positions = positionsByAuthId.getOrDefault(l2AuthId, Collections.emptyList());
36229 ranu 2020
                Set<Integer> l1RbmPositionIds = positions.stream()
2021
                        .filter(p -> ProfitMandiConstants.TICKET_CATEGORY_RBM == p.getCategoryId()
2022
                                && EscalationType.L1.equals(p.getEscalationType()))
2023
                        .map(Position::getId)
2024
                        .collect(Collectors.toSet());
2025
                // Fetch partner_position for only L1 RBM positions of this user
2026
                List<Integer> fofoIdList = partnerPositionRepository
2027
                        .selectByPositionIds(new ArrayList<>(l1RbmPositionIds)).stream()
2028
                        .map(pp -> pp.getFofoId())
2029
                        .distinct()
2030
                        .collect(Collectors.toList());
2031
                boolean isRBMAndL1 = !l1RbmPositionIds.isEmpty();
36225 ranu 2032
                List<Integer> l1FofoIds = new ArrayList<>(fofoIdList);
2033
                if (isRBMAndL1) {
2034
                    Map<Integer, PartnerCollectionRemark> partnerCollectionRemarks = new HashMap<>();
2035
                    for (Integer fofoId : fofoIdList) {
2036
                        if (allPartnerCollectionRemarks.containsKey(fofoId)) {
2037
                            partnerCollectionRemarks.put(fofoId, allPartnerCollectionRemarks.get(fofoId));
2038
                        }
2039
                    }
2040
                    l1FofoIds = partnerCollectionRemarks.entrySet().stream()
2041
                            .filter(entry -> {
2042
                                PartnerCollectionRemark pcrMap = entry.getValue();
2043
                                return !(CollectionRemark.RBM_L2_ESCALATION.equals(pcrMap.getRemark())
2044
                                        || CollectionRemark.SALES_ESCALATION.equals(pcrMap.getRemark()));
2045
                            })
2046
                            .map(Map.Entry::getKey)
2047
                            .collect(Collectors.toList());
2048
                }
2049
                Map<Integer, FofoStore> finalFofoStoresMap2 = fofoStoresMap;
2050
                List<Integer> validL1FofoIds = l1FofoIds.stream()
2051
                        .filter(fofoId -> {
2052
                            FofoStore store = finalFofoStoresMap2.get(fofoId);
2053
                            if (store == null || store.isInternal()) return false;
2054
                            return ActivationType.ACTIVE.equals(store.getActivationType())
2055
                                    || ActivationType.REVIVAL.equals(store.getActivationType());
2056
                        })
2057
                        .collect(Collectors.toList());
35631 ranu 2058
 
36229 ranu 2059
                // Categorize L1 partners — same logic as L1 processing
2060
                Set<Integer> planTodayPartners = new HashSet<>();
2061
                Set<Integer> carryForwardPartners = new HashSet<>();
2062
                Set<Integer> untouchedPartners = new HashSet<>();
2063
                Set<Integer> zeroBillingPartners = new HashSet<>();
2064
                Set<Integer> futurePlanPartners = new HashSet<>();
2065
                Set<Integer> normalPartners = new HashSet<>();
2066
                Set<Integer> revivalPartners = new HashSet<>();
2067
 
36225 ranu 2068
                for (Integer fofoId : validL1FofoIds) {
2069
                    int rank = allCollectionRankMap.getOrDefault(fofoId, 5);
2070
                    boolean hasZeroBilling = !allMtdBilledFofoIds.contains(fofoId);
36229 ranu 2071
                    FofoStore store = finalFofoStoresMap2.get(fofoId);
2072
                    if (store != null && ActivationType.REVIVAL.equals(store.getActivationType())) {
2073
                        revivalPartners.add(fofoId);
36225 ranu 2074
                    }
36229 ranu 2075
                    if (rank == 1) {
2076
                        planTodayPartners.add(fofoId);
2077
                    } else if (rank == 2) {
2078
                        carryForwardPartners.add(fofoId);
2079
                    } else if (hasZeroBilling) {
2080
                        zeroBillingPartners.add(fofoId);
2081
                    } else if (rank == 3) {
2082
                        untouchedPartners.add(fofoId);
2083
                    } else if (rank == 4) {
2084
                        futurePlanPartners.add(fofoId);
2085
                    } else {
2086
                        normalPartners.add(fofoId);
2087
                    }
36225 ranu 2088
                }
36229 ranu 2089
 
2090
                // Set L1 breakdown fields on L2 model
2091
                l2Model.setPlanToday(planTodayPartners.size());
2092
                l2Model.setCarryForward(carryForwardPartners.size());
2093
                l2Model.setZeroBilling(zeroBillingPartners.size());
2094
                l2Model.setUntouched(untouchedPartners.size());
2095
                l2Model.setFuturePlan(futurePlanPartners.size());
2096
                l2Model.setNormal(normalPartners.size());
2097
                l2Model.setRevival(revivalPartners.size());
2098
 
2099
                long l1OwnTarget = planTodayPartners.size() + carryForwardPartners.size()
2100
                        + zeroBillingPartners.size() + untouchedPartners.size();
2101
 
37022 ranu 2102
                // Feed the L1 target sets up to the outer scope so TGT Calls can include them.
2103
                l1MergedTargetPartners.addAll(planTodayPartners);
2104
                l1MergedTargetPartners.addAll(carryForwardPartners);
2105
                l1MergedTargetPartners.addAll(zeroBillingPartners);
2106
                l1MergedTargetPartners.addAll(untouchedPartners);
2107
 
36229 ranu 2108
                // Today Target = own L1 target + L2 escalation
2109
                l2Model.setTodayTargetOfCall(l2TargetFofoIds.size() + l1OwnTarget);
2110
 
2111
                // Moved to Future from L1 partners
2112
                List<PartnerCollectionRemark> todayRemarks = remarksByAuthId.getOrDefault(l2AuthId, Collections.emptyList());
2113
                Set<Integer> todayRemarkedFofoIds = todayRemarks.stream()
2114
                        .map(PartnerCollectionRemark::getFofoId)
2115
                        .collect(Collectors.toSet());
2116
                long movedToFuture = futurePlanPartners.stream()
2117
                        .filter(todayRemarkedFofoIds::contains)
2118
                        .count();
2119
                l2Model.setMovedToFuture(movedToFuture);
2120
            } else {
2121
                // Pure L2 (not also L1) — target is only L2 escalation
2122
                l2Model.setTodayTargetOfCall(l2TargetFofoIds.size());
36225 ranu 2123
            }
2124
 
36284 ranu 2125
            // Value Achieved = All distinct partners called today (from pre-fetched call logs)
37010 ranu 2126
            List<AgentCallLog> l2Logs = callLogsByAuthId.get((long) l2AuthId);
2127
            long[] l2CallStats = getCallStatsFromLogs(l2Logs, mobileToFofoIdMap);
36276 ranu 2128
            l2Model.setValueTargetAchieved(l2CallStats[0]);
2129
            l2Model.setTotalRecordingCalls(l2CallStats[1]);
2130
            l2Model.setUniqueRecordingCalls(l2CallStats[2]);
37022 ranu 2131
            l2Model.setTriedUniqueCalls(computeUniqueTriedCount(l2Logs, mobileToFofoIdMap));
35631 ranu 2132
 
37022 ranu 2133
            // TGT Calls scope: L2 escalation + (if user is also L1) the L1 target buckets.
2134
            Set<Integer> l2TgtSet = new HashSet<>(l2TargetFofoIds);
2135
            l2TgtSet.addAll(l1MergedTargetPartners);
2136
            l2Model.setTgtCalls(computeUniqueTriedCountForTargets(l2Logs, mobileToFofoIdMap, l2TgtSet));
2137
 
35631 ranu 2138
            l2Model.setOutOfSequenceCount(outOfSequenceCountByAuthId.getOrDefault(l2AuthId, 0L));
2139
            rbmCallTargetModels.add(l2Model);
2140
        }
2141
 
36210 ranu 2142
        // Process L3 RBMs (escalated ticket logic with categorization)
2143
        for (int l3AuthId : l3AuthIds) {
2144
            AuthUser authUser = authUserMap.get(l3AuthId);
2145
            if (authUser == null) {
2146
                continue;
2147
            }
2148
 
2149
            List<Integer> l3FofoIdList = l3AuthIdToFofoIds.getOrDefault(l3AuthId, Collections.emptyList());
2150
 
2151
            // For L3, use unique fofoIds with RBM_L3_ESCALATION remark as target
2152
            Set<Integer> l3TargetFofoIds = new HashSet<>(l3FofoIdList);
2153
 
2154
            RbmCallTargetModel l3Model = new RbmCallTargetModel();
2155
            l3Model.setAuthId(l3AuthId);
2156
            l3Model.setRbmName(authUser.getFullName() + " (L3)");
2157
            l3Model.setL3Position(true);
2158
            l3Model.setL3CallingList(l3TargetFofoIds.size());
36359 ranu 2159
            // Partner count = total assigned partners (excluding internal)
2160
            Map<Integer, FofoStore> finalFofoStoresMapL3 = fofoStoresMap;
36210 ranu 2161
            List<Integer> l3AssignedFofoIds = rbmToFofoIdsMap.getOrDefault(l3AuthId, Collections.emptyList());
36359 ranu 2162
            long l3ExternalPartnerCount = l3AssignedFofoIds.stream()
2163
                    .filter(fofoId -> {
2164
                        FofoStore store = finalFofoStoresMapL3.get(fofoId);
2165
                        return store != null && !store.isInternal();
2166
                    })
2167
                    .count();
2168
            l3Model.setPartnerCount(l3ExternalPartnerCount);
36210 ranu 2169
 
2170
            // L3 Target = partners with RBM_L3_ESCALATION as latest remark
2171
            l3Model.setTodayTargetOfCall(l3TargetFofoIds.size());
2172
 
36284 ranu 2173
            // Value Achieved = All distinct partners called today (from pre-fetched call logs)
37010 ranu 2174
            List<AgentCallLog> l3Logs = callLogsByAuthId.get((long) l3AuthId);
2175
            long[] l3CallStats = getCallStatsFromLogs(l3Logs, mobileToFofoIdMap);
36276 ranu 2176
            l3Model.setValueTargetAchieved(l3CallStats[0]);
2177
            l3Model.setTotalRecordingCalls(l3CallStats[1]);
2178
            l3Model.setUniqueRecordingCalls(l3CallStats[2]);
37022 ranu 2179
            l3Model.setTriedUniqueCalls(computeUniqueTriedCount(l3Logs, mobileToFofoIdMap));
2180
            // L3 TGT Calls scope: L3 escalation partners.
2181
            l3Model.setTgtCalls(computeUniqueTriedCountForTargets(l3Logs, mobileToFofoIdMap, l3TargetFofoIds));
36210 ranu 2182
 
2183
            l3Model.setOutOfSequenceCount(outOfSequenceCountByAuthId.getOrDefault(l3AuthId, 0L));
2184
            rbmCallTargetModels.add(l3Model);
2185
        }
2186
 
36225 ranu 2187
        // Group models by escalation level
36210 ranu 2188
        Map<Integer, RbmCallTargetModel> l3ModelsByAuthId = new HashMap<>();
35631 ranu 2189
        Map<Integer, RbmCallTargetModel> l2ModelsByAuthId = new HashMap<>();
2190
        Map<Integer, RbmCallTargetModel> l1ModelsByAuthId = new HashMap<>();
2191
        for (RbmCallTargetModel m : rbmCallTargetModels) {
36210 ranu 2192
            if (m.isL3Position()) {
2193
                l3ModelsByAuthId.put(m.getAuthId(), m);
2194
            } else if (m.isL2Position()) {
35631 ranu 2195
                l2ModelsByAuthId.put(m.getAuthId(), m);
2196
            } else {
2197
                l1ModelsByAuthId.put(m.getAuthId(), m);
2198
            }
2199
        }
2200
 
36225 ranu 2201
        // Build partner-based hierarchy using partner_position table
2202
        // Map positionId -> Position for quick lookup
2203
        Map<Integer, Position> positionByIdMap = allRbmPositions.stream()
2204
                .collect(Collectors.toMap(Position::getId, p -> p, (a, b) -> a));
2205
 
2206
        // Get all RBM position IDs and fetch their partner assignments
2207
        List<Integer> allRbmPositionIds = allRbmPositions.stream()
2208
                .map(Position::getId).collect(Collectors.toList());
2209
        List<com.spice.profitmandi.dao.entity.cs.PartnerPosition> allPartnerPositions =
2210
                partnerPositionRepository.selectByPositionIds(allRbmPositionIds);
2211
 
2212
        // Build partnerId -> map of escalationType -> Set<authUserIds>
2213
        // This tells us for each partner, who is their L1, L2, L3
2214
        Map<Integer, Map<EscalationType, Set<Integer>>> partnerToAuthByLevel = new HashMap<>();
2215
        for (com.spice.profitmandi.dao.entity.cs.PartnerPosition pp : allPartnerPositions) {
2216
            Position pos = positionByIdMap.get(pp.getPositionId());
2217
            if (pos != null && pos.getEscalationType() != null) {
2218
                partnerToAuthByLevel
2219
                        .computeIfAbsent(pp.getFofoId(), k -> new HashMap<>())
2220
                        .computeIfAbsent(pos.getEscalationType(), k -> new HashSet<>())
2221
                        .add(pos.getAuthUserId());
2222
            }
2223
        }
2224
 
2225
        // Build L2 -> L1 team map based on shared partners
2226
        // If an L1 and L2 share partners (L1 at L1 level, L2 at L2 level), that L1 belongs under that L2
2227
        Map<Integer, List<RbmCallTargetModel>> l2TeamMap = new LinkedHashMap<>();
2228
        for (RbmCallTargetModel l2Model : l2ModelsByAuthId.values()) {
2229
            l2TeamMap.put(l2Model.getAuthId(), new ArrayList<>());
2230
        }
2231
 
2232
        // Build L3 -> L2 team map based on shared partners
36210 ranu 2233
        Map<Integer, List<RbmCallTargetModel>> l3TeamMap = new LinkedHashMap<>();
2234
        for (RbmCallTargetModel l3Model : l3ModelsByAuthId.values()) {
2235
            l3TeamMap.put(l3Model.getAuthId(), new ArrayList<>());
2236
        }
2237
 
36225 ranu 2238
        // For each L1, find which L2 shares the most partners -> that's their L2
2239
        Set<Integer> addedL1AuthIds = new HashSet<>();
2240
        for (RbmCallTargetModel l1Model : l1ModelsByAuthId.values()) {
2241
            Map<Integer, Integer> l2SharedCount = new HashMap<>(); // l2AuthId -> shared partner count
2242
            for (Map.Entry<Integer, Map<EscalationType, Set<Integer>>> entry : partnerToAuthByLevel.entrySet()) {
2243
                Map<EscalationType, Set<Integer>> levelMap = entry.getValue();
2244
                Set<Integer> l1IdsForPartner = levelMap.getOrDefault(EscalationType.L1, Collections.emptySet());
2245
                Set<Integer> l2AuthIdsForPartner = levelMap.getOrDefault(EscalationType.L2, Collections.emptySet());
2246
                if (l1IdsForPartner.contains(l1Model.getAuthId())) {
2247
                    for (int l2Id : l2AuthIdsForPartner) {
2248
                        if (l2ModelsByAuthId.containsKey(l2Id) && l2Id != l1Model.getAuthId()) {
2249
                            l2SharedCount.merge(l2Id, 1, Integer::sum);
2250
                        }
2251
                    }
2252
                }
2253
            }
2254
            // Assign L1 to the L2 with most shared partners
2255
            if (!l2SharedCount.isEmpty()) {
2256
                int bestL2 = l2SharedCount.entrySet().stream()
2257
                        .max(Map.Entry.comparingByValue()).get().getKey();
2258
                l2TeamMap.get(bestL2).add(l1Model);
2259
                addedL1AuthIds.add(l1Model.getAuthId());
2260
            }
2261
        }
2262
 
2263
        // For each L2, find which L3 shares the most partners -> that's their L3
36210 ranu 2264
        Set<Integer> addedL2AuthIds = new HashSet<>();
2265
        for (RbmCallTargetModel l2Model : l2ModelsByAuthId.values()) {
36225 ranu 2266
            Map<Integer, Integer> l3SharedCount = new HashMap<>();
2267
            for (Map.Entry<Integer, Map<EscalationType, Set<Integer>>> entry : partnerToAuthByLevel.entrySet()) {
2268
                Map<EscalationType, Set<Integer>> levelMap = entry.getValue();
2269
                Set<Integer> l2AuthIdsForPartner = levelMap.getOrDefault(EscalationType.L2, Collections.emptySet());
2270
                Set<Integer> l3AuthIdsForPartner = levelMap.getOrDefault(EscalationType.L3, Collections.emptySet());
2271
                if (l2AuthIdsForPartner.contains(l2Model.getAuthId())) {
2272
                    for (int l3Id : l3AuthIdsForPartner) {
2273
                        if (l3ModelsByAuthId.containsKey(l3Id)) {
2274
                            l3SharedCount.merge(l3Id, 1, Integer::sum);
2275
                        }
2276
                    }
2277
                }
2278
            }
2279
            if (!l3SharedCount.isEmpty()) {
2280
                int bestL3 = l3SharedCount.entrySet().stream()
2281
                        .max(Map.Entry.comparingByValue()).get().getKey();
2282
                l3TeamMap.get(bestL3).add(l2Model);
36210 ranu 2283
                addedL2AuthIds.add(l2Model.getAuthId());
2284
            }
2285
        }
2286
 
36225 ranu 2287
        // For L1s not mapped to any L2, check if they map directly to an L3 via shared partners
2288
        Map<Integer, List<RbmCallTargetModel>> l3DirectL1Map = new LinkedHashMap<>();
2289
        for (RbmCallTargetModel l3Model : l3ModelsByAuthId.values()) {
2290
            l3DirectL1Map.put(l3Model.getAuthId(), new ArrayList<>());
35631 ranu 2291
        }
2292
        for (RbmCallTargetModel l1Model : l1ModelsByAuthId.values()) {
36225 ranu 2293
            if (addedL1AuthIds.contains(l1Model.getAuthId())) continue;
2294
            Map<Integer, Integer> l3SharedCount = new HashMap<>();
2295
            for (Map.Entry<Integer, Map<EscalationType, Set<Integer>>> entry : partnerToAuthByLevel.entrySet()) {
2296
                Map<EscalationType, Set<Integer>> levelMap = entry.getValue();
2297
                Set<Integer> l1IdsForPartner = levelMap.getOrDefault(EscalationType.L1, Collections.emptySet());
2298
                Set<Integer> l3AuthIdsForPartner = levelMap.getOrDefault(EscalationType.L3, Collections.emptySet());
2299
                if (l1IdsForPartner.contains(l1Model.getAuthId())) {
2300
                    for (int l3Id : l3AuthIdsForPartner) {
2301
                        if (l3ModelsByAuthId.containsKey(l3Id)) {
2302
                            l3SharedCount.merge(l3Id, 1, Integer::sum);
2303
                        }
2304
                    }
2305
                }
2306
            }
2307
            if (!l3SharedCount.isEmpty()) {
2308
                int bestL3 = l3SharedCount.entrySet().stream()
2309
                        .max(Map.Entry.comparingByValue()).get().getKey();
2310
                l3DirectL1Map.get(bestL3).add(l1Model);
35631 ranu 2311
                addedL1AuthIds.add(l1Model.getAuthId());
2312
            }
2313
        }
2314
 
36225 ranu 2315
        // Build sorted result: L3 -> L2 -> L1 (with direct L1s under L3 if no L2)
35631 ranu 2316
        List<RbmCallTargetModel> sortedModels = new ArrayList<>();
2317
 
36210 ranu 2318
        List<RbmCallTargetModel> l3Sorted = new ArrayList<>(l3ModelsByAuthId.values());
2319
        l3Sorted.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
35631 ranu 2320
 
36210 ranu 2321
        for (RbmCallTargetModel l3Model : l3Sorted) {
2322
            sortedModels.add(l3Model);
2323
            List<RbmCallTargetModel> l2Team = l3TeamMap.getOrDefault(l3Model.getAuthId(), Collections.emptyList());
2324
            l2Team.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
2325
            for (RbmCallTargetModel l2Model : l2Team) {
2326
                sortedModels.add(l2Model);
2327
                List<RbmCallTargetModel> l1Team = l2TeamMap.getOrDefault(l2Model.getAuthId(), Collections.emptyList());
2328
                l1Team.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
2329
                sortedModels.addAll(l1Team);
2330
            }
36225 ranu 2331
            // Add L1s that report directly to this L3 (no L2 in between)
2332
            List<RbmCallTargetModel> directL1Team = l3DirectL1Map.getOrDefault(l3Model.getAuthId(), Collections.emptyList());
2333
            directL1Team.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
2334
            sortedModels.addAll(directL1Team);
36210 ranu 2335
        }
2336
 
36225 ranu 2337
        // Add L2s not mapped to any L3
36210 ranu 2338
        List<RbmCallTargetModel> unmappedL2 = new ArrayList<>();
2339
        for (RbmCallTargetModel l2Model : l2ModelsByAuthId.values()) {
2340
            if (!addedL2AuthIds.contains(l2Model.getAuthId())) {
2341
                unmappedL2.add(l2Model);
2342
            }
2343
        }
2344
        unmappedL2.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
2345
        for (RbmCallTargetModel l2Model : unmappedL2) {
35631 ranu 2346
            sortedModels.add(l2Model);
2347
            List<RbmCallTargetModel> team = l2TeamMap.getOrDefault(l2Model.getAuthId(), Collections.emptyList());
2348
            team.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
2349
            sortedModels.addAll(team);
2350
        }
2351
 
36225 ranu 2352
        // Add any L1s not mapped to any L2 or L3
35631 ranu 2353
        List<RbmCallTargetModel> unmappedL1 = new ArrayList<>();
2354
        for (RbmCallTargetModel m : l1ModelsByAuthId.values()) {
2355
            if (!addedL1AuthIds.contains(m.getAuthId())) {
2356
                unmappedL1.add(m);
2357
            }
2358
        }
2359
        unmappedL1.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
2360
        sortedModels.addAll(unmappedL1);
2361
 
2362
        LOGGER.info("RBM Call Target - TOTAL TIME: {}ms, RBM count: {}", System.currentTimeMillis() - methodStart, sortedModels.size());
2363
        return sortedModels;
2364
    }
2365
 
35843 ranu 2366
    /**
37011 ranu 2367
     * Rule: count each distinct customer number this RBM attempted today, based on
37012 ranu 2368
     * the vendor-reported customer-side outcome (AgentCallLog.customerStatus):
2369
     *   - If ANY call to this number has customerStatus that is not "Missed"
2370
     *     → count as 1 (customer was reached at some point).
2371
     *   - Else (every call to this number was Missed) → count only if attempts >= 3
37011 ranu 2372
     *     (persistence credit).
37012 ranu 2373
     * null/empty customerStatus is treated as "not Missed" (favours counting when
2374
     * the vendor didn't classify the outcome).
35843 ranu 2375
     */
37022 ranu 2376
    private long computeUniqueTriedCount(List<AgentCallLog> callLogs,
2377
                                         Map<String, Integer> mobileToFofoIdMap) {
37010 ranu 2378
        if (callLogs == null || callLogs.isEmpty()) return 0L;
37022 ranu 2379
        // Group by fofoId (not raw number) — numbers that don't resolve to a partner via
2380
        // retailer_contact/address are skipped. Once a number gets added to retailer_contact
2381
        // it'll automatically resolve and start counting on the next page load.
2382
        Map<Integer, List<AgentCallLog>> byFofoId = new HashMap<>();
37010 ranu 2383
        for (AgentCallLog log : callLogs) {
2384
            String num = log.getCustomerNumber();
2385
            if (num == null) continue;
2386
            String normalized = num.startsWith("+91") ? num.substring(3) : num;
37022 ranu 2387
            Integer fofoId = mobileToFofoIdMap != null ? mobileToFofoIdMap.get(normalized) : null;
2388
            if (fofoId == null) continue; // unknown number — excluded from Tried
2389
            byFofoId.computeIfAbsent(fofoId, k -> new ArrayList<>()).add(log);
36284 ranu 2390
        }
37010 ranu 2391
        long count = 0L;
37022 ranu 2392
        for (List<AgentCallLog> logs : byFofoId.values()) {
37012 ranu 2393
            boolean hasNonMissed = false;
2394
            for (AgentCallLog l : logs) {
2395
                if (!isMissedCustomerStatus(l.getCustomerStatus())) {
2396
                    hasNonMissed = true;
37010 ranu 2397
                    break;
36284 ranu 2398
                }
2399
            }
37012 ranu 2400
            if (hasNonMissed) count++;
2401
            else if (logs.size() >= 3) count++;
36284 ranu 2402
        }
37010 ranu 2403
        return count;
36284 ranu 2404
    }
2405
 
2406
    /**
36276 ranu 2407
     * Returns call stats: [0] = called count, [1] = total recording calls, [2] = unique recording calls
2408
     */
2409
    public long[] getCallStats(long authId, LocalDate date) {
36234 ranu 2410
        List<AgentCallLog> callLogs = agentCallLogRepository.findByAuthIdAndDate(authId, date);
2411
 
35843 ranu 2412
        if (callLogs == null || callLogs.isEmpty()) {
36276 ranu 2413
            return new long[]{0, 0, 0};
35843 ranu 2414
        }
2415
 
2416
        Set<Integer> calledFofoIds = new HashSet<>();
2417
        Set<String> calledNumbersWithoutFofoId = new HashSet<>();
36276 ranu 2418
        long totalRecordingCalls = 0;
2419
        Set<String> uniqueRecordingNumbers = new HashSet<>();
35843 ranu 2420
 
2421
        for (AgentCallLog callLog : callLogs) {
2422
            String customerNumber = callLog.getCustomerNumber();
2423
            if (customerNumber != null) {
2424
                // Normalize the phone number (remove +91 prefix if present)
2425
                String normalized = customerNumber.startsWith("+91") ? customerNumber.substring(3) : customerNumber;
2426
 
2427
                // Find fofoId from retailer_contact or address
2428
                Integer fofoId = findFofoIdByMobile(normalized);
2429
                if (fofoId != null) {
2430
                    calledFofoIds.add(fofoId);
2431
                } else {
2432
                    // Number not found in retailer_contact or address, count by distinct number
2433
                    calledNumbersWithoutFofoId.add(normalized);
2434
                }
36276 ranu 2435
 
2436
                // Count calls with recordings
2437
                if (callLog.getRecordingUrl() != null && !callLog.getRecordingUrl().isEmpty()
2438
                        && !"None".equalsIgnoreCase(callLog.getRecordingUrl())) {
2439
                    totalRecordingCalls++;
2440
                    uniqueRecordingNumbers.add(normalized);
2441
                }
35843 ranu 2442
            }
2443
        }
2444
 
2445
        // Total called = distinct fofoIds + distinct numbers without fofoId mapping
36276 ranu 2446
        long calledCount = calledFofoIds.size() + calledNumbersWithoutFofoId.size();
2447
        return new long[]{calledCount, totalRecordingCalls, uniqueRecordingNumbers.size()};
35843 ranu 2448
    }
2449
 
35852 ranu 2450
    @Override
2451
    public List<List<String>> getAllCallDataByDate(LocalDate date) throws Exception {
2452
        List<List<String>> rows = new ArrayList<>();
2453
 
2454
        // Add header row
2455
        rows.add(Arrays.asList("RBM Name", "Partner Name", "Code", "Remark", "Call Status", "Call Duration", "Call Date Time", "Recording URL"));
2456
 
2457
        // Get all call logs for the date
2458
        List<AgentCallLog> allCallLogs = agentCallLogRepository.findAllByDate(date);
2459
        LOGGER.info("getAllCallDataByDate: Found {} call logs for date {}", allCallLogs.size(), date);
2460
 
2461
        if (allCallLogs.isEmpty()) {
2462
            return rows;
2463
        }
2464
 
2465
        // Get unique authIds from call logs
2466
        Set<Long> authIds = allCallLogs.stream()
2467
                .map(AgentCallLog::getAuthId)
2468
                .collect(Collectors.toSet());
2469
 
2470
        // Get auth users for RBM names
2471
        List<Integer> authIdInts = authIds.stream().map(Long::intValue).collect(Collectors.toList());
2472
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(authIdInts).stream()
2473
                .collect(Collectors.toMap(AuthUser::getId, au -> au, (a, b) -> a));
2474
 
2475
        // Build a map of normalized customer number -> fofoId
2476
        Map<String, Integer> customerToFofoIdMap = new HashMap<>();
2477
        Set<String> normalizedNumbers = new HashSet<>();
2478
 
2479
        for (AgentCallLog callLog : allCallLogs) {
2480
            String customerNumber = callLog.getCustomerNumber();
2481
            if (customerNumber != null) {
2482
                String normalized = customerNumber.startsWith("+91") ? customerNumber.substring(3) : customerNumber;
2483
                normalizedNumbers.add(normalized);
2484
            }
2485
        }
2486
 
2487
        // For each normalized number, find fofoId
2488
        for (String mobile : normalizedNumbers) {
2489
            Integer fofoId = findFofoIdByMobile(mobile);
2490
            if (fofoId != null) {
2491
                customerToFofoIdMap.put(mobile, fofoId);
2492
            }
2493
        }
2494
 
2495
        // Get unique fofoIds for retailer lookup
2496
        Set<Integer> fofoIds = new HashSet<>(customerToFofoIdMap.values());
2497
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
2498
        if (!fofoIds.isEmpty()) {
2499
            try {
2500
                retailerMap = retailerService.getFofoRetailers(new ArrayList<>(fofoIds));
2501
            } catch (ProfitMandiBusinessException e) {
2502
                LOGGER.error("Error fetching fofo stores", e);
2503
            }
2504
        }
2505
 
2506
        // Get remarks for these fofoIds on this date
2507
        Map<Integer, List<PartnerCollectionRemark>> fofoRemarkMap = new HashMap<>();
2508
        if (!fofoIds.isEmpty()) {
2509
            List<PartnerCollectionRemark> dateRemarks = partnerCollectionRemarkRepository
2510
                    .selectAllByFofoIdsOnDate(new ArrayList<>(fofoIds), date);
2511
            for (PartnerCollectionRemark remark : dateRemarks) {
2512
                fofoRemarkMap.computeIfAbsent(remark.getFofoId(), k -> new ArrayList<>()).add(remark);
2513
            }
2514
        }
2515
 
2516
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
2517
 
2518
        // Build rows
2519
        for (AgentCallLog callLog : allCallLogs) {
2520
            String customerNumber = callLog.getCustomerNumber();
2521
            if (customerNumber == null) {
2522
                continue;
2523
            }
2524
 
2525
            // Get RBM Name
2526
            AuthUser authUser = authUserMap.get((int) callLog.getAuthId());
2527
            String rbmName = authUser != null ? authUser.getFullName() : "Unknown";
2528
 
2529
            String normalized = customerNumber.startsWith("+91") ? customerNumber.substring(3) : customerNumber;
2530
            Integer fofoId = customerToFofoIdMap.get(normalized);
2531
 
2532
            String partyName = "Unknown";
2533
            String code = "-";
2534
 
2535
            if (fofoId != null) {
2536
                CustomRetailer retailer = retailerMap.get(fofoId);
2537
                if (retailer != null) {
2538
                    partyName = retailer.getBusinessName();
2539
                    code = retailer.getCode();
2540
                } else {
2541
                    partyName = "Unknown (" + fofoId + ")";
2542
                }
2543
            } else {
2544
                partyName = "Unknown (" + normalized + ")";
2545
            }
2546
 
2547
            // Get remark if available
2548
            String remarkValue = "-";
2549
            if (fofoId != null && fofoRemarkMap.containsKey(fofoId)) {
2550
                List<PartnerCollectionRemark> remarks = fofoRemarkMap.get(fofoId);
2551
                if (!remarks.isEmpty()) {
2552
                    PartnerCollectionRemark remark = remarks.get(0);
2553
                    remarkValue = remark.getRemark() != null ? remark.getRemark().getValue() : "-";
2554
                    if (remark.getMessage() != null && !remark.getMessage().isEmpty()) {
2555
                        remarkValue = remarkValue + " - " + remark.getMessage();
2556
                    }
2557
                }
2558
            }
2559
 
2560
            // Call status from customerStatus field
2561
            String callStatus = callLog.getCustomerStatus() != null ? callLog.getCustomerStatus() : "-";
2562
            String callDuration = callLog.getCallDuration() != null ? callLog.getCallDuration() : "-";
2563
 
2564
            String callDateTime = "-";
2565
            if (callLog.getCallDate() != null && callLog.getCallTime() != null) {
2566
                LocalDateTime callDateTimeObj = LocalDateTime.of(callLog.getCallDate(), callLog.getCallTime());
2567
                callDateTime = callDateTimeObj.format(dateTimeFormatter);
2568
            }
2569
 
2570
            String recordingUrl = callLog.getRecordingUrl() != null ? callLog.getRecordingUrl() : "-";
2571
 
2572
            rows.add(Arrays.asList(rbmName, partyName, code, remarkValue, callStatus, callDuration, callDateTime, recordingUrl));
2573
        }
2574
 
2575
        return rows;
2576
    }
2577
 
33917 ranu 2578
}