Subversion Repositories SmartDukaan

Rev

Rev 36181 | Rev 36212 | 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
 
35631 ranu 609
    @Override
610
    public List<RbmCallTargetModel> getRbmCallTargetModels() throws Exception {
611
        long methodStart = System.currentTimeMillis();
612
        List<RbmCallTargetModel> rbmCallTargetModels = new ArrayList<>();
613
 
614
        // Get all RBM positions (L1 and L2)
615
        long start = System.currentTimeMillis();
616
        List<Position> allRbmPositions = positionRepository
617
                .selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_RBM).stream()
36210 ranu 618
                .filter(x -> Arrays.asList(EscalationType.L1, EscalationType.L2, EscalationType.L3).contains(x.getEscalationType()))
35631 ranu 619
                .collect(Collectors.toList());
620
 
36210 ranu 621
        // Separate L1, L2 and L3 auth IDs
35631 ranu 622
        List<Integer> l1AuthIds = allRbmPositions.stream()
623
                .filter(p -> EscalationType.L1.equals(p.getEscalationType()))
624
                .map(Position::getAuthUserId).distinct().collect(Collectors.toList());
625
        List<Integer> l2AuthIds = allRbmPositions.stream()
626
                .filter(p -> EscalationType.L2.equals(p.getEscalationType()))
627
                .map(Position::getAuthUserId).distinct().collect(Collectors.toList());
36210 ranu 628
        List<Integer> l3AuthIds = allRbmPositions.stream()
629
                .filter(p -> EscalationType.L3.equals(p.getEscalationType()))
630
                .map(Position::getAuthUserId).distinct().collect(Collectors.toList());
35631 ranu 631
 
632
        // Union of all auth IDs for batch fetching
633
        List<Integer> rbmPositionsAuthIds = allRbmPositions.stream()
634
                .map(Position::getAuthUserId).distinct().collect(Collectors.toList());
36210 ranu 635
        LOGGER.info("RBM Call Target - RBM positions fetch: {}ms, L1: {}, L2: {}, L3: {}", System.currentTimeMillis() - start, l1AuthIds.size(), l2AuthIds.size(), l3AuthIds.size());
35631 ranu 636
 
637
        start = System.currentTimeMillis();
638
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
639
        LOGGER.info("RBM Call Target - StoreGuyMap fetch: {}ms", System.currentTimeMillis() - start);
640
 
641
        LocalDateTime startDate = LocalDate.now().atStartOfDay();
642
        LocalDate firstOfMonth = LocalDate.now().withDayOfMonth(1);
643
        LocalDate endOfMonth = LocalDate.now().withDayOfMonth(LocalDate.now().lengthOfMonth()).plusDays(1);
644
 
645
        // Get auth user map
646
        start = System.currentTimeMillis();
647
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(rbmPositionsAuthIds).stream()
648
                .collect(Collectors.toMap(AuthUser::getId, au -> au));
649
        LOGGER.info("RBM Call Target - AuthUser fetch: {}ms", System.currentTimeMillis() - start);
650
 
651
        // Batch fetch positions by auth IDs (to check if RBM is L1)
652
        start = System.currentTimeMillis();
653
        Map<Integer, List<Position>> positionsByAuthId = positionRepository.selectPositionByAuthIds(rbmPositionsAuthIds).stream()
654
                .collect(Collectors.groupingBy(Position::getAuthUserId));
655
        LOGGER.info("RBM Call Target - Positions by AuthId fetch: {}ms", System.currentTimeMillis() - start);
656
 
657
        // Get all fofo IDs for all RBMs
658
        Set<Integer> allFofoIds = new HashSet<>();
659
        Map<Integer, List<Integer>> rbmToFofoIdsMap = new HashMap<>();
660
        for (int rbmAuthId : rbmPositionsAuthIds) {
661
            AuthUser au = authUserMap.get(rbmAuthId);
662
            if (au != null && storeGuyMap.containsKey(au.getEmailId())) {
663
                List<Integer> fofoIds = new ArrayList<>(storeGuyMap.get(au.getEmailId()));
664
                allFofoIds.addAll(fofoIds);
665
                rbmToFofoIdsMap.put(rbmAuthId, fofoIds);
666
            }
667
        }
35816 ranu 668
        // Initialize L2 calling list map - will be populated after fetching remarks
35631 ranu 669
        Map<Integer, List<Integer>> l2AuthIdToFofoIds = new HashMap<>();
35816 ranu 670
        for (int l2AuthId : l2AuthIds) {
671
            l2AuthIdToFofoIds.put(l2AuthId, new ArrayList<>());
35631 ranu 672
        }
36210 ranu 673
        // Initialize L3 calling list map - will be populated after fetching remarks
674
        Map<Integer, List<Integer>> l3AuthIdToFofoIds = new HashMap<>();
675
        for (int l3AuthId : l3AuthIds) {
676
            l3AuthIdToFofoIds.put(l3AuthId, new ArrayList<>());
677
        }
35631 ranu 678
        LOGGER.info("RBM Call Target - Total fofo IDs to process: {}", allFofoIds.size());
679
 
680
        // Get only needed fofo stores (OPTIMIZED - was fetching ALL stores before)
681
        start = System.currentTimeMillis();
682
        Map<Integer, FofoStore> fofoStoresMap = new HashMap<>();
683
        if (!allFofoIds.isEmpty()) {
684
            try {
685
                fofoStoresMap = fofoStoreRepository.selectByRetailerIds(new ArrayList<>(allFofoIds)).stream()
686
                        .collect(Collectors.toMap(FofoStore::getId, x -> x, (a, b) -> a));
687
            } catch (ProfitMandiBusinessException e) {
688
                LOGGER.error("Error fetching fofo stores", e);
689
            }
690
        }
691
        LOGGER.info("RBM Call Target - FofoStores fetch (only needed): {}ms, count: {}", System.currentTimeMillis() - start, fofoStoresMap.size());
692
 
693
        // Batch fetch max remark ids for all fofoIds (for escalation filtering)
694
        start = System.currentTimeMillis();
695
        Map<Integer, PartnerCollectionRemark> allPartnerCollectionRemarks = new HashMap<>();
696
        if (!allFofoIds.isEmpty()) {
697
            List<Integer> allRemarkIds = partnerCollectionRemarkRepository.selectMaxRemarkId(new ArrayList<>(allFofoIds));
698
            if (!allRemarkIds.isEmpty()) {
699
                allPartnerCollectionRemarks = partnerCollectionRemarkRepository.selectByIds(allRemarkIds).stream()
700
                        .collect(Collectors.toMap(PartnerCollectionRemark::getFofoId, x -> x, (a, b) -> a));
701
            }
702
        }
703
        LOGGER.info("RBM Call Target - PartnerCollectionRemarks fetch: {}ms", System.currentTimeMillis() - start);
704
 
35816 ranu 705
        // Populate L2 calling list based on partners whose latest remark is RBM_L2_ESCALATION
706
        // Find the L1 who has the partner and add to that L1's manager (L2) calling list
