Subversion Repositories SmartDukaan

Rev

Rev 35816 | Rev 35821 | 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()
618
                .filter(x -> Arrays.asList(EscalationType.L1, EscalationType.L2).contains(x.getEscalationType()))
619
                .collect(Collectors.toList());
620
 
621
        // Separate L1 and L2 auth IDs
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());
628
 
629
        // Union of all auth IDs for batch fetching
630
        List<Integer> rbmPositionsAuthIds = allRbmPositions.stream()
631
                .map(Position::getAuthUserId).distinct().collect(Collectors.toList());
632
        LOGGER.info("RBM Call Target - RBM positions fetch: {}ms, L1: {}, L2: {}", System.currentTimeMillis() - start, l1AuthIds.size(), l2AuthIds.size());
633
 
634
        start = System.currentTimeMillis();
635
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
636
        LOGGER.info("RBM Call Target - StoreGuyMap fetch: {}ms", System.currentTimeMillis() - start);
637
 
638
        LocalDateTime startDate = LocalDate.now().atStartOfDay();
639
        LocalDate firstOfMonth = LocalDate.now().withDayOfMonth(1);
640
        LocalDate endOfMonth = LocalDate.now().withDayOfMonth(LocalDate.now().lengthOfMonth()).plusDays(1);
641
 
642
        // Get auth user map
643
        start = System.currentTimeMillis();
644
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(rbmPositionsAuthIds).stream()
645
                .collect(Collectors.toMap(AuthUser::getId, au -> au));
646
        LOGGER.info("RBM Call Target - AuthUser fetch: {}ms", System.currentTimeMillis() - start);
647
 
648
        // Batch fetch positions by auth IDs (to check if RBM is L1)
649
        start = System.currentTimeMillis();
650
        Map<Integer, List<Position>> positionsByAuthId = positionRepository.selectPositionByAuthIds(rbmPositionsAuthIds).stream()
651
                .collect(Collectors.groupingBy(Position::getAuthUserId));
652
        LOGGER.info("RBM Call Target - Positions by AuthId fetch: {}ms", System.currentTimeMillis() - start);
653
 
654
        // Get all fofo IDs for all RBMs
655
        Set<Integer> allFofoIds = new HashSet<>();
656
        Map<Integer, List<Integer>> rbmToFofoIdsMap = new HashMap<>();
657
        for (int rbmAuthId : rbmPositionsAuthIds) {
658
            AuthUser au = authUserMap.get(rbmAuthId);
659
            if (au != null && storeGuyMap.containsKey(au.getEmailId())) {
660
                List<Integer> fofoIds = new ArrayList<>(storeGuyMap.get(au.getEmailId()));
661
                allFofoIds.addAll(fofoIds);
662
                rbmToFofoIdsMap.put(rbmAuthId, fofoIds);
663
            }
664
        }
35816 ranu 665
        // Initialize L2 calling list map - will be populated after fetching remarks
35631 ranu 666
        Map<Integer, List<Integer>> l2AuthIdToFofoIds = new HashMap<>();
35816 ranu 667
        for (int l2AuthId : l2AuthIds) {
668
            l2AuthIdToFofoIds.put(l2AuthId, new ArrayList<>());
35631 ranu 669
        }
670
        LOGGER.info("RBM Call Target - Total fofo IDs to process: {}", allFofoIds.size());
671
 
672
        // Get only needed fofo stores (OPTIMIZED - was fetching ALL stores before)
673
        start = System.currentTimeMillis();
674
        Map<Integer, FofoStore> fofoStoresMap = new HashMap<>();
675
        if (!allFofoIds.isEmpty()) {
676
            try {
677
                fofoStoresMap = fofoStoreRepository.selectByRetailerIds(new ArrayList<>(allFofoIds)).stream()
678
                        .collect(Collectors.toMap(FofoStore::getId, x -> x, (a, b) -> a));
679
            } catch (ProfitMandiBusinessException e) {
680
                LOGGER.error("Error fetching fofo stores", e);
681
            }
682
        }
683
        LOGGER.info("RBM Call Target - FofoStores fetch (only needed): {}ms, count: {}", System.currentTimeMillis() - start, fofoStoresMap.size());
684
 
685
        // Batch fetch max remark ids for all fofoIds (for escalation filtering)
686
        start = System.currentTimeMillis();
687
        Map<Integer, PartnerCollectionRemark> allPartnerCollectionRemarks = new HashMap<>();
688
        if (!allFofoIds.isEmpty()) {
689
            List<Integer> allRemarkIds = partnerCollectionRemarkRepository.selectMaxRemarkId(new ArrayList<>(allFofoIds));
690
            if (!allRemarkIds.isEmpty()) {
691
                allPartnerCollectionRemarks = partnerCollectionRemarkRepository.selectByIds(allRemarkIds).stream()
692
                        .collect(Collectors.toMap(PartnerCollectionRemark::getFofoId, x -> x, (a, b) -> a));
693
            }
694
        }
695
        LOGGER.info("RBM Call Target - PartnerCollectionRemarks fetch: {}ms", System.currentTimeMillis() - start);
696
 
35816 ranu 697
        // Populate L2 calling list based on partners whose latest remark is RBM_L2_ESCALATION
698
        // Find the L1 who has the partner and add to that L1's manager (L2) calling list
