Subversion Repositories SmartDukaan

Rev

Rev 35662 | Rev 35669 | 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
 
711
        // Get MTD billing data for zero billing calculation
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());
718
        LOGGER.info("RBM Call Target - MTD Billing fetch: {}ms", System.currentTimeMillis() - start);
719
 
720
        // Batch fetch today's remarks for all auth IDs (to calculate Value Achieved)
721
        start = System.currentTimeMillis();
722
        Map<Integer, List<PartnerCollectionRemark>> remarksByAuthId = partnerCollectionRemarkRepository
723
                .selectAllByAuthIdsOnDate(rbmPositionsAuthIds, LocalDate.now()).stream()
724
                .collect(Collectors.groupingBy(PartnerCollectionRemark::getAuthId));
725
        LOGGER.info("RBM Call Target - Today Remarks fetch: {}ms", System.currentTimeMillis() - start);
726
 
727
        // Batch fetch today's out-of-sequence logs for all RBMs
728
        start = System.currentTimeMillis();
729
        LocalDateTime todayStart = LocalDate.now().atStartOfDay();
730
        LocalDateTime todayEnd = LocalDate.now().plusDays(1).atStartOfDay();
731
        List<RbmCallSequenceLog> outOfSequenceLogs = rbmCallSequenceLogRepository.selectOutOfSequenceByDateRange(todayStart, todayEnd);
732
        Map<Integer, Long> outOfSequenceCountByAuthId = outOfSequenceLogs.stream()
35654 ranu 733
                .collect(Collectors.groupingBy(RbmCallSequenceLog::getAuthId,
734
                        Collectors.mapping(RbmCallSequenceLog::getFofoId, Collectors.collectingAndThen(Collectors.toSet(), s -> (long) s.size()))));
35631 ranu 735
        LOGGER.info("RBM Call Target - Out of Sequence fetch: {}ms", System.currentTimeMillis() - start);
736
 
737
        // Process L1 RBMs (existing logic)
