Subversion Repositories SmartDukaan

Rev

Rev 35672 | Rev 35702 | 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;
10
import com.spice.profitmandi.dao.entity.cs.Position;
11
import com.spice.profitmandi.dao.entity.cs.Ticket;
12
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
34397 ranu 13
import com.spice.profitmandi.dao.entity.fofo.MonthlyTarget;
33985 ranu 14
import com.spice.profitmandi.dao.entity.inventory.RbmAchievements;
33926 ranu 15
import com.spice.profitmandi.dao.entity.inventory.RbmTargets;
35631 ranu 16
import com.spice.profitmandi.dao.enumuration.auth.CollectionRemark;
17
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
33917 ranu 18
import com.spice.profitmandi.dao.model.*;
35631 ranu 19
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
20
import com.spice.profitmandi.dao.repository.auth.PartnerCollectionRemarkRepository;
21
import com.spice.profitmandi.dao.repository.auth.RbmCallSequenceLogRepository;
33985 ranu 22
import com.spice.profitmandi.dao.repository.catalog.RbmAchievementsRepository;
33926 ranu 23
import com.spice.profitmandi.dao.repository.catalog.RbmTargetsRepository;
35631 ranu 24
import com.spice.profitmandi.dao.repository.cs.CsService;
25
import com.spice.profitmandi.dao.repository.cs.PositionRepository;
26
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
34397 ranu 27
import com.spice.profitmandi.dao.repository.fofo.MonthlyTargetRepository;
34880 ranu 28
import com.spice.profitmandi.dao.repository.logistics.PublicHolidaysRepository;
35631 ranu 29
import com.spice.profitmandi.dao.repository.transaction.LoanRepository;
34397 ranu 30
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
35631 ranu 31
import com.spice.profitmandi.service.user.RetailerService;
33917 ranu 32
import org.apache.logging.log4j.LogManager;
33
import org.apache.logging.log4j.Logger;
34
import org.hibernate.Session;
35
import org.hibernate.SessionFactory;
36
import org.hibernate.query.NativeQuery;
37
import org.springframework.beans.factory.annotation.Autowired;
38
import org.springframework.stereotype.Component;
39
 
40
import javax.persistence.TypedQuery;
34880 ranu 41
import java.time.*;
35631 ranu 42
import java.time.format.DateTimeFormatter;
34880 ranu 43
import java.time.temporal.ChronoUnit;
35631 ranu 44
import java.util.*;
33997 ranu 45
import java.util.stream.Collectors;
33917 ranu 46
 