699
        for (Map.Entry<Integer, PartnerCollectionRemark> entry : allPartnerCollectionRemarks.entrySet()) {
700
            Integer fofoId = entry.getKey();
701
            PartnerCollectionRemark remark = entry.getValue();
702
 
703
            if (CollectionRemark.RBM_L2_ESCALATION.equals(remark.getRemark())) {
704
                // Find which L1 RBM has this partner assigned
705
                for (int l1AuthId : l1AuthIds) {
706
                    List<Integer> l1FofoIds = rbmToFofoIdsMap.getOrDefault(l1AuthId, Collections.emptyList());
707
                    if (l1FofoIds.contains(fofoId)) {
708
                        // Get L1's manager (L2)
709
                        AuthUser l1User = authUserMap.get(l1AuthId);
710
                        if (l1User != null && l2AuthIdToFofoIds.containsKey(l1User.getManagerId())) {
711
                            int l2ManagerId = l1User.getManagerId();
712
                            l2AuthIdToFofoIds.get(l2ManagerId).add(fofoId);
713
                        }
714
                        break; // Found the L1 for this fofoId
715
                    }
716
                }
717
            }
718
        }
719
        LOGGER.info("RBM Call Target - L2 calling lists populated from RBM_L2_ESCALATION remarks");
720
 
35631 ranu 721
        // Batch fetch collection RANK map for all fofoIds (OPTIMIZED - only fetches rank, not full model)
722
        start = System.currentTimeMillis();
723
        Map<Integer, Integer> allCollectionRankMap = new HashMap<>();
724
        if (!allFofoIds.isEmpty()) {
725
            try {
726
                allCollectionRankMap = partnerCollectionService.getCollectionRankMap(new ArrayList<>(allFofoIds), startDate);
727
            } catch (ProfitMandiBusinessException e) {
728
                LOGGER.error("Error fetching collection rank map for all fofoIds", e);
729
            }
730
        }
731
        LOGGER.info("RBM Call Target - CollectionRankMap fetch (OPTIMIZED): {}ms", System.currentTimeMillis() - start);
732
 
35669 ranu 733
        // Get MTD billing data for zero billing calculation and partner counts
35631 ranu 734
        start = System.currentTimeMillis();
735
        List<RbmWeeklyBillingModel> mtdBillingData = getWeeklyBillingDataForMonth(firstOfMonth, endOfMonth);
736
        Set<Integer> allMtdBilledFofoIds = mtdBillingData.stream()
737
                .filter(RbmWeeklyBillingModel::isMtdBilled)
738
                .map(RbmWeeklyBillingModel::getFofoId)
739
                .collect(Collectors.toSet());
35669 ranu 740
        // Build partner count and fofoIds per RBM from mtdBillingData (same source as Today ARR page)
741
        Map<Integer, Set<Integer>> mtdFofoIdsByAuthId = mtdBillingData.stream()
742
                .filter(RbmWeeklyBillingModel::isTargetedPartner)
743
                .collect(Collectors.groupingBy(RbmWeeklyBillingModel::getAuthId,
744
                        Collectors.mapping(RbmWeeklyBillingModel::getFofoId, Collectors.toSet())));
35631 ranu 745
        LOGGER.info("RBM Call Target - MTD Billing fetch: {}ms", System.currentTimeMillis() - start);
746
 
747
        // Batch fetch today's remarks for all auth IDs (to calculate Value Achieved)
748
        start = System.currentTimeMillis();
749
        Map<Integer, List<PartnerCollectionRemark>> remarksByAuthId = partnerCollectionRemarkRepository
750
                .selectAllByAuthIdsOnDate(rbmPositionsAuthIds, LocalDate.now()).stream()
751
                .collect(Collectors.groupingBy(PartnerCollectionRemark::getAuthId));
752
        LOGGER.info("RBM Call Target - Today Remarks fetch: {}ms", System.currentTimeMillis() - start);
753
 
754
        // Batch fetch today's out-of-sequence logs for all RBMs
755
        start = System.currentTimeMillis();
756
        LocalDateTime todayStart = LocalDate.now().atStartOfDay();
757
        LocalDateTime todayEnd = LocalDate.now().plusDays(1).atStartOfDay();
758
        List<RbmCallSequenceLog> outOfSequenceLogs = rbmCallSequenceLogRepository.selectOutOfSequenceByDateRange(todayStart, todayEnd);
759
        Map<Integer, Long> outOfSequenceCountByAuthId = outOfSequenceLogs.stream()
35654 ranu 760
                .collect(Collectors.groupingBy(RbmCallSequenceLog::getAuthId,
761
                        Collectors.mapping(RbmCallSequenceLog::getFofoId, Collectors.collectingAndThen(Collectors.toSet(), s -> (long) s.size()))));
35631 ranu 762
        LOGGER.info("RBM Call Target - Out of Sequence fetch: {}ms", System.currentTimeMillis() - start);
763
 
764
        // Process L1 RBMs (existing logic)