707
        for (Map.Entry<Integer, PartnerCollectionRemark> entry : allPartnerCollectionRemarks.entrySet()) {
708
            Integer fofoId = entry.getKey();
709
            PartnerCollectionRemark remark = entry.getValue();
710
 
711
            if (CollectionRemark.RBM_L2_ESCALATION.equals(remark.getRemark())) {
712
                // Find which L1 RBM has this partner assigned
713
                for (int l1AuthId : l1AuthIds) {
714
                    List<Integer> l1FofoIds = rbmToFofoIdsMap.getOrDefault(l1AuthId, Collections.emptyList());
715
                    if (l1FofoIds.contains(fofoId)) {
716
                        // Get L1's manager (L2)
717
                        AuthUser l1User = authUserMap.get(l1AuthId);
718
                        if (l1User != null && l2AuthIdToFofoIds.containsKey(l1User.getManagerId())) {
719
                            int l2ManagerId = l1User.getManagerId();
720
                            l2AuthIdToFofoIds.get(l2ManagerId).add(fofoId);
721
                        }
722
                        break; // Found the L1 for this fofoId
723
                    }
724
                }
725
            }
726
        }
727
        LOGGER.info("RBM Call Target - L2 calling lists populated from RBM_L2_ESCALATION remarks");
728
 
36210 ranu 729
        // Populate L3 calling list based on partners whose latest remark is RBM_L3_ESCALATION
730
        // Find the L1 who originally has the partner, then traverse: L1 -> L2 (manager) -> L3 (manager's manager)
731
        for (Map.Entry<Integer, PartnerCollectionRemark> entry : allPartnerCollectionRemarks.entrySet()) {
732
            Integer fofoId = entry.getKey();
733
            PartnerCollectionRemark remark = entry.getValue();
734
 
735
            if (CollectionRemark.RBM_L3_ESCALATION.equals(remark.getRemark())) {
736
                // Find which L1 RBM originally has this partner assigned
737
                for (int l1AuthId : l1AuthIds) {
738
                    List<Integer> l1FofoIds = rbmToFofoIdsMap.getOrDefault(l1AuthId, Collections.emptyList());
739
                    if (l1FofoIds.contains(fofoId)) {
740
                        // Get L1's manager (L2)
741
                        AuthUser l1User = authUserMap.get(l1AuthId);
742
                        if (l1User != null) {
743
                            int l2ManagerId = l1User.getManagerId();
744
                            AuthUser l2User = authUserMap.get(l2ManagerId);
745
                            // Get L2's manager (L3)
746
                            if (l2User != null && l3AuthIdToFofoIds.containsKey(l2User.getManagerId())) {
747
                                int l3ManagerId = l2User.getManagerId();
748
                                l3AuthIdToFofoIds.get(l3ManagerId).add(fofoId);
749
                                LOGGER.debug("L3 Calling List: fofoId={} -> L1={} -> L2={} -> L3={}",
750
                                        fofoId, l1AuthId, l2ManagerId, l3ManagerId);
751
                            }
752
                        }
753
                        break; // Found the L1 for this fofoId
754
                    }
755
                }
756
            }
757
        }
758
        LOGGER.info("RBM Call Target - L3 calling lists populated from RBM_L3_ESCALATION remarks");
759
 
35631 ranu 760
        // Batch fetch collection RANK map for all fofoIds (OPTIMIZED - only fetches rank, not full model)
761
        start = System.currentTimeMillis();
762
        Map<Integer, Integer> allCollectionRankMap = new HashMap<>();
763
        if (!allFofoIds.isEmpty()) {
764
            try {
765
                allCollectionRankMap = partnerCollectionService.getCollectionRankMap(new ArrayList<>(allFofoIds), startDate);
766
            } catch (ProfitMandiBusinessException e) {
767
                LOGGER.error("Error fetching collection rank map for all fofoIds", e);
768
            }
769
        }
770
        LOGGER.info("RBM Call Target - CollectionRankMap fetch (OPTIMIZED): {}ms", System.currentTimeMillis() - start);
771
 
35669 ranu 772
        // Get MTD billing data for zero billing calculation and partner counts
35631 ranu 773
        start = System.currentTimeMillis();
774
        List<RbmWeeklyBillingModel> mtdBillingData = getWeeklyBillingDataForMonth(firstOfMonth, endOfMonth);
775
        Set<Integer> allMtdBilledFofoIds = mtdBillingData.stream()
776
                .filter(RbmWeeklyBillingModel::isMtdBilled)
777
                .map(RbmWeeklyBillingModel::getFofoId)
778
                .collect(Collectors.toSet());
35669 ranu 779
        // Build partner count and fofoIds per RBM from mtdBillingData (same source as Today ARR page)
780
        Map<Integer, Set<Integer>> mtdFofoIdsByAuthId = mtdBillingData.stream()
781
                .filter(RbmWeeklyBillingModel::isTargetedPartner)
782
                .collect(Collectors.groupingBy(RbmWeeklyBillingModel::getAuthId,
783
                        Collectors.mapping(RbmWeeklyBillingModel::getFofoId, Collectors.toSet())));
35631 ranu 784
        LOGGER.info("RBM Call Target - MTD Billing fetch: {}ms", System.currentTimeMillis() - start);
785
 
786
        // Batch fetch today's remarks for all auth IDs (to calculate Value Achieved)
787
        start = System.currentTimeMillis();
788
        Map<Integer, List<PartnerCollectionRemark>> remarksByAuthId = partnerCollectionRemarkRepository
789
                .selectAllByAuthIdsOnDate(rbmPositionsAuthIds, LocalDate.now()).stream()
790
                .collect(Collectors.groupingBy(PartnerCollectionRemark::getAuthId));
791
        LOGGER.info("RBM Call Target - Today Remarks fetch: {}ms", System.currentTimeMillis() - start);
792
 
793
        // Batch fetch today's out-of-sequence logs for all RBMs
794
        start = System.currentTimeMillis();
795
        LocalDateTime todayStart = LocalDate.now().atStartOfDay();
796
        LocalDateTime todayEnd = LocalDate.now().plusDays(1).atStartOfDay();
797
        List<RbmCallSequenceLog> outOfSequenceLogs = rbmCallSequenceLogRepository.selectOutOfSequenceByDateRange(todayStart, todayEnd);
798
        Map<Integer, Long> outOfSequenceCountByAuthId = outOfSequenceLogs.stream()
35654 ranu 799
                .collect(Collectors.groupingBy(RbmCallSequenceLog::getAuthId,
800
                        Collectors.mapping(RbmCallSequenceLog::getFofoId, Collectors.collectingAndThen(Collectors.toSet(), s -> (long) s.size()))));
35631 ranu 801
        LOGGER.info("RBM Call Target - Out of Sequence fetch: {}ms", System.currentTimeMillis() - start);
802
 
803
        // Process L1 RBMs (existing logic)
