Subversion Repositories SmartDukaan

Rev

Rev 36284 | Rev 36329 | 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",
504
            cacheManager = "twoMintimeoutCacheManager",
505
            unless = "#result == null or #result.isEmpty()")
35453 amit 506
    public List<RbmWeeklyBillingModel> getWeeklyBillingDataForMonth(LocalDate monthStart, LocalDate monthEnd) {
507
        Session session = sessionFactory.getCurrentSession();
508
        final TypedQuery<RbmWeeklyBillingModel> typedQuery = session.createNamedQuery("RBM.WeeklyBilling", RbmWeeklyBillingModel.class);
509
        typedQuery.setParameter("startDate", monthStart);
510
        typedQuery.setParameter("endDate", monthEnd);
511
        return typedQuery.getResultList();
34103 ranu 512
    }
513
 
34055 ranu 514
    public List<Our15DaysOldAgingStock> our15DaysAgingStock() {
515
        Session session = sessionFactory.getCurrentSession();
516
        final TypedQuery<Our15DaysOldAgingStock> typedQuerySimilar = session.createNamedQuery("Aging.15DaysOurStock", Our15DaysOldAgingStock.class);
517
        return typedQuerySimilar.getResultList();
518
 
519
    }
520
 
34397 ranu 521
    @Autowired
522
    OrderRepository orderRepository;
34055 ranu 523
 
34397 ranu 524
    @Override
34641 ranu 525
    public double calculateFofoIdTodayTarget(int fofoId, double secondryMtd,LocalDate date) {
34397 ranu 526
 
527
        MonthlyTarget monthlyTarget = monthlyTargetRepository.selectByDateAndFofoId(YearMonth.now(), fofoId);
34404 ranu 528
        if (monthlyTarget == null) {
529
            // Log or handle as needed
530
            return 0; // or -1 or some fallback
531
        }
34397 ranu 532
 
533
        double remainingTarget = monthlyTarget.getPurchaseTarget() - secondryMtd;
34880 ranu 534
//        double remainingWorkingDays = getWorkingDaysCount(date);
535
        double remainingWorkingDays = (double) getRemainingDaysInMonth(date);
34397 ranu 536
 
537
 
34716 ranu 538
 
34397 ranu 539
        if (remainingWorkingDays == 0) return remainingTarget; // Last day
34716 ranu 540
        LOGGER.info("remainingWorkingDays {}", remainingWorkingDays);
541
        LOGGER.info("remainingTarget {}", remainingTarget);
34397 ranu 542
 
543
        return (int) Math.ceil(remainingTarget / remainingWorkingDays);
544
    }
545
 
34880 ranu 546
    @Override
547
    public long getRemainingDaysInMonth(LocalDate date) {
548
        LocalDate lastDayOfMonth = YearMonth.from(date).atEndOfMonth();
34397 ranu 549
 
34880 ranu 550
        long totalDays = ChronoUnit.DAYS.between(date, lastDayOfMonth) + 1;
34397 ranu 551
 
34880 ranu 552
        // Count Sundays manually
553
        long sundayCount = 0;
554
        LocalDate current = date;
555
        while (!current.isAfter(lastDayOfMonth)) {
556
            if (current.getDayOfWeek() == DayOfWeek.SUNDAY) {
557
                sundayCount++;
558
            }
559
            current = current.plusDays(1);
560
        }
561
 
562
        // Public holidays in the range
563
        long publicHolidays = publicHolidaysRepository
564
                .selectAllBetweenDates(date, lastDayOfMonth)
565
                .size();
566
 
567
        long remainingDays = totalDays - sundayCount - publicHolidays;
568
 
569
        LOGGER.info("remainingDays {}", remainingDays);
570
        LOGGER.info("totalDays {}", totalDays);
571
        LOGGER.info("sundays {}", sundayCount);
572
        LOGGER.info("publicHolidays {}", publicHolidays);
573
 
574
        return remainingDays;
575
    }
576
 
35631 ranu 577
    @Autowired
578
    PositionRepository positionRepository;
34880 ranu 579
 
35631 ranu 580
    @Autowired
581
    CsService csService;
34880 ranu 582
 
35631 ranu 583
    @Autowired
584
    FofoStoreRepository fofoStoreRepository;
585
 
586
    @Autowired
587
    AuthRepository authRepository;
588
 
589
    @Autowired
590
    LoanRepository loanRepository;
591
 
592
    @Autowired
593
    PartnerCollectionService partnerCollectionService;
594
 
595
    @Autowired
596
    PartnerCollectionRemarkRepository partnerCollectionRemarkRepository;
597
 
598
    @Autowired
599
    RbmCallSequenceLogRepository rbmCallSequenceLogRepository;
600
 
601
    @Autowired
602
    com.spice.profitmandi.dao.repository.cs.TicketRepository ticketRepository;
603
 
35702 ranu 604
    @Autowired
605
    com.spice.profitmandi.dao.repository.cs.AgentCallLogRepository agentCallLogRepository;
606
 
35759 ranu 607
    @Autowired
608
    RetailerContactRepository retailerContactRepository;
609
 
610
    @Autowired
611
    AddressRepository addressRepository;
612
 
36225 ranu 613
    @Autowired
614
    com.spice.profitmandi.dao.repository.cs.PartnerPositionRepository partnerPositionRepository;
615
 
35631 ranu 616
    @Override
617
    public List<RbmCallTargetModel> getRbmCallTargetModels() throws Exception {
36234 ranu 618
        return getRbmCallTargetModels(LocalDate.now());
619
    }
620
 
621
    public List<RbmCallTargetModel> getRbmCallTargetModels(LocalDate queryDate) throws Exception {
35631 ranu 622
        long methodStart = System.currentTimeMillis();
623
        List<RbmCallTargetModel> rbmCallTargetModels = new ArrayList<>();
624
 
625
        // Get all RBM positions (L1 and L2)
626
        long start = System.currentTimeMillis();
627
        List<Position> allRbmPositions = positionRepository
628
                .selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_RBM).stream()
36210 ranu 629
                .filter(x -> Arrays.asList(EscalationType.L1, EscalationType.L2, EscalationType.L3).contains(x.getEscalationType()))
35631 ranu 630
                .collect(Collectors.toList());
631
 
36210 ranu 632
        // Separate L1, L2 and L3 auth IDs
35631 ranu 633
        List<Integer> l1AuthIds = allRbmPositions.stream()
634
                .filter(p -> EscalationType.L1.equals(p.getEscalationType()))
635
                .map(Position::getAuthUserId).distinct().collect(Collectors.toList());
636
        List<Integer> l2AuthIds = allRbmPositions.stream()
637
                .filter(p -> EscalationType.L2.equals(p.getEscalationType()))
638
                .map(Position::getAuthUserId).distinct().collect(Collectors.toList());
36210 ranu 639
        List<Integer> l3AuthIds = allRbmPositions.stream()
640
                .filter(p -> EscalationType.L3.equals(p.getEscalationType()))
641
                .map(Position::getAuthUserId).distinct().collect(Collectors.toList());
35631 ranu 642
 
643
        // Union of all auth IDs for batch fetching
644
        List<Integer> rbmPositionsAuthIds = allRbmPositions.stream()
645
                .map(Position::getAuthUserId).distinct().collect(Collectors.toList());
36210 ranu 646
        LOGGER.info("RBM Call Target - RBM positions fetch: {}ms, L1: {}, L2: {}, L3: {}", System.currentTimeMillis() - start, l1AuthIds.size(), l2AuthIds.size(), l3AuthIds.size());
35631 ranu 647
 
648
        start = System.currentTimeMillis();
649
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
650
        LOGGER.info("RBM Call Target - StoreGuyMap fetch: {}ms", System.currentTimeMillis() - start);
651
 
36234 ranu 652
        LocalDateTime startDate = queryDate.atStartOfDay();
653
        LocalDate firstOfMonth = queryDate.withDayOfMonth(1);
654
        LocalDate endOfMonth = queryDate.withDayOfMonth(queryDate.lengthOfMonth()).plusDays(1);
35631 ranu 655
 
656
        // Get auth user map
657
        start = System.currentTimeMillis();
658
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(rbmPositionsAuthIds).stream()
659
                .collect(Collectors.toMap(AuthUser::getId, au -> au));
660
        LOGGER.info("RBM Call Target - AuthUser fetch: {}ms", System.currentTimeMillis() - start);
661
 
662
        // Batch fetch positions by auth IDs (to check if RBM is L1)
663
        start = System.currentTimeMillis();
664
        Map<Integer, List<Position>> positionsByAuthId = positionRepository.selectPositionByAuthIds(rbmPositionsAuthIds).stream()
665
                .collect(Collectors.groupingBy(Position::getAuthUserId));
666
        LOGGER.info("RBM Call Target - Positions by AuthId fetch: {}ms", System.currentTimeMillis() - start);
667
 
668
        // Get all fofo IDs for all RBMs
669
        Set<Integer> allFofoIds = new HashSet<>();
670
        Map<Integer, List<Integer>> rbmToFofoIdsMap = new HashMap<>();
671
        for (int rbmAuthId : rbmPositionsAuthIds) {
672
            AuthUser au = authUserMap.get(rbmAuthId);
673
            if (au != null && storeGuyMap.containsKey(au.getEmailId())) {
674
                List<Integer> fofoIds = new ArrayList<>(storeGuyMap.get(au.getEmailId()));
675
                allFofoIds.addAll(fofoIds);
676
                rbmToFofoIdsMap.put(rbmAuthId, fofoIds);
677
            }
678
        }
35816 ranu 679
        // Initialize L2 calling list map - will be populated after fetching remarks
35631 ranu 680
        Map<Integer, List<Integer>> l2AuthIdToFofoIds = new HashMap<>();
35816 ranu 681
        for (int l2AuthId : l2AuthIds) {
682
            l2AuthIdToFofoIds.put(l2AuthId, new ArrayList<>());
35631 ranu 683
        }
36210 ranu 684
        // Initialize L3 calling list map - will be populated after fetching remarks
685
        Map<Integer, List<Integer>> l3AuthIdToFofoIds = new HashMap<>();
686
        for (int l3AuthId : l3AuthIds) {
687
            l3AuthIdToFofoIds.put(l3AuthId, new ArrayList<>());
688
        }
35631 ranu 689
        LOGGER.info("RBM Call Target - Total fofo IDs to process: {}", allFofoIds.size());
690
 
691
        // Get only needed fofo stores (OPTIMIZED - was fetching ALL stores before)
692
        start = System.currentTimeMillis();
693
        Map<Integer, FofoStore> fofoStoresMap = new HashMap<>();