765
        for (int rbmAuthId : l1AuthIds) {
766
            AuthUser authUser = authUserMap.get(rbmAuthId);
767
            if (authUser == null || !storeGuyMap.containsKey(authUser.getEmailId())) {
768
                continue;
769
            }
770
 
771
            List<Integer> fofoIdList = rbmToFofoIdsMap.getOrDefault(rbmAuthId, Collections.emptyList());
772
 
773
            // Check if RBM is L1 (same logic as getSummaryModel)
774
            List<Position> positions = positionsByAuthId.getOrDefault(authUser.getId(), Collections.emptyList());
775
            boolean isRBMAndL1 = positions.stream()
776
                    .anyMatch(position ->
777
                            ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId()
778
                                    && EscalationType.L1.equals(position.getEscalationType()));
779
 
780
            // Filter escalated partners for L1 RBMs (same logic as getSummaryModel)
781
            List<Integer> fofoIds = fofoIdList;
782
            if (isRBMAndL1) {
783
                Map<Integer, PartnerCollectionRemark> partnerCollectionRemarks = new HashMap<>();
784
                for (Integer fofoId : fofoIdList) {
785
                    if (allPartnerCollectionRemarks.containsKey(fofoId)) {
786
                        partnerCollectionRemarks.put(fofoId, allPartnerCollectionRemarks.get(fofoId));
787
                    }
788
                }
789
                fofoIds = partnerCollectionRemarks.entrySet().stream()
790
                        .filter(entry -> {
791
                            PartnerCollectionRemark pcrMap = entry.getValue();
792
                            return !(CollectionRemark.RBM_L2_ESCALATION.equals(pcrMap.getRemark())
793
                                    || CollectionRemark.SALES_ESCALATION.equals(pcrMap.getRemark()));
794
                        })
795
                        .map(Map.Entry::getKey)
796
                        .collect(Collectors.toList());
797
            }
798
 
35669 ranu 799
            // Filter to only external, ACTIVE stores (collection plan not required)
35631 ranu 800
            Map<Integer, Integer> finalAllCollectionRankMap = allCollectionRankMap;
801
            Map<Integer, FofoStore> finalFofoStoresMap = fofoStoresMap;
802
            List<Integer> validFofoIds = fofoIds.stream()
803
                    .filter(fofoId -> {
804
                        FofoStore store = finalFofoStoresMap.get(fofoId);
805
                        if (store == null || store.isInternal()) {
806
                            return false;
807
                        }
808
                        // Only include ACTIVE partners (not Low Sale, not Disputed, not Billing Pending)
35669 ranu 809
                        return ActivationType.ACTIVE.equals(store.getActivationType());
35631 ranu 810
                    })
811
                    .collect(Collectors.toList());
812
 
813
            if (validFofoIds.isEmpty()) {
814
                continue;
815
            }
816
 
817
            RbmCallTargetModel targetModel = new RbmCallTargetModel();
818
            targetModel.setAuthId(rbmAuthId);
819
            targetModel.setRbmName(authUser.getFullName());
35669 ranu 820
            // Use partner count from mtdBillingData (same source as Today ARR page)
821
            Set<Integer> mtdFofoIds = mtdFofoIdsByAuthId.getOrDefault(rbmAuthId, Collections.emptySet());
822
            targetModel.setPartnerCount(mtdFofoIds.size());
35631 ranu 823
 
824
            // Categorize each partner - each partner belongs to ONE category only
35665 ranu 825
            // Priority: PlanToday > CarryForward > ZeroBilling > Untouched > FuturePlan > Normal
35631 ranu 826
            Set<Integer> planTodayPartners = new HashSet<>();
827
            Set<Integer> carryForwardPartners = new HashSet<>();
828
            Set<Integer> untouchedPartners = new HashSet<>();
829
            Set<Integer> zeroBillingPartners = new HashSet<>();
830
            Set<Integer> futurePlanPartners = new HashSet<>();
831
            Set<Integer> normalPartners = new HashSet<>();
832
 
833
            for (Integer fofoId : validFofoIds) {
834
                // Get collection plan rank (from optimized rank map)
835
                int rank = allCollectionRankMap.getOrDefault(fofoId, 5); // default to Normal if no plan
836
 
837
                // Check if partner has zero billing in MTD
838
                boolean hasZeroBilling = !allMtdBilledFofoIds.contains(fofoId);
839
 
840
                // Assign to category based on priority
841
                if (rank == 1) {
842
                    planTodayPartners.add(fofoId);
843
                } else if (rank == 2) {
844
                    carryForwardPartners.add(fofoId);
35665 ranu 845
                } else if (hasZeroBilling) {
846
                    zeroBillingPartners.add(fofoId);
35631 ranu 847
                } else if (rank == 3) {
848
                    untouchedPartners.add(fofoId);
849
                } else if (rank == 4) {
850
                    futurePlanPartners.add(fofoId);
851
                } else {
852
                    normalPartners.add(fofoId);
853
                }
854
            }
855
 
856
            // Set counts
857
            targetModel.setCreditCollection(0); // Credit collection is handled in separate list
858
            targetModel.setPlanToday(planTodayPartners.size());
859
            targetModel.setCarryForward(carryForwardPartners.size());
860
            targetModel.setUntouched(untouchedPartners.size());
861
            targetModel.setZeroBilling(zeroBillingPartners.size());
862
            targetModel.setFuturePlan(futurePlanPartners.size());
863
            targetModel.setNormal(normalPartners.size());
864
 
865
            // Today Target = PlanToday + CarryForward + ZeroBilling + Untouched
866
            // These are mutually exclusive now, so we can sum them
867
            long todayTarget = planTodayPartners.size() +
868
                    carryForwardPartners.size() + zeroBillingPartners.size() + untouchedPartners.size();
869
            targetModel.setTodayTargetOfCall(todayTarget);
870
 
871
            // Create set of partners in Today Target categories
872
            Set<Integer> todayTargetPartners = new HashSet<>();
873
            todayTargetPartners.addAll(planTodayPartners);
874
            todayTargetPartners.addAll(carryForwardPartners);
875
            todayTargetPartners.addAll(zeroBillingPartners);
876
            todayTargetPartners.addAll(untouchedPartners);
877
 
35818 ranu 878
            // Value Achieved = All distinct partners contacted today (all remarks made today by this RBM)
35631 ranu 879
            List<PartnerCollectionRemark> todayRemarks = remarksByAuthId.getOrDefault(rbmAuthId, Collections.emptyList());
880
            long valueAchieved = todayRemarks.stream()
881
                    .map(PartnerCollectionRemark::getFofoId)
882
                    .distinct()
883
                    .count();
884
            targetModel.setValueTargetAchieved(valueAchieved);
885
 
886
            // Moved to Future = Partners in Future Plan category who have a remark today
887
            // These are partners who were contacted today but moved to a future date
888
            Set<Integer> todayRemarkedFofoIds = todayRemarks.stream()
889
                    .map(PartnerCollectionRemark::getFofoId)
890
                    .collect(Collectors.toSet());
891
            long movedToFuture = futurePlanPartners.stream()
892
                    .filter(todayRemarkedFofoIds::contains)
893
                    .count();
894
            targetModel.setMovedToFuture(movedToFuture);
895
 
896
            // Set out of sequence count for this RBM
897
            targetModel.setOutOfSequenceCount(outOfSequenceCountByAuthId.getOrDefault(rbmAuthId, 0L));
898
 
899
            rbmCallTargetModels.add(targetModel);
900
        }