804
        for (int rbmAuthId : l1AuthIds) {
805
            AuthUser authUser = authUserMap.get(rbmAuthId);
806
            if (authUser == null || !storeGuyMap.containsKey(authUser.getEmailId())) {
807
                continue;
808
            }
809
 
810
            List<Integer> fofoIdList = rbmToFofoIdsMap.getOrDefault(rbmAuthId, Collections.emptyList());
811
 
812
            // Check if RBM is L1 (same logic as getSummaryModel)
813
            List<Position> positions = positionsByAuthId.getOrDefault(authUser.getId(), Collections.emptyList());
814
            boolean isRBMAndL1 = positions.stream()
815
                    .anyMatch(position ->
816
                            ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId()
817
                                    && EscalationType.L1.equals(position.getEscalationType()));
818
 
819
            // Filter escalated partners for L1 RBMs (same logic as getSummaryModel)
820
            List<Integer> fofoIds = fofoIdList;
821
            if (isRBMAndL1) {
822
                Map<Integer, PartnerCollectionRemark> partnerCollectionRemarks = new HashMap<>();
823
                for (Integer fofoId : fofoIdList) {
824
                    if (allPartnerCollectionRemarks.containsKey(fofoId)) {
825
                        partnerCollectionRemarks.put(fofoId, allPartnerCollectionRemarks.get(fofoId));
826
                    }
827
                }
828
                fofoIds = partnerCollectionRemarks.entrySet().stream()
829
                        .filter(entry -> {
830
                            PartnerCollectionRemark pcrMap = entry.getValue();
831
                            return !(CollectionRemark.RBM_L2_ESCALATION.equals(pcrMap.getRemark())
832
                                    || CollectionRemark.SALES_ESCALATION.equals(pcrMap.getRemark()));
833
                        })
834
                        .map(Map.Entry::getKey)
835
                        .collect(Collectors.toList());
836
            }
837
 
36181 ranu 838
            // Filter to only external, ACTIVE or REVIVAL stores (collection plan not required)
35631 ranu 839
            Map<Integer, Integer> finalAllCollectionRankMap = allCollectionRankMap;
840
            Map<Integer, FofoStore> finalFofoStoresMap = fofoStoresMap;
841
            List<Integer> validFofoIds = fofoIds.stream()
842
                    .filter(fofoId -> {
843
                        FofoStore store = finalFofoStoresMap.get(fofoId);
844
                        if (store == null || store.isInternal()) {
845
                            return false;
846
                        }
36181 ranu 847
                        // Only include ACTIVE or REVIVAL partners (not Low Sale, not Disputed, not Billing Pending)
848
                        return ActivationType.ACTIVE.equals(store.getActivationType())
849
                                || ActivationType.REVIVAL.equals(store.getActivationType());
35631 ranu 850
                    })
851
                    .collect(Collectors.toList());
852
 
853
            if (validFofoIds.isEmpty()) {
854
                continue;
855
            }
856
 
857
            RbmCallTargetModel targetModel = new RbmCallTargetModel();
858
            targetModel.setAuthId(rbmAuthId);
859
            targetModel.setRbmName(authUser.getFullName());
35669 ranu 860
            // Use partner count from mtdBillingData (same source as Today ARR page)
861
            Set<Integer> mtdFofoIds = mtdFofoIdsByAuthId.getOrDefault(rbmAuthId, Collections.emptySet());
862
            targetModel.setPartnerCount(mtdFofoIds.size());
35631 ranu 863
 
864
            // Categorize each partner - each partner belongs to ONE category only
35665 ranu 865
            // Priority: PlanToday > CarryForward > ZeroBilling > Untouched > FuturePlan > Normal
36181 ranu 866
            // Revival is counted separately (just for display, doesn't affect categorization)
35631 ranu 867
            Set<Integer> planTodayPartners = new HashSet<>();
868
            Set<Integer> carryForwardPartners = new HashSet<>();
869
            Set<Integer> untouchedPartners = new HashSet<>();
870
            Set<Integer> zeroBillingPartners = new HashSet<>();
871
            Set<Integer> futurePlanPartners = new HashSet<>();
872
            Set<Integer> normalPartners = new HashSet<>();
36181 ranu 873
            Set<Integer> revivalPartners = new HashSet<>();
35631 ranu 874
 
875
            for (Integer fofoId : validFofoIds) {
876
                // Get collection plan rank (from optimized rank map)
877
                int rank = allCollectionRankMap.getOrDefault(fofoId, 5); // default to Normal if no plan
878
 
879
                // Check if partner has zero billing in MTD
880
                boolean hasZeroBilling = !allMtdBilledFofoIds.contains(fofoId);
881
 
36181 ranu 882
                // Count REVIVAL partners separately (just for display, doesn't affect categorization)
883
                FofoStore store = finalFofoStoresMap.get(fofoId);
884
                if (store != null && ActivationType.REVIVAL.equals(store.getActivationType())) {
885
                    revivalPartners.add(fofoId);
886
                }
887
 
35631 ranu 888
                // Assign to category based on priority
889
                if (rank == 1) {
890
                    planTodayPartners.add(fofoId);
891
                } else if (rank == 2) {
892
                    carryForwardPartners.add(fofoId);
35665 ranu 893
                } else if (hasZeroBilling) {
894
                    zeroBillingPartners.add(fofoId);
35631 ranu 895
                } else if (rank == 3) {
896
                    untouchedPartners.add(fofoId);
897
                } else if (rank == 4) {
898
                    futurePlanPartners.add(fofoId);
899
                } else {
900
                    normalPartners.add(fofoId);
901
                }
902
            }
903
 
904
            // Set counts
905
            targetModel.setCreditCollection(0); // Credit collection is handled in separate list
906
            targetModel.setPlanToday(planTodayPartners.size());
907
            targetModel.setCarryForward(carryForwardPartners.size());
908
            targetModel.setUntouched(untouchedPartners.size());
909
            targetModel.setZeroBilling(zeroBillingPartners.size());
910
            targetModel.setFuturePlan(futurePlanPartners.size());
911
            targetModel.setNormal(normalPartners.size());
36181 ranu 912
            targetModel.setRevival(revivalPartners.size());
35631 ranu 913
 
914
            // Today Target = PlanToday + CarryForward + ZeroBilling + Untouched
915
            // These are mutually exclusive now, so we can sum them
916
            long todayTarget = planTodayPartners.size() +
917
                    carryForwardPartners.size() + zeroBillingPartners.size() + untouchedPartners.size();
918
            targetModel.setTodayTargetOfCall(todayTarget);
919
 
920
            // Create set of partners in Today Target categories
921
            Set<Integer> todayTargetPartners = new HashSet<>();
922
            todayTargetPartners.addAll(planTodayPartners);
923
            todayTargetPartners.addAll(carryForwardPartners);
924
            todayTargetPartners.addAll(zeroBillingPartners);
925
            todayTargetPartners.addAll(untouchedPartners);
926
 
35843 ranu 927
            // Value Achieved = All distinct partners called today (from call logs)
928
            long valueAchieved = getCalledCountFromCallLogs(rbmAuthId);
35631 ranu 929
            targetModel.setValueTargetAchieved(valueAchieved);
930
 
35843 ranu 931
            // Keep todayRemarks for movedToFuture calculation
932
            List<PartnerCollectionRemark> todayRemarks = remarksByAuthId.getOrDefault(rbmAuthId, Collections.emptyList());
933
 
35631 ranu 934
            // Moved to Future = Partners in Future Plan category who have a remark today
935
            // These are partners who were contacted today but moved to a future date
936
            Set<Integer> todayRemarkedFofoIds = todayRemarks.stream()
937
                    .map(PartnerCollectionRemark::getFofoId)
938
                    .collect(Collectors.toSet());
939
            long movedToFuture = futurePlanPartners.stream()
940
                    .filter(todayRemarkedFofoIds::contains)
941
                    .count();
942
            targetModel.setMovedToFuture(movedToFuture);
943
 
944
            // Set out of sequence count for this RBM
945
            targetModel.setOutOfSequenceCount(outOfSequenceCountByAuthId.getOrDefault(rbmAuthId, 0L));
946
 
947
            rbmCallTargetModels.add(targetModel);
948
        }
949
 
950
        // Process L2 RBMs (escalated ticket logic with categorization)