694
        if (!allFofoIds.isEmpty()) {
695
            try {
696
                fofoStoresMap = fofoStoreRepository.selectByRetailerIds(new ArrayList<>(allFofoIds)).stream()
697
                        .collect(Collectors.toMap(FofoStore::getId, x -> x, (a, b) -> a));
698
            } catch (ProfitMandiBusinessException e) {
699
                LOGGER.error("Error fetching fofo stores", e);
700
            }
701
        }
702
        LOGGER.info("RBM Call Target - FofoStores fetch (only needed): {}ms, count: {}", System.currentTimeMillis() - start, fofoStoresMap.size());
703
 
704
        // Batch fetch max remark ids for all fofoIds (for escalation filtering)
705
        start = System.currentTimeMillis();
706
        Map<Integer, PartnerCollectionRemark> allPartnerCollectionRemarks = new HashMap<>();
707
        if (!allFofoIds.isEmpty()) {
708
            List<Integer> allRemarkIds = partnerCollectionRemarkRepository.selectMaxRemarkId(new ArrayList<>(allFofoIds));
709
            if (!allRemarkIds.isEmpty()) {
710
                allPartnerCollectionRemarks = partnerCollectionRemarkRepository.selectByIds(allRemarkIds).stream()
711
                        .collect(Collectors.toMap(PartnerCollectionRemark::getFofoId, x -> x, (a, b) -> a));
712
            }
713
        }
714
        LOGGER.info("RBM Call Target - PartnerCollectionRemarks fetch: {}ms", System.currentTimeMillis() - start);
715
 
35816 ranu 716
        // Populate L2 calling list based on partners whose latest remark is RBM_L2_ESCALATION
717
        // Find the L1 who has the partner and add to that L1's manager (L2) calling list
718
        for (Map.Entry<Integer, PartnerCollectionRemark> entry : allPartnerCollectionRemarks.entrySet()) {
719
            Integer fofoId = entry.getKey();
720
            PartnerCollectionRemark remark = entry.getValue();
721
 
722
            if (CollectionRemark.RBM_L2_ESCALATION.equals(remark.getRemark())) {
723
                // Find which L1 RBM has this partner assigned
724
                for (int l1AuthId : l1AuthIds) {
725
                    List<Integer> l1FofoIds = rbmToFofoIdsMap.getOrDefault(l1AuthId, Collections.emptyList());
726
                    if (l1FofoIds.contains(fofoId)) {
727
                        // Get L1's manager (L2)
728
                        AuthUser l1User = authUserMap.get(l1AuthId);
729
                        if (l1User != null && l2AuthIdToFofoIds.containsKey(l1User.getManagerId())) {
730
                            int l2ManagerId = l1User.getManagerId();
731
                            l2AuthIdToFofoIds.get(l2ManagerId).add(fofoId);
732
                        }
733
                        break; // Found the L1 for this fofoId
734
                    }
735
                }
736
            }
737
        }
738
        LOGGER.info("RBM Call Target - L2 calling lists populated from RBM_L2_ESCALATION remarks");
739
 
36210 ranu 740
        // Populate L3 calling list based on partners whose latest remark is RBM_L3_ESCALATION
36212 ranu 741
        // Find the L1 who originally has the partner, then:
742
        // Case 1: L1 -> L3 directly (if L1's manager IS L3)
743
        // Case 2: L1 -> L2 -> L3 (if L1's manager is L2, then L2's manager is L3)
36210 ranu 744
        for (Map.Entry<Integer, PartnerCollectionRemark> entry : allPartnerCollectionRemarks.entrySet()) {
745
            Integer fofoId = entry.getKey();
746
            PartnerCollectionRemark remark = entry.getValue();
747
 
748
            if (CollectionRemark.RBM_L3_ESCALATION.equals(remark.getRemark())) {
749
                // Find which L1 RBM originally has this partner assigned
750
                for (int l1AuthId : l1AuthIds) {
751
                    List<Integer> l1FofoIds = rbmToFofoIdsMap.getOrDefault(l1AuthId, Collections.emptyList());
752
                    if (l1FofoIds.contains(fofoId)) {
753
                        AuthUser l1User = authUserMap.get(l1AuthId);
754
                        if (l1User != null) {
36212 ranu 755
                            int l1ManagerId = l1User.getManagerId();
756
                            // Case 1: L1's manager IS L3 directly (L1 → L3, no L2 in between)
757
                            if (l3AuthIdToFofoIds.containsKey(l1ManagerId)) {
758
                                l3AuthIdToFofoIds.get(l1ManagerId).add(fofoId);
759
                                LOGGER.debug("L3 Calling List (direct): fofoId={} -> L1={} -> L3={}",
760
                                        fofoId, l1AuthId, l1ManagerId);
761
                            } else {
762
                                // Case 2: L1 -> L2 -> L3
763
                                AuthUser l2User = authUserMap.get(l1ManagerId);
764
                                if (l2User != null && l3AuthIdToFofoIds.containsKey(l2User.getManagerId())) {
765
                                    int l3ManagerId = l2User.getManagerId();
766
                                    l3AuthIdToFofoIds.get(l3ManagerId).add(fofoId);
767
                                    LOGGER.debug("L3 Calling List: fofoId={} -> L1={} -> L2={} -> L3={}",
768
                                            fofoId, l1AuthId, l1ManagerId, l3ManagerId);
769
                                }
36210 ranu 770
                            }
771
                        }
772
                        break; // Found the L1 for this fofoId
773
                    }
774
                }
775
            }
776
        }
777
        LOGGER.info("RBM Call Target - L3 calling lists populated from RBM_L3_ESCALATION remarks");
778
 
35631 ranu 779
        // Batch fetch collection RANK map for all fofoIds (OPTIMIZED - only fetches rank, not full model)
780
        start = System.currentTimeMillis();
781
        Map<Integer, Integer> allCollectionRankMap = new HashMap<>();
782
        if (!allFofoIds.isEmpty()) {
783
            try {
784
                allCollectionRankMap = partnerCollectionService.getCollectionRankMap(new ArrayList<>(allFofoIds), startDate);
785
            } catch (ProfitMandiBusinessException e) {
786
                LOGGER.error("Error fetching collection rank map for all fofoIds", e);
787
            }
788
        }
789
        LOGGER.info("RBM Call Target - CollectionRankMap fetch (OPTIMIZED): {}ms", System.currentTimeMillis() - start);
790
 
35669 ranu 791
        // Get MTD billing data for zero billing calculation and partner counts
35631 ranu 792
        start = System.currentTimeMillis();
793
        List<RbmWeeklyBillingModel> mtdBillingData = getWeeklyBillingDataForMonth(firstOfMonth, endOfMonth);
794
        Set<Integer> allMtdBilledFofoIds = mtdBillingData.stream()
795
                .filter(RbmWeeklyBillingModel::isMtdBilled)
796
                .map(RbmWeeklyBillingModel::getFofoId)
797
                .collect(Collectors.toSet());
35669 ranu 798
        // Build partner count and fofoIds per RBM from mtdBillingData (same source as Today ARR page)
799
        Map<Integer, Set<Integer>> mtdFofoIdsByAuthId = mtdBillingData.stream()
800
                .filter(RbmWeeklyBillingModel::isTargetedPartner)
801
                .collect(Collectors.groupingBy(RbmWeeklyBillingModel::getAuthId,
802
                        Collectors.mapping(RbmWeeklyBillingModel::getFofoId, Collectors.toSet())));
35631 ranu 803
        LOGGER.info("RBM Call Target - MTD Billing fetch: {}ms", System.currentTimeMillis() - start);
804
 
805
        // Batch fetch today's remarks for all auth IDs (to calculate Value Achieved)
806
        start = System.currentTimeMillis();
807
        Map<Integer, List<PartnerCollectionRemark>> remarksByAuthId = partnerCollectionRemarkRepository
808
                .selectAllByAuthIdsOnDate(rbmPositionsAuthIds, LocalDate.now()).stream()
809
                .collect(Collectors.groupingBy(PartnerCollectionRemark::getAuthId));
810
        LOGGER.info("RBM Call Target - Today Remarks fetch: {}ms", System.currentTimeMillis() - start);
811
 
812
        // Batch fetch today's out-of-sequence logs for all RBMs
813
        start = System.currentTimeMillis();
814
        LocalDateTime todayStart = LocalDate.now().atStartOfDay();
815
        LocalDateTime todayEnd = LocalDate.now().plusDays(1).atStartOfDay();
816
        List<RbmCallSequenceLog> outOfSequenceLogs = rbmCallSequenceLogRepository.selectOutOfSequenceByDateRange(todayStart, todayEnd);
817
        Map<Integer, Long> outOfSequenceCountByAuthId = outOfSequenceLogs.stream()
35654 ranu 818
                .collect(Collectors.groupingBy(RbmCallSequenceLog::getAuthId,
819
                        Collectors.mapping(RbmCallSequenceLog::getFofoId, Collectors.collectingAndThen(Collectors.toSet(), s -> (long) s.size()))));
35631 ranu 820
        LOGGER.info("RBM Call Target - Out of Sequence fetch: {}ms", System.currentTimeMillis() - start);
821
 
36284 ranu 822
        // BATCH FETCH: All call logs for all RBMs (L1 + L2 + L3) in a single query.
823
        // Replaces the previous N+1 pattern where getCallStats() was called per RBM.
824
        start = System.currentTimeMillis();
825
        List<AgentCallLog> allCallLogs = agentCallLogRepository.findByAuthIdsAndDate(rbmPositionsAuthIds, queryDate);
826
        Map<Long, List<AgentCallLog>> callLogsByAuthId = allCallLogs.stream()
827
                .collect(Collectors.groupingBy(AgentCallLog::getAuthId));
828
        LOGGER.info("RBM Call Target - Call logs batch fetch: {}ms ({} logs across {} RBMs)",
829
                System.currentTimeMillis() - start, allCallLogs.size(), callLogsByAuthId.size());
830
 
831
        // BATCH FETCH: Build a single mobile -> fofoId map from all unique customer numbers across all call logs.
832
        // Replaces the previous N+1 pattern where findFofoIdByMobile() was called per call log entry.
833
        start = System.currentTimeMillis();
834
        Set<String> allNormalizedMobiles = new HashSet<>();
835
        for (AgentCallLog callLog : allCallLogs) {
836
            String customerNumber = callLog.getCustomerNumber();
837
            if (customerNumber != null) {
838
                String normalized = customerNumber.startsWith("+91") ? customerNumber.substring(3) : customerNumber;
839
                allNormalizedMobiles.add(normalized);
840
            }
841
        }
842
        Map<String, Integer> mobileToFofoIdMap = buildMobileToFofoIdMap(allNormalizedMobiles);
843
        LOGGER.info("RBM Call Target - Mobile→FofoId batch fetch: {}ms ({} unique mobiles, {} mapped)",
844
                System.currentTimeMillis() - start, allNormalizedMobiles.size(), mobileToFofoIdMap.size());
845
 
36225 ranu 846
        // Identify users who are both L1 and L2 — they will be shown only as L2