738
        for (int rbmAuthId : l1AuthIds) {
739
            AuthUser authUser = authUserMap.get(rbmAuthId);
740
            if (authUser == null || !storeGuyMap.containsKey(authUser.getEmailId())) {
741
                continue;
742
            }
743
 
744
            List<Integer> fofoIdList = rbmToFofoIdsMap.getOrDefault(rbmAuthId, Collections.emptyList());
745
 
746
            // Check if RBM is L1 (same logic as getSummaryModel)
747
            List<Position> positions = positionsByAuthId.getOrDefault(authUser.getId(), Collections.emptyList());
748
            boolean isRBMAndL1 = positions.stream()
749
                    .anyMatch(position ->
750
                            ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId()
751
                                    && EscalationType.L1.equals(position.getEscalationType()));
752
 
753
            // Filter escalated partners for L1 RBMs (same logic as getSummaryModel)
754
            List<Integer> fofoIds = fofoIdList;
755
            if (isRBMAndL1) {
756
                Map<Integer, PartnerCollectionRemark> partnerCollectionRemarks = new HashMap<>();
757
                for (Integer fofoId : fofoIdList) {
758
                    if (allPartnerCollectionRemarks.containsKey(fofoId)) {
759
                        partnerCollectionRemarks.put(fofoId, allPartnerCollectionRemarks.get(fofoId));
760
                    }
761
                }
762
                fofoIds = partnerCollectionRemarks.entrySet().stream()
763
                        .filter(entry -> {
764
                            PartnerCollectionRemark pcrMap = entry.getValue();
765
                            return !(CollectionRemark.RBM_L2_ESCALATION.equals(pcrMap.getRemark())
766
                                    || CollectionRemark.SALES_ESCALATION.equals(pcrMap.getRemark()));
767
                        })
768
                        .map(Map.Entry::getKey)
769
                        .collect(Collectors.toList());
770
            }
771
 
772
            // Filter to only external, ACTIVE stores with collection plan (like today_target Active section)
773
            Map<Integer, Integer> finalAllCollectionRankMap = allCollectionRankMap;
774
            Map<Integer, FofoStore> finalFofoStoresMap = fofoStoresMap;
775
            List<Integer> validFofoIds = fofoIds.stream()
776
                    .filter(fofoId -> {
777
                        FofoStore store = finalFofoStoresMap.get(fofoId);
778
                        if (store == null || store.isInternal()) {
779
                            return false;
780
                        }
781
                        // Only include ACTIVE partners (not Low Sale, not Disputed, not Billing Pending)
782
                        if (!ActivationType.ACTIVE.equals(store.getActivationType())) {
783
                            return false;
784
                        }
785
                        // Only include partners who have a collection plan (to match today_target Active section)
786
                        return finalAllCollectionRankMap.containsKey(fofoId);
787
                    })
788
                    .collect(Collectors.toList());
789
 
790
            if (validFofoIds.isEmpty()) {
791
                continue;
792
            }
793
 
794
            RbmCallTargetModel targetModel = new RbmCallTargetModel();
795
            targetModel.setAuthId(rbmAuthId);
796
            targetModel.setRbmName(authUser.getFullName());
797
            targetModel.setPartnerCount(validFofoIds.size());
798
 
799
            // Categorize each partner - each partner belongs to ONE category only
35665 ranu 800
            // Priority: PlanToday > CarryForward > ZeroBilling > Untouched > FuturePlan > Normal
35631 ranu 801
            Set<Integer> planTodayPartners = new HashSet<>();
802
            Set<Integer> carryForwardPartners = new HashSet<>();
803
            Set<Integer> untouchedPartners = new HashSet<>();
804
            Set<Integer> zeroBillingPartners = new HashSet<>();
805
            Set<Integer> futurePlanPartners = new HashSet<>();
806
            Set<Integer> normalPartners = new HashSet<>();
807
 
808
            for (Integer fofoId : validFofoIds) {
809
                // Get collection plan rank (from optimized rank map)
810
                int rank = allCollectionRankMap.getOrDefault(fofoId, 5); // default to Normal if no plan
811
 
812
                // Check if partner has zero billing in MTD
813
                boolean hasZeroBilling = !allMtdBilledFofoIds.contains(fofoId);
814
 
815
                // Assign to category based on priority
816
                if (rank == 1) {
817
                    planTodayPartners.add(fofoId);
818
                } else if (rank == 2) {
819
                    carryForwardPartners.add(fofoId);
35665 ranu 820
                } else if (hasZeroBilling) {
821
                    zeroBillingPartners.add(fofoId);
35631 ranu 822
                } else if (rank == 3) {
823
                    untouchedPartners.add(fofoId);
824
                } else if (rank == 4) {
825
                    futurePlanPartners.add(fofoId);
826
                } else {
827
                    normalPartners.add(fofoId);
828
                }
829
            }
830
 
831
            // Set counts
832
            targetModel.setCreditCollection(0); // Credit collection is handled in separate list
833
            targetModel.setPlanToday(planTodayPartners.size());
834
            targetModel.setCarryForward(carryForwardPartners.size());
835
            targetModel.setUntouched(untouchedPartners.size());
836
            targetModel.setZeroBilling(zeroBillingPartners.size());
837
            targetModel.setFuturePlan(futurePlanPartners.size());
838
            targetModel.setNormal(normalPartners.size());
839
 
840
            // Today Target = PlanToday + CarryForward + ZeroBilling + Untouched
841
            // These are mutually exclusive now, so we can sum them
842
            long todayTarget = planTodayPartners.size() +
843
                    carryForwardPartners.size() + zeroBillingPartners.size() + untouchedPartners.size();
844
            targetModel.setTodayTargetOfCall(todayTarget);
845
 
846
            // Create set of partners in Today Target categories
847
            Set<Integer> todayTargetPartners = new HashSet<>();
848
            todayTargetPartners.addAll(planTodayPartners);
849
            todayTargetPartners.addAll(carryForwardPartners);
850
            todayTargetPartners.addAll(zeroBillingPartners);
851
            todayTargetPartners.addAll(untouchedPartners);
852
 
853
            // Value Achieved = Partners from Today Target that have been contacted today (have remark today)
854
            List<PartnerCollectionRemark> todayRemarks = remarksByAuthId.getOrDefault(rbmAuthId, Collections.emptyList());
855
            long valueAchieved = todayRemarks.stream()
856
                    .map(PartnerCollectionRemark::getFofoId)
857
                    .filter(todayTargetPartners::contains)
858
                    .distinct()
859
                    .count();
860
            targetModel.setValueTargetAchieved(valueAchieved);
861
 
862
            // Moved to Future = Partners in Future Plan category who have a remark today
863
            // These are partners who were contacted today but moved to a future date
864
            Set<Integer> todayRemarkedFofoIds = todayRemarks.stream()
865
                    .map(PartnerCollectionRemark::getFofoId)
866
                    .collect(Collectors.toSet());
867
            long movedToFuture = futurePlanPartners.stream()
868
                    .filter(todayRemarkedFofoIds::contains)
869
                    .count();
870
            targetModel.setMovedToFuture(movedToFuture);
871
 
872
            // Set out of sequence count for this RBM
873
            targetModel.setOutOfSequenceCount(outOfSequenceCountByAuthId.getOrDefault(rbmAuthId, 0L));
874
 
875
            rbmCallTargetModels.add(targetModel);
876
        }