951
        for (int l2AuthId : l2AuthIds) {
952
            AuthUser authUser = authUserMap.get(l2AuthId);
953
            if (authUser == null) {
954
                continue;
955
            }
956
 
957
            List<Integer> l2FofoIdList = l2AuthIdToFofoIds.getOrDefault(l2AuthId, Collections.emptyList());
958
 
35816 ranu 959
            // For L2, use unique fofoIds with RBM_L2_ESCALATION remark as target
35662 ranu 960
            Set<Integer> l2TargetFofoIds = new HashSet<>(l2FofoIdList);
35631 ranu 961
 
962
            RbmCallTargetModel l2Model = new RbmCallTargetModel();
963
            l2Model.setAuthId(l2AuthId);
964
            l2Model.setRbmName(authUser.getFullName() + " (L2)");
965
            l2Model.setL2Position(true);
35816 ranu 966
            l2Model.setL2CallingList(l2TargetFofoIds.size());
35631 ranu 967
            // Partner count = total assigned partners (same as L1 source)
968
            List<Integer> l2AssignedFofoIds = rbmToFofoIdsMap.getOrDefault(l2AuthId, Collections.emptyList());
969
            l2Model.setPartnerCount(l2AssignedFofoIds.size());
970
 
35816 ranu 971
            // L2 Target = partners with RBM_L2_ESCALATION as latest remark
35662 ranu 972
            l2Model.setTodayTargetOfCall(l2TargetFofoIds.size());
35631 ranu 973
 
35843 ranu 974
            // Value Achieved = All distinct partners called today (from call logs)
975
            long l2ValueAchieved = getCalledCountFromCallLogs(l2AuthId);
35662 ranu 976
            l2Model.setValueTargetAchieved(l2ValueAchieved);
35631 ranu 977
 
978
            l2Model.setOutOfSequenceCount(outOfSequenceCountByAuthId.getOrDefault(l2AuthId, 0L));
979
            rbmCallTargetModels.add(l2Model);
980
        }
981
 
36210 ranu 982
        // Process L3 RBMs (escalated ticket logic with categorization)
983
        for (int l3AuthId : l3AuthIds) {
984
            AuthUser authUser = authUserMap.get(l3AuthId);
985
            if (authUser == null) {
986
                continue;
987
            }
988
 
989
            List<Integer> l3FofoIdList = l3AuthIdToFofoIds.getOrDefault(l3AuthId, Collections.emptyList());
990
 
991
            // For L3, use unique fofoIds with RBM_L3_ESCALATION remark as target
992
            Set<Integer> l3TargetFofoIds = new HashSet<>(l3FofoIdList);
993
 
994
            RbmCallTargetModel l3Model = new RbmCallTargetModel();
995
            l3Model.setAuthId(l3AuthId);
996
            l3Model.setRbmName(authUser.getFullName() + " (L3)");
997
            l3Model.setL3Position(true);
998
            l3Model.setL3CallingList(l3TargetFofoIds.size());
999
            // Partner count = total assigned partners (same as L2 source)
1000
            List<Integer> l3AssignedFofoIds = rbmToFofoIdsMap.getOrDefault(l3AuthId, Collections.emptyList());
1001
            l3Model.setPartnerCount(l3AssignedFofoIds.size());
1002
 
1003
            // L3 Target = partners with RBM_L3_ESCALATION as latest remark
1004
            l3Model.setTodayTargetOfCall(l3TargetFofoIds.size());
1005
 
1006
            // Value Achieved = All distinct partners called today (from call logs)
1007
            long l3ValueAchieved = getCalledCountFromCallLogs(l3AuthId);
1008
            l3Model.setValueTargetAchieved(l3ValueAchieved);
1009
 
1010
            l3Model.setOutOfSequenceCount(outOfSequenceCountByAuthId.getOrDefault(l3AuthId, 0L));
1011
            rbmCallTargetModels.add(l3Model);
1012
        }
1013
 
1014
        // Group L1 under their L2 manager, and L2 under their L3 manager using authUser.managerId
1015
        Map<Integer, RbmCallTargetModel> l3ModelsByAuthId = new HashMap<>();
35631 ranu 1016
        Map<Integer, RbmCallTargetModel> l2ModelsByAuthId = new HashMap<>();
1017
        Map<Integer, RbmCallTargetModel> l1ModelsByAuthId = new HashMap<>();
1018
        for (RbmCallTargetModel m : rbmCallTargetModels) {
36210 ranu 1019
            if (m.isL3Position()) {
1020
                l3ModelsByAuthId.put(m.getAuthId(), m);
1021
            } else if (m.isL2Position()) {
35631 ranu 1022
                l2ModelsByAuthId.put(m.getAuthId(), m);
1023
            } else {
1024
                l1ModelsByAuthId.put(m.getAuthId(), m);
1025
            }
1026
        }
1027
 
36210 ranu 1028
        // Build L3 -> L2 team map using managerId from AuthUser
1029
        Map<Integer, List<RbmCallTargetModel>> l3TeamMap = new LinkedHashMap<>();
1030
        for (RbmCallTargetModel l3Model : l3ModelsByAuthId.values()) {
1031
            l3TeamMap.put(l3Model.getAuthId(), new ArrayList<>());
1032
        }
1033
 
1034
        Set<Integer> addedL2AuthIds = new HashSet<>();
1035
        for (RbmCallTargetModel l2Model : l2ModelsByAuthId.values()) {
1036
            AuthUser l2User = authUserMap.get(l2Model.getAuthId());
1037
            if (l2User != null && l3TeamMap.containsKey(l2User.getManagerId())) {
1038
                l3TeamMap.get(l2User.getManagerId()).add(l2Model);
1039
                addedL2AuthIds.add(l2Model.getAuthId());
1040
            }
1041
        }
1042
 
35631 ranu 1043
        // Build L2 -> L1 team map using managerId from AuthUser
1044
        Map<Integer, List<RbmCallTargetModel>> l2TeamMap = new LinkedHashMap<>();
1045
        for (RbmCallTargetModel l2Model : l2ModelsByAuthId.values()) {
1046
            l2TeamMap.put(l2Model.getAuthId(), new ArrayList<>());
1047
        }
1048
 
1049
        Set<Integer> addedL1AuthIds = new HashSet<>();
1050
        for (RbmCallTargetModel l1Model : l1ModelsByAuthId.values()) {
1051
            AuthUser l1User = authUserMap.get(l1Model.getAuthId());
1052
            if (l1User != null && l2TeamMap.containsKey(l1User.getManagerId())) {
1053
                l2TeamMap.get(l1User.getManagerId()).add(l1Model);
1054
                addedL1AuthIds.add(l1Model.getAuthId());
1055
            }
1056
        }
1057
 
36210 ranu 1058
        // Build sorted result: L3 row, then its L2 team with their L1 teams (sorted by name)
35631 ranu 1059
        List<RbmCallTargetModel> sortedModels = new ArrayList<>();
1060
 
36210 ranu 1061
        // First add L3 with their L2 teams
1062
        List<RbmCallTargetModel> l3Sorted = new ArrayList<>(l3ModelsByAuthId.values());
1063
        l3Sorted.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
35631 ranu 1064
 
36210 ranu 1065
        for (RbmCallTargetModel l3Model : l3Sorted) {
1066
            sortedModels.add(l3Model);
1067
            List<RbmCallTargetModel> l2Team = l3TeamMap.getOrDefault(l3Model.getAuthId(), Collections.emptyList());
1068
            l2Team.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
1069
            for (RbmCallTargetModel l2Model : l2Team) {
1070
                sortedModels.add(l2Model);
1071
                List<RbmCallTargetModel> l1Team = l2TeamMap.getOrDefault(l2Model.getAuthId(), Collections.emptyList());
1072
                l1Team.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
1073
                sortedModels.addAll(l1Team);
1074
            }
1075
        }