847
        Set<Integer> l2AuthIdSet = new HashSet<>(l2AuthIds);
848
 
849
        // Process L1 RBMs (skip users who are also L2 — their data will be merged into L2 model)
35631 ranu 850
        for (int rbmAuthId : l1AuthIds) {
36225 ranu 851
            if (l2AuthIdSet.contains(rbmAuthId)) {
852
                continue; // Will be handled in L2 processing with merged L1 data
853
            }
35631 ranu 854
            AuthUser authUser = authUserMap.get(rbmAuthId);
855
            if (authUser == null || !storeGuyMap.containsKey(authUser.getEmailId())) {
856
                continue;
857
            }
858
 
859
            List<Integer> fofoIdList = rbmToFofoIdsMap.getOrDefault(rbmAuthId, Collections.emptyList());
860
 
861
            // Check if RBM is L1 (same logic as getSummaryModel)
862
            List<Position> positions = positionsByAuthId.getOrDefault(authUser.getId(), Collections.emptyList());
863
            boolean isRBMAndL1 = positions.stream()
864
                    .anyMatch(position ->
865
                            ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId()
866
                                    && EscalationType.L1.equals(position.getEscalationType()));
867
 
868
            // Filter escalated partners for L1 RBMs (same logic as getSummaryModel)
869
            List<Integer> fofoIds = fofoIdList;
870
            if (isRBMAndL1) {
871
                Map<Integer, PartnerCollectionRemark> partnerCollectionRemarks = new HashMap<>();
872
                for (Integer fofoId : fofoIdList) {
873
                    if (allPartnerCollectionRemarks.containsKey(fofoId)) {
874
                        partnerCollectionRemarks.put(fofoId, allPartnerCollectionRemarks.get(fofoId));
875
                    }
876
                }
877
                fofoIds = partnerCollectionRemarks.entrySet().stream()
878
                        .filter(entry -> {
879
                            PartnerCollectionRemark pcrMap = entry.getValue();
880
                            return !(CollectionRemark.RBM_L2_ESCALATION.equals(pcrMap.getRemark())
881
                                    || CollectionRemark.SALES_ESCALATION.equals(pcrMap.getRemark()));
882
                        })
883
                        .map(Map.Entry::getKey)
884
                        .collect(Collectors.toList());
885
            }
886
 
36181 ranu 887
            // Filter to only external, ACTIVE or REVIVAL stores (collection plan not required)
35631 ranu 888
            Map<Integer, Integer> finalAllCollectionRankMap = allCollectionRankMap;
889
            Map<Integer, FofoStore> finalFofoStoresMap = fofoStoresMap;
890
            List<Integer> validFofoIds = fofoIds.stream()
891
                    .filter(fofoId -> {
892
                        FofoStore store = finalFofoStoresMap.get(fofoId);
893
                        if (store == null || store.isInternal()) {
894
                            return false;
895
                        }
36181 ranu 896
                        // Only include ACTIVE or REVIVAL partners (not Low Sale, not Disputed, not Billing Pending)
897
                        return ActivationType.ACTIVE.equals(store.getActivationType())
898
                                || ActivationType.REVIVAL.equals(store.getActivationType());
35631 ranu 899
                    })
900
                    .collect(Collectors.toList());
901
 
902
            if (validFofoIds.isEmpty()) {
903
                continue;
904
            }
905
 
906
            RbmCallTargetModel targetModel = new RbmCallTargetModel();
907
            targetModel.setAuthId(rbmAuthId);
908
            targetModel.setRbmName(authUser.getFullName());
35669 ranu 909
            // Use partner count from mtdBillingData (same source as Today ARR page)
910
            Set<Integer> mtdFofoIds = mtdFofoIdsByAuthId.getOrDefault(rbmAuthId, Collections.emptySet());
911
            targetModel.setPartnerCount(mtdFofoIds.size());
35631 ranu 912
 
913
            // Categorize each partner - each partner belongs to ONE category only
35665 ranu 914
            // Priority: PlanToday > CarryForward > ZeroBilling > Untouched > FuturePlan > Normal
36181 ranu 915
            // Revival is counted separately (just for display, doesn't affect categorization)
35631 ranu 916
            Set<Integer> planTodayPartners = new HashSet<>();
917
            Set<Integer> carryForwardPartners = new HashSet<>();
918
            Set<Integer> untouchedPartners = new HashSet<>();
919
            Set<Integer> zeroBillingPartners = new HashSet<>();
920
            Set<Integer> futurePlanPartners = new HashSet<>();
921
            Set<Integer> normalPartners = new HashSet<>();
36181 ranu 922
            Set<Integer> revivalPartners = new HashSet<>();
35631 ranu 923
 
924
            for (Integer fofoId : validFofoIds) {
925
                // Get collection plan rank (from optimized rank map)
926
                int rank = allCollectionRankMap.getOrDefault(fofoId, 5); // default to Normal if no plan
927
 
928
                // Check if partner has zero billing in MTD
929
                boolean hasZeroBilling = !allMtdBilledFofoIds.contains(fofoId);
930
 
36181 ranu 931
                // Count REVIVAL partners separately (just for display, doesn't affect categorization)
932
                FofoStore store = finalFofoStoresMap.get(fofoId);
933
                if (store != null && ActivationType.REVIVAL.equals(store.getActivationType())) {
934
                    revivalPartners.add(fofoId);
935
                }
936
 
35631 ranu 937
                // Assign to category based on priority
938
                if (rank == 1) {
939
                    planTodayPartners.add(fofoId);
940
                } else if (rank == 2) {
941
                    carryForwardPartners.add(fofoId);
35665 ranu 942
                } else if (hasZeroBilling) {
943
                    zeroBillingPartners.add(fofoId);
35631 ranu 944
                } else if (rank == 3) {
945
                    untouchedPartners.add(fofoId);
946
                } else if (rank == 4) {
947
                    futurePlanPartners.add(fofoId);
948
                } else {
949
                    normalPartners.add(fofoId);
950
                }
951
            }
952
 
953
            // Set counts
954
            targetModel.setCreditCollection(0); // Credit collection is handled in separate list
955
            targetModel.setPlanToday(planTodayPartners.size());
956
            targetModel.setCarryForward(carryForwardPartners.size());
957
            targetModel.setUntouched(untouchedPartners.size());
958
            targetModel.setZeroBilling(zeroBillingPartners.size());
959
            targetModel.setFuturePlan(futurePlanPartners.size());
960
            targetModel.setNormal(normalPartners.size());
36181 ranu 961
            targetModel.setRevival(revivalPartners.size());
35631 ranu 962
 
963
            // Today Target = PlanToday + CarryForward + ZeroBilling + Untouched
964
            // These are mutually exclusive now, so we can sum them
965
            long todayTarget = planTodayPartners.size() +
966
                    carryForwardPartners.size() + zeroBillingPartners.size() + untouchedPartners.size();
967
            targetModel.setTodayTargetOfCall(todayTarget);
968
 
969
            // Create set of partners in Today Target categories
970
            Set<Integer> todayTargetPartners = new HashSet<>();
971
            todayTargetPartners.addAll(planTodayPartners);
972
            todayTargetPartners.addAll(carryForwardPartners);
973
            todayTargetPartners.addAll(zeroBillingPartners);
974
            todayTargetPartners.addAll(untouchedPartners);
975
 
36284 ranu 976
            // Value Achieved = All distinct partners called today (from pre-fetched call logs)
977
            long[] callStats = getCallStatsFromLogs(callLogsByAuthId.get((long) rbmAuthId), mobileToFofoIdMap);
36276 ranu 978
            targetModel.setValueTargetAchieved(callStats[0]);
979
            targetModel.setTotalRecordingCalls(callStats[1]);
980
            targetModel.setUniqueRecordingCalls(callStats[2]);
35631 ranu 981
 
35843 ranu 982
            // Keep todayRemarks for movedToFuture calculation
983
            List<PartnerCollectionRemark> todayRemarks = remarksByAuthId.getOrDefault(rbmAuthId, Collections.emptyList());
984
 
35631 ranu 985
            // Moved to Future = Partners in Future Plan category who have a remark today
986
            // These are partners who were contacted today but moved to a future date
987
            Set<Integer> todayRemarkedFofoIds = todayRemarks.stream()
988
                    .map(PartnerCollectionRemark::getFofoId)
989
                    .collect(Collectors.toSet());
990
            long movedToFuture = futurePlanPartners.stream()
991
                    .filter(todayRemarkedFofoIds::contains)
992
                    .count();
993
            targetModel.setMovedToFuture(movedToFuture);
994
 
995
            // Set out of sequence count for this RBM
996
            targetModel.setOutOfSequenceCount(outOfSequenceCountByAuthId.getOrDefault(rbmAuthId, 0L));
997
 
998
            rbmCallTargetModels.add(targetModel);
999
        }
1000
 
1001
        // Process L2 RBMs (escalated ticket logic with categorization)
36225 ranu 1002
        // For users who are both L1 and L2, merge their L1 calling target into L2 model