877
 
878
        // Process L2 RBMs (escalated ticket logic with categorization)
879
        for (int l2AuthId : l2AuthIds) {
880
            AuthUser authUser = authUserMap.get(l2AuthId);
881
            if (authUser == null) {
882
                continue;
883
            }
884
 
885
            List<Integer> l2FofoIdList = l2AuthIdToFofoIds.getOrDefault(l2AuthId, Collections.emptyList());
886
 
35662 ranu 887
            // For L2, use all escalated ticket fofoIds as target (no collection plan filter)
888
            Set<Integer> l2TargetFofoIds = new HashSet<>(l2FofoIdList);
35631 ranu 889
 
890
            RbmCallTargetModel l2Model = new RbmCallTargetModel();
891
            l2Model.setAuthId(l2AuthId);
892
            l2Model.setRbmName(authUser.getFullName() + " (L2)");
893
            l2Model.setL2Position(true);
894
            l2Model.setL2CallingList(l2FofoIdList.size());
895
            // Partner count = total assigned partners (same as L1 source)
896
            List<Integer> l2AssignedFofoIds = rbmToFofoIdsMap.getOrDefault(l2AuthId, Collections.emptyList());
897
            l2Model.setPartnerCount(l2AssignedFofoIds.size());
898
 
35662 ranu 899
            // L2 Target = all escalated ticket fofoIds
900
            l2Model.setTodayTargetOfCall(l2TargetFofoIds.size());
35631 ranu 901
 
35662 ranu 902
            // Value Achieved = distinct fofoIds from today's remarks that are in escalated tickets
903
            List<PartnerCollectionRemark> l2TodayRemarks = remarksByAuthId.getOrDefault(l2AuthId, Collections.emptyList());
904
            long l2ValueAchieved = l2TodayRemarks.stream()
905
                    .map(PartnerCollectionRemark::getFofoId)
906
                    .filter(l2TargetFofoIds::contains)
907
                    .distinct()
908
                    .count();
909
            l2Model.setValueTargetAchieved(l2ValueAchieved);
35631 ranu 910
 
911
            l2Model.setOutOfSequenceCount(outOfSequenceCountByAuthId.getOrDefault(l2AuthId, 0L));
912
            rbmCallTargetModels.add(l2Model);
913
        }
914
 
915
        // Group L1 under their L2 manager using authUser.managerId
916
        Map<Integer, RbmCallTargetModel> l2ModelsByAuthId = new HashMap<>();
917
        Map<Integer, RbmCallTargetModel> l1ModelsByAuthId = new HashMap<>();
918
        for (RbmCallTargetModel m : rbmCallTargetModels) {
919
            if (m.isL2Position()) {
920
                l2ModelsByAuthId.put(m.getAuthId(), m);
921
            } else {
922
                l1ModelsByAuthId.put(m.getAuthId(), m);
923
            }
924
        }
925
 
926
        // Build L2 -> L1 team map using managerId from AuthUser
927
        Map<Integer, List<RbmCallTargetModel>> l2TeamMap = new LinkedHashMap<>();