1076
 
1077
        // Add L2s not mapped to any L3 with their L1 teams
1078
        List<RbmCallTargetModel> unmappedL2 = new ArrayList<>();
1079
        for (RbmCallTargetModel l2Model : l2ModelsByAuthId.values()) {
1080
            if (!addedL2AuthIds.contains(l2Model.getAuthId())) {
1081
                unmappedL2.add(l2Model);
1082
            }
1083
        }
1084
        unmappedL2.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
1085
 
1086
        for (RbmCallTargetModel l2Model : unmappedL2) {
35631 ranu 1087
            sortedModels.add(l2Model);
1088
            List<RbmCallTargetModel> team = l2TeamMap.getOrDefault(l2Model.getAuthId(), Collections.emptyList());
1089
            team.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
1090
            sortedModels.addAll(team);
1091
        }
1092
 
1093
        // Add any L1 RBMs not mapped to any L2 (sorted by name)
1094
        List<RbmCallTargetModel> unmappedL1 = new ArrayList<>();
1095
        for (RbmCallTargetModel m : l1ModelsByAuthId.values()) {
1096
            if (!addedL1AuthIds.contains(m.getAuthId())) {
1097
                unmappedL1.add(m);
1098
            }
1099
        }
1100
        unmappedL1.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
1101
        sortedModels.addAll(unmappedL1);
1102
 
1103
        LOGGER.info("RBM Call Target - TOTAL TIME: {}ms, RBM count: {}", System.currentTimeMillis() - methodStart, sortedModels.size());
1104
        return sortedModels;
1105
    }
1106
 
1107
    @Override
1108
    public List<OutOfSequenceDetailModel> getOutOfSequenceDetails(int authId) {
1109
 
1110
        LocalDate today = LocalDate.now();
1111
        LocalDateTime start = today.atStartOfDay();
1112
        LocalDateTime end = today.plusDays(1).atStartOfDay();
1113
 
1114
        List<RbmCallSequenceLog> logs =
1115
                rbmCallSequenceLogRepository.selectByAuthIdAndDateRange(authId, start, end);
1116
 
35654 ranu 1117
        Map<Integer, RbmCallSequenceLog> uniqueOosLogsByFofoId = new LinkedHashMap<>();
35631 ranu 1118
 
1119
        for (RbmCallSequenceLog log : logs) {
1120
            if (log.isOutOfSequence()) {
35654 ranu 1121
                // Keep only the first occurrence per fofoId (latest entry since ordered by id DESC)
1122
                uniqueOosLogsByFofoId.putIfAbsent(log.getFofoId(), log);
35631 ranu 1123
            }
1124
        }
1125
 
35654 ranu 1126
        if (uniqueOosLogsByFofoId.isEmpty()) {
35631 ranu 1127
            return Collections.emptyList();
1128
        }
1129
 
35654 ranu 1130
        Set<Integer> fofoIds = uniqueOosLogsByFofoId.keySet();
35631 ranu 1131
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
1132
        try {
1133
            retailerMap = retailerService.getFofoRetailers(new ArrayList<>(fofoIds));
1134
        } catch (ProfitMandiBusinessException e) {
1135
            LOGGER.error("Error fetching fofo stores", e);
1136
        }
1137
 
1138
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
1139
        List<OutOfSequenceDetailModel> result = new ArrayList<>();
1140
 
35654 ranu 1141
        for (RbmCallSequenceLog log : uniqueOosLogsByFofoId.values()) {
35631 ranu 1142
            CustomRetailer retailer = retailerMap.get(log.getFofoId());
1143
            String partyName = retailer != null
1144
                    ? retailer.getBusinessName()
1145
                    : "Unknown (" + log.getFofoId() + ")";
1146
            String code = retailer != null
1147
                    ? retailer.getCode()
1148
                    : "-";
1149
 
1150
            String time = log.getCreateTimestamp() != null
1151
                    ? log.getCreateTimestamp().format(timeFormatter)
1152
                    : "-";
1153
 
1154
            result.add(new OutOfSequenceDetailModel(partyName, code, time));
1155
        }
1156
 
1157
        return result;
1158
    }
1159
 
35645 ranu 1160
    @Override
35672 ranu 1161
    public List<CalledPartnerDetailModel> getCalledPartnerDetails(int authId) throws ProfitMandiBusinessException {
35730 ranu 1162
        return getCalledPartnerDetails(authId, LocalDate.now());
1163
    }
1164
 
1165
    @Override
1166
    public List<CalledPartnerDetailModel> getCalledPartnerDetails(int authId, LocalDate date) throws ProfitMandiBusinessException {
35759 ranu 1167
        // Get all call logs for this auth user on this date
35760 ranu 1168
        LOGGER.info("getCalledPartnerDetails: authId={}, date={}", authId, date);
35761 ranu 1169
        List<AgentCallLog> callLogs = agentCallLogRepository.findByAuthIdAndDate(authId, date);
35760 ranu 1170
        LOGGER.info("Found {} call logs for authId={} on date={}", callLogs.size(), authId, date);
35670 ranu 1171
 
35759 ranu 1172
        if (callLogs.isEmpty()) {
35672 ranu 1173
            return Collections.emptyList();
1174
        }
35670 ranu 1175
 
35759 ranu 1176
        // Build a map of normalized customer number -> fofoId
1177
        Map<String, Integer> customerToFofoIdMap = new HashMap<>();
1178
        Set<String> normalizedNumbers = new HashSet<>();
35672 ranu 1179
 
35763 ranu 1180
        for (AgentCallLog callLog : callLogs) {
35759 ranu 1181
            String customerNumber = callLog.getCustomerNumber();
1182
            if (customerNumber != null) {
1183
                String normalized = customerNumber.startsWith("+91") ? customerNumber.substring(3) : customerNumber;
1184
                normalizedNumbers.add(normalized);
1185
            }
35672 ranu 1186
        }
1187
 
35759 ranu 1188
        // For each normalized number, find fofoId from retailer_contact first, then address
1189
        for (String mobile : normalizedNumbers) {
1190
            Integer fofoId = findFofoIdByMobile(mobile);
1191
            if (fofoId != null) {
1192
                customerToFofoIdMap.put(mobile, fofoId);
1193
            }
35670 ranu 1194
        }
1195
 
35759 ranu 1196
        // Get unique fofoIds for retailer lookup
1197
        Set<Integer> fofoIds = new HashSet<>(customerToFofoIdMap.values());
1198
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
1199
        if (!fofoIds.isEmpty()) {
1200
            try {
1201
                retailerMap = retailerService.getFofoRetailers(new ArrayList<>(fofoIds));
1202
            } catch (ProfitMandiBusinessException e) {
1203
                LOGGER.error("Error fetching fofo stores", e);
1204
            }
35672 ranu 1205
        }
1206
 
35759 ranu 1207
        // Get today's remarks for these fofoIds
1208
        Map<Integer, List<PartnerCollectionRemark>> fofoRemarkMap = new HashMap<>();
1209
        if (!fofoIds.isEmpty()) {
1210
            List<PartnerCollectionRemark> todayRemarks = partnerCollectionRemarkRepository
1211
                    .selectAllByFofoIdsOnDate(new ArrayList<>(fofoIds), date);
1212
            for (PartnerCollectionRemark remark : todayRemarks) {
1213
                fofoRemarkMap.computeIfAbsent(remark.getFofoId(), k -> new ArrayList<>()).add(remark);
1214
            }
35672 ranu 1215
        }
1216
 
35759 ranu 1217
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
1218
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
1219
        List<CalledPartnerDetailModel> result = new ArrayList<>();
35672 ranu 1220
 
35759 ranu 1221
        for (com.spice.profitmandi.dao.entity.cs.AgentCallLog callLog : callLogs) {
1222
            String customerNumber = callLog.getCustomerNumber();
1223
            if (customerNumber == null) {
1224
                continue;
1225
            }
35672 ranu 1226
 
35759 ranu 1227
            String normalized = customerNumber.startsWith("+91") ? customerNumber.substring(3) : customerNumber;
1228
            Integer fofoId = customerToFofoIdMap.get(normalized);
35672 ranu 1229
 
35759 ranu 1230
            String partyName = "Unknown";
1231
            String code = "-";
35672 ranu 1232
 
35759 ranu 1233
            if (fofoId != null) {
1234
                CustomRetailer retailer = retailerMap.get(fofoId);
1235
                if (retailer != null) {
1236
                    partyName = retailer.getBusinessName();
1237
                    code = retailer.getCode();
1238
                } else {
1239
                    partyName = "Unknown (" + fofoId + ")";
1240
                }
1241
            } else {
1242
                partyName = "Unknown (" + normalized + ")";
1243
            }
35672 ranu 1244
 
35759 ranu 1245
            // Get remark if available
1246
            String remarkValue = "-";
1247
            String messageValue = "-";
1248
            String remarkTime = "-";
35672 ranu 1249
 
35759 ranu 1250
            if (fofoId != null && fofoRemarkMap.containsKey(fofoId)) {
1251
                List<PartnerCollectionRemark> remarks = fofoRemarkMap.get(fofoId);
1252
                if (!remarks.isEmpty()) {
1253
                    PartnerCollectionRemark remark = remarks.get(0);
1254
                    remarkValue = remark.getRemark() != null ? remark.getRemark().getValue() : "-";
1255
                    messageValue = remark.getMessage() != null ? remark.getMessage() : "-";
1256
                    remarkTime = remark.getCreateTimestamp() != null ? remark.getCreateTimestamp().format(timeFormatter) : "-";
1257
                }
1258
            }
35672 ranu 1259
 
35759 ranu 1260
            // Build call log data
1261
            String recordingUrl = callLog.getRecordingUrl();
1262
            String callStatus = callLog.getCallStatus();
1263
            String callDuration = callLog.getCallDuration();
1264
            String callDateTime = null;
1265
            if (callLog.getCallDate() != null && callLog.getCallTime() != null) {
1266
                LocalDateTime callDateTimeObj = LocalDateTime.of(callLog.getCallDate(), callLog.getCallTime());
1267
                callDateTime = callDateTimeObj.format(dateTimeFormatter);
35672 ranu 1268
            }
35759 ranu 1269
 
1270
            result.add(new CalledPartnerDetailModel(partyName, code, remarkValue, messageValue, remarkTime,
1271
                    recordingUrl, callStatus, callDuration, callDateTime));
35672 ranu 1272
        }
1273
 
35759 ranu 1274
        return result;
1275
    }