35631 ranu 1003
        for (int l2AuthId : l2AuthIds) {
1004
            AuthUser authUser = authUserMap.get(l2AuthId);
1005
            if (authUser == null) {
1006
                continue;
1007
            }
1008
 
1009
            List<Integer> l2FofoIdList = l2AuthIdToFofoIds.getOrDefault(l2AuthId, Collections.emptyList());
1010
 
35816 ranu 1011
            // For L2, use unique fofoIds with RBM_L2_ESCALATION remark as target
35662 ranu 1012
            Set<Integer> l2TargetFofoIds = new HashSet<>(l2FofoIdList);
35631 ranu 1013
 
1014
            RbmCallTargetModel l2Model = new RbmCallTargetModel();
1015
            l2Model.setAuthId(l2AuthId);
1016
            l2Model.setRbmName(authUser.getFullName() + " (L2)");
1017
            l2Model.setL2Position(true);
35816 ranu 1018
            l2Model.setL2CallingList(l2TargetFofoIds.size());
36228 ranu 1019
            // Partner count: if user is also L1, use L1 partner count (MTD targeted partners)
1020
            if (l1AuthIds.contains(l2AuthId)) {
1021
                Set<Integer> mtdFofoIds = mtdFofoIdsByAuthId.getOrDefault(l2AuthId, Collections.emptySet());
1022
                l2Model.setPartnerCount(mtdFofoIds.size());
1023
            } else {
1024
                List<Integer> l2AssignedFofoIds = rbmToFofoIdsMap.getOrDefault(l2AuthId, Collections.emptyList());
1025
                l2Model.setPartnerCount(l2AssignedFofoIds.size());
1026
            }
35631 ranu 1027
 
36229 ranu 1028
            // If user is also L1, calculate full L1 breakdown and merge into L2 model
36225 ranu 1029
            if (l1AuthIds.contains(l2AuthId) && storeGuyMap.containsKey(authUser.getEmailId())) {
36229 ranu 1030
                // Get only L1 RBM position partners (not L2 partners) from partner_position
36225 ranu 1031
                List<Position> positions = positionsByAuthId.getOrDefault(l2AuthId, Collections.emptyList());
36229 ranu 1032
                Set<Integer> l1RbmPositionIds = positions.stream()
1033
                        .filter(p -> ProfitMandiConstants.TICKET_CATEGORY_RBM == p.getCategoryId()
1034
                                && EscalationType.L1.equals(p.getEscalationType()))
1035
                        .map(Position::getId)
1036
                        .collect(Collectors.toSet());
1037
                // Fetch partner_position for only L1 RBM positions of this user
1038
                List<Integer> fofoIdList = partnerPositionRepository
1039
                        .selectByPositionIds(new ArrayList<>(l1RbmPositionIds)).stream()
1040
                        .map(pp -> pp.getFofoId())
1041
                        .distinct()
1042
                        .collect(Collectors.toList());
1043
                boolean isRBMAndL1 = !l1RbmPositionIds.isEmpty();
36225 ranu 1044
                List<Integer> l1FofoIds = new ArrayList<>(fofoIdList);
1045
                if (isRBMAndL1) {
1046
                    Map<Integer, PartnerCollectionRemark> partnerCollectionRemarks = new HashMap<>();
1047
                    for (Integer fofoId : fofoIdList) {
1048
                        if (allPartnerCollectionRemarks.containsKey(fofoId)) {
1049
                            partnerCollectionRemarks.put(fofoId, allPartnerCollectionRemarks.get(fofoId));
1050
                        }
1051
                    }
1052
                    l1FofoIds = partnerCollectionRemarks.entrySet().stream()
1053
                            .filter(entry -> {
1054
                                PartnerCollectionRemark pcrMap = entry.getValue();
1055
                                return !(CollectionRemark.RBM_L2_ESCALATION.equals(pcrMap.getRemark())
1056
                                        || CollectionRemark.SALES_ESCALATION.equals(pcrMap.getRemark()));
1057
                            })
1058
                            .map(Map.Entry::getKey)
1059
                            .collect(Collectors.toList());
1060
                }
1061
                Map<Integer, FofoStore> finalFofoStoresMap2 = fofoStoresMap;
1062
                List<Integer> validL1FofoIds = l1FofoIds.stream()
1063
                        .filter(fofoId -> {
1064
                            FofoStore store = finalFofoStoresMap2.get(fofoId);
1065
                            if (store == null || store.isInternal()) return false;
1066
                            return ActivationType.ACTIVE.equals(store.getActivationType())
1067
                                    || ActivationType.REVIVAL.equals(store.getActivationType());
1068
                        })
1069
                        .collect(Collectors.toList());
35631 ranu 1070
 
36229 ranu 1071
                // Categorize L1 partners — same logic as L1 processing
1072
                Set<Integer> planTodayPartners = new HashSet<>();
1073
                Set<Integer> carryForwardPartners = new HashSet<>();
1074
                Set<Integer> untouchedPartners = new HashSet<>();
1075
                Set<Integer> zeroBillingPartners = new HashSet<>();
1076
                Set<Integer> futurePlanPartners = new HashSet<>();
1077
                Set<Integer> normalPartners = new HashSet<>();
1078
                Set<Integer> revivalPartners = new HashSet<>();
1079
 
36225 ranu 1080
                for (Integer fofoId : validL1FofoIds) {
1081
                    int rank = allCollectionRankMap.getOrDefault(fofoId, 5);
1082
                    boolean hasZeroBilling = !allMtdBilledFofoIds.contains(fofoId);
36229 ranu 1083
                    FofoStore store = finalFofoStoresMap2.get(fofoId);
1084
                    if (store != null && ActivationType.REVIVAL.equals(store.getActivationType())) {
1085
                        revivalPartners.add(fofoId);
36225 ranu 1086
                    }
36229 ranu 1087
                    if (rank == 1) {
1088
                        planTodayPartners.add(fofoId);
1089
                    } else if (rank == 2) {
1090
                        carryForwardPartners.add(fofoId);
1091
                    } else if (hasZeroBilling) {
1092
                        zeroBillingPartners.add(fofoId);
1093
                    } else if (rank == 3) {
1094
                        untouchedPartners.add(fofoId);
1095
                    } else if (rank == 4) {
1096
                        futurePlanPartners.add(fofoId);
1097
                    } else {
1098
                        normalPartners.add(fofoId);
1099
                    }
36225 ranu 1100
                }
36229 ranu 1101
 
1102
                // Set L1 breakdown fields on L2 model
1103
                l2Model.setPlanToday(planTodayPartners.size());
1104
                l2Model.setCarryForward(carryForwardPartners.size());
1105
                l2Model.setZeroBilling(zeroBillingPartners.size());
1106
                l2Model.setUntouched(untouchedPartners.size());
1107
                l2Model.setFuturePlan(futurePlanPartners.size());
1108
                l2Model.setNormal(normalPartners.size());
1109
                l2Model.setRevival(revivalPartners.size());
1110
 
1111
                long l1OwnTarget = planTodayPartners.size() + carryForwardPartners.size()
1112
                        + zeroBillingPartners.size() + untouchedPartners.size();
1113
 
1114
                // Today Target = own L1 target + L2 escalation
1115
                l2Model.setTodayTargetOfCall(l2TargetFofoIds.size() + l1OwnTarget);
1116
 
1117
                // Moved to Future from L1 partners
1118
                List<PartnerCollectionRemark> todayRemarks = remarksByAuthId.getOrDefault(l2AuthId, Collections.emptyList());
1119
                Set<Integer> todayRemarkedFofoIds = todayRemarks.stream()
1120
                        .map(PartnerCollectionRemark::getFofoId)
1121
                        .collect(Collectors.toSet());
1122
                long movedToFuture = futurePlanPartners.stream()
1123
                        .filter(todayRemarkedFofoIds::contains)
1124
                        .count();
1125
                l2Model.setMovedToFuture(movedToFuture);
1126
            } else {
1127
                // Pure L2 (not also L1) — target is only L2 escalation
1128
                l2Model.setTodayTargetOfCall(l2TargetFofoIds.size());
36225 ranu 1129
            }
1130
 
36284 ranu 1131
            // Value Achieved = All distinct partners called today (from pre-fetched call logs)
1132
            long[] l2CallStats = getCallStatsFromLogs(callLogsByAuthId.get((long) l2AuthId), mobileToFofoIdMap);
36276 ranu 1133
            l2Model.setValueTargetAchieved(l2CallStats[0]);
1134
            l2Model.setTotalRecordingCalls(l2CallStats[1]);
1135
            l2Model.setUniqueRecordingCalls(l2CallStats[2]);
35631 ranu 1136
 
1137
            l2Model.setOutOfSequenceCount(outOfSequenceCountByAuthId.getOrDefault(l2AuthId, 0L));
1138
            rbmCallTargetModels.add(l2Model);
1139
        }
1140
 
36210 ranu 1141
        // Process L3 RBMs (escalated ticket logic with categorization)
1142
        for (int l3AuthId : l3AuthIds) {
1143
            AuthUser authUser = authUserMap.get(l3AuthId);
1144
            if (authUser == null) {
1145
                continue;
1146
            }
1147
 
1148
            List<Integer> l3FofoIdList = l3AuthIdToFofoIds.getOrDefault(l3AuthId, Collections.emptyList());
1149
 
1150
            // For L3, use unique fofoIds with RBM_L3_ESCALATION remark as target
1151
            Set<Integer> l3TargetFofoIds = new HashSet<>(l3FofoIdList);
1152
 
1153
            RbmCallTargetModel l3Model = new RbmCallTargetModel();
1154
            l3Model.setAuthId(l3AuthId);
1155
            l3Model.setRbmName(authUser.getFullName() + " (L3)");
1156
            l3Model.setL3Position(true);
1157
            l3Model.setL3CallingList(l3TargetFofoIds.size());
1158
            // Partner count = total assigned partners (same as L2 source)
1159
            List<Integer> l3AssignedFofoIds = rbmToFofoIdsMap.getOrDefault(l3AuthId, Collections.emptyList());
1160
            l3Model.setPartnerCount(l3AssignedFofoIds.size());
1161
 
1162
            // L3 Target = partners with RBM_L3_ESCALATION as latest remark
1163
            l3Model.setTodayTargetOfCall(l3TargetFofoIds.size());
1164
 
36284 ranu 1165
            // Value Achieved = All distinct partners called today (from pre-fetched call logs)
1166
            long[] l3CallStats = getCallStatsFromLogs(callLogsByAuthId.get((long) l3AuthId), mobileToFofoIdMap);
36276 ranu 1167
            l3Model.setValueTargetAchieved(l3CallStats[0]);
1168
            l3Model.setTotalRecordingCalls(l3CallStats[1]);
1169
            l3Model.setUniqueRecordingCalls(l3CallStats[2]);
36210 ranu 1170
 
1171
            l3Model.setOutOfSequenceCount(outOfSequenceCountByAuthId.getOrDefault(l3AuthId, 0L));
1172
            rbmCallTargetModels.add(l3Model);
1173
        }
1174
 
36225 ranu 1175
        // Group models by escalation level
36210 ranu 1176
        Map<Integer, RbmCallTargetModel> l3ModelsByAuthId = new HashMap<>();
35631 ranu 1177
        Map<Integer, RbmCallTargetModel> l2ModelsByAuthId = new HashMap<>();
1178
        Map<Integer, RbmCallTargetModel> l1ModelsByAuthId = new HashMap<>();
1179
        for (RbmCallTargetModel m : rbmCallTargetModels) {
36210 ranu 1180
            if (m.isL3Position()) {
1181
                l3ModelsByAuthId.put(m.getAuthId(), m);
1182
            } else if (m.isL2Position()) {
35631 ranu 1183
                l2ModelsByAuthId.put(m.getAuthId(), m);
1184
            } else {
1185
                l1ModelsByAuthId.put(m.getAuthId(), m);
1186
            }
1187
        }
1188
 
36225 ranu 1189
        // Build partner-based hierarchy using partner_position table
1190
        // Map positionId -> Position for quick lookup
1191
        Map<Integer, Position> positionByIdMap = allRbmPositions.stream()
1192
                .collect(Collectors.toMap(Position::getId, p -> p, (a, b) -> a));
1193
 
1194
        // Get all RBM position IDs and fetch their partner assignments
1195
        List<Integer> allRbmPositionIds = allRbmPositions.stream()
1196
                .map(Position::getId).collect(Collectors.toList());
1197
        List<com.spice.profitmandi.dao.entity.cs.PartnerPosition> allPartnerPositions =
1198
                partnerPositionRepository.selectByPositionIds(allRbmPositionIds);