901
 
902
        // Process L2 RBMs (escalated ticket logic with categorization)
903
        for (int l2AuthId : l2AuthIds) {
904
            AuthUser authUser = authUserMap.get(l2AuthId);
905
            if (authUser == null) {
906
                continue;
907
            }
908
 
909
            List<Integer> l2FofoIdList = l2AuthIdToFofoIds.getOrDefault(l2AuthId, Collections.emptyList());
910
 
35816 ranu 911
            // For L2, use unique fofoIds with RBM_L2_ESCALATION remark as target
35662 ranu 912
            Set<Integer> l2TargetFofoIds = new HashSet<>(l2FofoIdList);
35631 ranu 913
 
914
            RbmCallTargetModel l2Model = new RbmCallTargetModel();
915
            l2Model.setAuthId(l2AuthId);
916
            l2Model.setRbmName(authUser.getFullName() + " (L2)");
917
            l2Model.setL2Position(true);
35816 ranu 918
            l2Model.setL2CallingList(l2TargetFofoIds.size());
35631 ranu 919
            // Partner count = total assigned partners (same as L1 source)
920
            List<Integer> l2AssignedFofoIds = rbmToFofoIdsMap.getOrDefault(l2AuthId, Collections.emptyList());
921
            l2Model.setPartnerCount(l2AssignedFofoIds.size());
922
 
35816 ranu 923
            // L2 Target = partners with RBM_L2_ESCALATION as latest remark
35662 ranu 924
            l2Model.setTodayTargetOfCall(l2TargetFofoIds.size());
35631 ranu 925
 
35818 ranu 926
            // Value Achieved = All distinct partners contacted today (all remarks made today by this L2)
35662 ranu 927
            List<PartnerCollectionRemark> l2TodayRemarks = remarksByAuthId.getOrDefault(l2AuthId, Collections.emptyList());
928
            long l2ValueAchieved = l2TodayRemarks.stream()
929
                    .map(PartnerCollectionRemark::getFofoId)
930
                    .distinct()
931
                    .count();
932
            l2Model.setValueTargetAchieved(l2ValueAchieved);
35631 ranu 933
 
934
            l2Model.setOutOfSequenceCount(outOfSequenceCountByAuthId.getOrDefault(l2AuthId, 0L));
935
            rbmCallTargetModels.add(l2Model);
936
        }
937
 
938
        // Group L1 under their L2 manager using authUser.managerId
939
        Map<Integer, RbmCallTargetModel> l2ModelsByAuthId = new HashMap<>();
940
        Map<Integer, RbmCallTargetModel> l1ModelsByAuthId = new HashMap<>();
941
        for (RbmCallTargetModel m : rbmCallTargetModels) {
942
            if (m.isL2Position()) {
943
                l2ModelsByAuthId.put(m.getAuthId(), m);
944
            } else {
945
                l1ModelsByAuthId.put(m.getAuthId(), m);
946
            }
947
        }
948
 
949
        // Build L2 -> L1 team map using managerId from AuthUser
950
        Map<Integer, List<RbmCallTargetModel>> l2TeamMap = new LinkedHashMap<>();
951
        for (RbmCallTargetModel l2Model : l2ModelsByAuthId.values()) {
952
            l2TeamMap.put(l2Model.getAuthId(), new ArrayList<>());
953
        }
954
 
955
        Set<Integer> addedL1AuthIds = new HashSet<>();
956
        for (RbmCallTargetModel l1Model : l1ModelsByAuthId.values()) {
957
            AuthUser l1User = authUserMap.get(l1Model.getAuthId());
958
            if (l1User != null && l2TeamMap.containsKey(l1User.getManagerId())) {
959
                l2TeamMap.get(l1User.getManagerId()).add(l1Model);
960
                addedL1AuthIds.add(l1Model.getAuthId());
961
            }
962
        }
963
 
964
        // Build sorted result: L2 row, then its L1 team (sorted by name)