35672 ranu 1276
 
35759 ranu 1277
    private Integer findFofoIdByMobile(String mobile) {
1278
        // First check retailer_contact
1279
        List<RetailerContact> contacts = retailerContactRepository.selectByMobile(mobile);
1280
        if (contacts != null && !contacts.isEmpty()) {
1281
            return contacts.get(0).getFofoId();
1282
        }
1283
 
1284
        // Fallback to user.address
35762 ranu 1285
        List<Address> addresses = addressRepository.selectAllByPhoneNumber(mobile);
1286
        if (addresses != null && !addresses.isEmpty()) {
1287
            return addresses.get(0).getRetaierId();
35759 ranu 1288
        }
1289
 
1290
        return null;
35672 ranu 1291
    }
1292
 
35757 ranu 1293
    private List<CalledPartnerDetailModel> buildCalledPartnerResult(List<PartnerCollectionRemark> allRemarks) {
1294
        if (allRemarks.isEmpty()) {
35672 ranu 1295
            return Collections.emptyList();
1296
        }
1297
 
35757 ranu 1298
        // Get unique fofoIds for retailer lookup
1299
        Set<Integer> fofoIds = allRemarks.stream()
1300
                .map(PartnerCollectionRemark::getFofoId)
1301
                .collect(Collectors.toSet());
35670 ranu 1302
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
1303
        try {
1304
            retailerMap = retailerService.getFofoRetailers(new ArrayList<>(fofoIds));
1305
        } catch (ProfitMandiBusinessException e) {
1306
            LOGGER.error("Error fetching fofo stores", e);
1307
        }
1308
 
35702 ranu 1309
        // Fetch call logs for remarks that have agentCallLogId
35721 ranu 1310
        Map<Long, com.spice.profitmandi.dao.entity.cs.AgentCallLog> callLogMap = new HashMap<>();
1311
        try {
35757 ranu 1312
            List<Long> callLogIds = allRemarks.stream()
35721 ranu 1313
                    .filter(r -> r.getAgentCallLogId() > 0)
1314
                    .map(PartnerCollectionRemark::getAgentCallLogId)
1315
                    .collect(Collectors.toList());
35702 ranu 1316
 
35721 ranu 1317
            if (!callLogIds.isEmpty()) {
35720 ranu 1318
                List<com.spice.profitmandi.dao.entity.cs.AgentCallLog> callLogs = agentCallLogRepository.findByIds(callLogIds);
35721 ranu 1319
                if (callLogs != null) {
1320
                    callLogMap = callLogs.stream()
1321
                            .collect(Collectors.toMap(com.spice.profitmandi.dao.entity.cs.AgentCallLog::getId, c -> c, (a, b) -> a));
1322
                }
35720 ranu 1323
            }
35721 ranu 1324
        } catch (Exception e) {
1325
            LOGGER.error("Error fetching call logs by ids", e);
35702 ranu 1326
        }
1327
 
35670 ranu 1328
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
35702 ranu 1329
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
35670 ranu 1330
        List<CalledPartnerDetailModel> result = new ArrayList<>();
1331
 
35757 ranu 1332
        for (PartnerCollectionRemark remark : allRemarks) {
35670 ranu 1333
            CustomRetailer retailer = retailerMap.get(remark.getFofoId());
1334
            String partyName = retailer != null
1335
                    ? retailer.getBusinessName()
1336
                    : "Unknown (" + remark.getFofoId() + ")";
1337
            String code = retailer != null
1338
                    ? retailer.getCode()
1339
                    : "-";
1340
 
1341
            String remarkValue = remark.getRemark() != null
1342
                    ? remark.getRemark().getValue()
1343
                    : "-";
1344
 
35677 ranu 1345
            String messageValue = remark.getMessage() != null
1346
                    ? remark.getMessage()
1347
                    : "-";
1348
 
35670 ranu 1349
            String time = remark.getCreateTimestamp() != null
1350
                    ? remark.getCreateTimestamp().format(timeFormatter)
1351
                    : "-";
1352
 
35702 ranu 1353
            // Get call log data if available
1354
            String recordingUrl = null;
1355
            String callStatus = null;
1356
            String callDuration = null;
1357
            String callDateTime = null;
1358
 
35721 ranu 1359
            try {
1360
                if (remark.getAgentCallLogId() > 0 && callLogMap.containsKey(remark.getAgentCallLogId())) {
1361
                    com.spice.profitmandi.dao.entity.cs.AgentCallLog callLog = callLogMap.get(remark.getAgentCallLogId());
1362
                    recordingUrl = callLog.getRecordingUrl();
1363
                    callStatus = callLog.getCallStatus();
1364
                    callDuration = callLog.getCallDuration();
1365
                    if (callLog.getCallDate() != null && callLog.getCallTime() != null) {
1366
                        LocalDateTime callDateTimeObj = LocalDateTime.of(callLog.getCallDate(), callLog.getCallTime());
1367
                        callDateTime = callDateTimeObj.format(dateTimeFormatter);
1368
                    }
35702 ranu 1369
                }
35721 ranu 1370
            } catch (Exception e) {
1371
                LOGGER.error("Error processing call log for remark id: {}", remark.getId(), e);
35702 ranu 1372
            }
1373
 
1374
            result.add(new CalledPartnerDetailModel(partyName, code, remarkValue, messageValue, time,
1375
                    recordingUrl, callStatus, callDuration, callDateTime));
35670 ranu 1376
        }
1377
 
1378
        return result;
1379
    }
