Subversion Repositories SmartDukaan

Rev

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