928
        for (RbmCallTargetModel l2Model : l2ModelsByAuthId.values()) {
929
            l2TeamMap.put(l2Model.getAuthId(), new ArrayList<>());
930
        }
931
 
932
        Set<Integer> addedL1AuthIds = new HashSet<>();
933
        for (RbmCallTargetModel l1Model : l1ModelsByAuthId.values()) {
934
            AuthUser l1User = authUserMap.get(l1Model.getAuthId());
935
            if (l1User != null && l2TeamMap.containsKey(l1User.getManagerId())) {
936
                l2TeamMap.get(l1User.getManagerId()).add(l1Model);
937
                addedL1AuthIds.add(l1Model.getAuthId());
938
            }
939
        }
940
 
941
        // Build sorted result: L2 row, then its L1 team (sorted by name)
942
        List<RbmCallTargetModel> sortedModels = new ArrayList<>();
943
 
944
        List<RbmCallTargetModel> l2Sorted = new ArrayList<>(l2ModelsByAuthId.values());
945
        l2Sorted.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
946
 
947
        for (RbmCallTargetModel l2Model : l2Sorted) {
948
            sortedModels.add(l2Model);
949
            List<RbmCallTargetModel> team = l2TeamMap.getOrDefault(l2Model.getAuthId(), Collections.emptyList());
950
            team.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
951
            sortedModels.addAll(team);
952
        }
953
 
954
        // Add any L1 RBMs not mapped to any L2 (sorted by name)
955
        List<RbmCallTargetModel> unmappedL1 = new ArrayList<>();
956
        for (RbmCallTargetModel m : l1ModelsByAuthId.values()) {
957
            if (!addedL1AuthIds.contains(m.getAuthId())) {
958
                unmappedL1.add(m);
959
            }
960
        }
961
        unmappedL1.sort(Comparator.comparing(RbmCallTargetModel::getRbmName));
962
        sortedModels.addAll(unmappedL1);
963
 
964
        LOGGER.info("RBM Call Target - TOTAL TIME: {}ms, RBM count: {}", System.currentTimeMillis() - methodStart, sortedModels.size());
965
        return sortedModels;
966
    }
967
 
968
    @Override
969
    public List<OutOfSequenceDetailModel> getOutOfSequenceDetails(int authId) {
970
 
971
        LocalDate today = LocalDate.now();
972
        LocalDateTime start = today.atStartOfDay();
973
        LocalDateTime end = today.plusDays(1).atStartOfDay();
974
 
975
        List<RbmCallSequenceLog> logs =
976
                rbmCallSequenceLogRepository.selectByAuthIdAndDateRange(authId, start, end);
977
 
35654 ranu 978
        Map<Integer, RbmCallSequenceLog> uniqueOosLogsByFofoId = new LinkedHashMap<>();
35631 ranu 979
 
980
        for (RbmCallSequenceLog log : logs) {
981
            if (log.isOutOfSequence()) {
35654 ranu 982
                // Keep only the first occurrence per fofoId (latest entry since ordered by id DESC)
983
                uniqueOosLogsByFofoId.putIfAbsent(log.getFofoId(), log);
35631 ranu 984
            }
985
        }
986
 
35654 ranu 987
        if (uniqueOosLogsByFofoId.isEmpty()) {
35631 ranu 988
            return Collections.emptyList();
989
        }
990
 
35654 ranu 991
        Set<Integer> fofoIds = uniqueOosLogsByFofoId.keySet();
35631 ranu 992
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
993
        try {
994
            retailerMap = retailerService.getFofoRetailers(new ArrayList<>(fofoIds));
995
        } catch (ProfitMandiBusinessException e) {
996
            LOGGER.error("Error fetching fofo stores", e);
997
        }
998
 
999
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
1000
        List<OutOfSequenceDetailModel> result = new ArrayList<>();
1001
 
35654 ranu 1002
        for (RbmCallSequenceLog log : uniqueOosLogsByFofoId.values()) {
35631 ranu 1003
            CustomRetailer retailer = retailerMap.get(log.getFofoId());
1004
            String partyName = retailer != null
1005
                    ? retailer.getBusinessName()
1006
                    : "Unknown (" + log.getFofoId() + ")";
1007
            String code = retailer != null
1008
                    ? retailer.getCode()
1009
                    : "-";
1010
 
1011
            String time = log.getCreateTimestamp() != null
1012
                    ? log.getCreateTimestamp().format(timeFormatter)
1013
                    : "-";
1014
 
1015
            result.add(new OutOfSequenceDetailModel(partyName, code, time));
1016
        }
1017
 
1018
        return result;
1019
    }