1380
 
1381
    @Override
35645 ranu 1382
    public List<List<String>> getRbmCallTargetRawDataByAuthId(int authId) throws Exception {
1383
        List<List<String>> rows = new ArrayList<>();
35631 ranu 1384
 
35645 ranu 1385
        // Get auth user
1386
        List<AuthUser> authUsers = authRepository.selectByIds(Collections.singletonList(authId));
1387
        if (authUsers.isEmpty()) {
1388
            return rows;
1389
        }
1390
        AuthUser authUser = authUsers.get(0);
1391
 
35757 ranu 1392
        // Get positions to determine if L2
35645 ranu 1393
        List<Position> positions = positionRepository.selectPositionByAuthIds(Collections.singletonList(authId));
1394
        boolean isL2 = positions.stream()
1395
                .anyMatch(p -> ProfitMandiConstants.TICKET_CATEGORY_RBM == p.getCategoryId()
1396
                        && EscalationType.L2.equals(p.getEscalationType()));
1397
 
35757 ranu 1398
        LocalDateTime startDate = LocalDate.now().atStartOfDay();
1399
        LocalDate firstOfMonth = LocalDate.now().withDayOfMonth(1);
1400
        LocalDate endOfMonth = LocalDate.now().withDayOfMonth(LocalDate.now().lengthOfMonth()).plusDays(1);
35645 ranu 1401
 
35757 ranu 1402
        // Get fofo IDs from mtdBillingData (same source as Partner Count in getRbmCallTargetModels)
1403
        List<RbmWeeklyBillingModel> mtdBillingData = getWeeklyBillingDataForMonth(firstOfMonth, endOfMonth);
1404
 
1405
        List<Integer> fofoIdList;
35645 ranu 1406
        if (isL2) {
35757 ranu 1407
            // L2: get fofo IDs from escalated tickets (same as getRbmCallTargetModels)
35645 ranu 1408
            List<Ticket> escalatedTickets = ticketRepository.selectOpenEscalatedTicketsByAuthIds(Collections.singletonList(authId));
1409
            fofoIdList = escalatedTickets.stream()
1410
                    .filter(t -> t.getL2AuthUser() == authId
1411
                            || t.getL3AuthUser() == authId
1412
                            || t.getL4AuthUser() == authId
1413
                            || t.getL5AuthUser() == authId)
1414
                    .map(Ticket::getFofoId)
1415
                    .distinct()
1416
                    .collect(Collectors.toList());
35757 ranu 1417
        } else {
1418
            // L1: get fofo IDs from mtdBillingData with isTargetedPartner (same as Partner Count)
1419
            fofoIdList = mtdBillingData.stream()
1420
                    .filter(RbmWeeklyBillingModel::isTargetedPartner)
1421
                    .filter(m -> m.getAuthId() == authId)
1422
                    .map(RbmWeeklyBillingModel::getFofoId)
1423
                    .distinct()
1424
                    .collect(Collectors.toList());
35645 ranu 1425
        }
1426
 
1427
        if (fofoIdList.isEmpty()) {
1428
            return rows;
1429
        }
1430
 
35757 ranu 1431
        // MTD billed fofoIds for zero billing check
1432
        Set<Integer> mtdBilledFofoIds = mtdBillingData.stream()
1433
                .filter(RbmWeeklyBillingModel::isMtdBilled)
1434
                .map(RbmWeeklyBillingModel::getFofoId)
1435
                .collect(Collectors.toSet());
35645 ranu 1436
 
35757 ranu 1437
        // Collection rank map for status calculation
35645 ranu 1438
        Map<Integer, Integer> collectionRankMap = new HashMap<>();
1439
        try {
1440
            collectionRankMap = partnerCollectionService.getCollectionRankMap(fofoIdList, startDate);
1441
        } catch (ProfitMandiBusinessException e) {
1442
            LOGGER.error("Error fetching collection rank map", e);
1443
        }
1444
 
1445
        // Resolve partner names/codes
1446
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
35757 ranu 1447
        if (!fofoIdList.isEmpty()) {
35645 ranu 1448
            try {
35757 ranu 1449
                retailerMap = retailerService.getFofoRetailers(fofoIdList);
35645 ranu 1450
            } catch (ProfitMandiBusinessException e) {
1451
                LOGGER.error("Error fetching fofo retailers for raw data", e);
1452
            }
1453
        }
1454
 
1455
        String rbmName = authUser.getFullName() + (isL2 ? " (L2)" : "");
1456
 
35757 ranu 1457
        // Build rows for ALL partners (same count as Partner Count)
1458
        for (Integer fofoId : fofoIdList) {
1459
            // Default to rank 5 (Normal) for partners without collection plan
35645 ranu 1460
            int rank = collectionRankMap.getOrDefault(fofoId, 5);
1461
            boolean hasZeroBilling = !mtdBilledFofoIds.contains(fofoId);
1462
 
35757 ranu 1463
            // Status assignment with same priority as getRbmCallTargetModels
35645 ranu 1464
            String status;
1465
            if (rank == 1) {
1466
                status = "Plan Today";
1467
            } else if (rank == 2) {
1468
                status = "Carry Forward";
35757 ranu 1469
            } else if (hasZeroBilling) {
1470
                status = "Zero Billing";
35645 ranu 1471
            } else if (rank == 3) {
1472
                status = "Untouched";
1473
            } else if (rank == 4) {
1474
                status = "Future Plan";
1475
            } else {
1476
                status = "Normal";
1477
            }
1478
 
1479
            CustomRetailer retailer = retailerMap.get(fofoId);
1480
            String partnerName = retailer != null ? retailer.getBusinessName() : "Unknown (" + fofoId + ")";
1481
            String partnerCode = retailer != null ? retailer.getCode() : "-";
1482
 
1483
            rows.add(Arrays.asList(partnerName, partnerCode, status, rbmName));
1484
        }
1485
 
1486
        return rows;
1487
    }
1488
 
35843 ranu 1489
    /**
1490
     * Get count of distinct partners called today based on call logs.
1491
     * Maps customerNumber from call log to fofoId using retailer_contact and address.
1492
     * If same fofoId is called multiple times, counts only once.
1493
     * Numbers without fofoId mapping are also counted (by distinct customer number).
1494
     *
1495
     * @param authId the RBM auth ID
1496
     * @return count of distinct partners/numbers called today
1497
     */