1199
 
1200
        // Build partnerId -> map of escalationType -> Set<authUserIds>
1201
        // This tells us for each partner, who is their L1, L2, L3
1202
        Map<Integer, Map<EscalationType, Set<Integer>>> partnerToAuthByLevel = new HashMap<>();
1203
        for (com.spice.profitmandi.dao.entity.cs.PartnerPosition pp : allPartnerPositions) {
1204
            Position pos = positionByIdMap.get(pp.getPositionId());
1205
            if (pos != null && pos.getEscalationType() != null) {
1206
                partnerToAuthByLevel
1207
                        .computeIfAbsent(pp.getFofoId(), k -> new HashMap<>())
1208
                        .computeIfAbsent(pos.getEscalationType(), k -> new HashSet<>())
1209
                        .add(pos.getAuthUserId());
1210
            }
1211
        }
1212
 
1213
        // Build L2 -> L1 team map based on shared partners
1214
        // If an L1 and L2 share partners (L1 at L1 level, L2 at L2 level), that L1 belongs under that L2
1215
        Map<Integer, List<RbmCallTargetModel>> l2TeamMap = new LinkedHashMap<>();
1216
        for (RbmCallTargetModel l2Model : l2ModelsByAuthId.values()) {
1217
            l2TeamMap.put(l2Model.getAuthId(), new ArrayList<>());
1218
        }
1219
 
1220
        // Build L3 -> L2 team map based on shared partners
36210 ranu 1221
        Map<Integer, List<RbmCallTargetModel>> l3TeamMap = new LinkedHashMap<>();
1222
        for (RbmCallTargetModel l3Model : l3ModelsByAuthId.values()) {
1223
            l3TeamMap.put(l3Model.getAuthId(), new ArrayList<>());
1224
        }
1225
 
36225 ranu 1226
        // For each L1, find which L2 shares the most partners -> that's their L2
1227
        Set<Integer> addedL1AuthIds = new HashSet<>();
1228
        for (RbmCallTargetModel l1Model : l1ModelsByAuthId.values()) {
1229
            Map<Integer, Integer> l2SharedCount = new HashMap<>(); // l2AuthId -> shared partner count
1230
            for (Map.Entry<Integer, Map<EscalationType, Set<Integer>>> entry : partnerToAuthByLevel.entrySet()) {
1231
                Map<EscalationType, Set<Integer>> levelMap = entry.getValue();
1232
                Set<Integer> l1IdsForPartner = levelMap.getOrDefault(EscalationType.L1, Collections.emptySet());
1233
                Set<Integer> l2AuthIdsForPartner = levelMap.getOrDefault(EscalationType.L2, Collections.emptySet());
1234
                if (l1IdsForPartner.contains(l1Model.getAuthId())) {
1235
                    for (int l2Id : l2AuthIdsForPartner) {
1236
                        if (l2ModelsByAuthId.containsKey(l2Id) && l2Id != l1Model.getAuthId()) {
1237
                            l2SharedCount.merge(l2Id, 1, Integer::sum);
1238
                        }
1239
                    }
1240
                }
1241
            }
1242
            // Assign L1 to the L2 with most shared partners
1243
            if (!l2SharedCount.isEmpty()) {
1244
                int bestL2 = l2SharedCount.entrySet().stream()
1245
                        .max(Map.Entry.comparingByValue()).get().getKey();
1246
                l2TeamMap.get(bestL2).add(l1Model);
1247
                addedL1AuthIds.add(l1Model.getAuthId());
1248
            }
1249
        }
1250
 
1251
        // For each L2, find which L3 shares the most partners -> that's their L3
36210 ranu 1252
        Set<Integer> addedL2AuthIds = new HashSet<>();
1253
        for (RbmCallTargetModel l2Model : l2ModelsByAuthId.values()) {
36225 ranu 1254
            Map<Integer, Integer> l3SharedCount = new HashMap<>();
1255
            for (Map.Entry<Integer, Map<EscalationType, Set<Integer>>> entry : partnerToAuthByLevel.entrySet()) {
1256
                Map<EscalationType, Set<Integer>> levelMap = entry.getValue();
1257
                Set<Integer> l2AuthIdsForPartner = levelMap.getOrDefault(EscalationType.L2, Collections.emptySet());
1258
                Set<Integer> l3AuthIdsForPartner = levelMap.getOrDefault(EscalationType.L3, Collections.emptySet());
1259
                if (l2AuthIdsForPartner.contains(l2Model.getAuthId())) {
1260
                    for (int l3Id : l3AuthIdsForPartner) {
1261
                        if (l3ModelsByAuthId.containsKey(l3Id)) {
1262
                            l3SharedCount.merge(l3Id, 1, Integer::sum);
1263
                        }
1264
                    }
1265
                }
1266
            }
1267
            if (!l3SharedCount.isEmpty()) {
1268
                int bestL3 = l3SharedCount.entrySet().stream()
1269
                        .max(Map.Entry.comparingByValue()).get().getKey();
1270
                l3TeamMap.get(bestL3).add(l2Model);
36210 ranu 1271
                addedL2AuthIds.add(l2Model.getAuthId());
1272
            }
1273
        }
1274
 
36225 ranu 1275
        // For L1s not mapped to any L2, check if they map directly to an L3 via shared partners
1276
        Map<Integer, List<RbmCallTargetModel>> l3DirectL1Map = new LinkedHashMap<>();
1277
        for (RbmCallTargetModel l3Model : l3ModelsByAuthId.values()) {
1278
            l3DirectL1Map.put(l3Model.getAuthId(), new ArrayList<>());
35631 ranu 1279
        }
1280
        for (RbmCallTargetModel l1Model : l1ModelsByAuthId.values()) {
36225 ranu 1281
            if (addedL1AuthIds.contains(l1Model.getAuthId())) continue;
1282
            Map<Integer, Integer> l3SharedCount = new HashMap<>();
1283
            for (Map.Entry<Integer, Map<EscalationType, Set<Integer>>> entry : partnerToAuthByLevel.entrySet()) {
1284
                Map<EscalationType, Set<Integer>> levelMap = entry.getValue();
1285
                Set<Integer> l1IdsForPartner = levelMap.getOrDefault(EscalationType.L1, Collections.emptySet());
1286
                Set<Integer> l3AuthIdsForPartner = levelMap.getOrDefault(EscalationType.L3, Collections.emptySet());
1287
                if (l1IdsForPartner.contains(l1Model.getAuthId())) {
1288
                    for (int l3Id : l3AuthIdsForPartner) {
1289
                        if (l3ModelsByAuthId.containsKey(l3Id)) {
1290
                            l3SharedCount.merge(l3Id, 1, Integer::sum);
1291
                        }
1292
                    }
1293
                }
1294
            }
1295
            if (!l3SharedCount.isEmpty()) {
1296
                int bestL3 = l3SharedCount.entrySet().stream()
1297
                        .max(Map.Entry.comparingByValue()).get().getKey();
1298
                l3DirectL1Map.get(bestL3).add(l1Model);
35631 ranu 1299
                addedL1AuthIds.add(l1Model.getAuthId());
1300
            }
1301
        }
1302
 
36225 ranu 1303
        // Build sorted result: L3 -> L2 -> L1 (with direct L1s under L3 if no L2)
35631 ranu 1304
        List<RbmCallTargetModel> sortedModels = new ArrayList<>();
1305
 
36210 ranu 1306
        List<RbmCallTargetModel> l3Sorted = new ArrayList<>(l3ModelsByAuthId.values());
1307
        l3Sorted.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
35631 ranu 1308
 
36210 ranu 1309
        for (RbmCallTargetModel l3Model : l3Sorted) {
1310
            sortedModels.add(l3Model);
1311
            List<RbmCallTargetModel> l2Team = l3TeamMap.getOrDefault(l3Model.getAuthId(), Collections.emptyList());
1312
            l2Team.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
1313
            for (RbmCallTargetModel l2Model : l2Team) {
1314
                sortedModels.add(l2Model);
1315
                List<RbmCallTargetModel> l1Team = l2TeamMap.getOrDefault(l2Model.getAuthId(), Collections.emptyList());
1316
                l1Team.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
1317
                sortedModels.addAll(l1Team);
1318
            }
36225 ranu 1319
            // Add L1s that report directly to this L3 (no L2 in between)
1320
            List<RbmCallTargetModel> directL1Team = l3DirectL1Map.getOrDefault(l3Model.getAuthId(), Collections.emptyList());
1321
            directL1Team.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
1322
            sortedModels.addAll(directL1Team);
36210 ranu 1323
        }
1324
 
36225 ranu 1325
        // Add L2s not mapped to any L3
36210 ranu 1326
        List<RbmCallTargetModel> unmappedL2 = new ArrayList<>();
1327
        for (RbmCallTargetModel l2Model : l2ModelsByAuthId.values()) {
1328
            if (!addedL2AuthIds.contains(l2Model.getAuthId())) {
1329
                unmappedL2.add(l2Model);
1330
            }
1331
        }
1332
        unmappedL2.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
1333
        for (RbmCallTargetModel l2Model : unmappedL2) {
35631 ranu 1334
            sortedModels.add(l2Model);
1335
            List<RbmCallTargetModel> team = l2TeamMap.getOrDefault(l2Model.getAuthId(), Collections.emptyList());
1336
            team.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
1337
            sortedModels.addAll(team);
1338
        }
1339
 
36225 ranu 1340
        // Add any L1s not mapped to any L2 or L3
35631 ranu 1341
        List<RbmCallTargetModel> unmappedL1 = new ArrayList<>();
1342
        for (RbmCallTargetModel m : l1ModelsByAuthId.values()) {
1343
            if (!addedL1AuthIds.contains(m.getAuthId())) {
1344
                unmappedL1.add(m);
1345
            }
1346
        }
1347
        unmappedL1.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
1348
        sortedModels.addAll(unmappedL1);
1349
 
1350
        LOGGER.info("RBM Call Target - TOTAL TIME: {}ms, RBM count: {}", System.currentTimeMillis() - methodStart, sortedModels.size());
1351
        return sortedModels;
1352
    }
1353
 
1354
    @Override