47
@Component
48
public class RbmTargetServiceImpl implements RbmTargetService {
49
    private static final Logger LOGGER = LogManager.getLogger(RbmTargetServiceImpl.class);
50
 
51
    @Autowired
52
    SessionFactory sessionFactory;
53
 
33926 ranu 54
    @Autowired
55
    RbmTargetsRepository rbmTargetsRepository;
33917 ranu 56
 
33985 ranu 57
    @Autowired
58
    RbmAchievementsRepository rbmAchievementsRepository;
59
 
34397 ranu 60
    @Autowired
61
    MonthlyTargetRepository monthlyTargetRepository;
62
 
34880 ranu 63
    @Autowired
64
    PublicHolidaysRepository publicHolidaysRepository;
65
 
35631 ranu 66
    @Autowired
67
    RetailerService retailerService;
68
 
33917 ranu 69
    @Override
70
    public List<WarehouseRbmTargetModel> getWarehouseWiseRbmMonthlyTarget() {
71
        Session session = sessionFactory.getCurrentSession();
72
        final TypedQuery<WarehouseRbmTargetModel> typedQuerySimilar = session.createNamedQuery("RbmTarget.getWarehouseWiseMonthlyTarget", WarehouseRbmTargetModel.class);
73
 
74
        return typedQuerySimilar.getResultList();
75
 
76
    }
77
 
78
    @Override
79
    public List<MTDAchievedTargetModel> getDateWiseAchievedTargetOfRbm(LocalDate startDate, LocalDate endDate) {
80
        Session session = sessionFactory.getCurrentSession();
81
        final TypedQuery<MTDAchievedTargetModel> typedQuerySimilar = session.createNamedQuery("RbmTarget.getRbmAchievedMonthlyTarget", MTDAchievedTargetModel.class);
82
        typedQuerySimilar.setParameter("startDate", startDate);
83
        typedQuerySimilar.setParameter("endDate", endDate);
84
        return typedQuerySimilar.getResultList();
85
 
86
    }
87
 
88
    @Override
34055 ranu 89
    public List<TodayAchievedMovementModel> getMovementWiseAchievementByDate(LocalDate startDate, LocalDate endDate) {
33917 ranu 90
        LOGGER.info("start date {}, end date {}", startDate, endDate);
91
        Session session = sessionFactory.getCurrentSession();
34055 ranu 92
        final TypedQuery<TodayAchievedMovementModel> typedQuerySimilar = session.createNamedQuery("RBMTarget.TodayAchivementByMovement", TodayAchievedMovementModel.class);
33917 ranu 93
        typedQuerySimilar.setParameter("startDate", startDate);
94
        typedQuerySimilar.setParameter("endDate", endDate);
95
        return typedQuerySimilar.getResultList();
96
 
97
    }
98
 
99
    @Override
100
    public List<WarehouseMobileStockByMovementModel> getWarehouseMobileStockByMovement() {
101
        Session session = sessionFactory.getCurrentSession();
102
        final TypedQuery<WarehouseMobileStockByMovementModel> typedQuerySimilar = session.createNamedQuery("WarehouseStock.MovementWiseMobileStock", WarehouseMobileStockByMovementModel.class);
103
 
104
        return typedQuerySimilar.getResultList();
105
 
106
    }
107
 
33991 ranu 108
    @Override
109
    public List<SoldCatalogsReportModel> getCatalogSoldReport(LocalDate startDate, LocalDate endDate) {
110
        Session session = sessionFactory.getCurrentSession();
111
        final TypedQuery<SoldCatalogsReportModel> typedQuerySimilar = session.createNamedQuery("CatalogsReport.SoldCatalogsReport", SoldCatalogsReportModel.class);
112
        typedQuerySimilar.setParameter("startDate", startDate);
113
        typedQuerySimilar.setParameter("endDate", endDate);
114
        return typedQuerySimilar.getResultList();
33917 ranu 115
 
33991 ranu 116
    }
117
 
118
 
33917 ranu 119
    public int getWorkingDaysCount(LocalDate startDate) {
120
        Session session = sessionFactory.getCurrentSession();
121
 
122
        // Convert the LocalDate to a format MySQL can interpret
123
        String startDateString = startDate.toString();
124
 
125
        final NativeQuery<?> nativeQuery = session.createNativeQuery(
126
                "SELECT (DATEDIFF(LAST_DAY(:startDate), :startDate) + 1) " +
127
                        " - (FLOOR((DATEDIFF(LAST_DAY(:startDate), :startDate) + (WEEKDAY(:startDate) + 1)) / 7)) " +
128
                        " - (SELECT COUNT(*) " +
129
                        " FROM logistics.publicholidays " +
130
                        " WHERE date BETWEEN :startDate AND LAST_DAY(:startDate) " +
131
                        " AND WEEKDAY(date) != 6) AS working_days"
132
        );
133
 
134
        // Set the start date parameter for each placeholder
135
        nativeQuery.setParameter("startDate", startDateString);
136
 
137
        Object result = nativeQuery.getSingleResult();
138
        return result != null ? ((Number) result).intValue() : 0;
139
    }
140
 
141
 
35044 ranu 142
 
33917 ranu 143
    @Override
144
    public List<RbmArrViewModel> getRbmTodayArr() throws Exception {
145
        LocalDate todayDate = LocalDate.now();
146
        return getRbmTodayArr(todayDate);
147
    }
148
 
149
    @Override
33997 ranu 150
    public List<RbmTargetAndAchievementsModel> getRbmTargetsAndAchievemnts(LocalDate startDate, LocalDate endDate) {
151
 
34002 ranu 152
        List<RbmTargetsModel> rbmTargetsList = rbmTargetsRepository.selectTargetsModelListByDates(startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
33997 ranu 153
 
154
        LOGGER.info("rbmTargetsList {}", rbmTargetsList);
155
        // Group Targtes by RBM and Warehouse
34002 ranu 156
        Map<String, RbmTargetsModel> targetsMap = rbmTargetsList.stream()
33997 ranu 157
                .collect(Collectors.toMap(
158
                        a -> a.getRbmAuthId() + "-" + a.getWarehouseId(),
159
                        a -> a,
160
                        (a1, a2) -> mergeTargets(a1, a2) // Handle duplicates by merging
161
                ));
162
 
163
 
34002 ranu 164
        List<RbmAchievementsModel> rbmAchievements = rbmAchievementsRepository.selectAchievementsModelListByDates(startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
33997 ranu 165
        LOGGER.info("rbmTargetsList {}", rbmAchievements);
166
        // Group achievements by RBM and Warehouse
34002 ranu 167
        Map<String, RbmAchievementsModel> achievementMap = rbmAchievements.stream()
33997 ranu 168
                .collect(Collectors.toMap(
169
                        a -> a.getRbmAuthId() + "-" + a.getWarehouseId(),
170
                        a -> a,
171
                        (a1, a2) -> mergeAchievements(a1, a2) // Handle duplicates by merging
172
                ));
173
 
174
        return targetsMap.keySet().stream()
175
                .map(key -> {
176
                    String[] parts = key.split("-");
177
                    int rbmAuthId = Integer.parseInt(parts[0]);
178
                    int warehouseId = Integer.parseInt(parts[1]);
179
 
34002 ranu 180
                    RbmTargetsModel target = targetsMap.get(key);
181
                    RbmAchievementsModel achievement = achievementMap.getOrDefault(key, new RbmAchievementsModel());
33997 ranu 182
 
183
                    RbmTargetAndAchievementsModel model = new RbmTargetAndAchievementsModel();
184
                    model.setAuthId(rbmAuthId);
185
                    model.setRbmName(target.getRbmName());
186
                    model.setWarehouseName(ProfitMandiConstants.WAREHOUSE_MAP.getOrDefault(warehouseId, "Unknown"));
187
 
188
                    // Set target values
34006 ranu 189
                    model.setHidTarget((long) target.getHidTarget());
34098 ranu 190
                    model.setRunningTarget((long) target.getRunningTarget());
34006 ranu 191
                    model.setFastMovingTarget((long) target.getFastMovingTarget());
192
                    model.setSlowMovingTarget((long) target.getSlowMovingTarget());
193
                    model.setOtherMovingTarget((long) target.getOtherTarget());
33997 ranu 194
 
195
                    // Set achievement values
34006 ranu 196
                    model.setAchievedHid((long) achievement.getAchievedHidTarget());
34098 ranu 197
                    model.setAchievedRunning((long) achievement.getAchievedRunningTarget());
34006 ranu 198
                    model.setAchievedFastMoving((long) achievement.getAchievedFastMovingTarget());
199
                    model.setAchievedSlowMoving((long) achievement.getAchievedSlowMovingTarget());
200
                    model.setAchievedOtherMoving((long) achievement.getAchievedOtherTarget());
33997 ranu 201
 
202
                    model.setTotalTarget(
34006 ranu 203
                            (long) target.getHidTarget() +
34098 ranu 204
                                    (long) target.getRunningTarget() +
34006 ranu 205
                                    (long) target.getFastMovingTarget() +
206
                                    (long) target.getSlowMovingTarget() +
207
                                    (long) target.getOtherTarget()
33997 ranu 208
                    );
209
                    model.setTotalAchievemnt(
34006 ranu 210
                            (long) achievement.getAchievedHidTarget() +
34098 ranu 211
                                    (long) achievement.getAchievedRunningTarget() +
34006 ranu 212
                                    (long) achievement.getAchievedFastMovingTarget() +
213
                                    (long) achievement.getAchievedSlowMovingTarget() +
214
                                    (long) achievement.getAchievedOtherTarget()
33997 ranu 215
                    );
216
 
217
                    return model;
218
                })
219
                .collect(Collectors.toList());
220
 
221
    }
222
 
34002 ranu 223
    private RbmTargetsModel mergeTargets(RbmTargetsModel a1, RbmTargetsModel a2) {
33997 ranu 224
 
225
        // Merge logic for achievements (aggregate the target and achieved values)
34006 ranu 226
        a1.setHidTarget((a1.getHidTarget()) +
227
                (a2.getHidTarget()));
33997 ranu 228
 
34006 ranu 229
        a1.setFastMovingTarget((a1.getFastMovingTarget()) +
230
                (a2.getFastMovingTarget()));
33997 ranu 231
 
34006 ranu 232
        a1.setSlowMovingTarget((a1.getSlowMovingTarget()) +
233
                (a2.getSlowMovingTarget()));
33997 ranu 234
 
34098 ranu 235
        a1.setRunningTarget((a1.getRunningTarget()) +
236
                (a2.getRunningTarget()));
33997 ranu 237
 
34006 ranu 238
        a1.setOtherTarget((a1.getOtherTarget()) +
239
                (a2.getOtherTarget()));
33997 ranu 240
        return a1;
241
    }
242
 
34002 ranu 243
    private RbmAchievementsModel mergeAchievements(RbmAchievementsModel a1, RbmAchievementsModel a2) {
33997 ranu 244
        // Merge logic for achievements (aggregate the target and achieved values)
34006 ranu 245
        a1.setAchievedHidTarget((a1.getAchievedHidTarget()) +
246
                (a2.getAchievedHidTarget()));
33997 ranu 247
 
34098 ranu 248
        a1.setAchievedRunningTarget((a1.getAchievedRunningTarget()) +
249
                (a2.getAchievedRunningTarget()));
33997 ranu 250
 
34006 ranu 251
        a1.setAchievedFastMovingTarget((a1.getAchievedFastMovingTarget()) +
252
                (a2.getAchievedFastMovingTarget()));
33997 ranu 253
 
34006 ranu 254
        a1.setAchievedSlowMovingTarget((a1.getAchievedSlowMovingTarget()) +
255
                (a2.getAchievedSlowMovingTarget()));
33997 ranu 256
 
34006 ranu 257
        a1.setAchievedOtherTarget((a1.getAchievedOtherTarget()) +
258
                (a2.getAchievedOtherTarget()));
33997 ranu 259
 
260
        return a1;
261
    }
34002 ranu 262
 
33997 ranu 263
    @Override
33917 ranu 264
    public List<RbmArrViewModel> getRbmTodayArr(LocalDate todayDate) throws Exception {
265
 
266
        LocalDate startDateOfMonthDay1 = LocalDate.now().withDayOfMonth(1);
267
 
34289 ranu 268
        List<WarehouseRbmTargetModel> warehouseRbmTargetModelList = this.getWarehouseWiseRbmMonthlyTarget();
269
        List<WarehouseRbmTargetModel> warehouseRbmTargetModels = warehouseRbmTargetModelList.stream().filter(x -> x.getMonthlyTarget() > 0).collect(Collectors.toList());
270
        LOGGER.info("warehouseRbmTargetModels {}", warehouseRbmTargetModels);
271
        List<TodayAchievedMovementModel> todayAchievedMovementModels = getMovementWiseAchievementByDate(todayDate, todayDate.plusDays(1));
33917 ranu 272
 
273
        List<MTDAchievedTargetModel> mtdAchievedTargetModels = getDateWiseAchievedTargetOfRbm(startDateOfMonthDay1, todayDate);
274
 
35044 ranu 275
        int remainingWorkingDaysCount = (int) getRemainingDaysInMonth(todayDate);
33917 ranu 276
 
33926 ranu 277
        List<RbmTargets> todayRbmTargetsList = rbmTargetsRepository.selectTargetsByDates(todayDate.atStartOfDay(), todayDate.atTime(LocalTime.MAX));
33917 ranu 278
 
33926 ranu 279
        LOGGER.info("todayRbmTargetsList {}", todayRbmTargetsList);
33917 ranu 280
 
281
        List<RbmArrViewModel> rbmArrViewModels = new ArrayList<>();
282
 
34028 ranu 283
        if (!todayRbmTargetsList.isEmpty()) {
33917 ranu 284
 
35454 amit 285
            // OPTIMIZED: Pre-build maps for O(1) lookup instead of O(n) filter in each iteration
286
            // Map key: "authId-warehouseId"
287
            Map<String, Double> mtdAchievedMap = mtdAchievedTargetModels.stream()
288
                    .collect(Collectors.groupingBy(
289
                            x -> x.getAuthId() + "-" + x.getWarehouseId(),
290
                            Collectors.summingDouble(MTDAchievedTargetModel::getAcheivedMonthlyTarget)
291
                    ));
292
 
293
            Map<String, TodayAchievedMovementModel> todayAchievedMap = todayAchievedMovementModels.stream()
294
                    .collect(Collectors.toMap(
295
                            x -> x.getAuthId() + "-" + x.getWarehouseId(),
296
                            x -> x,
297
                            (a, b) -> a
298
                    ));
299
 
300
            Map<String, RbmTargets> todayRbmTargetsMap = todayRbmTargetsList.stream()
301
                    .collect(Collectors.toMap(
302
                            x -> x.getRbmAuthId() + "-" + x.getWarehouseId(),
303
                            x -> x,
304
                            (a, b) -> a
305
                    ));
306
 
34028 ranu 307
            for (WarehouseRbmTargetModel rbmTarget : warehouseRbmTargetModels) {
33917 ranu 308
 
35454 amit 309
                String lookupKey = rbmTarget.getAuthId() + "-" + rbmTarget.getWarehouseId();
310
 
34028 ranu 311
                float monthlyTarget = rbmTarget.getMonthlyTarget();
35454 amit 312
                float achievedSoFar = mtdAchievedMap.getOrDefault(lookupKey, 0.0).floatValue();
33917 ranu 313
 
34028 ranu 314
                float remainingTarget = monthlyTarget - achievedSoFar;
33953 ranu 315
 
34028 ranu 316
                float todayTarget = (remainingWorkingDaysCount > 0 && remainingTarget > 0) ? remainingTarget / remainingWorkingDaysCount : 0;
317
 
33926 ranu 318
                String warehouseName = ProfitMandiConstants.WAREHOUSE_MAP.getOrDefault(rbmTarget.getWarehouseId(), "Unknown");
33917 ranu 319
 
34288 ranu 320
                LOGGER.info("rbmTarget ==== {}", rbmTarget);
34281 ranu 321
 
35454 amit 322
                TodayAchievedMovementModel todayAchievedMovementModel = todayAchievedMap.get(lookupKey);
34283 ranu 323
 
35454 amit 324
                RbmTargets todayRbmTargets = todayRbmTargetsMap.get(lookupKey);
34285 ranu 325
 
35454 amit 326
                if (todayRbmTargets != null) {
34034 ranu 327
                    LOGGER.info("todayRbmTargets {}", todayRbmTargets);
328
                    RbmArrViewModel viewModel = new RbmArrViewModel();
33917 ranu 329
 
34034 ranu 330
                    viewModel.setAuthId(rbmTarget.getAuthId());
331
                    viewModel.setRbmName(rbmTarget.getRbmName());
332
                    viewModel.setWarehouseName(warehouseName);
333
                    viewModel.setTodayTarget(Math.round(todayTarget));
334
                    viewModel.setMonthlyTarget(Math.round(monthlyTarget));
335
                    viewModel.setMtdAchievedTarget(Math.round(achievedSoFar));
33926 ranu 336
 
34034 ranu 337
                    viewModel.setTodayHidTarget(Math.round((todayRbmTargets.getHidTarget())));
338
                    viewModel.setTodayFastMovingTarget(Math.round(todayRbmTargets.getFastMovingTarget()));
34098 ranu 339
                    viewModel.setTodaySlowMovingTarget(Math.round(todayRbmTargets.getSlowMovingtarget()));
340
                    viewModel.setTodayRunningTarget(Math.round(todayRbmTargets.getRunningtarget()));
34034 ranu 341
                    viewModel.setTodayOtherMovingTarget(Math.round(todayRbmTargets.getOtherTarget()));
33926 ranu 342
 
34283 ranu 343
                    if (todayAchievedMovementModel != null) {
344
                        viewModel.setTodayAchievedHidTarget(Math.round(todayAchievedMovementModel.getHidBilled()));
345
                        viewModel.setTodayAchievedFastMovingTarget(Math.round(todayAchievedMovementModel.getFastMovingBilled()));
346
                        viewModel.setTodayAchievedSlowMovingTarget(Math.round(todayAchievedMovementModel.getSlowMovinBilled()));
347
                        viewModel.setTodayAchievedRunningTarget(Math.round(todayAchievedMovementModel.getRunningBilled()));
348
                        viewModel.setTodayAchievedOtherMovingTarget(Math.round(todayAchievedMovementModel.getOtherBilled()));
349
                        viewModel.setTotalAchievedTarget(Math.round(todayAchievedMovementModel.getHidBilled() + todayAchievedMovementModel.getFastMovingBilled() + todayAchievedMovementModel.getSlowMovinBilled() + todayAchievedMovementModel.getRunningBilled() + todayAchievedMovementModel.getOtherBilled()));
350
                    } else {
351
                        viewModel.setTodayAchievedHidTarget(0);
352
                        viewModel.setTodayAchievedFastMovingTarget(0);
353
                        viewModel.setTodayAchievedSlowMovingTarget(0);
354
                        viewModel.setTodayAchievedRunningTarget(0);
355
                        viewModel.setTodayAchievedOtherMovingTarget(0);
356
                        viewModel.setTotalAchievedTarget(0);
357
                    }
34034 ranu 358
                    rbmArrViewModels.add(viewModel);
359
                } else {
360
                    LOGGER.info("No matching RbmTargets found for AuthId: {} and rbmname {} and WarehouseId: {}", rbmTarget.getAuthId(), rbmTarget.getRbmName(), rbmTarget.getWarehouseId());
361
                }
33917 ranu 362
 
34034 ranu 363
 
364
 
34028 ranu 365
            }
33917 ranu 366
        }
367
 
368
        LOGGER.info("rbmArrViewModels {}", rbmArrViewModels);
369
        return rbmArrViewModels;
370
    }
371
 
33926 ranu 372
    @Override
373
    public void setMovementWiseRbmTargets() {
374
        LocalDate todayDate = LocalDate.now();
33917 ranu 375
 
33926 ranu 376
        LocalDate startDateOfMonthDay1 = LocalDate.now().withDayOfMonth(1);
377
 
378
        List<WarehouseRbmTargetModel> warehouseRbmTargetModels = this.getWarehouseWiseRbmMonthlyTarget();
379
 
380
        List<MTDAchievedTargetModel> mtdAchievedTargetModels = getDateWiseAchievedTargetOfRbm(startDateOfMonthDay1, todayDate);
381
 
382
 
35044 ranu 383
        int remainingWorkingDaysCount = (int) getRemainingDaysInMonth(todayDate);
33926 ranu 384
 
385
        List<WarehouseMobileStockByMovementModel> warehouseMobileStockByMovementModels = getWarehouseMobileStockByMovement();
386
 
35454 amit 387
        // OPTIMIZED: Pre-build maps for O(1) lookup instead of O(n) filter in each iteration
388
        Map<String, Double> mtdAchievedMap = mtdAchievedTargetModels.stream()
389
                .collect(Collectors.groupingBy(
390
                        x -> x.getAuthId() + "-" + x.getWarehouseId(),
391
                        Collectors.summingDouble(MTDAchievedTargetModel::getAcheivedMonthlyTarget)
392
                ));
393
 
394
        Map<Integer, WarehouseMobileStockByMovementModel> warehouseStockMap = warehouseMobileStockByMovementModels.stream()
395
                .collect(Collectors.toMap(
396
                        WarehouseMobileStockByMovementModel::getWarehouseId,
397
                        x -> x,
398
                        (a, b) -> a
399
                ));
400
 
33926 ranu 401
        for (WarehouseRbmTargetModel rbmTarget : warehouseRbmTargetModels) {
402
 
35454 amit 403
            String lookupKey = rbmTarget.getAuthId() + "-" + rbmTarget.getWarehouseId();
404
 
33926 ranu 405
            float monthlyTarget = rbmTarget.getMonthlyTarget();
35454 amit 406
            float achievedSoFar = mtdAchievedMap.getOrDefault(lookupKey, 0.0).floatValue();
33926 ranu 407
 
408
 
409
            float remainingTarget = monthlyTarget - achievedSoFar;
33953 ranu 410
            LOGGER.info("remainingTarget {}", remainingTarget);
33926 ranu 411
 
33953 ranu 412
            float todayTarget = (remainingWorkingDaysCount > 0 && remainingTarget > 0) ? remainingTarget / remainingWorkingDaysCount : 0;
413
            LOGGER.info("todayTarget {}", todayTarget);
414
 
33926 ranu 415
            // Get the warehouse stock data
35454 amit 416
            WarehouseMobileStockByMovementModel warehouseMobileStockByMovementModel = warehouseStockMap.get(rbmTarget.getWarehouseId());
33926 ranu 417
 
418
 
419
            if (warehouseMobileStockByMovementModel != null) {
420
 
421
                // Total stock value for this warehouse
422
                float totalStockValue = warehouseMobileStockByMovementModel.getTotalAvailabilityPrice();
423
 
424
                // Calculate target allocation based on stock value proportion
425
                float hidTarget = (warehouseMobileStockByMovementModel.getTotalHidCatalogPrice() / totalStockValue) * todayTarget;
426
                float fastMovingTarget = (warehouseMobileStockByMovementModel.getTotalFastMovingCatalogPrice() / totalStockValue) * todayTarget;
427
                float slowMovingTarget = (warehouseMobileStockByMovementModel.getTotalSlowMovingCatalogPrice() / totalStockValue) * todayTarget;
34098 ranu 428
                float runningTarget = (warehouseMobileStockByMovementModel.getTotalRunningCatalogPrice() / totalStockValue) * todayTarget;
33926 ranu 429
                float otherTarget = (warehouseMobileStockByMovementModel.getTotalOtherCategoryCatalogPrice() / totalStockValue) * todayTarget;
430
 
431
                RbmTargets rbmTargets = new RbmTargets();
432
                rbmTargets.setWarehouseId(rbmTarget.getWarehouseId());
433
                rbmTargets.setRbmAuthId(rbmTarget.getAuthId());
434
                rbmTargets.setRbmName(rbmTarget.getRbmName());
34098 ranu 435
                rbmTargets.setRunningtarget(runningTarget);
33926 ranu 436
                rbmTargets.setHidTarget(hidTarget);
437
                rbmTargets.setFastMovingTarget(fastMovingTarget);
34098 ranu 438
                rbmTargets.setSlowMovingtarget(slowMovingTarget);
33926 ranu 439
                rbmTargets.setOtherTarget(otherTarget);
440
                rbmTargets.setCreateTimestamp(LocalDateTime.now());
441
 
442
                rbmTargetsRepository.persist(rbmTargets);
443
 
444
            }
445
        }
446
 
447
    }
448
 
449
 
33985 ranu 450
    @Override
451
    public void setMovementWiseRbmAchievement() {
452
        LocalDate todayDate = LocalDate.now();
453
 
34055 ranu 454
        List<TodayAchievedMovementModel> todayAchievedMovementModels = getMovementWiseAchievementByDate(todayDate, todayDate.plusDays(1));
33985 ranu 455
 
456
 
457
        for (TodayAchievedMovementModel achievement : todayAchievedMovementModels) {
458
 
459
            RbmAchievements rbmAchievements = new RbmAchievements();
460
 
461
            rbmAchievements.setRbmAuthId(achievement.getAuthId());
462
            rbmAchievements.setRbmName(achievement.getRbmName());
463
            rbmAchievements.setWarehouseId(achievement.getWarehouseId());
464
            rbmAchievements.setAchievedHidTarget(achievement.getHidBilled());
465
            rbmAchievements.setAchievedFastMovingTarget(achievement.getFastMovingBilled());
34098 ranu 466
            rbmAchievements.setAchievedSlowMovingTarget(achievement.getSlowMovinBilled());
467
            rbmAchievements.setAchievedRunningTarget(achievement.getRunningBilled());
34012 ranu 468
            rbmAchievements.setAchievedOtherTarget(achievement.getOtherBilled());
33985 ranu 469
            rbmAchievements.setCreateTimestamp(LocalDateTime.now());
470
 
471
            rbmAchievementsRepository.persist(rbmAchievements);
472
 
473
        }
474
 
475
    }
476
 
34055 ranu 477
    @Override
478
    public List<Sold15daysOldAgingModel> getAgingSale(LocalDate startDate, LocalDate endDate) {
479
        Session session = sessionFactory.getCurrentSession();
480
        final TypedQuery<Sold15daysOldAgingModel> typedQuerySimilar = session.createNamedQuery("Aging.SoldAgingModel", Sold15daysOldAgingModel.class);
34056 ranu 481
        typedQuerySimilar.setParameter("startDate", startDate);
482
        typedQuerySimilar.setParameter("endDate", endDate);
34055 ranu 483
        return typedQuerySimilar.getResultList();
33985 ranu 484
 
34055 ranu 485
    }
486
 
34103 ranu 487
    @Override
488
    public List<RbmBilledFofoIdsModel> getDateWiseBilledFofoIdByRbm(LocalDate startDate, LocalDate endDate) {
489
        Session session = sessionFactory.getCurrentSession();
490
        final TypedQuery<RbmBilledFofoIdsModel> typedQuerySimilar = session.createNamedQuery("RBM.RbmBilledFofoId", RbmBilledFofoIdsModel.class);
491
        typedQuerySimilar.setParameter("startDate", startDate);
492
        typedQuerySimilar.setParameter("endDate", endDate);
493
        return typedQuerySimilar.getResultList();
35453 amit 494
    }
34103 ranu 495
 
35453 amit 496
    @Override
497
    public List<RbmWeeklyBillingModel> getWeeklyBillingDataForMonth(LocalDate monthStart, LocalDate monthEnd) {
498
        Session session = sessionFactory.getCurrentSession();
499
        final TypedQuery<RbmWeeklyBillingModel> typedQuery = session.createNamedQuery("RBM.WeeklyBilling", RbmWeeklyBillingModel.class);
500
        typedQuery.setParameter("startDate", monthStart);
501
        typedQuery.setParameter("endDate", monthEnd);
502
        return typedQuery.getResultList();
34103 ranu 503
    }
504
 
34055 ranu 505
    public List<Our15DaysOldAgingStock> our15DaysAgingStock() {
506
        Session session = sessionFactory.getCurrentSession();
507
        final TypedQuery<Our15DaysOldAgingStock> typedQuerySimilar = session.createNamedQuery("Aging.15DaysOurStock", Our15DaysOldAgingStock.class);
508
        return typedQuerySimilar.getResultList();
509
 
510
    }
511
 
34397 ranu 512
    @Autowired
513
    OrderRepository orderRepository;
34055 ranu 514
 
34397 ranu 515
    @Override
34641 ranu 516
    public double calculateFofoIdTodayTarget(int fofoId, double secondryMtd,LocalDate date) {
34397 ranu 517
 
518
        MonthlyTarget monthlyTarget = monthlyTargetRepository.selectByDateAndFofoId(YearMonth.now(), fofoId);
34404 ranu 519
        if (monthlyTarget == null) {
520
            // Log or handle as needed
521
            return 0; // or -1 or some fallback
522
        }
34397 ranu 523
 
524
        double remainingTarget = monthlyTarget.getPurchaseTarget() - secondryMtd;
34880 ranu 525
//        double remainingWorkingDays = getWorkingDaysCount(date);
526
        double remainingWorkingDays = (double) getRemainingDaysInMonth(date);
34397 ranu 527
 
528
 
34716 ranu 529
 
34397 ranu 530
        if (remainingWorkingDays == 0) return remainingTarget; // Last day
34716 ranu 531
        LOGGER.info("remainingWorkingDays {}", remainingWorkingDays);
532
        LOGGER.info("remainingTarget {}", remainingTarget);
34397 ranu 533
 
534
        return (int) Math.ceil(remainingTarget / remainingWorkingDays);
535
    }
536
 
34880 ranu 537
    @Override
538
    public long getRemainingDaysInMonth(LocalDate date) {
539
        LocalDate lastDayOfMonth = YearMonth.from(date).atEndOfMonth();
34397 ranu 540
 
34880 ranu 541
        long totalDays = ChronoUnit.DAYS.between(date, lastDayOfMonth) + 1;
34397 ranu 542
 
34880 ranu 543
        // Count Sundays manually
544
        long sundayCount = 0;
545
        LocalDate current = date;
546
        while (!current.isAfter(lastDayOfMonth)) {
547
            if (current.getDayOfWeek() == DayOfWeek.SUNDAY) {
548
                sundayCount++;
549
            }
550
            current = current.plusDays(1);
551
        }
552
 
553
        // Public holidays in the range
554
        long publicHolidays = publicHolidaysRepository
555
                .selectAllBetweenDates(date, lastDayOfMonth)
556
                .size();
557
 
558
        long remainingDays = totalDays - sundayCount - publicHolidays;
559
 
560
        LOGGER.info("remainingDays {}", remainingDays);
561
        LOGGER.info("totalDays {}", totalDays);
562
        LOGGER.info("sundays {}", sundayCount);
563
        LOGGER.info("publicHolidays {}", publicHolidays);
564
 
565
        return remainingDays;
566
    }
567
 
35631 ranu 568
    @Autowired
569
    PositionRepository positionRepository;
34880 ranu 570
 
35631 ranu 571
    @Autowired
572
    CsService csService;
34880 ranu 573
 
35631 ranu 574
    @Autowired
575
    FofoStoreRepository fofoStoreRepository;
576
 
577
    @Autowired
578
    AuthRepository authRepository;
579
 
580
    @Autowired
581
    LoanRepository loanRepository;
582
 
583
    @Autowired
584
    PartnerCollectionService partnerCollectionService;
585
 
586
    @Autowired
587
    PartnerCollectionRemarkRepository partnerCollectionRemarkRepository;
588
 
589
    @Autowired
590
    RbmCallSequenceLogRepository rbmCallSequenceLogRepository;
591
 
592
    @Autowired
593
    com.spice.profitmandi.dao.repository.cs.TicketRepository ticketRepository;
594
 
595
    @Override
596
    public List<RbmCallTargetModel> getRbmCallTargetModels() throws Exception {
597
        long methodStart = System.currentTimeMillis();
598
        List<RbmCallTargetModel> rbmCallTargetModels = new ArrayList<>();
599
 
600
        // Get all RBM positions (L1 and L2)
601
        long start = System.currentTimeMillis();
602
        List<Position> allRbmPositions = positionRepository
603
                .selectPositionByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_RBM).stream()
604
                .filter(x -> Arrays.asList(EscalationType.L1, EscalationType.L2).contains(x.getEscalationType()))
605
                .collect(Collectors.toList());
606
 
607
        // Separate L1 and L2 auth IDs
608
        List<Integer> l1AuthIds = allRbmPositions.stream()
609
                .filter(p -> EscalationType.L1.equals(p.getEscalationType()))
610
                .map(Position::getAuthUserId).distinct().collect(Collectors.toList());
611
        List<Integer> l2AuthIds = allRbmPositions.stream()
612
                .filter(p -> EscalationType.L2.equals(p.getEscalationType()))
613
                .map(Position::getAuthUserId).distinct().collect(Collectors.toList());
614
 
615
        // Union of all auth IDs for batch fetching
616
        List<Integer> rbmPositionsAuthIds = allRbmPositions.stream()
617
                .map(Position::getAuthUserId).distinct().collect(Collectors.toList());
618
        LOGGER.info("RBM Call Target - RBM positions fetch: {}ms, L1: {}, L2: {}", System.currentTimeMillis() - start, l1AuthIds.size(), l2AuthIds.size());
619
 
620
        start = System.currentTimeMillis();
621
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
622
        LOGGER.info("RBM Call Target - StoreGuyMap fetch: {}ms", System.currentTimeMillis() - start);
623
 
624
        LocalDateTime startDate = LocalDate.now().atStartOfDay();
625
        LocalDate firstOfMonth = LocalDate.now().withDayOfMonth(1);
626
        LocalDate endOfMonth = LocalDate.now().withDayOfMonth(LocalDate.now().lengthOfMonth()).plusDays(1);
627
 
628
        // Get auth user map
629
        start = System.currentTimeMillis();
630
        Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(rbmPositionsAuthIds).stream()
631
                .collect(Collectors.toMap(AuthUser::getId, au -> au));
632
        LOGGER.info("RBM Call Target - AuthUser fetch: {}ms", System.currentTimeMillis() - start);
633
 
634
        // Batch fetch positions by auth IDs (to check if RBM is L1)
635
        start = System.currentTimeMillis();
636
        Map<Integer, List<Position>> positionsByAuthId = positionRepository.selectPositionByAuthIds(rbmPositionsAuthIds).stream()
637
                .collect(Collectors.groupingBy(Position::getAuthUserId));
638
        LOGGER.info("RBM Call Target - Positions by AuthId fetch: {}ms", System.currentTimeMillis() - start);
639
 
640
        // Get all fofo IDs for all RBMs
641
        Set<Integer> allFofoIds = new HashSet<>();
642
        Map<Integer, List<Integer>> rbmToFofoIdsMap = new HashMap<>();
643
        for (int rbmAuthId : rbmPositionsAuthIds) {
644
            AuthUser au = authUserMap.get(rbmAuthId);
645
            if (au != null && storeGuyMap.containsKey(au.getEmailId())) {
646
                List<Integer> fofoIds = new ArrayList<>(storeGuyMap.get(au.getEmailId()));
647
                allFofoIds.addAll(fofoIds);
648
                rbmToFofoIdsMap.put(rbmAuthId, fofoIds);
649
            }
650
        }
651
        // Fetch escalated tickets for L2 early so their fofoIds are included in batch fetches
652
        List<Ticket> escalatedTickets = Collections.emptyList();
653
        Map<Integer, List<Integer>> l2AuthIdToFofoIds = new HashMap<>();
654
        if (!l2AuthIds.isEmpty()) {
655
            start = System.currentTimeMillis();
656
            escalatedTickets = ticketRepository.selectOpenEscalatedTicketsByAuthIds(l2AuthIds);
657
            LOGGER.info("RBM Call Target - Escalated tickets fetch: {}ms, count: {}", System.currentTimeMillis() - start, escalatedTickets.size());
658
 
659
            for (int l2AuthId : l2AuthIds) {
660
                List<Integer> l2FofoIds = escalatedTickets.stream()
661
                        .filter(t -> t.getL2AuthUser() == l2AuthId
662
                                || t.getL3AuthUser() == l2AuthId
663
                                || t.getL4AuthUser() == l2AuthId
664
                                || t.getL5AuthUser() == l2AuthId)
665
                        .map(Ticket::getFofoId)
666
                        .distinct()
667
                        .collect(Collectors.toList());
668
                l2AuthIdToFofoIds.put(l2AuthId, l2FofoIds);
669
                allFofoIds.addAll(l2FofoIds);
670
            }
671
        }
672
        LOGGER.info("RBM Call Target - Total fofo IDs to process: {}", allFofoIds.size());
673
 
674
        // Get only needed fofo stores (OPTIMIZED - was fetching ALL stores before)
675
        start = System.currentTimeMillis();
676
        Map<Integer, FofoStore> fofoStoresMap = new HashMap<>();
677
        if (!allFofoIds.isEmpty()) {
678
            try {
679
                fofoStoresMap = fofoStoreRepository.selectByRetailerIds(new ArrayList<>(allFofoIds)).stream()
680
                        .collect(Collectors.toMap(FofoStore::getId, x -> x, (a, b) -> a));
681
            } catch (ProfitMandiBusinessException e) {
682
                LOGGER.error("Error fetching fofo stores", e);
683
            }
684
        }
685
        LOGGER.info("RBM Call Target - FofoStores fetch (only needed): {}ms, count: {}", System.currentTimeMillis() - start, fofoStoresMap.size());
686
 
687
        // Batch fetch max remark ids for all fofoIds (for escalation filtering)
688
        start = System.currentTimeMillis();
689
        Map<Integer, PartnerCollectionRemark> allPartnerCollectionRemarks = new HashMap<>();
690
        if (!allFofoIds.isEmpty()) {
691
            List<Integer> allRemarkIds = partnerCollectionRemarkRepository.selectMaxRemarkId(new ArrayList<>(allFofoIds));
692
            if (!allRemarkIds.isEmpty()) {
693
                allPartnerCollectionRemarks = partnerCollectionRemarkRepository.selectByIds(allRemarkIds).stream()
694
                        .collect(Collectors.toMap(PartnerCollectionRemark::getFofoId, x -> x, (a, b) -> a));
695
            }
696
        }
697
        LOGGER.info("RBM Call Target - PartnerCollectionRemarks fetch: {}ms", System.currentTimeMillis() - start);
698
 
699
        // Batch fetch collection RANK map for all fofoIds (OPTIMIZED - only fetches rank, not full model)
700
        start = System.currentTimeMillis();
701
        Map<Integer, Integer> allCollectionRankMap = new HashMap<>();
702
        if (!allFofoIds.isEmpty()) {
703
            try {
704
                allCollectionRankMap = partnerCollectionService.getCollectionRankMap(new ArrayList<>(allFofoIds), startDate);
705
            } catch (ProfitMandiBusinessException e) {
706
                LOGGER.error("Error fetching collection rank map for all fofoIds", e);
707
            }
708
        }
709
        LOGGER.info("RBM Call Target - CollectionRankMap fetch (OPTIMIZED): {}ms", System.currentTimeMillis() - start);
710
 
35669 ranu 711
        // Get MTD billing data for zero billing calculation and partner counts
35631 ranu 712
        start = System.currentTimeMillis();
713
        List<RbmWeeklyBillingModel> mtdBillingData = getWeeklyBillingDataForMonth(firstOfMonth, endOfMonth);
714
        Set<Integer> allMtdBilledFofoIds = mtdBillingData.stream()
715
                .filter(RbmWeeklyBillingModel::isMtdBilled)
716
                .map(RbmWeeklyBillingModel::getFofoId)
717
                .collect(Collectors.toSet());
35669 ranu 718
        // Build partner count and fofoIds per RBM from mtdBillingData (same source as Today ARR page)
719
        Map<Integer, Set<Integer>> mtdFofoIdsByAuthId = mtdBillingData.stream()
720
                .filter(RbmWeeklyBillingModel::isTargetedPartner)
721
                .collect(Collectors.groupingBy(RbmWeeklyBillingModel::getAuthId,
722
                        Collectors.mapping(RbmWeeklyBillingModel::getFofoId, Collectors.toSet())));
35631 ranu 723
        LOGGER.info("RBM Call Target - MTD Billing fetch: {}ms", System.currentTimeMillis() - start);
724
 
725
        // Batch fetch today's remarks for all auth IDs (to calculate Value Achieved)
726
        start = System.currentTimeMillis();
727
        Map<Integer, List<PartnerCollectionRemark>> remarksByAuthId = partnerCollectionRemarkRepository
728
                .selectAllByAuthIdsOnDate(rbmPositionsAuthIds, LocalDate.now()).stream()
729
                .collect(Collectors.groupingBy(PartnerCollectionRemark::getAuthId));
730
        LOGGER.info("RBM Call Target - Today Remarks fetch: {}ms", System.currentTimeMillis() - start);
731
 
732
        // Batch fetch today's out-of-sequence logs for all RBMs
733
        start = System.currentTimeMillis();
734
        LocalDateTime todayStart = LocalDate.now().atStartOfDay();
735
        LocalDateTime todayEnd = LocalDate.now().plusDays(1).atStartOfDay();
736
        List<RbmCallSequenceLog> outOfSequenceLogs = rbmCallSequenceLogRepository.selectOutOfSequenceByDateRange(todayStart, todayEnd);
737
        Map<Integer, Long> outOfSequenceCountByAuthId = outOfSequenceLogs.stream()
35654 ranu 738
                .collect(Collectors.groupingBy(RbmCallSequenceLog::getAuthId,
739
                        Collectors.mapping(RbmCallSequenceLog::getFofoId, Collectors.collectingAndThen(Collectors.toSet(), s -> (long) s.size()))));
35631 ranu 740
        LOGGER.info("RBM Call Target - Out of Sequence fetch: {}ms", System.currentTimeMillis() - start);
741
 
742
        // Process L1 RBMs (existing logic)
743
        for (int rbmAuthId : l1AuthIds) {
744
            AuthUser authUser = authUserMap.get(rbmAuthId);
745
            if (authUser == null || !storeGuyMap.containsKey(authUser.getEmailId())) {
746
                continue;
747
            }
748
 
749
            List<Integer> fofoIdList = rbmToFofoIdsMap.getOrDefault(rbmAuthId, Collections.emptyList());
750
 
751
            // Check if RBM is L1 (same logic as getSummaryModel)
752
            List<Position> positions = positionsByAuthId.getOrDefault(authUser.getId(), Collections.emptyList());
753
            boolean isRBMAndL1 = positions.stream()
754
                    .anyMatch(position ->
755
                            ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId()
756
                                    && EscalationType.L1.equals(position.getEscalationType()));
757
 
758
            // Filter escalated partners for L1 RBMs (same logic as getSummaryModel)
759
            List<Integer> fofoIds = fofoIdList;
760
            if (isRBMAndL1) {
761
                Map<Integer, PartnerCollectionRemark> partnerCollectionRemarks = new HashMap<>();
762
                for (Integer fofoId : fofoIdList) {
763
                    if (allPartnerCollectionRemarks.containsKey(fofoId)) {
764
                        partnerCollectionRemarks.put(fofoId, allPartnerCollectionRemarks.get(fofoId));
765
                    }
766
                }
767
                fofoIds = partnerCollectionRemarks.entrySet().stream()
768
                        .filter(entry -> {
769
                            PartnerCollectionRemark pcrMap = entry.getValue();
770
                            return !(CollectionRemark.RBM_L2_ESCALATION.equals(pcrMap.getRemark())
771
                                    || CollectionRemark.SALES_ESCALATION.equals(pcrMap.getRemark()));
772
                        })
773
                        .map(Map.Entry::getKey)
774
                        .collect(Collectors.toList());
775
            }
776
 
35669 ranu 777
            // Filter to only external, ACTIVE stores (collection plan not required)
35631 ranu 778
            Map<Integer, Integer> finalAllCollectionRankMap = allCollectionRankMap;
779
            Map<Integer, FofoStore> finalFofoStoresMap = fofoStoresMap;
780
            List<Integer> validFofoIds = fofoIds.stream()
781
                    .filter(fofoId -> {
782
                        FofoStore store = finalFofoStoresMap.get(fofoId);
783
                        if (store == null || store.isInternal()) {
784
                            return false;
785
                        }
786
                        // Only include ACTIVE partners (not Low Sale, not Disputed, not Billing Pending)
35669 ranu 787
                        return ActivationType.ACTIVE.equals(store.getActivationType());
35631 ranu 788
                    })
789
                    .collect(Collectors.toList());
790
 
791
            if (validFofoIds.isEmpty()) {
792
                continue;
793
            }
794
 
795
            RbmCallTargetModel targetModel = new RbmCallTargetModel();
796
            targetModel.setAuthId(rbmAuthId);
797
            targetModel.setRbmName(authUser.getFullName());
35669 ranu 798
            // Use partner count from mtdBillingData (same source as Today ARR page)
799
            Set<Integer> mtdFofoIds = mtdFofoIdsByAuthId.getOrDefault(rbmAuthId, Collections.emptySet());
800
            targetModel.setPartnerCount(mtdFofoIds.size());
35631 ranu 801
 
802
            // Categorize each partner - each partner belongs to ONE category only
35665 ranu 803
            // Priority: PlanToday > CarryForward > ZeroBilling > Untouched > FuturePlan > Normal
35631 ranu 804
            Set<Integer> planTodayPartners = new HashSet<>();
805
            Set<Integer> carryForwardPartners = new HashSet<>();
806
            Set<Integer> untouchedPartners = new HashSet<>();
807
            Set<Integer> zeroBillingPartners = new HashSet<>();
808
            Set<Integer> futurePlanPartners = new HashSet<>();
809
            Set<Integer> normalPartners = new HashSet<>();
810
 
811
            for (Integer fofoId : validFofoIds) {
812
                // Get collection plan rank (from optimized rank map)
813
                int rank = allCollectionRankMap.getOrDefault(fofoId, 5); // default to Normal if no plan
814
 
815
                // Check if partner has zero billing in MTD
816
                boolean hasZeroBilling = !allMtdBilledFofoIds.contains(fofoId);
817
 
818
                // Assign to category based on priority
819
                if (rank == 1) {
820
                    planTodayPartners.add(fofoId);
821
                } else if (rank == 2) {
822
                    carryForwardPartners.add(fofoId);
35665 ranu 823
                } else if (hasZeroBilling) {
824
                    zeroBillingPartners.add(fofoId);
35631 ranu 825
                } else if (rank == 3) {
826
                    untouchedPartners.add(fofoId);
827
                } else if (rank == 4) {
828
                    futurePlanPartners.add(fofoId);
829
                } else {
830
                    normalPartners.add(fofoId);
831
                }
832
            }
833
 
834
            // Set counts
835
            targetModel.setCreditCollection(0); // Credit collection is handled in separate list
836
            targetModel.setPlanToday(planTodayPartners.size());
837
            targetModel.setCarryForward(carryForwardPartners.size());
838
            targetModel.setUntouched(untouchedPartners.size());
839
            targetModel.setZeroBilling(zeroBillingPartners.size());
840
            targetModel.setFuturePlan(futurePlanPartners.size());
841
            targetModel.setNormal(normalPartners.size());
842
 
843
            // Today Target = PlanToday + CarryForward + ZeroBilling + Untouched
844
            // These are mutually exclusive now, so we can sum them
845
            long todayTarget = planTodayPartners.size() +
846
                    carryForwardPartners.size() + zeroBillingPartners.size() + untouchedPartners.size();
847
            targetModel.setTodayTargetOfCall(todayTarget);
848
 
849
            // Create set of partners in Today Target categories
850
            Set<Integer> todayTargetPartners = new HashSet<>();
851
            todayTargetPartners.addAll(planTodayPartners);
852
            todayTargetPartners.addAll(carryForwardPartners);
853
            todayTargetPartners.addAll(zeroBillingPartners);
854
            todayTargetPartners.addAll(untouchedPartners);
855
 
856
            // Value Achieved = Partners from Today Target that have been contacted today (have remark today)
857
            List<PartnerCollectionRemark> todayRemarks = remarksByAuthId.getOrDefault(rbmAuthId, Collections.emptyList());
858
            long valueAchieved = todayRemarks.stream()
859
                    .map(PartnerCollectionRemark::getFofoId)
860
                    .filter(todayTargetPartners::contains)
861
                    .distinct()
862
                    .count();
863
            targetModel.setValueTargetAchieved(valueAchieved);
864
 
865
            // Moved to Future = Partners in Future Plan category who have a remark today
866
            // These are partners who were contacted today but moved to a future date
867
            Set<Integer> todayRemarkedFofoIds = todayRemarks.stream()
868
                    .map(PartnerCollectionRemark::getFofoId)
869
                    .collect(Collectors.toSet());
870
            long movedToFuture = futurePlanPartners.stream()
871
                    .filter(todayRemarkedFofoIds::contains)
872
                    .count();
873
            targetModel.setMovedToFuture(movedToFuture);
874
 
875
            // Set out of sequence count for this RBM
876
            targetModel.setOutOfSequenceCount(outOfSequenceCountByAuthId.getOrDefault(rbmAuthId, 0L));
877
 
878
            rbmCallTargetModels.add(targetModel);
879
        }
880
 
881
        // Process L2 RBMs (escalated ticket logic with categorization)
882
        for (int l2AuthId : l2AuthIds) {
883
            AuthUser authUser = authUserMap.get(l2AuthId);
884
            if (authUser == null) {
885
                continue;
886
            }
887
 
888
            List<Integer> l2FofoIdList = l2AuthIdToFofoIds.getOrDefault(l2AuthId, Collections.emptyList());
889
 
35662 ranu 890
            // For L2, use all escalated ticket fofoIds as target (no collection plan filter)
891
            Set<Integer> l2TargetFofoIds = new HashSet<>(l2FofoIdList);
35631 ranu 892
 
893
            RbmCallTargetModel l2Model = new RbmCallTargetModel();
894
            l2Model.setAuthId(l2AuthId);
895
            l2Model.setRbmName(authUser.getFullName() + " (L2)");
896
            l2Model.setL2Position(true);
897
            l2Model.setL2CallingList(l2FofoIdList.size());
898
            // Partner count = total assigned partners (same as L1 source)
899
            List<Integer> l2AssignedFofoIds = rbmToFofoIdsMap.getOrDefault(l2AuthId, Collections.emptyList());
900
            l2Model.setPartnerCount(l2AssignedFofoIds.size());
901
 
35662 ranu 902
            // L2 Target = all escalated ticket fofoIds
903
            l2Model.setTodayTargetOfCall(l2TargetFofoIds.size());
35631 ranu 904
 
35662 ranu 905
            // Value Achieved = distinct fofoIds from today's remarks that are in escalated tickets
906
            List<PartnerCollectionRemark> l2TodayRemarks = remarksByAuthId.getOrDefault(l2AuthId, Collections.emptyList());
907
            long l2ValueAchieved = l2TodayRemarks.stream()
908
                    .map(PartnerCollectionRemark::getFofoId)
909
                    .filter(l2TargetFofoIds::contains)
910
                    .distinct()
911
                    .count();
912
            l2Model.setValueTargetAchieved(l2ValueAchieved);
35631 ranu 913
 
914
            l2Model.setOutOfSequenceCount(outOfSequenceCountByAuthId.getOrDefault(l2AuthId, 0L));
915
            rbmCallTargetModels.add(l2Model);
916
        }
917
 
918
        // Group L1 under their L2 manager using authUser.managerId
919
        Map<Integer, RbmCallTargetModel> l2ModelsByAuthId = new HashMap<>();
920
        Map<Integer, RbmCallTargetModel> l1ModelsByAuthId = new HashMap<>();
921
        for (RbmCallTargetModel m : rbmCallTargetModels) {
922
            if (m.isL2Position()) {
923
                l2ModelsByAuthId.put(m.getAuthId(), m);
924
            } else {
925
                l1ModelsByAuthId.put(m.getAuthId(), m);
926
            }
927
        }
928
 
929
        // Build L2 -> L1 team map using managerId from AuthUser
930
        Map<Integer, List<RbmCallTargetModel>> l2TeamMap = new LinkedHashMap<>();
931
        for (RbmCallTargetModel l2Model : l2ModelsByAuthId.values()) {
932
            l2TeamMap.put(l2Model.getAuthId(), new ArrayList<>());
933
        }
934
 
935
        Set<Integer> addedL1AuthIds = new HashSet<>();
936
        for (RbmCallTargetModel l1Model : l1ModelsByAuthId.values()) {
937
            AuthUser l1User = authUserMap.get(l1Model.getAuthId());
938
            if (l1User != null && l2TeamMap.containsKey(l1User.getManagerId())) {
939
                l2TeamMap.get(l1User.getManagerId()).add(l1Model);
940
                addedL1AuthIds.add(l1Model.getAuthId());
941
            }
942
        }
943
 
944
        // Build sorted result: L2 row, then its L1 team (sorted by name)
945
        List<RbmCallTargetModel> sortedModels = new ArrayList<>();
946
 
947
        List<RbmCallTargetModel> l2Sorted = new ArrayList<>(l2ModelsByAuthId.values());
948
        l2Sorted.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
949
 
950
        for (RbmCallTargetModel l2Model : l2Sorted) {
951
            sortedModels.add(l2Model);
952
            List<RbmCallTargetModel> team = l2TeamMap.getOrDefault(l2Model.getAuthId(), Collections.emptyList());
953
            team.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
954
            sortedModels.addAll(team);
955
        }
956
 
957
        // Add any L1 RBMs not mapped to any L2 (sorted by name)
958
        List<RbmCallTargetModel> unmappedL1 = new ArrayList<>();
959
        for (RbmCallTargetModel m : l1ModelsByAuthId.values()) {
960
            if (!addedL1AuthIds.contains(m.getAuthId())) {
961
                unmappedL1.add(m);
962
            }
963
        }
964
        unmappedL1.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
965
        sortedModels.addAll(unmappedL1);
966
 
967
        LOGGER.info("RBM Call Target - TOTAL TIME: {}ms, RBM count: {}", System.currentTimeMillis() - methodStart, sortedModels.size());
968
        return sortedModels;
969
    }
970
 
971
    @Override
972
    public List<OutOfSequenceDetailModel> getOutOfSequenceDetails(int authId) {
973
 
974
        LocalDate today = LocalDate.now();
975
        LocalDateTime start = today.atStartOfDay();
976
        LocalDateTime end = today.plusDays(1).atStartOfDay();
977
 
978
        List<RbmCallSequenceLog> logs =
979
                rbmCallSequenceLogRepository.selectByAuthIdAndDateRange(authId, start, end);
980
 
35654 ranu 981
        Map<Integer, RbmCallSequenceLog> uniqueOosLogsByFofoId = new LinkedHashMap<>();
35631 ranu 982
 
983
        for (RbmCallSequenceLog log : logs) {
984
            if (log.isOutOfSequence()) {
35654 ranu 985
                // Keep only the first occurrence per fofoId (latest entry since ordered by id DESC)
986
                uniqueOosLogsByFofoId.putIfAbsent(log.getFofoId(), log);
35631 ranu 987
            }
988
        }
989
 
35654 ranu 990
        if (uniqueOosLogsByFofoId.isEmpty()) {
35631 ranu 991
            return Collections.emptyList();
992
        }
993
 
35654 ranu 994
        Set<Integer> fofoIds = uniqueOosLogsByFofoId.keySet();
35631 ranu 995
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
996
        try {
997
            retailerMap = retailerService.getFofoRetailers(new ArrayList<>(fofoIds));
998
        } catch (ProfitMandiBusinessException e) {
999
            LOGGER.error("Error fetching fofo stores", e);
1000
        }
1001
 
1002
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
1003
        List<OutOfSequenceDetailModel> result = new ArrayList<>();
1004
 
35654 ranu 1005
        for (RbmCallSequenceLog log : uniqueOosLogsByFofoId.values()) {
35631 ranu 1006
            CustomRetailer retailer = retailerMap.get(log.getFofoId());
1007
            String partyName = retailer != null
1008
                    ? retailer.getBusinessName()
1009
                    : "Unknown (" + log.getFofoId() + ")";
1010
            String code = retailer != null
1011
                    ? retailer.getCode()
1012
                    : "-";
1013
 
1014
            String time = log.getCreateTimestamp() != null
1015
                    ? log.getCreateTimestamp().format(timeFormatter)
1016
                    : "-";
1017
 
1018
            result.add(new OutOfSequenceDetailModel(partyName, code, time));
1019
        }
1020
 
1021
        return result;
1022
    }
1023
 
35645 ranu 1024
    @Override
35672 ranu 1025
    public List<CalledPartnerDetailModel> getCalledPartnerDetails(int authId) throws ProfitMandiBusinessException {
35670 ranu 1026
        LocalDate today = LocalDate.now();
35672 ranu 1027
        LocalDateTime startDate = today.atStartOfDay();
1028
        LocalDate firstOfMonth = today.withDayOfMonth(1);
1029
        LocalDate endOfMonth = today.withDayOfMonth(today.lengthOfMonth()).plusDays(1);
35670 ranu 1030
 
35672 ranu 1031
        // Get auth user
1032
        List<AuthUser> authUsers = authRepository.selectByIds(Collections.singletonList(authId));
1033
        if (authUsers.isEmpty()) {
1034
            return Collections.emptyList();
1035
        }
1036
        AuthUser authUser = authUsers.get(0);
35670 ranu 1037
 
35672 ranu 1038
        // Check if L1 or L2
1039
        List<Position> positions = positionRepository.selectPositionByAuthIds(Collections.singletonList(authId));
1040
        boolean isL2 = positions.stream()
1041
                .anyMatch(p -> ProfitMandiConstants.TICKET_CATEGORY_RBM == p.getCategoryId()
1042
                        && EscalationType.L2.equals(p.getEscalationType()));
1043
 
1044
        // Get fofo IDs for this RBM
1045
        List<Integer> fofoIdList;
1046
        if (isL2) {
1047
            // L2: get fofo IDs from escalated tickets (all escalated tickets are target)
1048
            List<Ticket> escalatedTickets = ticketRepository.selectOpenEscalatedTicketsByAuthIds(Collections.singletonList(authId));
1049
            fofoIdList = escalatedTickets.stream()
1050
                    .filter(t -> t.getL2AuthUser() == authId
1051
                            || t.getL3AuthUser() == authId
1052
                            || t.getL4AuthUser() == authId
1053
                            || t.getL5AuthUser() == authId)
1054
                    .map(Ticket::getFofoId)
1055
                    .distinct()
1056
                    .collect(Collectors.toList());
1057
 
1058
            // For L2, all escalated tickets are target
1059
            Set<Integer> targetFofoIds = new HashSet<>(fofoIdList);
1060
 
1061
            // Get today's remarks
1062
            List<PartnerCollectionRemark> todayRemarks = partnerCollectionRemarkRepository
1063
                    .selectAllByAuthIdsOnDate(Collections.singletonList(authId), today);
1064
 
1065
            // Filter to only target partners and deduplicate
1066
            Map<Integer, PartnerCollectionRemark> uniqueRemarksByFofoId = new LinkedHashMap<>();
1067
            for (PartnerCollectionRemark remark : todayRemarks) {
1068
                if (targetFofoIds.contains(remark.getFofoId())) {
1069
                    uniqueRemarksByFofoId.putIfAbsent(remark.getFofoId(), remark);
1070
                }
1071
            }
1072
 
1073
            return buildCalledPartnerResult(uniqueRemarksByFofoId);
1074
        }
1075
 
1076
        // L1 Logic
1077
        Map<String, Set<Integer>> storeGuyMap;
1078
        try {
1079
            storeGuyMap = csService.getAuthUserPartnerIdMapping();
1080
        } catch (ProfitMandiBusinessException e) {
1081
            LOGGER.error("Error fetching store guy map", e);
35670 ranu 1082
            return Collections.emptyList();
1083
        }
1084
 
35672 ranu 1085
        if (!storeGuyMap.containsKey(authUser.getEmailId())) {
1086
            return Collections.emptyList();
1087
        }
1088
        fofoIdList = new ArrayList<>(storeGuyMap.get(authUser.getEmailId()));
1089
 
1090
        if (fofoIdList.isEmpty()) {
1091
            return Collections.emptyList();
1092
        }
1093
 
1094
        // Get fofo stores for filtering
1095
        Map<Integer, FofoStore> fofoStoresMap;
1096
        try {
1097
            fofoStoresMap = fofoStoreRepository.selectByRetailerIds(fofoIdList).stream()
1098
                    .collect(Collectors.toMap(FofoStore::getId, x -> x, (a, b) -> a));
1099
        } catch (ProfitMandiBusinessException e) {
1100
            LOGGER.error("Error fetching fofo stores", e);
1101
            return Collections.emptyList();
1102
        }
1103
 
1104
        // Filter escalated partners for L1
1105
        List<Integer> allRemarkIds = partnerCollectionRemarkRepository.selectMaxRemarkId(fofoIdList);
1106
        if (!allRemarkIds.isEmpty()) {
1107
            Map<Integer, PartnerCollectionRemark> partnerCollectionRemarks = partnerCollectionRemarkRepository.selectByIds(allRemarkIds).stream()
1108
                    .collect(Collectors.toMap(PartnerCollectionRemark::getFofoId, x -> x, (a, b) -> a));
1109
            fofoIdList = partnerCollectionRemarks.entrySet().stream()
1110
                    .filter(entry -> {
1111
                        PartnerCollectionRemark pcrMap = entry.getValue();
1112
                        return !(CollectionRemark.RBM_L2_ESCALATION.equals(pcrMap.getRemark())
1113
                                || CollectionRemark.SALES_ESCALATION.equals(pcrMap.getRemark()));
1114
                    })
1115
                    .map(Map.Entry::getKey)
1116
                    .collect(Collectors.toList());
1117
        }
1118
 
1119
        // Filter to only external, ACTIVE stores
1120
        List<Integer> validFofoIds = fofoIdList.stream()
1121
                .filter(fofoId -> {
1122
                    FofoStore store = fofoStoresMap.get(fofoId);
1123
                    if (store == null || store.isInternal()) {
1124
                        return false;
1125
                    }
1126
                    return ActivationType.ACTIVE.equals(store.getActivationType());
1127
                })
1128
                .collect(Collectors.toList());
1129
 
1130
        if (validFofoIds.isEmpty()) {
1131
            return Collections.emptyList();
1132
        }
1133
 
1134
        // Get collection rank map
1135
        Map<Integer, Integer> collectionRankMap;
1136
        try {
1137
            collectionRankMap = partnerCollectionService.getCollectionRankMap(validFofoIds, startDate);
1138
        } catch (ProfitMandiBusinessException e) {
1139
            LOGGER.error("Error fetching collection rank map", e);
1140
            collectionRankMap = new HashMap<>();
1141
        }
1142
 
1143
        // Get MTD billing data for zero billing check
1144
        List<RbmWeeklyBillingModel> mtdBillingData = getWeeklyBillingDataForMonth(firstOfMonth, endOfMonth);
1145
        Set<Integer> mtdBilledFofoIds = mtdBillingData.stream()
1146
                .filter(RbmWeeklyBillingModel::isMtdBilled)
1147
                .map(RbmWeeklyBillingModel::getFofoId)
1148
                .collect(Collectors.toSet());
1149
 
1150
        // Build target partner set (PlanToday + CarryForward + ZeroBilling + Untouched)
1151
        Set<Integer> targetFofoIds = new HashSet<>();
1152
        for (Integer fofoId : validFofoIds) {
1153
            int rank = collectionRankMap.getOrDefault(fofoId, 5);
1154
            boolean hasZeroBilling = !mtdBilledFofoIds.contains(fofoId);
1155
 
1156
            // Same priority logic as in getRbmCallTargetModels
1157
            if (rank == 1 || rank == 2 || hasZeroBilling || rank == 3) {
1158
                targetFofoIds.add(fofoId);
1159
            }
1160
            // rank 4 (FuturePlan) and rank 5 (Normal) are NOT in target
1161
        }
1162
 
1163
        // Get today's remarks
1164
        List<PartnerCollectionRemark> todayRemarks = partnerCollectionRemarkRepository
1165
                .selectAllByAuthIdsOnDate(Collections.singletonList(authId), today);
1166
 
1167
        // Filter to only target partners and deduplicate
35670 ranu 1168
        Map<Integer, PartnerCollectionRemark> uniqueRemarksByFofoId = new LinkedHashMap<>();
1169
        for (PartnerCollectionRemark remark : todayRemarks) {
35672 ranu 1170
            if (targetFofoIds.contains(remark.getFofoId())) {
1171
                uniqueRemarksByFofoId.putIfAbsent(remark.getFofoId(), remark);
1172
            }
35670 ranu 1173
        }
1174
 
35672 ranu 1175
        return buildCalledPartnerResult(uniqueRemarksByFofoId);
1176
    }
1177
 
1178
    private List<CalledPartnerDetailModel> buildCalledPartnerResult(Map<Integer, PartnerCollectionRemark> uniqueRemarksByFofoId) {
1179
        if (uniqueRemarksByFofoId.isEmpty()) {
1180
            return Collections.emptyList();
1181
        }
1182
 
35670 ranu 1183
        Set<Integer> fofoIds = uniqueRemarksByFofoId.keySet();
1184
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
1185
        try {
1186
            retailerMap = retailerService.getFofoRetailers(new ArrayList<>(fofoIds));
1187
        } catch (ProfitMandiBusinessException e) {
1188
            LOGGER.error("Error fetching fofo stores", e);
1189
        }
1190
 
1191
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
1192
        List<CalledPartnerDetailModel> result = new ArrayList<>();
1193
 
1194
        for (PartnerCollectionRemark remark : uniqueRemarksByFofoId.values()) {
1195
            CustomRetailer retailer = retailerMap.get(remark.getFofoId());
1196
            String partyName = retailer != null
1197
                    ? retailer.getBusinessName()
1198
                    : "Unknown (" + remark.getFofoId() + ")";
1199
            String code = retailer != null
1200
                    ? retailer.getCode()
1201
                    : "-";
1202
 
1203
            String remarkValue = remark.getRemark() != null
1204
                    ? remark.getRemark().getValue()
1205
                    : "-";
1206
 
35677 ranu 1207
            String messageValue = remark.getMessage() != null
1208
                    ? remark.getMessage()
1209
                    : "-";
1210
 
35670 ranu 1211
            String time = remark.getCreateTimestamp() != null
1212
                    ? remark.getCreateTimestamp().format(timeFormatter)
1213
                    : "-";
1214
 
35677 ranu 1215
            result.add(new CalledPartnerDetailModel(partyName, code, remarkValue, messageValue, time));
35670 ranu 1216
        }
1217
 
1218
        return result;
1219
    }
1220
 
1221
    @Override
35645 ranu 1222
    public List<List<String>> getRbmCallTargetRawDataByAuthId(int authId) throws Exception {
1223
        List<List<String>> rows = new ArrayList<>();
35631 ranu 1224
 
35645 ranu 1225
        // Get auth user
1226
        List<AuthUser> authUsers = authRepository.selectByIds(Collections.singletonList(authId));
1227
        if (authUsers.isEmpty()) {
1228
            return rows;
1229
        }
1230
        AuthUser authUser = authUsers.get(0);
1231
 
1232
        // Get positions to determine if L1 or L2
1233
        List<Position> positions = positionRepository.selectPositionByAuthIds(Collections.singletonList(authId));
1234
        boolean isL1 = positions.stream()
1235
                .anyMatch(p -> ProfitMandiConstants.TICKET_CATEGORY_RBM == p.getCategoryId()
1236
                        && EscalationType.L1.equals(p.getEscalationType()));
1237
        boolean isL2 = positions.stream()
1238
                .anyMatch(p -> ProfitMandiConstants.TICKET_CATEGORY_RBM == p.getCategoryId()
1239
                        && EscalationType.L2.equals(p.getEscalationType()));
1240
 
1241
        // Get fofo IDs for this RBM
1242
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1243
        List<Integer> fofoIdList = new ArrayList<>();
1244
 
1245
        if (isL2) {
1246
            // L2: get fofo IDs from escalated tickets
1247
            List<Ticket> escalatedTickets = ticketRepository.selectOpenEscalatedTicketsByAuthIds(Collections.singletonList(authId));
1248
            fofoIdList = escalatedTickets.stream()
1249
                    .filter(t -> t.getL2AuthUser() == authId
1250
                            || t.getL3AuthUser() == authId
1251
                            || t.getL4AuthUser() == authId
1252
                            || t.getL5AuthUser() == authId)
1253
                    .map(Ticket::getFofoId)
1254
                    .distinct()
1255
                    .collect(Collectors.toList());
1256
        } else if (storeGuyMap.containsKey(authUser.getEmailId())) {
1257
            fofoIdList = new ArrayList<>(storeGuyMap.get(authUser.getEmailId()));
1258
        }
1259
 
1260
        if (fofoIdList.isEmpty()) {
1261
            return rows;
1262
        }
1263
 
1264
        LocalDateTime startDate = LocalDate.now().atStartOfDay();
1265
        LocalDate firstOfMonth = LocalDate.now().withDayOfMonth(1);
1266
        LocalDate endOfMonth = LocalDate.now().withDayOfMonth(LocalDate.now().lengthOfMonth()).plusDays(1);
1267
 
1268
        // Get fofo stores
1269
        Map<Integer, FofoStore> fofoStoresMap = new HashMap<>();
1270
        try {
1271
            fofoStoresMap = fofoStoreRepository.selectByRetailerIds(fofoIdList).stream()
1272
                    .collect(Collectors.toMap(FofoStore::getId, x -> x, (a, b) -> a));
1273
        } catch (ProfitMandiBusinessException e) {
1274
            LOGGER.error("Error fetching fofo stores", e);
1275
        }
1276
 
1277
        // For L1 RBMs, filter escalated partners
1278
        if (isL1) {
1279
            List<Integer> allRemarkIds = partnerCollectionRemarkRepository.selectMaxRemarkId(fofoIdList);
1280
            if (!allRemarkIds.isEmpty()) {
1281
                Map<Integer, PartnerCollectionRemark> partnerCollectionRemarks = partnerCollectionRemarkRepository.selectByIds(allRemarkIds).stream()
1282
                        .collect(Collectors.toMap(PartnerCollectionRemark::getFofoId, x -> x, (a, b) -> a));
1283
                fofoIdList = partnerCollectionRemarks.entrySet().stream()
1284
                        .filter(entry -> {
1285
                            PartnerCollectionRemark pcrMap = entry.getValue();
1286
                            return !(CollectionRemark.RBM_L2_ESCALATION.equals(pcrMap.getRemark())
1287
                                    || CollectionRemark.SALES_ESCALATION.equals(pcrMap.getRemark()));
1288
                        })
1289
                        .map(Map.Entry::getKey)
1290
                        .collect(Collectors.toList());
1291
            }
1292
        }
1293
 
1294
        // Collection rank map
1295
        Map<Integer, Integer> collectionRankMap = new HashMap<>();
1296
        try {
1297
            collectionRankMap = partnerCollectionService.getCollectionRankMap(fofoIdList, startDate);
1298
        } catch (ProfitMandiBusinessException e) {
1299
            LOGGER.error("Error fetching collection rank map", e);
1300
        }
1301
 
1302
        // MTD billing data
1303
        List<RbmWeeklyBillingModel> mtdBillingData = getWeeklyBillingDataForMonth(firstOfMonth, endOfMonth);
1304
        Set<Integer> mtdBilledFofoIds = mtdBillingData.stream()
1305
                .filter(RbmWeeklyBillingModel::isMtdBilled)
1306
                .map(RbmWeeklyBillingModel::getFofoId)
1307
                .collect(Collectors.toSet());
1308
 
1309
        // Filter to valid fofo IDs (external, ACTIVE, has collection plan)
1310
        Map<Integer, Integer> finalCollectionRankMap = collectionRankMap;
1311
        Map<Integer, FofoStore> finalFofoStoresMap = fofoStoresMap;
1312
        List<Integer> validFofoIds = fofoIdList.stream()
1313
                .filter(fofoId -> {
1314
                    FofoStore store = finalFofoStoresMap.get(fofoId);
1315
                    if (store == null || store.isInternal()) return false;
1316
                    if (!ActivationType.ACTIVE.equals(store.getActivationType())) return false;
1317
                    return finalCollectionRankMap.containsKey(fofoId);
1318
                })
1319
                .collect(Collectors.toList());
1320
 
1321
        // Resolve partner names/codes
1322
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
1323
        if (!validFofoIds.isEmpty()) {
1324
            try {
1325
                retailerMap = retailerService.getFofoRetailers(validFofoIds);
1326
            } catch (ProfitMandiBusinessException e) {
1327
                LOGGER.error("Error fetching fofo retailers for raw data", e);
1328
            }
1329
        }
1330
 
1331
        String rbmName = authUser.getFullName() + (isL2 ? " (L2)" : "");
1332
 
1333
        // Build rows
1334
        for (Integer fofoId : validFofoIds) {
1335
            int rank = collectionRankMap.getOrDefault(fofoId, 5);
1336
            boolean hasZeroBilling = !mtdBilledFofoIds.contains(fofoId);
1337
 
1338
            String status;
1339
            if (rank == 1) {
1340
                status = "Plan Today";
1341
            } else if (rank == 2) {
1342
                status = "Carry Forward";
1343
            } else if (rank == 3) {
1344
                status = "Untouched";
1345
            } else if (hasZeroBilling) {
1346
                status = "Zero Billing";
1347
            } else if (rank == 4) {
1348
                status = "Future Plan";
1349
            } else {
1350
                status = "Normal";
1351
            }
1352
 
1353
            CustomRetailer retailer = retailerMap.get(fofoId);
1354
            String partnerName = retailer != null ? retailer.getBusinessName() : "Unknown (" + fofoId + ")";
1355
            String partnerCode = retailer != null ? retailer.getCode() : "-";
1356
 
1357
            rows.add(Arrays.asList(partnerName, partnerCode, status, rbmName));
1358
        }
1359
 
1360
        return rows;
1361
    }
1362
 
33917 ranu 1363
}