1020
 
35645 ranu 1021
    @Override
1022
    public List<List<String>> getRbmCallTargetRawDataByAuthId(int authId) throws Exception {
1023
        List<List<String>> rows = new ArrayList<>();
35631 ranu 1024
 
35645 ranu 1025
        // Get auth user
1026
        List<AuthUser> authUsers = authRepository.selectByIds(Collections.singletonList(authId));
1027
        if (authUsers.isEmpty()) {
1028
            return rows;
1029
        }
1030
        AuthUser authUser = authUsers.get(0);
1031
 
1032
        // Get positions to determine if L1 or L2
1033
        List<Position> positions = positionRepository.selectPositionByAuthIds(Collections.singletonList(authId));
1034
        boolean isL1 = positions.stream()
1035
                .anyMatch(p -> ProfitMandiConstants.TICKET_CATEGORY_RBM == p.getCategoryId()
1036
                        && EscalationType.L1.equals(p.getEscalationType()));
1037
        boolean isL2 = positions.stream()
1038
                .anyMatch(p -> ProfitMandiConstants.TICKET_CATEGORY_RBM == p.getCategoryId()
1039
                        && EscalationType.L2.equals(p.getEscalationType()));
1040
 
1041
        // Get fofo IDs for this RBM
1042
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1043
        List<Integer> fofoIdList = new ArrayList<>();
1044
 
1045
        if (isL2) {
1046
            // L2: get fofo IDs from escalated tickets
1047
            List<Ticket> escalatedTickets = ticketRepository.selectOpenEscalatedTicketsByAuthIds(Collections.singletonList(authId));
1048
            fofoIdList = escalatedTickets.stream()
1049
                    .filter(t -> t.getL2AuthUser() == authId
1050
                            || t.getL3AuthUser() == authId
1051
                            || t.getL4AuthUser() == authId
1052
                            || t.getL5AuthUser() == authId)
1053
                    .map(Ticket::getFofoId)
1054
                    .distinct()
1055
                    .collect(Collectors.toList());
1056
        } else if (storeGuyMap.containsKey(authUser.getEmailId())) {
1057
            fofoIdList = new ArrayList<>(storeGuyMap.get(authUser.getEmailId()));
1058
        }
1059
 
1060
        if (fofoIdList.isEmpty()) {
1061
            return rows;
1062
        }
1063
 
1064
        LocalDateTime startDate = LocalDate.now().atStartOfDay();
1065
        LocalDate firstOfMonth = LocalDate.now().withDayOfMonth(1);
1066
        LocalDate endOfMonth = LocalDate.now().withDayOfMonth(LocalDate.now().lengthOfMonth()).plusDays(1);
1067
 
1068
        // Get fofo stores
1069
        Map<Integer, FofoStore> fofoStoresMap = new HashMap<>();
1070
        try {
1071
            fofoStoresMap = fofoStoreRepository.selectByRetailerIds(fofoIdList).stream()
1072
                    .collect(Collectors.toMap(FofoStore::getId, x -> x, (a, b) -> a));
1073
        } catch (ProfitMandiBusinessException e) {
1074
            LOGGER.error("Error fetching fofo stores", e);
1075
        }
1076
 
1077
        // For L1 RBMs, filter escalated partners
1078
        if (isL1) {
1079
            List<Integer> allRemarkIds = partnerCollectionRemarkRepository.selectMaxRemarkId(fofoIdList);
1080
            if (!allRemarkIds.isEmpty()) {
1081
                Map<Integer, PartnerCollectionRemark> partnerCollectionRemarks = partnerCollectionRemarkRepository.selectByIds(allRemarkIds).stream()
1082
                        .collect(Collectors.toMap(PartnerCollectionRemark::getFofoId, x -> x, (a, b) -> a));
1083
                fofoIdList = partnerCollectionRemarks.entrySet().stream()
1084
                        .filter(entry -> {
1085
                            PartnerCollectionRemark pcrMap = entry.getValue();
1086
                            return !(CollectionRemark.RBM_L2_ESCALATION.equals(pcrMap.getRemark())
1087
                                    || CollectionRemark.SALES_ESCALATION.equals(pcrMap.getRemark()));
1088
                        })
1089
                        .map(Map.Entry::getKey)
1090
                        .collect(Collectors.toList());
1091
            }
1092
        }
1093
 
1094
        // Collection rank map
1095
        Map<Integer, Integer> collectionRankMap = new HashMap<>();
1096
        try {
1097
            collectionRankMap = partnerCollectionService.getCollectionRankMap(fofoIdList, startDate);
1098
        } catch (ProfitMandiBusinessException e) {
1099
            LOGGER.error("Error fetching collection rank map", e);
1100
        }
1101
 
1102
        // MTD billing data
1103
        List<RbmWeeklyBillingModel> mtdBillingData = getWeeklyBillingDataForMonth(firstOfMonth, endOfMonth);
1104
        Set<Integer> mtdBilledFofoIds = mtdBillingData.stream()
1105
                .filter(RbmWeeklyBillingModel::isMtdBilled)
1106
                .map(RbmWeeklyBillingModel::getFofoId)
1107
                .collect(Collectors.toSet());
1108
 
1109
        // Filter to valid fofo IDs (external, ACTIVE, has collection plan)
1110
        Map<Integer, Integer> finalCollectionRankMap = collectionRankMap;
1111
        Map<Integer, FofoStore> finalFofoStoresMap = fofoStoresMap;
1112
        List<Integer> validFofoIds = fofoIdList.stream()
1113
                .filter(fofoId -> {
1114
                    FofoStore store = finalFofoStoresMap.get(fofoId);
1115
                    if (store == null || store.isInternal()) return false;
1116
                    if (!ActivationType.ACTIVE.equals(store.getActivationType())) return false;
1117
                    return finalCollectionRankMap.containsKey(fofoId);
1118
                })
1119
                .collect(Collectors.toList());
1120
 
1121
        // Resolve partner names/codes
1122
        Map<Integer, CustomRetailer> retailerMap = Collections.emptyMap();
1123
        if (!validFofoIds.isEmpty()) {
1124
            try {
1125
                retailerMap = retailerService.getFofoRetailers(validFofoIds);
1126
            } catch (ProfitMandiBusinessException e) {
1127
                LOGGER.error("Error fetching fofo retailers for raw data", e);
1128
            }
1129
        }
1130
 
1131
        String rbmName = authUser.getFullName() + (isL2 ? " (L2)" : "");
1132
 
1133
        // Build rows
1134
        for (Integer fofoId : validFofoIds) {
1135
            int rank = collectionRankMap.getOrDefault(fofoId, 5);
1136
            boolean hasZeroBilling = !mtdBilledFofoIds.contains(fofoId);
1137
 
1138
            String status;
1139
            if (rank == 1) {
1140
                status = "Plan Today";
1141
            } else if (rank == 2) {
1142
                status = "Carry Forward";
1143
            } else if (rank == 3) {
1144
                status = "Untouched";
1145
            } else if (hasZeroBilling) {
1146
                status = "Zero Billing";
1147
            } else if (rank == 4) {
1148
                status = "Future Plan";
1149
            } else {
1150
                status = "Normal";
1151
            }
1152
 
1153
            CustomRetailer retailer = retailerMap.get(fofoId);
1154
            String partnerName = retailer != null ? retailer.getBusinessName() : "Unknown (" + fofoId + ")";
1155
            String partnerCode = retailer != null ? retailer.getCode() : "-";
1156
 
1157
            rows.add(Arrays.asList(partnerName, partnerCode, status, rbmName));
1158
        }
1159
 
1160
        return rows;
1161
    }
1162
 
33917 ranu 1163
}