965
        List<RbmCallTargetModel> sortedModels = new ArrayList<>();
966
 
967
        List<RbmCallTargetModel> l2Sorted = new ArrayList<>(l2ModelsByAuthId.values());
968
        l2Sorted.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
969
 
970
        for (RbmCallTargetModel l2Model : l2Sorted) {
971
            sortedModels.add(l2Model);
972
            List<RbmCallTargetModel> team = l2TeamMap.getOrDefault(l2Model.getAuthId(), Collections.emptyList());
973
            team.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
974
            sortedModels.addAll(team);
975
        }
976
 
977
        // Add any L1 RBMs not mapped to any L2 (sorted by name)
978
        List<RbmCallTargetModel> unmappedL1 = new ArrayList<>();
979
        for (RbmCallTargetModel m : l1ModelsByAuthId.values()) {
980
            if (!addedL1AuthIds.contains(m.getAuthId())) {
981
                unmappedL1.add(m);
982
            }
983
        }
984
        unmappedL1.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
985
        sortedModels.addAll(unmappedL1);
986
 
987
        LOGGER.info("RBM Call Target - TOTAL TIME: {}ms, RBM count: {}", System.currentTimeMillis() - methodStart, sortedModels.size());
988
        return sortedModels;
989
    }
990
 
991
    @Override
992
    public List<OutOfSequenceDetailModel> getOutOfSequenceDetails(int authId) {
993
 
994
        LocalDate today = LocalDate.now();
995
        LocalDateTime start = today.atStartOfDay();
996
        LocalDateTime end = today.plusDays(1).atStartOfDay();
997
 
998
        List<RbmCallSequenceLog> logs =
999
                rbmCallSequenceLogRepository.selectByAuthIdAndDateRange(authId, start, end);
1000
 
35654 ranu 1001
        Map<Integer, RbmCallSequenceLog> uniqueOosLogsByFofoId = new LinkedHashMap<>();
35631 ranu 1002
 
1003
        for (RbmCallSequenceLog log : logs) {
1004
            if (log.isOutOfSequence()) {
35654 ranu 1005
                // Keep only the first occurrence per fofoId (latest entry since ordered by id DESC)
1006
                uniqueOosLogsByFofoId.putIfAbsent(log.getFofoId(), log);
35631 ranu 1007
            }
1008
        }
1009
 
35654 ranu 1010
        if (uniqueOosLogsByFofoId.isEmpty()) {
35631 ranu 1011
            return Collections.emptyList();
1012
        }
1013
 
35654 ranu 1014
        Set<Integer> fofoIds = uniqueOosLogsByFofoId.keySet();
35631 ranu 1015
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
1016
        try {
1017
            retailerMap = retailerService.getFofoRetailers(new ArrayList<>(fofoIds));
1018
        } catch (ProfitMandiBusinessException e) {
1019
            LOGGER.error("Error fetching fofo stores", e);
1020
        }
1021
 
1022
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
1023
        List<OutOfSequenceDetailModel> result = new ArrayList<>();
1024
 
35654 ranu 1025
        for (RbmCallSequenceLog log : uniqueOosLogsByFofoId.values()) {
35631 ranu 1026
            CustomRetailer retailer = retailerMap.get(log.getFofoId());
1027
            String partyName = retailer != null
1028
                    ? retailer.getBusinessName()
1029
                    : "Unknown (" + log.getFofoId() + ")";
1030
            String code = retailer != null
1031
                    ? retailer.getCode()
1032
                    : "-";
1033
 
1034
            String time = log.getCreateTimestamp() != null
1035
                    ? log.getCreateTimestamp().format(timeFormatter)
1036
                    : "-";
1037
 
1038
            result.add(new OutOfSequenceDetailModel(partyName, code, time));
1039
        }
1040
 
1041
        return result;
1042
    }
1043
 
35645 ranu 1044
    @Override
35672 ranu 1045
    public List<CalledPartnerDetailModel> getCalledPartnerDetails(int authId) throws ProfitMandiBusinessException {
35730 ranu 1046
        return getCalledPartnerDetails(authId, LocalDate.now());
1047
    }
1048
 
1049
    @Override