1355
    public List<OutOfSequenceDetailModel> getOutOfSequenceDetails(int authId) {
1356
 
1357
        LocalDate today = LocalDate.now();
1358
        LocalDateTime start = today.atStartOfDay();
1359
        LocalDateTime end = today.plusDays(1).atStartOfDay();
1360
 
1361
        List<RbmCallSequenceLog> logs =
1362
                rbmCallSequenceLogRepository.selectByAuthIdAndDateRange(authId, start, end);
1363
 
35654 ranu 1364
        Map<Integer, RbmCallSequenceLog> uniqueOosLogsByFofoId = new LinkedHashMap<>();
35631 ranu 1365
 
1366
        for (RbmCallSequenceLog log : logs) {
1367
            if (log.isOutOfSequence()) {
35654 ranu 1368
                // Keep only the first occurrence per fofoId (latest entry since ordered by id DESC)
1369
                uniqueOosLogsByFofoId.putIfAbsent(log.getFofoId(), log);
35631 ranu 1370
            }
1371
        }
1372
 
35654 ranu 1373
        if (uniqueOosLogsByFofoId.isEmpty()) {
35631 ranu 1374
            return Collections.emptyList();
1375
        }
1376
 
35654 ranu 1377
        Set<Integer> fofoIds = uniqueOosLogsByFofoId.keySet();
35631 ranu 1378
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
1379
        try {
1380
            retailerMap = retailerService.getFofoRetailers(new ArrayList<>(fofoIds));
1381
        } catch (ProfitMandiBusinessException e) {
1382
            LOGGER.error("Error fetching fofo stores", e);
1383
        }
1384
 
1385
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
1386
        List<OutOfSequenceDetailModel> result = new ArrayList<>();
1387
 
35654 ranu 1388
        for (RbmCallSequenceLog log : uniqueOosLogsByFofoId.values()) {
35631 ranu 1389
            CustomRetailer retailer = retailerMap.get(log.getFofoId());
1390
            String partyName = retailer != null
1391
                    ? retailer.getBusinessName()
1392
                    : "Unknown (" + log.getFofoId() + ")";
1393
            String code = retailer != null
1394
                    ? retailer.getCode()
1395
                    : "-";
1396
 
1397
            String time = log.getCreateTimestamp() != null
1398
                    ? log.getCreateTimestamp().format(timeFormatter)
1399
                    : "-";
1400
 
1401
            result.add(new OutOfSequenceDetailModel(partyName, code, time));
1402
        }
1403
 
1404
        return result;
1405
    }
1406
 
35645 ranu 1407
    @Override
35672 ranu 1408
    public List<CalledPartnerDetailModel> getCalledPartnerDetails(int authId) throws ProfitMandiBusinessException {
35730 ranu 1409
        return getCalledPartnerDetails(authId, LocalDate.now());
1410
    }
1411
 
1412
    @Override
1413
    public List<CalledPartnerDetailModel> getCalledPartnerDetails(int authId, LocalDate date) throws ProfitMandiBusinessException {
35759 ranu 1414
        // Get all call logs for this auth user on this date
35760 ranu 1415
        LOGGER.info("getCalledPartnerDetails: authId={}, date={}", authId, date);
35761 ranu 1416
        List<AgentCallLog> callLogs = agentCallLogRepository.findByAuthIdAndDate(authId, date);
35760 ranu 1417
        LOGGER.info("Found {} call logs for authId={} on date={}", callLogs.size(), authId, date);
35670 ranu 1418
 
35759 ranu 1419
        if (callLogs.isEmpty()) {
35672 ranu 1420
            return Collections.emptyList();
1421
        }
35670 ranu 1422
 
35759 ranu 1423
        // Build a map of normalized customer number -> fofoId
1424
        Map<String, Integer> customerToFofoIdMap = new HashMap<>();
1425
        Set<String> normalizedNumbers = new HashSet<>();
35672 ranu 1426
 
35763 ranu 1427
        for (AgentCallLog callLog : callLogs) {
35759 ranu 1428
            String customerNumber = callLog.getCustomerNumber();
1429
            if (customerNumber != null) {
1430
                String normalized = customerNumber.startsWith("+91") ? customerNumber.substring(3) : customerNumber;
1431
                normalizedNumbers.add(normalized);
1432
            }
35672 ranu 1433
        }
1434
 
35759 ranu 1435
        // For each normalized number, find fofoId from retailer_contact first, then address
1436
        for (String mobile : normalizedNumbers) {
1437
            Integer fofoId = findFofoIdByMobile(mobile);
1438
            if (fofoId != null) {
1439
                customerToFofoIdMap.put(mobile, fofoId);
1440
            }
35670 ranu 1441
        }
1442
 
35759 ranu 1443
        // Get unique fofoIds for retailer lookup
1444
        Set<Integer> fofoIds = new HashSet<>(customerToFofoIdMap.values());
1445
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
1446
        if (!fofoIds.isEmpty()) {
1447
            try {
1448
                retailerMap = retailerService.getFofoRetailers(new ArrayList<>(fofoIds));
1449
            } catch (ProfitMandiBusinessException e) {
1450
                LOGGER.error("Error fetching fofo stores", e);
1451
            }
35672 ranu 1452
        }
1453
 
35759 ranu 1454
        // Get today's remarks for these fofoIds
1455
        Map<Integer, List<PartnerCollectionRemark>> fofoRemarkMap = new HashMap<>();
1456
        if (!fofoIds.isEmpty()) {
1457
            List<PartnerCollectionRemark> todayRemarks = partnerCollectionRemarkRepository
1458
                    .selectAllByFofoIdsOnDate(new ArrayList<>(fofoIds), date);
1459
            for (PartnerCollectionRemark remark : todayRemarks) {
1460
                fofoRemarkMap.computeIfAbsent(remark.getFofoId(), k -> new ArrayList<>()).add(remark);
1461
            }
35672 ranu 1462
        }
1463
 
35759 ranu 1464
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
1465
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
1466
        List<CalledPartnerDetailModel> result = new ArrayList<>();
35672 ranu 1467
 
35759 ranu 1468
        for (com.spice.profitmandi.dao.entity.cs.AgentCallLog callLog : callLogs) {
1469
            String customerNumber = callLog.getCustomerNumber();
1470
            if (customerNumber == null) {
1471
                continue;
1472
            }
35672 ranu 1473
 
35759 ranu 1474
            String normalized = customerNumber.startsWith("+91") ? customerNumber.substring(3) : customerNumber;
1475
            Integer fofoId = customerToFofoIdMap.get(normalized);
35672 ranu 1476
 
35759 ranu 1477
            String partyName = "Unknown";
1478
            String code = "-";
35672 ranu 1479
 
35759 ranu 1480
            if (fofoId != null) {
1481
                CustomRetailer retailer = retailerMap.get(fofoId);
1482
                if (retailer != null) {
1483
                    partyName = retailer.getBusinessName();
1484
                    code = retailer.getCode();
1485
                } else {
1486
                    partyName = "Unknown (" + fofoId + ")";
1487
                }
1488
            } else {
1489
                partyName = "Unknown (" + normalized + ")";
1490
            }
35672 ranu 1491
 
35759 ranu 1492
            // Get remark if available
1493
            String remarkValue = "-";
1494
            String messageValue = "-";
1495
            String remarkTime = "-";
35672 ranu 1496
 
35759 ranu 1497
            if (fofoId != null && fofoRemarkMap.containsKey(fofoId)) {
1498
                List<PartnerCollectionRemark> remarks = fofoRemarkMap.get(fofoId);
1499
                if (!remarks.isEmpty()) {
1500
                    PartnerCollectionRemark remark = remarks.get(0);
1501
                    remarkValue = remark.getRemark() != null ? remark.getRemark().getValue() : "-";
1502
                    messageValue = remark.getMessage() != null ? remark.getMessage() : "-";
1503
                    remarkTime = remark.getCreateTimestamp() != null ? remark.getCreateTimestamp().format(timeFormatter) : "-";
1504
                }
1505
            }
35672 ranu 1506
 
35759 ranu 1507
            // Build call log data
1508
            String recordingUrl = callLog.getRecordingUrl();
1509
            String callStatus = callLog.getCallStatus();
1510
            String callDuration = callLog.getCallDuration();
1511
            String callDateTime = null;
1512
            if (callLog.getCallDate() != null && callLog.getCallTime() != null) {
1513
                LocalDateTime callDateTimeObj = LocalDateTime.of(callLog.getCallDate(), callLog.getCallTime());
1514
                callDateTime = callDateTimeObj.format(dateTimeFormatter);
35672 ranu 1515
            }
35759 ranu 1516
 
1517
            result.add(new CalledPartnerDetailModel(partyName, code, remarkValue, messageValue, remarkTime,
1518
                    recordingUrl, callStatus, callDuration, callDateTime));
35672 ranu 1519
        }
1520
 
35759 ranu 1521
        return result;
1522
    }
35672 ranu 1523
 
35759 ranu 1524
    private Integer findFofoIdByMobile(String mobile) {
1525
        // First check retailer_contact
1526
        List<RetailerContact> contacts = retailerContactRepository.selectByMobile(mobile);
1527
        if (contacts != null && !contacts.isEmpty()) {
1528
            return contacts.get(0).getFofoId();
1529
        }
1530
 
1531
        // Fallback to user.address
35762 ranu 1532
        List<Address> addresses = addressRepository.selectAllByPhoneNumber(mobile);
1533
        if (addresses != null && !addresses.isEmpty()) {
1534
            return addresses.get(0).getRetaierId();
35759 ranu 1535
        }
1536
 
1537
        return null;
35672 ranu 1538
    }
1539
 
