Subversion Repositories SmartDukaan

Rev

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