1050
    public List<CalledPartnerDetailModel> getCalledPartnerDetails(int authId, LocalDate date) throws ProfitMandiBusinessException {
35759 ranu 1051
        // Get all call logs for this auth user on this date
35760 ranu 1052
        LOGGER.info("getCalledPartnerDetails: authId={}, date={}", authId, date);
35761 ranu 1053
        List<AgentCallLog> callLogs = agentCallLogRepository.findByAuthIdAndDate(authId, date);
35760 ranu 1054
        LOGGER.info("Found {} call logs for authId={} on date={}", callLogs.size(), authId, date);
35670 ranu 1055
 
35759 ranu 1056
        if (callLogs.isEmpty()) {
35672 ranu 1057
            return Collections.emptyList();
1058
        }
35670 ranu 1059
 
35759 ranu 1060
        // Build a map of normalized customer number -> fofoId
1061
        Map<String, Integer> customerToFofoIdMap = new HashMap<>();
1062
        Set<String> normalizedNumbers = new HashSet<>();
35672 ranu 1063
 
35763 ranu 1064
        for (AgentCallLog callLog : callLogs) {
35759 ranu 1065
            String customerNumber = callLog.getCustomerNumber();
1066
            if (customerNumber != null) {
1067
                String normalized = customerNumber.startsWith("+91") ? customerNumber.substring(3) : customerNumber;
1068
                normalizedNumbers.add(normalized);
1069
            }
35672 ranu 1070
        }
1071
 
35759 ranu 1072
        // For each normalized number, find fofoId from retailer_contact first, then address
1073
        for (String mobile : normalizedNumbers) {
1074
            Integer fofoId = findFofoIdByMobile(mobile);
1075
            if (fofoId != null) {
1076
                customerToFofoIdMap.put(mobile, fofoId);
1077
            }
35670 ranu 1078
        }
1079
 
35759 ranu 1080
        // Get unique fofoIds for retailer lookup
1081
        Set<Integer> fofoIds = new HashSet<>(customerToFofoIdMap.values());
1082
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
1083
        if (!fofoIds.isEmpty()) {
1084
            try {
1085
                retailerMap = retailerService.getFofoRetailers(new ArrayList<>(fofoIds));
1086
            } catch (ProfitMandiBusinessException e) {
1087
                LOGGER.error("Error fetching fofo stores", e);
1088
            }
35672 ranu 1089
        }
1090
 
35759 ranu 1091
        // Get today's remarks for these fofoIds
1092
        Map<Integer, List<PartnerCollectionRemark>> fofoRemarkMap = new HashMap<>();
1093
        if (!fofoIds.isEmpty()) {
1094
            List<PartnerCollectionRemark> todayRemarks = partnerCollectionRemarkRepository
1095
                    .selectAllByFofoIdsOnDate(new ArrayList<>(fofoIds), date);
1096
            for (PartnerCollectionRemark remark : todayRemarks) {
1097
                fofoRemarkMap.computeIfAbsent(remark.getFofoId(), k -> new ArrayList<>()).add(remark);
1098
            }
35672 ranu 1099
        }
1100
 
35759 ranu 1101
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
1102
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
1103
        List<CalledPartnerDetailModel> result = new ArrayList<>();
35672 ranu 1104
 
35759 ranu 1105
        for (com.spice.profitmandi.dao.entity.cs.AgentCallLog callLog : callLogs) {
1106
            String customerNumber = callLog.getCustomerNumber();
1107
            if (customerNumber == null) {
1108
                continue;
1109
            }
35672 ranu 1110
 
35759 ranu 1111
            String normalized = customerNumber.startsWith("+91") ? customerNumber.substring(3) : customerNumber;
1112
            Integer fofoId = customerToFofoIdMap.get(normalized);
35672 ranu 1113
 
35759 ranu 1114
            String partyName = "Unknown";
1115
            String code = "-";
35672 ranu 1116
 
35759 ranu 1117
            if (fofoId != null) {
1118
                CustomRetailer retailer = retailerMap.get(fofoId);
1119
                if (retailer != null) {
1120
                    partyName = retailer.getBusinessName();
1121
                    code = retailer.getCode();
1122
                } else {
1123
                    partyName = "Unknown (" + fofoId + ")";
1124
                }
1125
            } else {
1126
                partyName = "Unknown (" + normalized + ")";
1127
            }
35672 ranu 1128
 
35759 ranu 1129
            // Get remark if available
1130
            String remarkValue = "-";
1131
            String messageValue = "-";
1132
            String remarkTime = "-";
35672 ranu 1133
 
35759 ranu 1134
            if (fofoId != null && fofoRemarkMap.containsKey(fofoId)) {
1135
                List<PartnerCollectionRemark> remarks = fofoRemarkMap.get(fofoId);
1136
                if (!remarks.isEmpty()) {
1137
                    PartnerCollectionRemark remark = remarks.get(0);
1138
                    remarkValue = remark.getRemark() != null ? remark.getRemark().getValue() : "-";
1139
                    messageValue = remark.getMessage() != null ? remark.getMessage() : "-";
1140
                    remarkTime = remark.getCreateTimestamp() != null ? remark.getCreateTimestamp().format(timeFormatter) : "-";
1141
                }
1142
            }
35672 ranu 1143
 
35759 ranu 1144
            // Build call log data
1145
            String recordingUrl = callLog.getRecordingUrl();
1146
            String callStatus = callLog.getCallStatus();
1147
            String callDuration = callLog.getCallDuration();
1148
            String callDateTime = null;
1149
            if (callLog.getCallDate() != null && callLog.getCallTime() != null) {
1150
                LocalDateTime callDateTimeObj = LocalDateTime.of(callLog.getCallDate(), callLog.getCallTime());
1151
                callDateTime = callDateTimeObj.format(dateTimeFormatter);
35672 ranu 1152
            }
35759 ranu 1153
 
1154
            result.add(new CalledPartnerDetailModel(partyName, code, remarkValue, messageValue, remarkTime,
1155
                    recordingUrl, callStatus, callDuration, callDateTime));
35672 ranu 1156
        }
1157
 
35759 ranu 1158
        return result;
1159
    }
35672 ranu 1160
 
35759 ranu 1161
    private Integer findFofoIdByMobile(String mobile) {
1162
        // First check retailer_contact
1163
        List<RetailerContact> contacts = retailerContactRepository.selectByMobile(mobile);
1164
        if (contacts != null && !contacts.isEmpty()) {
1165
            return contacts.get(0).getFofoId();
1166
        }
1167
 
1168
        // Fallback to user.address
35762 ranu 1169
        List<Address> addresses = addressRepository.selectAllByPhoneNumber(mobile);
1170
        if (addresses != null && !addresses.isEmpty()) {
1171
            return addresses.get(0).getRetaierId();
35759 ranu 1172
        }
1173
 
1174
        return null;
35672 ranu 1175
    }