35757 ranu 1540
    private List<CalledPartnerDetailModel> buildCalledPartnerResult(List<PartnerCollectionRemark> allRemarks) {
1541
        if (allRemarks.isEmpty()) {
35672 ranu 1542
            return Collections.emptyList();
1543
        }
1544
 
35757 ranu 1545
        // Get unique fofoIds for retailer lookup
1546
        Set<Integer> fofoIds = allRemarks.stream()
1547
                .map(PartnerCollectionRemark::getFofoId)
1548
                .collect(Collectors.toSet());
35670 ranu 1549
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
1550
        try {
1551
            retailerMap = retailerService.getFofoRetailers(new ArrayList<>(fofoIds));
1552
        } catch (ProfitMandiBusinessException e) {
1553
            LOGGER.error("Error fetching fofo stores", e);
1554
        }
1555
 
35702 ranu 1556
        // Fetch call logs for remarks that have agentCallLogId
35721 ranu 1557
        Map<Long, com.spice.profitmandi.dao.entity.cs.AgentCallLog> callLogMap = new HashMap<>();
1558
        try {
35757 ranu 1559
            List<Long> callLogIds = allRemarks.stream()
35721 ranu 1560
                    .filter(r -> r.getAgentCallLogId() > 0)
1561
                    .map(PartnerCollectionRemark::getAgentCallLogId)
1562
                    .collect(Collectors.toList());
35702 ranu 1563
 
35721 ranu 1564
            if (!callLogIds.isEmpty()) {
35720 ranu 1565
                List<com.spice.profitmandi.dao.entity.cs.AgentCallLog> callLogs = agentCallLogRepository.findByIds(callLogIds);
35721 ranu 1566
                if (callLogs != null) {
1567
                    callLogMap = callLogs.stream()
1568
                            .collect(Collectors.toMap(com.spice.profitmandi.dao.entity.cs.AgentCallLog::getId, c -> c, (a, b) -> a));
1569
                }
35720 ranu 1570
            }
35721 ranu 1571
        } catch (Exception e) {
1572
            LOGGER.error("Error fetching call logs by ids", e);
35702 ranu 1573
        }
1574
 
35670 ranu 1575
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
35702 ranu 1576
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
35670 ranu 1577
        List<CalledPartnerDetailModel> result = new ArrayList<>();
1578
 
35757 ranu 1579
        for (PartnerCollectionRemark remark : allRemarks) {
35670 ranu 1580
            CustomRetailer retailer = retailerMap.get(remark.getFofoId());
1581
            String partyName = retailer != null
1582
                    ? retailer.getBusinessName()
1583
                    : "Unknown (" + remark.getFofoId() + ")";
1584
            String code = retailer != null
1585
                    ? retailer.getCode()
1586
                    : "-";
1587
 
1588
            String remarkValue = remark.getRemark() != null
1589
                    ? remark.getRemark().getValue()
1590
                    : "-";
1591
 
35677 ranu 1592
            String messageValue = remark.getMessage() != null
1593
                    ? remark.getMessage()
1594
                    : "-";
1595
 
35670 ranu 1596
            String time = remark.getCreateTimestamp() != null
1597
                    ? remark.getCreateTimestamp().format(timeFormatter)
1598
                    : "-";
1599
 
35702 ranu 1600
            // Get call log data if available
1601
            String recordingUrl = null;
1602
            String callStatus = null;
1603
            String callDuration = null;
1604
            String callDateTime = null;
1605
 
35721 ranu 1606
            try {
1607
                if (remark.getAgentCallLogId() > 0 && callLogMap.containsKey(remark.getAgentCallLogId())) {
1608
                    com.spice.profitmandi.dao.entity.cs.AgentCallLog callLog = callLogMap.get(remark.getAgentCallLogId());
1609
                    recordingUrl = callLog.getRecordingUrl();
1610
                    callStatus = callLog.getCallStatus();
1611
                    callDuration = callLog.getCallDuration();
1612
                    if (callLog.getCallDate() != null && callLog.getCallTime() != null) {
1613
                        LocalDateTime callDateTimeObj = LocalDateTime.of(callLog.getCallDate(), callLog.getCallTime());
1614
                        callDateTime = callDateTimeObj.format(dateTimeFormatter);
1615
                    }
35702 ranu 1616
                }
35721 ranu 1617
            } catch (Exception e) {
1618
                LOGGER.error("Error processing call log for remark id: {}", remark.getId(), e);
35702 ranu 1619
            }
1620
 
1621
            result.add(new CalledPartnerDetailModel(partyName, code, remarkValue, messageValue, time,
1622
                    recordingUrl, callStatus, callDuration, callDateTime));
35670 ranu 1623
        }
1624
 
1625
        return result;
1626
    }
1627
 
1628
    @Override
35645 ranu 1629
    public List<List<String>> getRbmCallTargetRawDataByAuthId(int authId) throws Exception {
1630
        List<List<String>> rows = new ArrayList<>();
35631 ranu 1631
 
35645 ranu 1632
        // Get auth user
1633
        List<AuthUser> authUsers = authRepository.selectByIds(Collections.singletonList(authId));
1634
        if (authUsers.isEmpty()) {
1635
            return rows;
1636
        }
1637
        AuthUser authUser = authUsers.get(0);
1638
 
35757 ranu 1639
        // Get positions to determine if L2
35645 ranu 1640
        List<Position> positions = positionRepository.selectPositionByAuthIds(Collections.singletonList(authId));
1641
        boolean isL2 = positions.stream()
1642
                .anyMatch(p -> ProfitMandiConstants.TICKET_CATEGORY_RBM == p.getCategoryId()
1643
                        && EscalationType.L2.equals(p.getEscalationType()));
1644
 
35757 ranu 1645
        LocalDateTime startDate = LocalDate.now().atStartOfDay();
1646
        LocalDate firstOfMonth = LocalDate.now().withDayOfMonth(1);
1647
        LocalDate endOfMonth = LocalDate.now().withDayOfMonth(LocalDate.now().lengthOfMonth()).plusDays(1);
35645 ranu 1648
 
35757 ranu 1649
        // Get fofo IDs from mtdBillingData (same source as Partner Count in getRbmCallTargetModels)
1650
        List<RbmWeeklyBillingModel> mtdBillingData = getWeeklyBillingDataForMonth(firstOfMonth, endOfMonth);
1651
 
1652
        List<Integer> fofoIdList;
35645 ranu 1653
        if (isL2) {
35757 ranu 1654
            // L2: get fofo IDs from escalated tickets (same as getRbmCallTargetModels)
35645 ranu 1655
            List<Ticket> escalatedTickets = ticketRepository.selectOpenEscalatedTicketsByAuthIds(Collections.singletonList(authId));
1656
            fofoIdList = escalatedTickets.stream()
1657
                    .filter(t -> t.getL2AuthUser() == authId
1658
                            || t.getL3AuthUser() == authId
1659
                            || t.getL4AuthUser() == authId
1660
                            || t.getL5AuthUser() == authId)
1661
                    .map(Ticket::getFofoId)
1662
                    .distinct()
1663
                    .collect(Collectors.toList());
35757 ranu 1664
        } else {
1665
            // L1: get fofo IDs from mtdBillingData with isTargetedPartner (same as Partner Count)
1666
            fofoIdList = mtdBillingData.stream()
1667
                    .filter(RbmWeeklyBillingModel::isTargetedPartner)
1668
                    .filter(m -> m.getAuthId() == authId)
1669
                    .map(RbmWeeklyBillingModel::getFofoId)
1670
                    .distinct()
1671
                    .collect(Collectors.toList());
35645 ranu 1672
        }
1673
 
1674
        if (fofoIdList.isEmpty()) {
1675
            return rows;
1676
        }
1677
 
35757 ranu 1678
        // MTD billed fofoIds for zero billing check
1679
        Set<Integer> mtdBilledFofoIds = mtdBillingData.stream()
1680
                .filter(RbmWeeklyBillingModel::isMtdBilled)
1681
                .map(RbmWeeklyBillingModel::getFofoId)
1682
                .collect(Collectors.toSet());
35645 ranu 1683
 
35757 ranu 1684
        // Collection rank map for status calculation
35645 ranu 1685
        Map<Integer, Integer> collectionRankMap = new HashMap<>();
1686
        try {
1687
            collectionRankMap = partnerCollectionService.getCollectionRankMap(fofoIdList, startDate);
1688
        } catch (ProfitMandiBusinessException e) {
1689
            LOGGER.error("Error fetching collection rank map", e);
1690
        }
1691
 
1692
        // Resolve partner names/codes
1693
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
35757 ranu 1694
        if (!fofoIdList.isEmpty()) {
35645 ranu 1695
            try {
35757 ranu 1696
                retailerMap = retailerService.getFofoRetailers(fofoIdList);
35645 ranu 1697
            } catch (ProfitMandiBusinessException e) {
1698
                LOGGER.error("Error fetching fofo retailers for raw data", e);
1699
            }
1700
        }
1701
 
1702
        String rbmName = authUser.getFullName() + (isL2 ? " (L2)" : "");
1703
 
35757 ranu 1704
        // Build rows for ALL partners (same count as Partner Count)
1705
        for (Integer fofoId : fofoIdList) {
1706
            // Default to rank 5 (Normal) for partners without collection plan
35645 ranu 1707
            int rank = collectionRankMap.getOrDefault(fofoId, 5);
1708
            boolean hasZeroBilling = !mtdBilledFofoIds.contains(fofoId);
1709
 
35757 ranu 1710
            // Status assignment with same priority as getRbmCallTargetModels
35645 ranu 1711
            String status;
1712
            if (rank == 1) {
1713
                status = "Plan Today";
1714
            } else if (rank == 2) {
1715
                status = "Carry Forward";
35757 ranu 1716
            } else if (hasZeroBilling) {
1717
                status = "Zero Billing";
35645 ranu 1718
            } else if (rank == 3) {
1719
                status = "Untouched";
1720
            } else if (rank == 4) {
1721
                status = "Future Plan";
1722
            } else {
1723
                status = "Normal";
1724
            }
1725
 
1726
            CustomRetailer retailer = retailerMap.get(fofoId);
1727
            String partnerName = retailer != null ? retailer.getBusinessName() : "Unknown (" + fofoId + ")";
1728
            String partnerCode = retailer != null ? retailer.getCode() : "-";
1729
 
1730
            rows.add(Arrays.asList(partnerName, partnerCode, status, rbmName));
1731
        }
1732
 
1733
        return rows;
1734
    }
1735
 
35843 ranu 1736
    /**
1737
     * Get count of distinct partners called today based on call logs.
1738
     * Maps customerNumber from call log to fofoId using retailer_contact and address.
1739
     * If same fofoId is called multiple times, counts only once.
1740
     * Numbers without fofoId mapping are also counted (by distinct customer number).
1741
     *
1742
     * @param authId the RBM auth ID
1743
     * @return count of distinct partners/numbers called today
1744
     */
1745
    public long getCalledCountFromCallLogs(long authId) {
36234 ranu 1746
        return getCalledCountFromCallLogs(authId, LocalDate.now());
1747
    }
35843 ranu 1748
 
36234 ranu 1749
    public long getCalledCountFromCallLogs(long authId, LocalDate date) {
36276 ranu 1750
        return getCallStats(authId, date)[0];
1751
    }
1752
 
1753
    /**
36284 ranu 1754
     * Batch-builds a mobile (normalized, +91 stripped) -> fofoId mapping for all the given mobiles
1755
     * in just two queries (retailer_contact, then address fallback for unmapped numbers).
1756
     * Replaces the previous per-call-log findFofoIdByMobile() N+1 lookups.
1757
     */
1758
    private Map<String, Integer> buildMobileToFofoIdMap(Set<String> normalizedMobiles) {
1759
        Map<String, Integer> result = new HashMap<>();
1760
        if (normalizedMobiles == null || normalizedMobiles.isEmpty()) {
1761
            return result;
1762
        }
1763
        List<String> mobilesList = new ArrayList<>(normalizedMobiles);
1764
 
1765
        // First pass: retailer_contact
1766
        List<RetailerContact> contacts = retailerContactRepository.selectByMobiles(mobilesList);
1767
        for (RetailerContact rc : contacts) {
1768
            // Keep the first fofoId we see per mobile (matches old single-mobile behavior of get(0))
1769
            result.putIfAbsent(rc.getMobile(), rc.getFofoId());
1770
        }
1771
 
1772
        // Second pass: address fallback for mobiles not yet mapped
1773
        List<String> unmapped = mobilesList.stream()
1774
                .filter(m -> !result.containsKey(m))
1775
                .collect(Collectors.toList());
1776
        if (!unmapped.isEmpty()) {
1777
            List<Address> addresses = addressRepository.selectAllByPhoneNumbers(unmapped);
1778
            for (Address addr : addresses) {
1779
                result.putIfAbsent(addr.getPhoneNumber(), addr.getRetaierId());
1780
            }
1781
        }
1782
        return result;
1783
    }