1498
    public long getCalledCountFromCallLogs(long authId) {
1499
        List<AgentCallLog> callLogs = agentCallLogRepository.findByAuthIdAndDate(authId, LocalDate.now());
1500
 
1501
        if (callLogs == null || callLogs.isEmpty()) {
1502
            return 0;
1503
        }
1504
 
1505
        Set<Integer> calledFofoIds = new HashSet<>();
1506
        Set<String> calledNumbersWithoutFofoId = new HashSet<>();
1507
 
1508
        for (AgentCallLog callLog : callLogs) {
1509
            String customerNumber = callLog.getCustomerNumber();
1510
            if (customerNumber != null) {
1511
                // Normalize the phone number (remove +91 prefix if present)
1512
                String normalized = customerNumber.startsWith("+91") ? customerNumber.substring(3) : customerNumber;
1513
 
1514
                // Find fofoId from retailer_contact or address
1515
                Integer fofoId = findFofoIdByMobile(normalized);
1516
                if (fofoId != null) {
1517
                    calledFofoIds.add(fofoId);
1518
                } else {
1519
                    // Number not found in retailer_contact or address, count by distinct number
1520
                    calledNumbersWithoutFofoId.add(normalized);
1521
                }
1522
            }
1523
        }
1524
 
1525
        // Total called = distinct fofoIds + distinct numbers without fofoId mapping
1526
        return calledFofoIds.size() + calledNumbersWithoutFofoId.size();
1527
    }
1528
 
35852 ranu 1529
    @Override
1530
    public List<List<String>> getAllCallDataByDate(LocalDate date) throws Exception {
1531
        List<List<String>> rows = new ArrayList<>();
1532
 
1533
        // Add header row
1534
        rows.add(Arrays.asList("RBM Name", "Partner Name", "Code", "Remark", "Call Status", "Call Duration", "Call Date Time", "Recording URL"));
1535
 
1536
        // Get all call logs for the date
1537
        List<AgentCallLog> allCallLogs = agentCallLogRepository.findAllByDate(date);
1538
        LOGGER.info("getAllCallDataByDate: Found {} call logs for date {}", allCallLogs.size(), date);
1539
 
1540
        if (allCallLogs.isEmpty()) {
1541
            return rows;
1542
        }
1543
 
1544
        // Get unique authIds from call logs
1545
        Set<Long> authIds = allCallLogs.stream()
1546
                .map(AgentCallLog::getAuthId)
1547
                .collect(Collectors.toSet());
1548
 
1549
        // Get auth users for RBM names
1550
        List<Integer> authIdInts = authIds.stream().map(Long::intValue).collect(Collectors.toList());
1551
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(authIdInts).stream()
1552
                .collect(Collectors.toMap(AuthUser::getId, au -> au, (a, b) -> a));
1553
 
1554
        // Build a map of normalized customer number -> fofoId
1555
        Map<String, Integer> customerToFofoIdMap = new HashMap<>();
1556
        Set<String> normalizedNumbers = new HashSet<>();
1557
 
1558
        for (AgentCallLog callLog : allCallLogs) {
1559
            String customerNumber = callLog.getCustomerNumber();
1560
            if (customerNumber != null) {
1561
                String normalized = customerNumber.startsWith("+91") ? customerNumber.substring(3) : customerNumber;
1562
                normalizedNumbers.add(normalized);
1563
            }
1564
        }
1565
 
1566
        // For each normalized number, find fofoId
1567
        for (String mobile : normalizedNumbers) {
1568
            Integer fofoId = findFofoIdByMobile(mobile);
1569
            if (fofoId != null) {
1570
                customerToFofoIdMap.put(mobile, fofoId);
1571
            }
1572
        }
1573
 
1574
        // Get unique fofoIds for retailer lookup
1575
        Set<Integer> fofoIds = new HashSet<>(customerToFofoIdMap.values());
1576
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
1577
        if (!fofoIds.isEmpty()) {
1578
            try {
1579
                retailerMap = retailerService.getFofoRetailers(new ArrayList<>(fofoIds));
1580
            } catch (ProfitMandiBusinessException e) {
1581
                LOGGER.error("Error fetching fofo stores", e);
1582
            }
1583
        }
1584
 
1585
        // Get remarks for these fofoIds on this date
1586
        Map<Integer, List<PartnerCollectionRemark>> fofoRemarkMap = new HashMap<>();
1587
        if (!fofoIds.isEmpty()) {
1588
            List<PartnerCollectionRemark> dateRemarks = partnerCollectionRemarkRepository
1589
                    .selectAllByFofoIdsOnDate(new ArrayList<>(fofoIds), date);
1590
            for (PartnerCollectionRemark remark : dateRemarks) {
1591
                fofoRemarkMap.computeIfAbsent(remark.getFofoId(), k -> new ArrayList<>()).add(remark);
1592
            }
1593
        }
1594
 
1595
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
1596
 
1597
        // Build rows
1598
        for (AgentCallLog callLog : allCallLogs) {
1599
            String customerNumber = callLog.getCustomerNumber();
1600
            if (customerNumber == null) {
1601
                continue;
1602
            }
1603
 
1604
            // Get RBM Name
1605
            AuthUser authUser = authUserMap.get((int) callLog.getAuthId());
1606
            String rbmName = authUser != null ? authUser.getFullName() : "Unknown";
1607
 
1608
            String normalized = customerNumber.startsWith("+91") ? customerNumber.substring(3) : customerNumber;
1609
            Integer fofoId = customerToFofoIdMap.get(normalized);
1610
 
1611
            String partyName = "Unknown";
1612
            String code = "-";
1613
 
1614
            if (fofoId != null) {
1615
                CustomRetailer retailer = retailerMap.get(fofoId);
1616
                if (retailer != null) {
1617
                    partyName = retailer.getBusinessName();
1618
                    code = retailer.getCode();
1619
                } else {
1620
                    partyName = "Unknown (" + fofoId + ")";
1621
                }
1622
            } else {
1623
                partyName = "Unknown (" + normalized + ")";
1624
            }
1625
 
1626
            // Get remark if available
1627
            String remarkValue = "-";
1628
            if (fofoId != null && fofoRemarkMap.containsKey(fofoId)) {
1629
                List<PartnerCollectionRemark> remarks = fofoRemarkMap.get(fofoId);
1630
                if (!remarks.isEmpty()) {
1631
                    PartnerCollectionRemark remark = remarks.get(0);
1632
                    remarkValue = remark.getRemark() != null ? remark.getRemark().getValue() : "-";
1633
                    if (remark.getMessage() != null && !remark.getMessage().isEmpty()) {
1634
                        remarkValue = remarkValue + " - " + remark.getMessage();
1635
                    }
1636
                }
1637
            }
1638
 
1639
            // Call status from customerStatus field
1640
            String callStatus = callLog.getCustomerStatus() != null ? callLog.getCustomerStatus() : "-";
1641
            String callDuration = callLog.getCallDuration() != null ? callLog.getCallDuration() : "-";
1642
 
1643
            String callDateTime = "-";
1644
            if (callLog.getCallDate() != null && callLog.getCallTime() != null) {
1645
                LocalDateTime callDateTimeObj = LocalDateTime.of(callLog.getCallDate(), callLog.getCallTime());
1646
                callDateTime = callDateTimeObj.format(dateTimeFormatter);
1647
            }
1648
 
1649
            String recordingUrl = callLog.getRecordingUrl() != null ? callLog.getRecordingUrl() : "-";
1650
 
1651
            rows.add(Arrays.asList(rbmName, partyName, code, remarkValue, callStatus, callDuration, callDateTime, recordingUrl));
1652
        }
1653
 
1654
        return rows;
1655
    }
1656
 
33917 ranu 1657
}