1176
 
35757 ranu 1177
    private List<CalledPartnerDetailModel> buildCalledPartnerResult(List<PartnerCollectionRemark> allRemarks) {
1178
        if (allRemarks.isEmpty()) {
35672 ranu 1179
            return Collections.emptyList();
1180
        }
1181
 
35757 ranu 1182
        // Get unique fofoIds for retailer lookup
1183
        Set<Integer> fofoIds = allRemarks.stream()
1184
                .map(PartnerCollectionRemark::getFofoId)
1185
                .collect(Collectors.toSet());
35670 ranu 1186
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
1187
        try {
1188
            retailerMap = retailerService.getFofoRetailers(new ArrayList<>(fofoIds));
1189
        } catch (ProfitMandiBusinessException e) {
1190
            LOGGER.error("Error fetching fofo stores", e);
1191
        }
1192
 
35702 ranu 1193
        // Fetch call logs for remarks that have agentCallLogId
35721 ranu 1194
        Map<Long, com.spice.profitmandi.dao.entity.cs.AgentCallLog> callLogMap = new HashMap<>();
1195
        try {
35757 ranu 1196
            List<Long> callLogIds = allRemarks.stream()
35721 ranu 1197
                    .filter(r -> r.getAgentCallLogId() > 0)
1198
                    .map(PartnerCollectionRemark::getAgentCallLogId)
1199
                    .collect(Collectors.toList());
35702 ranu 1200
 
35721 ranu 1201
            if (!callLogIds.isEmpty()) {
35720 ranu 1202
                List<com.spice.profitmandi.dao.entity.cs.AgentCallLog> callLogs = agentCallLogRepository.findByIds(callLogIds);
35721 ranu 1203
                if (callLogs != null) {
1204
                    callLogMap = callLogs.stream()
1205
                            .collect(Collectors.toMap(com.spice.profitmandi.dao.entity.cs.AgentCallLog::getId, c -> c, (a, b) -> a));
1206
                }
35720 ranu 1207
            }
35721 ranu 1208
        } catch (Exception e) {
1209
            LOGGER.error("Error fetching call logs by ids", e);
35702 ranu 1210
        }
1211
 
35670 ranu 1212
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
35702 ranu 1213
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
35670 ranu 1214
        List<CalledPartnerDetailModel> result = new ArrayList<>();
1215
 
35757 ranu 1216
        for (PartnerCollectionRemark remark : allRemarks) {
35670 ranu 1217
            CustomRetailer retailer = retailerMap.get(remark.getFofoId());
1218
            String partyName = retailer != null
1219
                    ? retailer.getBusinessName()
1220
                    : "Unknown (" + remark.getFofoId() + ")";
1221
            String code = retailer != null
1222
                    ? retailer.getCode()
1223
                    : "-";
1224
 
1225
            String remarkValue = remark.getRemark() != null
1226
                    ? remark.getRemark().getValue()
1227
                    : "-";
1228
 
35677 ranu 1229
            String messageValue = remark.getMessage() != null
1230
                    ? remark.getMessage()
1231
                    : "-";
1232
 
35670 ranu 1233
            String time = remark.getCreateTimestamp() != null
1234
                    ? remark.getCreateTimestamp().format(timeFormatter)
1235
                    : "-";
1236
 
35702 ranu 1237
            // Get call log data if available
1238
            String recordingUrl = null;
1239
            String callStatus = null;
1240
            String callDuration = null;
1241
            String callDateTime = null;
1242
 
35721 ranu 1243
            try {
1244
                if (remark.getAgentCallLogId() > 0 && callLogMap.containsKey(remark.getAgentCallLogId())) {
1245
                    com.spice.profitmandi.dao.entity.cs.AgentCallLog callLog = callLogMap.get(remark.getAgentCallLogId());
1246
                    recordingUrl = callLog.getRecordingUrl();
1247
                    callStatus = callLog.getCallStatus();
1248
                    callDuration = callLog.getCallDuration();
1249
                    if (callLog.getCallDate() != null && callLog.getCallTime() != null) {
1250
                        LocalDateTime callDateTimeObj = LocalDateTime.of(callLog.getCallDate(), callLog.getCallTime());
1251
                        callDateTime = callDateTimeObj.format(dateTimeFormatter);
1252
                    }
35702 ranu 1253
                }
35721 ranu 1254
            } catch (Exception e) {
1255
                LOGGER.error("Error processing call log for remark id: {}", remark.getId(), e);
35702 ranu 1256
            }
1257
 
1258
            result.add(new CalledPartnerDetailModel(partyName, code, remarkValue, messageValue, time,
1259
                    recordingUrl, callStatus, callDuration, callDateTime));
35670 ranu 1260
        }
1261
 
1262
        return result;
1263
    }
1264
 
1265
    @Override