1784
 
1785
    /**
1786
     * In-memory variant of getCallStats() that uses pre-fetched call logs and mobile→fofoId mapping.
1787
     * Used by the batch-fetched RBM Call Target loop to avoid N+1 query patterns.
1788
     */
1789
    private long[] getCallStatsFromLogs(List<AgentCallLog> callLogs, Map<String, Integer> mobileToFofoIdMap) {
1790
        if (callLogs == null || callLogs.isEmpty()) {
1791
            return new long[]{0, 0, 0};
1792
        }
1793
 
1794
        Set<Integer> calledFofoIds = new HashSet<>();
1795
        Set<String> calledNumbersWithoutFofoId = new HashSet<>();
1796
        long totalRecordingCalls = 0;
1797
        Set<String> uniqueRecordingNumbers = new HashSet<>();
1798
 
1799
        for (AgentCallLog callLog : callLogs) {
1800
            String customerNumber = callLog.getCustomerNumber();
1801
            if (customerNumber != null) {
1802
                String normalized = customerNumber.startsWith("+91") ? customerNumber.substring(3) : customerNumber;
1803
                Integer fofoId = mobileToFofoIdMap.get(normalized);
1804
                if (fofoId != null) {
1805
                    calledFofoIds.add(fofoId);
1806
                } else {
1807
                    calledNumbersWithoutFofoId.add(normalized);
1808
                }
1809
 
1810
                if (callLog.getRecordingUrl() != null && !callLog.getRecordingUrl().isEmpty()
1811
                        && !"None".equalsIgnoreCase(callLog.getRecordingUrl())) {
1812
                    totalRecordingCalls++;
1813
                    uniqueRecordingNumbers.add(normalized);
1814
                }
1815
            }
1816
        }
1817
 
1818
        long calledCount = calledFofoIds.size() + calledNumbersWithoutFofoId.size();
1819
        return new long[]{calledCount, totalRecordingCalls, uniqueRecordingNumbers.size()};
1820
    }
1821
 
1822
    /**
36276 ranu 1823
     * Returns call stats: [0] = called count, [1] = total recording calls, [2] = unique recording calls
1824
     */
1825
    public long[] getCallStats(long authId, LocalDate date) {
36234 ranu 1826
        List<AgentCallLog> callLogs = agentCallLogRepository.findByAuthIdAndDate(authId, date);
1827
 
35843 ranu 1828
        if (callLogs == null || callLogs.isEmpty()) {
36276 ranu 1829
            return new long[]{0, 0, 0};
35843 ranu 1830
        }
1831
 
1832
        Set<Integer> calledFofoIds = new HashSet<>();
1833
        Set<String> calledNumbersWithoutFofoId = new HashSet<>();
36276 ranu 1834
        long totalRecordingCalls = 0;
1835
        Set<String> uniqueRecordingNumbers = new HashSet<>();
35843 ranu 1836
 
1837
        for (AgentCallLog callLog : callLogs) {
1838
            String customerNumber = callLog.getCustomerNumber();
1839
            if (customerNumber != null) {
1840
                // Normalize the phone number (remove +91 prefix if present)
1841
                String normalized = customerNumber.startsWith("+91") ? customerNumber.substring(3) : customerNumber;
1842
 
1843
                // Find fofoId from retailer_contact or address
1844
                Integer fofoId = findFofoIdByMobile(normalized);
1845
                if (fofoId != null) {
1846
                    calledFofoIds.add(fofoId);
1847
                } else {
1848
                    // Number not found in retailer_contact or address, count by distinct number
1849
                    calledNumbersWithoutFofoId.add(normalized);
1850
                }
36276 ranu 1851
 
1852
                // Count calls with recordings
1853
                if (callLog.getRecordingUrl() != null && !callLog.getRecordingUrl().isEmpty()
1854
                        && !"None".equalsIgnoreCase(callLog.getRecordingUrl())) {
1855
                    totalRecordingCalls++;
1856
                    uniqueRecordingNumbers.add(normalized);
1857
                }
35843 ranu 1858
            }
1859
        }
1860
 
1861
        // Total called = distinct fofoIds + distinct numbers without fofoId mapping
36276 ranu 1862
        long calledCount = calledFofoIds.size() + calledNumbersWithoutFofoId.size();
1863
        return new long[]{calledCount, totalRecordingCalls, uniqueRecordingNumbers.size()};
35843 ranu 1864
    }
1865
 
35852 ranu 1866
    @Override
1867
    public List<List<String>> getAllCallDataByDate(LocalDate date) throws Exception {
1868
        List<List<String>> rows = new ArrayList<>();
1869
 
1870
        // Add header row
1871
        rows.add(Arrays.asList("RBM Name", "Partner Name", "Code", "Remark", "Call Status", "Call Duration", "Call Date Time", "Recording URL"));
1872
 
1873
        // Get all call logs for the date
1874
        List<AgentCallLog> allCallLogs = agentCallLogRepository.findAllByDate(date);
1875
        LOGGER.info("getAllCallDataByDate: Found {} call logs for date {}", allCallLogs.size(), date);
1876
 
1877
        if (allCallLogs.isEmpty()) {
1878
            return rows;
1879
        }
1880
 
1881
        // Get unique authIds from call logs
1882
        Set<Long> authIds = allCallLogs.stream()
1883
                .map(AgentCallLog::getAuthId)
1884
                .collect(Collectors.toSet());
1885
 
1886
        // Get auth users for RBM names
1887
        List<Integer> authIdInts = authIds.stream().map(Long::intValue).collect(Collectors.toList());
1888
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(authIdInts).stream()
1889
                .collect(Collectors.toMap(AuthUser::getId, au -> au, (a, b) -> a));
1890
 
1891
        // Build a map of normalized customer number -> fofoId
1892
        Map<String, Integer> customerToFofoIdMap = new HashMap<>();
1893
        Set<String> normalizedNumbers = new HashSet<>();
1894
 
1895
        for (AgentCallLog callLog : allCallLogs) {
1896
            String customerNumber = callLog.getCustomerNumber();
1897
            if (customerNumber != null) {
1898
                String normalized = customerNumber.startsWith("+91") ? customerNumber.substring(3) : customerNumber;
1899
                normalizedNumbers.add(normalized);
1900
            }
1901
        }
1902
 
1903
        // For each normalized number, find fofoId
1904
        for (String mobile : normalizedNumbers) {
1905
            Integer fofoId = findFofoIdByMobile(mobile);
1906
            if (fofoId != null) {
1907
                customerToFofoIdMap.put(mobile, fofoId);
1908
            }
1909
        }
1910
 
1911
        // Get unique fofoIds for retailer lookup
1912
        Set<Integer> fofoIds = new HashSet<>(customerToFofoIdMap.values());
1913
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
1914
        if (!fofoIds.isEmpty()) {
1915
            try {
1916
                retailerMap = retailerService.getFofoRetailers(new ArrayList<>(fofoIds));
1917
            } catch (ProfitMandiBusinessException e) {
1918
                LOGGER.error("Error fetching fofo stores", e);
1919
            }
1920
        }
1921
 
1922
        // Get remarks for these fofoIds on this date
1923
        Map<Integer, List<PartnerCollectionRemark>> fofoRemarkMap = new HashMap<>();
1924
        if (!fofoIds.isEmpty()) {
1925
            List<PartnerCollectionRemark> dateRemarks = partnerCollectionRemarkRepository
1926
                    .selectAllByFofoIdsOnDate(new ArrayList<>(fofoIds), date);
1927
            for (PartnerCollectionRemark remark : dateRemarks) {
1928
                fofoRemarkMap.computeIfAbsent(remark.getFofoId(), k -> new ArrayList<>()).add(remark);
1929
            }
1930
        }
1931
 
1932
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
1933
 
1934
        // Build rows
1935
        for (AgentCallLog callLog : allCallLogs) {
1936
            String customerNumber = callLog.getCustomerNumber();
1937
            if (customerNumber == null) {
1938
                continue;
1939
            }
1940
 
1941
            // Get RBM Name
1942
            AuthUser authUser = authUserMap.get((int) callLog.getAuthId());
1943
            String rbmName = authUser != null ? authUser.getFullName() : "Unknown";
1944
 
1945
            String normalized = customerNumber.startsWith("+91") ? customerNumber.substring(3) : customerNumber;
1946
            Integer fofoId = customerToFofoIdMap.get(normalized);
1947
 
1948
            String partyName = "Unknown";
1949
            String code = "-";
1950
 
1951
            if (fofoId != null) {
1952
                CustomRetailer retailer = retailerMap.get(fofoId);
1953
                if (retailer != null) {
1954
                    partyName = retailer.getBusinessName();
1955
                    code = retailer.getCode();
1956
                } else {
1957
                    partyName = "Unknown (" + fofoId + ")";
1958
                }
1959
            } else {
1960
                partyName = "Unknown (" + normalized + ")";
1961
            }
1962
 
1963
            // Get remark if available
1964
            String remarkValue = "-";
1965
            if (fofoId != null && fofoRemarkMap.containsKey(fofoId)) {
1966
                List<PartnerCollectionRemark> remarks = fofoRemarkMap.get(fofoId);
1967
                if (!remarks.isEmpty()) {
1968
                    PartnerCollectionRemark remark = remarks.get(0);
1969
                    remarkValue = remark.getRemark() != null ? remark.getRemark().getValue() : "-";
1970
                    if (remark.getMessage() != null && !remark.getMessage().isEmpty()) {
1971
                        remarkValue = remarkValue + " - " + remark.getMessage();
1972
                    }
1973
                }
1974
            }
1975
 
1976
            // Call status from customerStatus field
1977
            String callStatus = callLog.getCustomerStatus() != null ? callLog.getCustomerStatus() : "-";
1978
            String callDuration = callLog.getCallDuration() != null ? callLog.getCallDuration() : "-";
1979
 
1980
            String callDateTime = "-";
1981
            if (callLog.getCallDate() != null && callLog.getCallTime() != null) {
1982
                LocalDateTime callDateTimeObj = LocalDateTime.of(callLog.getCallDate(), callLog.getCallTime());
1983
                callDateTime = callDateTimeObj.format(dateTimeFormatter);
1984
            }
1985
 
1986
            String recordingUrl = callLog.getRecordingUrl() != null ? callLog.getRecordingUrl() : "-";
1987
 
1988
            rows.add(Arrays.asList(rbmName, partyName, code, remarkValue, callStatus, callDuration, callDateTime, recordingUrl));
1989
        }
1990
 
1991
        return rows;
1992
    }
1993
 
33917 ranu 1994
}