Subversion Repositories SmartDukaan

Rev

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