35645 ranu 1266
    public List<List<String>> getRbmCallTargetRawDataByAuthId(int authId) throws Exception {
1267
        List<List<String>> rows = new ArrayList<>();
35631 ranu 1268
 
35645 ranu 1269
        // Get auth user
1270
        List<AuthUser> authUsers = authRepository.selectByIds(Collections.singletonList(authId));
1271
        if (authUsers.isEmpty()) {
1272
            return rows;
1273
        }
1274
        AuthUser authUser = authUsers.get(0);
1275
 
35757 ranu 1276
        // Get positions to determine if L2
35645 ranu 1277
        List<Position> positions = positionRepository.selectPositionByAuthIds(Collections.singletonList(authId));
1278
        boolean isL2 = positions.stream()
1279
                .anyMatch(p -> ProfitMandiConstants.TICKET_CATEGORY_RBM == p.getCategoryId()
1280
                        && EscalationType.L2.equals(p.getEscalationType()));
1281
 
35757 ranu 1282
        LocalDateTime startDate = LocalDate.now().atStartOfDay();
1283
        LocalDate firstOfMonth = LocalDate.now().withDayOfMonth(1);
1284
        LocalDate endOfMonth = LocalDate.now().withDayOfMonth(LocalDate.now().lengthOfMonth()).plusDays(1);
35645 ranu 1285
 
35757 ranu 1286
        // Get fofo IDs from mtdBillingData (same source as Partner Count in getRbmCallTargetModels)
1287
        List<RbmWeeklyBillingModel> mtdBillingData = getWeeklyBillingDataForMonth(firstOfMonth, endOfMonth);
1288
 
1289
        List<Integer> fofoIdList;
35645 ranu 1290
        if (isL2) {
35757 ranu 1291
            // L2: get fofo IDs from escalated tickets (same as getRbmCallTargetModels)
35645 ranu 1292
            List<Ticket> escalatedTickets = ticketRepository.selectOpenEscalatedTicketsByAuthIds(Collections.singletonList(authId));
1293
            fofoIdList = escalatedTickets.stream()
1294
                    .filter(t -> t.getL2AuthUser() == authId
1295
                            || t.getL3AuthUser() == authId
1296
                            || t.getL4AuthUser() == authId
1297
                            || t.getL5AuthUser() == authId)
1298
                    .map(Ticket::getFofoId)
1299
                    .distinct()
1300
                    .collect(Collectors.toList());
35757 ranu 1301
        } else {
1302
            // L1: get fofo IDs from mtdBillingData with isTargetedPartner (same as Partner Count)
1303
            fofoIdList = mtdBillingData.stream()
1304
                    .filter(RbmWeeklyBillingModel::isTargetedPartner)
1305
                    .filter(m -> m.getAuthId() == authId)
1306
                    .map(RbmWeeklyBillingModel::getFofoId)
1307
                    .distinct()
1308
                    .collect(Collectors.toList());
35645 ranu 1309
        }
1310
 
1311
        if (fofoIdList.isEmpty()) {
1312
            return rows;
1313
        }
1314
 
35757 ranu 1315
        // MTD billed fofoIds for zero billing check
1316
        Set<Integer> mtdBilledFofoIds = mtdBillingData.stream()
1317
                .filter(RbmWeeklyBillingModel::isMtdBilled)
1318
                .map(RbmWeeklyBillingModel::getFofoId)
1319
                .collect(Collectors.toSet());
35645 ranu 1320
 
35757 ranu 1321
        // Collection rank map for status calculation
35645 ranu 1322
        Map<Integer, Integer> collectionRankMap = new HashMap<>();
1323
        try {
1324
            collectionRankMap = partnerCollectionService.getCollectionRankMap(fofoIdList, startDate);
1325
        } catch (ProfitMandiBusinessException e) {
1326
            LOGGER.error("Error fetching collection rank map", e);
1327
        }
1328
 
1329
        // Resolve partner names/codes
1330
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
35757 ranu 1331
        if (!fofoIdList.isEmpty()) {
35645 ranu 1332
            try {
35757 ranu 1333
                retailerMap = retailerService.getFofoRetailers(fofoIdList);
35645 ranu 1334
            } catch (ProfitMandiBusinessException e) {
1335
                LOGGER.error("Error fetching fofo retailers for raw data", e);
1336
            }
1337
        }
1338
 
1339
        String rbmName = authUser.getFullName() + (isL2 ? " (L2)" : "");
1340
 
35757 ranu 1341
        // Build rows for ALL partners (same count as Partner Count)
1342
        for (Integer fofoId : fofoIdList) {
1343
            // Default to rank 5 (Normal) for partners without collection plan
35645 ranu 1344
            int rank = collectionRankMap.getOrDefault(fofoId, 5);
1345
            boolean hasZeroBilling = !mtdBilledFofoIds.contains(fofoId);
1346
 
35757 ranu 1347
            // Status assignment with same priority as getRbmCallTargetModels
35645 ranu 1348
            String status;
1349
            if (rank == 1) {
1350
                status = "Plan Today";
1351
            } else if (rank == 2) {
1352
                status = "Carry Forward";
35757 ranu 1353
            } else if (hasZeroBilling) {
1354
                status = "Zero Billing";
35645 ranu 1355
            } else if (rank == 3) {
1356
                status = "Untouched";
1357
            } else if (rank == 4) {
1358
                status = "Future Plan";
1359
            } else {
1360
                status = "Normal";
1361
            }
1362
 
1363
            CustomRetailer retailer = retailerMap.get(fofoId);
1364
            String partnerName = retailer != null ? retailer.getBusinessName() : "Unknown (" + fofoId + ")";
1365
            String partnerCode = retailer != null ? retailer.getCode() : "-";
1366
 
1367
            rows.add(Arrays.asList(partnerName, partnerCode, status, rbmName));
1368
        }
1369
 
1370
        return rows;
1371
    }
1372
 
33917 ranu 1373
}