Subversion Repositories SmartDukaan

Rev

Rev 37692 | Rev 37743 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
37125 vikas 1
package com.spice.profitmandi.service;
2
 
3
import com.spice.profitmandi.dao.entity.auth.AuthUser;
4
import com.spice.profitmandi.dao.entity.cs.Region;
5
import com.spice.profitmandi.dao.entity.user.Lead;
6
import com.spice.profitmandi.dao.enumuration.dtr.LeadStage;
7
import com.spice.profitmandi.dao.entity.user.LeadActivity;
8
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
9
import com.spice.profitmandi.dao.repository.cs.RegionRepository;
37692 vikas 10
import com.spice.profitmandi.dao.entity.user.LeadDnd;
11
import com.spice.profitmandi.dao.entity.user.LeadLiveLocation;
37125 vikas 12
import com.spice.profitmandi.dao.repository.dtr.LeadActivityRepository;
37692 vikas 13
import com.spice.profitmandi.dao.entity.user.LeadCall;
14
import com.spice.profitmandi.dao.repository.dtr.LeadCallRepository;
15
import com.spice.profitmandi.dao.repository.dtr.LeadDndRepository;
37737 vikas 16
import com.spice.profitmandi.dao.entity.auth.VonageAgent;
17
import com.spice.profitmandi.dao.repository.auth.VonageAgentRepository;
18
import com.spice.profitmandi.dao.repository.dtr.LeadRecordingAccessRepository;
37692 vikas 19
import com.spice.profitmandi.dao.repository.dtr.LeadLiveLocationRepository;
37125 vikas 20
import com.spice.profitmandi.dao.repository.dtr.LeadRepository;
21
import org.apache.logging.log4j.LogManager;
22
import org.apache.logging.log4j.Logger;
23
import org.springframework.beans.factory.annotation.Autowired;
24
import org.springframework.stereotype.Service;
25
 
26
import java.time.LocalDateTime;
27
import java.util.ArrayList;
28
import java.util.HashMap;
29
import java.util.LinkedHashMap;
30
import java.util.List;
31
import java.util.Map;
32
 
33
/**
34
 * Read-only aggregation for the LMS management dashboards (SOP §18) — Command Center + Dashboards.
35
 * Buckets EVERY lead: rows with a real {@link LeadStage} use it; legacy rows derive one in SQL
36
 * (see {@link LeadRepository#countByDerivedStage}). Returns plain JSON-ready Maps so the controller
37
 * can {@code gson.toJson(...)} them straight into the page / AJAX endpoints. No mutation, no schema change.
38
 *
39
 * <p>Coverage caveat (SOP §18.2): call/recording/order metrics (BGC call volume, RBM servicing, DND) are
40
 * NOT in the {@code Lead} schema, so those dashboards are surfaced as placeholders by the views. What this
41
 * service computes is everything derivable from the lead record: stage funnel, SLA compliance, ageing,
42
 * attention queues and the roll-up KPIs.
43
 */
44
@Service
45
public class LmsDashboardService {
46
 
47
    private static final Logger LOGGER = LogManager.getLogger(LmsDashboardService.class);
48
 
49
    /** Ordered happy-path for cumulative "reached" funnel math. */
50
    private static final LeadStage[] FUNNEL = LeadStage.HAPPY_PATH;
51
 
37692 vikas 52
    /** Hard ceiling on one page of the pipeline table — a caller asking for 10,000 rows gets 500. */
53
    private static final int MAX_PAGE_SIZE = 500;
54
 
37125 vikas 55
    /** Leads not touched for this many days count as "ageing" (SOP §18.2). */
56
    private static final int AGEING_DAYS = 7;
57
 
58
    /** Most-recent weeks shown in the SLA owner heat-map. */
59
    private static final int HEATMAP_WEEKS = 6;
60
 
61
    /** Cap on rows returned to a drill-down drawer. */
62
    private static final int DRILL_LIMIT = 100;
63
 
64
    @Autowired
65
    private LeadRepository leadRepository;
66
 
67
    @Autowired
68
    private RegionRepository regionRepository;
69
 
70
    @Autowired
71
    private AuthRepository authRepository;
72
 
73
    @Autowired
74
    private LmsAssignmentService lmsAssignmentService;
75
 
76
    @Autowired
77
    private LeadActivityRepository leadActivityRepository;
78
 
37692 vikas 79
    @Autowired
80
    private LeadCallRepository leadCallRepository;
81
 
82
    @Autowired
83
    private LeadDndRepository leadDndRepository;
84
 
85
    @Autowired
37737 vikas 86
    private LeadRecordingAccessRepository leadRecordingAccessRepository;
87
 
88
    @Autowired
89
    private VonageAgentRepository vonageAgentRepository;
90
 
91
    @Autowired
37692 vikas 92
    private LeadLiveLocationRepository leadLiveLocationRepository;
93
 
37125 vikas 94
    // ---- Command Center + shared summary ----------------------------------------------------
95
 
96
    /** KPIs + lifecycle funnel + attention queue for the given region / created-date window. */
97
    public Map<String, Object> summary(Integer regionId, LocalDateTime from, LocalDateTime to) {
98
        Map<String, Long> stage = toCountMap(leadRepository.countByDerivedStage(regionId, from, to));
99
        long total = 0;
100
        for (Long v : stage.values()) {
101
            total += v;
102
        }
103
 
104
        // Cumulative "reached at least this stage" along the happy path (monotonic, drives the funnel bars).
105
        long[] reached = new long[FUNNEL.length];
106
        for (int i = 0; i < FUNNEL.length; i++) {
107
            long sum = 0;
108
            for (int j = i; j < FUNNEL.length; j++) {
109
                sum += stage.getOrDefault(FUNNEL[j].name(), 0L);
110
            }
111
            reached[i] = sum;
112
        }
113
 
114
        LocalDateTime now = LocalDateTime.now();
115
        Object[] att = leadRepository.attentionCounts(regionId, now, now.plusHours(1));
116
        long breachedNoContact = num(att, 0);
117
        long hold = num(att, 1);
118
        long slaUnder1h = num(att, 2);
119
        long missingDisp = num(att, 3);
120
        long qualifiedNoBeat = num(att, 4);
121
        long onboardedPending = num(att, 5);
122
 
123
        // Onboarded value (SOP §18.2) = summed potential of ONBOARDED + ACTIVE leads.
124
        Map<String, Double> potByStage = toSumMap(leadRepository.sumPotentialByDerivedStage(regionId, from, to));
125
        double onboardedValue = potByStage.getOrDefault("ONBOARDED", 0d) + potByStage.getOrDefault("ACTIVE", 0d);
126
 
127
        long onboarded = stage.getOrDefault("ONBOARDED", 0L) + stage.getOrDefault("ACTIVE", 0L);
128
        long assigned = stage.getOrDefault("ASSIGNED", 0L);
129
        long contacted = stage.getOrDefault("CONTACTED", 0L);
130
        long qualified = stage.getOrDefault("QUALIFIED", 0L);
131
        long newCount = stage.getOrDefault("NEW", 0L);
132
 
133
        // KPI tiles (Command Center).
134
        List<Map<String, Object>> kpis = new ArrayList<>();
135
        kpis.add(kpi("new", "New", newCount, "in selected period", "navy"));
136
        kpis.add(kpi("awaiting", "Awaiting 1st contact", assigned, "SLA 3–5 hrs running", "amber"));
137
        kpis.add(kpi("sla", "SLA at risk / breached", breachedNoContact + slaUnder1h,
138
                breachedNoContact + " breached · " + slaUnder1h + " < 1 hr left", "red"));
139
        kpis.add(kpi("contacted", "Contacted", contacted, "dispositioned", "navy"));
140
        kpis.add(kpi("qualified", "Qualified", qualified, "value validated", "navy"));
141
        kpis.add(kpi("onboarded", "Onboarded", onboarded, "of " + total + " in scope", "good"));
142
 
143
        // Lifecycle funnel.
144
        List<Map<String, Object>> funnel = new ArrayList<>();
145
        long topN = total > 0 ? total : 1;
146
        // Top of funnel = every lead in scope.
147
        funnel.add(funnelStep("ALL", "All leads", total, pct(total, topN)));
148
        for (int i = 1; i < FUNNEL.length; i++) { // skip NEW itself; ALL is the 100% anchor
149
            LeadStage s = FUNNEL[i];
150
            funnel.add(funnelStep(s.name(), pretty(s), reached[i], pct(reached[i], topN)));
151
        }
152
 
153
        // Attention queue.
154
        List<Map<String, Object>> attention = new ArrayList<>();
155
        attention.add(attn("BREACHED_NO_CONTACT", "SLA breached — no first contact", "First contact overdue", breachedNoContact, "red"));
156
        attention.add(attn("HOLD", "Assigned but BM/RSM not mapped", "Region has no active owner", hold, "red"));
157
        attention.add(attn("SLA_UNDER_1H", "SLA < 1 hr remaining", "First contact due soon", slaUnder1h, "amber"));
158
        attention.add(attn("MISSING_DISP", "Calls missing a disposition", "Contacted, not dispositioned", missingDisp, "amber"));
159
        attention.add(attn("QUALIFIED_NO_BEAT", "Qualified, no beat plan yet", "Awaiting an ASM beat stop", qualifiedNoBeat, "navy"));
160
        attention.add(attn("ONBOARDED_PENDING", "Onboarded — pending RBM handover", "Handover to post-sales", onboardedPending, "violet"));
161
 
162
        Map<String, Object> out = new LinkedHashMap<>();
163
        out.put("total", total);
164
        out.put("onboardedValue", onboardedValue);
165
        out.put("conversionPct", pct(onboarded, topN));
166
        out.put("kpis", kpis);
167
        out.put("funnel", funnel);
168
        out.put("attention", attention);
169
        return out;
170
    }
171
 
172
    // ---- Dashboards: state funnel -----------------------------------------------------------
173
 
174
    /** One row per region: reached counts across the funnel, conversion % and SLA %. */
175
    public Map<String, Object> stateFunnel(LocalDateTime from, LocalDateTime to) {
176
        // regionCode -> (stage -> count)
177
        Map<String, Map<String, Long>> byRegion = new LinkedHashMap<>();
178
        for (Object[] row : leadRepository.countByRegionAndDerivedStage(from, to)) {
179
            String rc = str(row[0]);
180
            String s = str(row[1]);
181
            long c = ((Number) row[2]).longValue();
182
            byRegion.computeIfAbsent(rc, k -> new HashMap<>()).merge(s, c, Long::sum);
183
        }
184
        // regionCode -> sla %
185
        Map<String, Integer> slaByRegion = new HashMap<>();
186
        for (Object[] row : leadRepository.slaComplianceByRegion(from, to)) {
187
            String rc = str(row[0]);
188
            long totalDue = ((Number) row[1]).longValue();
189
            long met = ((Number) row[2]).longValue();
190
            slaByRegion.put(rc, (int) pct(met, totalDue));
191
        }
192
        // Friendly names from cs.region (keyed by upper region_code).
193
        Map<String, String> nameByCode = new HashMap<>();
194
        for (Region r : regionRepository.selectAll()) {
195
            if (r.getRegionCode() != null && !r.getRegionCode().trim().isEmpty()) {
196
                nameByCode.put(r.getRegionCode().trim().toUpperCase(), r.getName());
197
            }
198
        }
199
 
200
        List<Map<String, Object>> rows = new ArrayList<>();
201
        for (Map.Entry<String, Map<String, Long>> e : byRegion.entrySet()) {
202
            String code = e.getKey();
203
            Map<String, Long> stage = e.getValue();
204
            long total = 0;
205
            for (Long v : stage.values()) {
206
                total += v;
207
            }
208
            long contacted = reachedAtLeast(stage, LeadStage.CONTACTED);
209
            long qualified = reachedAtLeast(stage, LeadStage.QUALIFIED);
210
            long visited = reachedAtLeast(stage, LeadStage.VISITED);
211
            long onboarded = reachedAtLeast(stage, LeadStage.ONBOARDED);
212
 
213
            Map<String, Object> r = new LinkedHashMap<>();
214
            r.put("regionCode", code);
215
            r.put("regionName", nameByCode.getOrDefault(code, "UNMAPPED".equals(code) ? "Unmapped" : code));
216
            r.put("newCount", total);
217
            r.put("contacted", contacted);
218
            r.put("qualified", qualified);
219
            r.put("visited", visited);
220
            r.put("onboarded", onboarded);
221
            r.put("convPct", pct(onboarded, total));
222
            r.put("slaPct", slaByRegion.getOrDefault(code, 0));
223
            rows.add(r);
224
        }
225
        rows.sort((a, b) -> Long.compare(((Number) b.get("newCount")).longValue(), ((Number) a.get("newCount")).longValue()));
226
 
227
        Map<String, Object> out = new LinkedHashMap<>();
228
        out.put("rows", rows);
229
        return out;
230
    }
231
 
232
    // ---- Dashboards: SLA owner heat-map -----------------------------------------------------
233
 
234
    /** BM × recent-week on-time %, for the SLA compliance heat-map. */
235
    public Map<String, Object> slaHeatmap(LocalDateTime from, LocalDateTime to) {
236
        // bmId -> (isoYearWeek -> pct)
237
        Map<Integer, Map<Integer, Integer>> byBm = new LinkedHashMap<>();
238
        java.util.TreeSet<Integer> weekSet = new java.util.TreeSet<>();
239
        for (Object[] row : leadRepository.slaComplianceByBmAndWeek(from, to)) {
240
            Integer bmId = ((Number) row[0]).intValue();
241
            Integer wk = ((Number) row[1]).intValue();
242
            long totalDue = ((Number) row[2]).longValue();
243
            long met = ((Number) row[3]).longValue();
244
            weekSet.add(wk);
245
            byBm.computeIfAbsent(bmId, k -> new HashMap<>()).put(wk, (int) pct(met, totalDue));
246
        }
247
        // Keep the most recent HEATMAP_WEEKS weeks.
248
        List<Integer> allWeeks = new ArrayList<>(weekSet);
249
        List<Integer> weeks = allWeeks.size() > HEATMAP_WEEKS
250
                ? allWeeks.subList(allWeeks.size() - HEATMAP_WEEKS, allWeeks.size())
251
                : allWeeks;
252
 
253
        List<Map<String, Object>> bms = new ArrayList<>();
254
        for (Map.Entry<Integer, Map<Integer, Integer>> e : byBm.entrySet()) {
255
            AuthUser bm = authRepository.selectById(e.getKey());
256
            List<Object> cells = new ArrayList<>();
257
            for (Integer wk : weeks) {
258
                Integer p = e.getValue().get(wk);
259
                Map<String, Object> cell = new LinkedHashMap<>();
260
                cell.put("week", weekLabel(wk));
261
                cell.put("pct", p); // null → no data that week
262
                cells.add(cell);
263
            }
264
            Map<String, Object> r = new LinkedHashMap<>();
265
            r.put("bmId", e.getKey());
266
            r.put("bmName", bm != null ? bm.getFullName() : ("BM #" + e.getKey()));
267
            r.put("cells", cells);
268
            bms.add(r);
269
        }
270
 
271
        List<String> weekLabels = new ArrayList<>();
272
        for (Integer wk : weeks) {
273
            weekLabels.add(weekLabel(wk));
274
        }
275
        Map<String, Object> out = new LinkedHashMap<>();
276
        out.put("weeks", weekLabels);
277
        out.put("bms", bms);
278
        return out;
279
    }
280
 
281
    // ---- Dashboards: ageing -----------------------------------------------------------------
282
 
283
    /** Open leads stuck (untouched > {@value #AGEING_DAYS} days) bucketed by stage. */
284
    public Map<String, Object> ageing() {
285
        LocalDateTime olderThan = LocalDateTime.now().minusDays(AGEING_DAYS);
286
        List<Map<String, Object>> rows = new ArrayList<>();
287
        long total = 0;
288
        for (Object[] row : leadRepository.ageingByDerivedStage(olderThan)) {
289
            String s = str(row[0]);
290
            long c = ((Number) row[1]).longValue();
291
            total += c;
292
            Map<String, Object> r = new LinkedHashMap<>();
293
            r.put("stage", s);
294
            r.put("label", pretty(safeStage(s)));
295
            r.put("count", c);
296
            rows.add(r);
297
        }
298
        rows.sort((a, b) -> Long.compare(((Number) b.get("count")).longValue(), ((Number) a.get("count")).longValue()));
299
        Map<String, Object> out = new LinkedHashMap<>();
300
        out.put("days", AGEING_DAYS);
301
        out.put("total", total);
302
        out.put("rows", rows);
303
        return out;
304
    }
305
 
37737 vikas 306
    // ---- Standard report suite (SOP §18.2) --------------------------------------------------
307
 
308
    /**
309
     * BGC Daily: calls made, connect rate, average talk time and dispositions — per agent, per day.
310
     *
311
     * <p>Real telephony, not the {@code contacted / days} proxy the tile used to show. That proxy
312
     * was invented before {@code user.lead_call} existed and reported a plausible-looking number
313
     * that no call had ever contributed to.
314
     */
315
    public Map<String, Object> bgcDaily(LocalDateTime from, LocalDateTime to) {
316
        List<Object[]> rows = leadCallRepository.countDailyByAgent(from, to);
317
        java.util.Set<Integer> authIds = new java.util.HashSet<>();
318
        for (Object[] r : rows) {
319
            if (r[0] != null) authIds.add(((Number) r[0]).intValue());
320
        }
321
        Map<Integer, AuthUser> agents = new HashMap<>();
322
        if (!authIds.isEmpty()) {
323
            for (AuthUser u : authRepository.selectByIds(new ArrayList<>(authIds))) agents.put(u.getId(), u);
324
        }
325
 
326
        List<Map<String, Object>> out = new ArrayList<>();
327
        long totCalls = 0, totConn = 0, totTalk = 0;
328
        for (Object[] r : rows) {
329
            int authId = r[0] == null ? 0 : ((Number) r[0]).intValue();
330
            long calls = ((Number) r[2]).longValue();
331
            long conn = ((Number) r[3]).longValue();
332
            long talk = ((Number) r[4]).longValue();
333
            totCalls += calls; totConn += conn; totTalk += talk;
334
            AuthUser a = agents.get(authId);
335
            Map<String, Object> m = new LinkedHashMap<>();
336
            m.put("authId", authId);
337
            m.put("agent", a != null ? a.getFullName() : ("#" + authId));
338
            m.put("day", r[1] == null ? null : r[1].toString());
339
            m.put("calls", calls);
340
            m.put("connected", conn);
341
            m.put("connectPct", calls > 0 ? Math.round(conn * 1000.0 / calls) / 10.0 : 0);
342
            // Average over CONNECTED calls: dividing by every dial would make a day of unanswered
343
            // ringing look like short conversations rather than no conversations.
344
            m.put("avgTalkSeconds", conn > 0 ? Math.round(talk / (double) conn) : 0);
345
            m.put("longestSeconds", ((Number) r[5]).longValue());
346
            out.add(m);
347
        }
348
 
349
        Map<String, Object> res = new LinkedHashMap<>();
350
        res.put("rows", out);
351
        res.put("calls", totCalls);
352
        res.put("connected", totConn);
353
        res.put("connectPct", totCalls > 0 ? Math.round(totConn * 1000.0 / totCalls) / 10.0 : 0);
354
        res.put("avgTalkSeconds", totConn > 0 ? Math.round(totTalk / (double) totConn) : 0);
355
        res.put("talkMinutes", Math.round(totTalk / 60.0));
356
        return res;
357
    }
358
 
359
    /**
360
     * Audit Hygiene (SOP §17): the breaches an audit review actually looks for.
361
     *
362
     * <p>Each figure is either measured or reported as unavailable — never estimated. A hygiene
363
     * report that guesses is worse than one that admits a gap, because the gap is the finding.
364
     */
365
    public Map<String, Object> auditHygiene(LocalDateTime from, LocalDateTime to) {
366
        LocalDateTime now = LocalDateTime.now();
367
        Map<String, Object> m = new LinkedHashMap<>();
368
 
369
        // Same source the Command Center's attention tiles use, so the two cannot disagree.
370
        Object[] att = leadRepository.attentionCounts(null, now, now.plusHours(1));
371
        m.put("slaBreached", num(att, 0));
372
        m.put("hold", num(att, 1));
373
        m.put("missingDisposition", num(att, 3));
374
 
375
        m.put("dndRegister", leadDndRepository.count());
376
        List<Object[]> breaches = leadCallRepository.selectDndBreaches(from, to, 50);
377
        List<Map<String, Object>> bl = new ArrayList<>();
378
        for (Object[] b : breaches) {
379
            Map<String, Object> row = new LinkedHashMap<>();
380
            row.put("callId", ((Number) b[0]).intValue());
381
            row.put("leadId", ((Number) b[1]).intValue());
382
            row.put("authId", b[2] == null ? 0 : ((Number) b[2]).intValue());
383
            row.put("mobile", b[3] == null ? null : b[3].toString());
384
            row.put("when", b[4] == null ? null : b[4].toString());
385
            bl.add(row);
386
        }
387
        m.put("dndBreaches", bl);
388
        m.put("dndBreachCount", bl.size());
389
 
390
        m.put("recordingOpens", leadRecordingAccessRepository.countInWindow(from, to, true));
391
        m.put("recordingDenied", leadRecordingAccessRepository.countInWindow(from, to, false));
392
        return m;
393
    }
394
 
395
    // ---- Live call board ---------------------------------------------------------------------
396
 
397
    /**
398
     * A non-terminal call older than this is not believed. Only the browser's 3-second poll
399
     * terminalises a VBC call, so an agent who closed the tab mid-call leaves a row that is
400
     * forever RINGING/ANSWERED with a null ended_at. Without this the board would show them On
401
     * Call indefinitely — wrong in its single most-read column.
402
     */
403
    private static final int LIVE_CALL_STALE_MINUTES = 30;
404
    /** Just off a call and no outcome logged yet. */
405
    private static final int WRAP_UP_MINUTES = 2;
406
    /** No call for this long and the agent reads as idle rather than merely available. */
407
    private static final int IDLE_MINUTES = 15;
408
 
409
    /**
410
     * Per-agent live board (the LMS answer to the RBM Call Target Summary).
411
     *
412
     * <p>The roster is {@code auth.vonage_agent}, not every user with leads: an agent without a
413
     * device mapping cannot dial at all, so they have no place on a call board.
414
     *
415
     * <p>Status is derived from call activity — Vonage exposes no presence of any kind, so there is
416
     * deliberately no Login or Break here rather than a guess dressed up as one.
417
     */
418
    public Map<String, Object> liveCallBoard() {
419
        LocalDateTime now = LocalDateTime.now();
420
        LocalDateTime dayStart = now.toLocalDate().atStartOfDay();
421
 
422
        Map<Integer, Object[]> calls = byAuthId(leadCallRepository.selectLiveAgentBoard(dayStart, now));
423
        Map<Integer, Object[]> leads = byAuthId(leadRepository.selectAgentLeadCounters(now));
424
        Map<Integer, Object[]> acts = byAuthId(leadActivityRepository.countAgentActivity(dayStart, now));
425
 
426
        List<VonageAgent> roster = vonageAgentRepository.selectAll();
427
        java.util.Set<Integer> ids = new java.util.HashSet<>();
428
        for (VonageAgent a : roster) {
429
            ids.add(a.getAuthId());
430
        }
431
        Map<Integer, AuthUser> users = new HashMap<>();
432
        if (!ids.isEmpty()) {
433
            for (AuthUser u : authRepository.selectByIds(new ArrayList<>(ids))) {
434
                users.put(u.getId(), u);
435
            }
436
        }
437
 
438
        List<Map<String, Object>> rows = new ArrayList<>();
439
        long totCalls = 0, totConn = 0, totTalk = 0, onCallNow = 0;
440
 
441
        for (VonageAgent agent : roster) {
442
            int authId = agent.getAuthId();
443
            Object[] c = calls.get(authId);
444
            Object[] l = leads.get(authId);
445
            Object[] a = acts.get(authId);
446
            AuthUser u = users.get(authId);
447
 
448
            long cCalls = c == null ? 0 : num(c, 1);
449
            long cConn = c == null ? 0 : num(c, 2);
450
            long cTalk = c == null ? 0 : num(c, 3);
451
            LocalDateTime lastStarted = c == null ? null : ts(c, 5);
452
            LocalDateTime lastEnded = c == null ? null : ts(c, 6);
453
            Integer liveCallId = c == null || c[7] == null ? null : ((Number) c[7]).intValue();
454
            LocalDateTime liveStarted = c == null ? null : ts(c, 9);
455
 
456
            // A live row past the staleness window is an abandoned tab, not a conversation.
457
            boolean stale = liveStarted != null && liveStarted.isBefore(now.minusMinutes(LIVE_CALL_STALE_MINUTES));
458
            boolean live = liveCallId != null && !stale;
459
 
460
            String status;
461
            LocalDateTime since;
462
            if (!agent.isActive()) {
463
                status = "—";
464
                since = null;
465
            } else if (live) {
466
                status = "On Call";
467
                since = liveStarted;
468
                onCallNow++;
469
            } else if (lastEnded != null && lastEnded.isAfter(now.minusMinutes(WRAP_UP_MINUTES))) {
470
                status = "Wrap Up";
471
                since = lastEnded;
472
            } else if (lastEnded != null && lastEnded.isBefore(now.minusMinutes(IDLE_MINUTES))) {
473
                status = "Idle";
474
                since = lastEnded;
475
            } else if (lastEnded != null) {
476
                status = "Available";
477
                since = lastEnded;
478
            } else {
479
                status = "Available";
480
                since = null;
481
            }
482
 
483
            Map<String, Object> r = new LinkedHashMap<>();
484
            r.put("authId", authId);
485
            r.put("agent", u != null ? u.getFullName() : agent.getVonageUserName());
486
            r.put("extension", agent.getVbcExtension());
487
            r.put("status", status);
488
            // Computed, never stored — the RBM board does the same rather than persisting a clock.
489
            r.put("sinceSeconds", since == null ? null : java.time.Duration.between(since, now).getSeconds());
490
            r.put("staleCall", stale);
491
            r.put("liveCallId", live ? liveCallId : null);
492
            r.put("liveLeadId", live && c[8] != null ? ((Number) c[8]).intValue() : null);
493
            r.put("calls", cCalls);
494
            r.put("connected", cConn);
495
            r.put("connectPct", cCalls > 0 ? Math.round(cConn * 1000.0 / cCalls) / 10.0 : 0);
496
            r.put("talkSeconds", cTalk);
497
            r.put("longestSeconds", c == null ? 0 : num(c, 4));
498
            r.put("lastCallAt", lastStarted == null ? null : lastStarted.toString());
499
            r.put("assigned", l == null ? 0 : num(l, 1));
500
            r.put("slaBreached", l == null ? 0 : num(l, 2));
501
            r.put("touched", a == null ? 0 : num(a, 1));
502
            r.put("dispositioned", a == null ? 0 : num(a, 2));
503
            rows.add(r);
504
 
505
            totCalls += cCalls; totConn += cConn; totTalk += cTalk;
506
        }
507
 
508
        Map<String, Object> out = new LinkedHashMap<>();
509
        out.put("rows", rows);
510
        out.put("agents", rows.size());
511
        out.put("onCallNow", onCallNow);
512
        out.put("calls", totCalls);
513
        out.put("connected", totConn);
514
        out.put("connectPct", totCalls > 0 ? Math.round(totConn * 1000.0 / totCalls) / 10.0 : 0);
515
        out.put("talkMinutes", Math.round(totTalk / 60.0));
516
        out.put("asOf", now.toString());
517
        return out;
518
    }
519
 
520
    /**
521
     * The full call log for a window — every call, with ring time, talk time, outcome and recording.
522
     *
523
     * <p>The agent's extension comes from {@code auth.vonage_agent}, not from the call's
524
     * {@code from_number}: click2dial addresses the agent by DEVICE, so that column holds an opaque
525
     * id like {@code VH7NdQbBHcmsR8wFLsiU}, which means nothing to anyone reading a report.
526
     */
527
    public Map<String, Object> callLog(LocalDateTime from, LocalDateTime to, int page, int pageSize) {
528
        int size = Math.min(Math.max(pageSize, 1), MAX_PAGE_SIZE);
529
        int p = Math.max(page, 1);
530
        long total = leadCallRepository.countCallLog(from, to);
531
        List<Object[]> rows = leadCallRepository.selectCallLog(from, to, (p - 1) * size, size);
532
 
533
        java.util.Set<Integer> authIds = new java.util.HashSet<>();
534
        for (Object[] r : rows) {
535
            if (r[7] != null) {
536
                authIds.add(((Number) r[7]).intValue());
537
            }
538
        }
539
        Map<Integer, AuthUser> users = new HashMap<>();
540
        Map<Integer, String> extByAuth = new HashMap<>();
541
        if (!authIds.isEmpty()) {
542
            for (AuthUser u : authRepository.selectByIds(new ArrayList<>(authIds))) {
543
                users.put(u.getId(), u);
544
            }
545
            for (VonageAgent a : vonageAgentRepository.selectAll()) {
546
                extByAuth.put(a.getAuthId(), a.getVbcExtension());
547
            }
548
        }
549
 
550
        List<Map<String, Object>> out = new ArrayList<>();
551
        for (Object[] r : rows) {
552
            int authId = r[7] == null ? 0 : ((Number) r[7]).intValue();
553
            AuthUser u = users.get(authId);
554
            Map<String, Object> m = new LinkedHashMap<>();
555
            m.put("callId", ((Number) r[0]).intValue());
556
            m.put("startedAt", str(ts(r, 1)));
557
            m.put("answeredAt", str(ts(r, 2)));
558
            m.put("endedAt", str(ts(r, 3)));
559
            m.put("status", r[4] == null ? null : r[4].toString());
560
            // Negative or null when never answered — normalise to null so the UI shows a dash.
561
            Long ring = r[5] == null ? null : ((Number) r[5]).longValue();
562
            m.put("ringSeconds", ring != null && ring >= 0 ? ring : null);
563
            m.put("talkSeconds", num(r, 6));
564
            m.put("authId", authId);
565
            m.put("agent", u != null ? u.getFullName() : (authId > 0 ? "#" + authId : "—"));
566
            m.put("extension", extByAuth.get(authId));
567
            m.put("leadId", r[8] == null ? null : ((Number) r[8]).intValue());
568
            m.put("toNumber", r[9] == null ? null : r[9].toString());
569
            m.put("direction", r[10] == null ? null : r[10].toString());
570
            m.put("lmsCode", r[11] == null ? null : r[11].toString());
571
            m.put("retailer", r[12] == null ? null : r[12].toString().trim());
572
            m.put("outlet", r[13] == null ? null : r[13].toString());
573
            m.put("recording", r[14] == null ? "none" : r[14].toString());
574
            m.put("disposition", r[15] == null ? null : r[15].toString());
575
            out.add(m);
576
        }
577
 
578
        Map<String, Object> res = new LinkedHashMap<>();
579
        res.put("rows", out);
580
        res.put("total", total);
581
        res.put("page", p);
582
        res.put("pageSize", size);
583
        res.put("pages", (int) Math.ceil(total / (double) size));
584
        return res;
585
    }
586
 
587
    private String str(LocalDateTime t) {
588
        return t == null ? null : t.toString();
589
    }
590
 
591
    /** Index an aggregate result by its first column (the auth id). */
592
    private Map<Integer, Object[]> byAuthId(List<Object[]> rows) {
593
        Map<Integer, Object[]> m = new HashMap<>();
594
        if (rows != null) {
595
            for (Object[] r : rows) {
596
                if (r[0] != null) {
597
                    m.put(((Number) r[0]).intValue(), r);
598
                }
599
            }
600
        }
601
        return m;
602
    }
603
 
604
    /** Native queries hand back java.sql.Timestamp; the entity side works in LocalDateTime. */
605
    private LocalDateTime ts(Object[] row, int i) {
606
        Object v = row[i];
607
        if (v == null) {
608
            return null;
609
        }
610
        if (v instanceof java.sql.Timestamp) {
611
            return ((java.sql.Timestamp) v).toLocalDateTime();
612
        }
613
        return v instanceof LocalDateTime ? (LocalDateTime) v : null;
614
    }
615
 
37125 vikas 616
    // ---- Drill-down -------------------------------------------------------------------------
617
 
618
    /** Lead rows for a drill bucket, shaped for the drawer table. */
619
    public List<Map<String, Object>> drill(String bucketType, String bucketKey, Integer regionId,
620
                                            LocalDateTime from, LocalDateTime to) {
621
        LocalDateTime now = LocalDateTime.now();
622
        List<Integer> ids = leadRepository.selectLeadIdsForBucket(bucketType, bucketKey, regionId,
623
                now, now.plusHours(1), from, to, DRILL_LIMIT);
624
        List<Map<String, Object>> out = new ArrayList<>();
625
        if (ids == null || ids.isEmpty()) {
626
            return out;
627
        }
628
        // selectAllByIds returns id-desc; preserve the bucket's newest-first order.
629
        Map<Integer, Lead> leadById = new HashMap<>();
630
        for (Lead l : leadRepository.selectAllByIds(ids)) {
631
            leadById.put(l.getId(), l);
632
        }
37651 vikas 633
        List<Lead> ordered = new ArrayList<>(ids.size());
634
        for (Integer id : ids) {
635
            Lead l = leadById.get(id);
636
            if (l != null) {
637
                ordered.add(l);
638
            }
639
        }
640
        return toRows(ordered);
641
    }
642
 
643
    /**
37692 vikas 644
     * The Lead-pipeline table: every matching lead, not a client-side slice of the first page.
645
     *
646
     * <p>Returns the page plus the true total, so the table can report "50 of 229" rather than
647
     * implying the twelve rows it drew are all there are. A non-empty {@code q} searches across all
648
     * leads and ignores the date window — see {@code LeadRepository.selectPipeline}.
649
     */
650
    public Map<String, Object> pipeline(String q, Integer regionId, LocalDateTime from, LocalDateTime to,
651
                                        String sort, String dir, int page, int pageSize) {
652
        int size = Math.min(Math.max(pageSize, 1), MAX_PAGE_SIZE);
653
        int p = Math.max(page, 1);
654
        boolean searching = q != null && !q.trim().isEmpty();
655
 
656
        long total = leadRepository.countPipeline(q, regionId, from, to);
657
        List<Lead> leads = leadRepository.selectPipeline(q, regionId, from, to, sort, dir, (p - 1) * size, size);
658
 
659
        Map<String, Object> out = new LinkedHashMap<>();
660
        out.put("rows", toRows(leads));
661
        out.put("total", total);
662
        out.put("page", p);
663
        out.put("pageSize", size);
664
        out.put("pages", (int) Math.ceil(total / (double) size));
665
        out.put("sort", sort);
666
        out.put("dir", dir);
667
        // The caller renders a different caption when the date filter is not in play, so it has to
668
        // be told which mode the server actually used rather than inferring it.
669
        out.put("searching", searching);
670
        return out;
671
    }
672
 
673
    /**
37651 vikas 674
     * Free-text lookup for the dashboard search box: LMS id / retailer / business / mobile / city.
675
     * Same row shape as {@link #drill}, so results render in the same drawer table.
676
     */
677
    public List<Map<String, Object>> search(String term) {
678
        if (term == null || term.trim().isEmpty()) {
679
            return new ArrayList<>();
680
        }
681
        return toRows(leadRepository.selectByGlobalSearch(term.trim(), DRILL_LIMIT));
682
    }
683
 
684
    /** Shared drawer-row mapping for {@link #drill} and {@link #search}; owner names fetched in one batch. */
685
    private List<Map<String, Object>> toRows(List<Lead> leads) {
686
        List<Map<String, Object>> out = new ArrayList<>();
687
        if (leads == null || leads.isEmpty()) {
688
            return out;
689
        }
37125 vikas 690
        // Owner names in one batch.
691
        java.util.Set<Integer> ownerIds = new java.util.HashSet<>();
37651 vikas 692
        for (Lead l : leads) {
37125 vikas 693
            if (l.getAssignTo() > 0) {
694
                ownerIds.add(l.getAssignTo());
695
            }
696
        }
697
        Map<Integer, AuthUser> owners = new HashMap<>();
698
        if (!ownerIds.isEmpty()) {
699
            for (AuthUser u : authRepository.selectByIds(new ArrayList<>(ownerIds))) {
700
                owners.put(u.getId(), u);
701
            }
702
        }
703
 
37651 vikas 704
        for (Lead l : leads) {
37125 vikas 705
            LeadStage eff = l.getEffectiveStage();
706
            AuthUser owner = owners.get(l.getAssignTo());
707
            Map<String, Object> r = new LinkedHashMap<>();
708
            r.put("id", l.getId());
709
            r.put("lmsCode", l.getLmsCode() != null ? l.getLmsCode() : ("Lead #" + l.getId()));
710
            r.put("name", trimName(l.getFirstName(), l.getLastName()));
711
            r.put("outlet", l.getOutLetName());
712
            r.put("path", l.getCreationPath());
713
            r.put("stage", eff != null ? eff.name() : null);
714
            r.put("stageLabel", pretty(eff));
715
            r.put("owner", owner != null ? owner.getFullName() : (l.getAssignTo() > 0 ? "#" + l.getAssignTo() : "—"));
716
            r.put("slaState", lmsAssignmentService.slaState(l));
717
            r.put("value", l.getPotential());
37692 vikas 718
            // Both are sortable columns on the pipeline table, so the row has to carry them.
719
            r.put("city", l.getCity());
720
            r.put("createdBy", l.getCreatedBy());
37737 vikas 721
            // Lets the assign picker surface whoever covers this lead's region first.
722
            r.put("regionId", l.getRegionId());
37125 vikas 723
            out.add(r);
724
        }
725
        return out;
726
    }
727
 
728
    // ---- Lead Record (native, sts-mockup styled — read-only JSON) ---------------------------
729
 
730
    /** Full record for one lead: details + derived stage + SLA + append-only trail. Null if not found. */
731
    public Map<String, Object> record(int leadId) {
732
        Lead l = leadRepository.selectById(leadId);
733
        if (l == null) {
734
            return null;
735
        }
736
        LeadStage eff = l.getEffectiveStage();
737
        int stageIndex = -1;
738
        for (int i = 0; i < FUNNEL.length; i++) {
739
            if (FUNNEL[i] == eff) {
740
                stageIndex = i;
741
            }
742
        }
743
        boolean terminal = eff == LeadStage.NOT_INTERESTED || eff == LeadStage.DROPPED;
744
 
745
        AuthUser owner = l.getAssignTo() > 0 ? authRepository.selectById(l.getAssignTo()) : null;
746
        AuthUser bm = (l.getOwnerBmId() != null && l.getOwnerBmId() > 0) ? authRepository.selectById(l.getOwnerBmId()) : null;
747
 
748
        // Append-only trail, newest first.
749
        List<LeadActivity> acts = leadActivityRepository.selectBYLeadId(leadId);
750
        acts.sort((a, b) -> {
751
            LocalDateTime ta = a.getCreatedTimestamp(), tb = b.getCreatedTimestamp();
752
            if (ta == null && tb == null) return 0;
753
            if (ta == null) return 1;
754
            if (tb == null) return -1;
755
            return tb.compareTo(ta);
756
        });
757
        // Actor names in one batch.
758
        java.util.Set<Integer> ids = new java.util.HashSet<>();
759
        for (LeadActivity a : acts) {
760
            if (a.getAuthId() > 0) ids.add(a.getAuthId());
761
        }
762
        Map<Integer, AuthUser> actors = new HashMap<>();
763
        if (!ids.isEmpty()) {
764
            for (AuthUser u : authRepository.selectByIds(new ArrayList<>(ids))) {
765
                actors.put(u.getId(), u);
766
            }
767
        }
37692 vikas 768
        // Calls keyed by id, so a disposition in the trail can carry the recording of the call it came
769
        // from. A disposition is the agent's account of the conversation; having to hunt for the audio
770
        // in a separate list to check it against the recording is the friction worth removing.
771
        Map<Integer, LeadCall> callById = new HashMap<>();
772
        List<LeadCall> calls = leadCallRepository.selectByLeadId(leadId);
773
        if (calls != null) {
774
            for (LeadCall c : calls) {
775
                callById.put(c.getId(), c);
776
            }
777
        }
778
 
37125 vikas 779
        List<Map<String, Object>> trail = new ArrayList<>();
780
        for (LeadActivity a : acts) {
781
            AuthUser act = actors.get(a.getAuthId());
782
            Map<String, Object> t = new LinkedHashMap<>();
783
            t.put("when", a.getCreatedTimestamp() == null ? null : a.getCreatedTimestamp().toString());
784
            t.put("actor", act != null ? act.getFullName() : (a.getAuthId() > 0 ? "#" + a.getAuthId() : "System"));
785
            t.put("type", a.getCommunicationType() == null ? null : a.getCommunicationType().name());
786
            t.put("body", a.getRemark());
787
            t.put("scheduled", a.getSchelduleTimestamp() == null ? null : a.getSchelduleTimestamp().toString());
37692 vikas 788
 
789
            // Either handle is enough to play: the gated endpoint serves our archived copy when there
790
            // is one and proxies the vendor's otherwise, so an agent is not made to wait on the
791
            // archival sweep to hear a call. The URL is never the raw vendor one — playback goes
792
            // through /lms/recording/{id}, which enforces the §15 matrix and logs the open.
793
            LeadCall call = a.getLeadCallId() == null ? null : callById.get(a.getLeadCallId());
794
            if (call != null && (call.getRecordingObjectKey() != null || call.getRecordingUuid() != null)) {
795
                t.put("callId", call.getId());
796
                t.put("durationSeconds", call.getDurationSeconds());
797
                t.put("archived", call.getRecordingObjectKey() != null);
798
            }
37125 vikas 799
            trail.add(t);
800
        }
801
 
802
        Map<String, Object> m = new LinkedHashMap<>();
803
        m.put("id", l.getId());
804
        m.put("lmsCode", l.getLmsCode());
805
        m.put("name", trimName(l.getFirstName(), l.getLastName()));
806
        m.put("outlet", l.getOutLetName());
807
        m.put("stage", eff != null ? eff.name() : null);
808
        m.put("stageLabel", pretty(eff));
809
        m.put("stageIndex", stageIndex);
810
        m.put("terminal", terminal);
811
        m.put("created", l.getCreatedTimestamp() == null ? null : l.getCreatedTimestamp().toString());
812
        m.put("createdBy", owner != null ? owner.getFullName() : null); // best-effort
813
        m.put("path", l.getCreationPath());
814
        m.put("contact", l.getLeadMobile());
815
        m.put("location", joinLoc(l.getAddress(), l.getCity(), l.getState()));
816
        m.put("regionCode", l.getRegionCode());
817
        m.put("value", l.getPotential());
818
        m.put("source", l.getSource());
819
        m.put("disposition", l.getDisposition() == null ? null : l.getDisposition().name());
820
        m.put("ownerBm", bm != null ? bm.getFullName() : null);
821
        m.put("owner", owner != null ? owner.getFullName() : null);
822
        m.put("assignmentStatus", l.getAssignmentStatus());
823
        m.put("slaState", lmsAssignmentService.slaState(l));
824
        m.put("firstContactDue", l.getFirstContactDue() == null ? null : l.getFirstContactDue().toString());
825
        m.put("firstContactedAt", l.getFirstContactedAt() == null ? null : l.getFirstContactedAt().toString());
826
        m.put("unreachableCount", l.getUnreachableCount());
37692 vikas 827
 
828
        // The dashboard's record tab acts on the lead rather than only displaying it, so it needs
829
        // the same three things the in-app screen reads before it offers a control:
830
        //   - the parts of the address, not just the joined string, or an edit would have to
831
        //     re-split "addr, city, state" and would corrupt any value containing a comma;
832
        //   - the region id, so the edit form can preselect it (regionCode alone cannot);
833
        //   - whether the number is blocked and whether the geo-pin is approved, so the call and
834
        //     beat controls can say why they are unavailable instead of failing on submit.
835
        m.put("regionId", l.getRegionId());
836
        m.put("address", l.getAddress());
837
        m.put("city", l.getCity());
838
        m.put("state", l.getState());
839
 
840
        LeadDnd dnd = leadDndRepository.selectByMobile(l.getLeadMobile());
841
        m.put("dnd", dnd != null);
842
        m.put("dndReason", dnd == null ? null : dnd.getReason());
843
 
844
        // The pin itself, not just a yes/no: the record card offers a map link when it is approved
845
        // and pre-fills the manual-verify form with the existing coords when it is not, so nudging
846
        // a slightly-off pin does not mean typing it from scratch.
847
        LeadLiveLocation geo = leadLiveLocationRepository.selectByLeadId(leadId);
848
        m.put("geoApproved", geo != null && geo.getStatus() != null
849
                && "APPROVED".equalsIgnoreCase(geo.getStatus().toString()));
850
        m.put("geoStatus", geo == null || geo.getStatus() == null ? null : geo.getStatus().toString());
851
        if (geo != null && (geo.getLatitude() != 0 || geo.getLongitude() != 0)) {
852
            m.put("geoLat", geo.getLatitude());
853
            m.put("geoLng", geo.getLongitude());
854
        }
855
        m.put("geoPhotoId", geo == null ? 0 : geo.getImageDocumentId());
856
 
37125 vikas 857
        m.put("trail", trail);
858
        return m;
859
    }
860
 
861
    private String joinLoc(String a, String c, String s) {
862
        StringBuilder sb = new StringBuilder();
863
        for (String p : new String[]{a, c, s}) {
864
            if (p != null && !p.trim().isEmpty()) {
865
                if (sb.length() > 0) sb.append(", ");
866
                sb.append(p.trim());
867
            }
868
        }
869
        return sb.toString();
870
    }
871
 
872
    // ---- helpers ----------------------------------------------------------------------------
873
 
874
    private long reachedAtLeast(Map<String, Long> stage, LeadStage at) {
875
        long sum = 0;
876
        boolean counting = false;
877
        for (LeadStage s : FUNNEL) {
878
            if (s == at) {
879
                counting = true;
880
            }
881
            if (counting) {
882
                sum += stage.getOrDefault(s.name(), 0L);
883
            }
884
        }
885
        return sum;
886
    }
887
 
888
    private Map<String, Long> toCountMap(List<Object[]> rows) {
889
        Map<String, Long> m = new HashMap<>();
890
        for (Object[] r : rows) {
891
            if (r[0] == null) {
892
                continue;
893
            }
894
            m.merge(String.valueOf(r[0]), ((Number) r[1]).longValue(), Long::sum);
895
        }
896
        return m;
897
    }
898
 
899
    private Map<String, Double> toSumMap(List<Object[]> rows) {
900
        Map<String, Double> m = new HashMap<>();
901
        for (Object[] r : rows) {
902
            if (r[0] == null) {
903
                continue;
904
            }
905
            double v = r[1] == null ? 0d : ((Number) r[1]).doubleValue();
906
            m.merge(String.valueOf(r[0]), v, Double::sum);
907
        }
908
        return m;
909
    }
910
 
911
    private long num(Object[] row, int i) {
912
        if (row == null || i >= row.length || row[i] == null) {
913
            return 0L;
914
        }
915
        return ((Number) row[i]).longValue();
916
    }
917
 
918
    private long pct(long part, long whole) {
919
        if (whole <= 0) {
920
            return 0;
921
        }
922
        return Math.round((part * 100.0) / whole);
923
    }
924
 
925
    private String str(Object o) {
926
        return o == null ? "" : String.valueOf(o);
927
    }
928
 
929
    private Map<String, Object> kpi(String key, String label, long value, String foot, String tone) {
930
        Map<String, Object> m = new LinkedHashMap<>();
931
        m.put("key", key);
932
        m.put("label", label);
933
        m.put("value", value);
934
        m.put("foot", foot);
935
        m.put("tone", tone);
936
        return m;
937
    }
938
 
939
    private Map<String, Object> funnelStep(String stage, String label, long count, long pct) {
940
        Map<String, Object> m = new LinkedHashMap<>();
941
        m.put("stage", stage);
942
        m.put("label", label);
943
        m.put("count", count);
944
        m.put("pct", pct);
945
        return m;
946
    }
947
 
948
    private Map<String, Object> attn(String key, String title, String detail, long count, String tone) {
949
        Map<String, Object> m = new LinkedHashMap<>();
950
        m.put("key", key);
951
        m.put("title", title);
952
        m.put("detail", detail);
953
        m.put("count", count);
954
        m.put("tone", tone);
955
        return m;
956
    }
957
 
958
    private String trimName(String first, String last) {
959
        String f = first == null ? "" : first.trim();
960
        String l = last == null ? "" : last.trim();
961
        return (f + " " + l).trim();
962
    }
963
 
964
    private LeadStage safeStage(String s) {
965
        try {
966
            return LeadStage.valueOf(s);
967
        } catch (Exception e) {
968
            return null;
969
        }
970
    }
971
 
972
    /** "NEW" → "New", "BEAT_PLANNED" → "Beat planned". */
973
    private String pretty(LeadStage s) {
974
        if (s == null) {
975
            return "—";
976
        }
977
        String[] parts = s.name().toLowerCase().split("_");
978
        StringBuilder sb = new StringBuilder();
979
        for (int i = 0; i < parts.length; i++) {
980
            if (parts[i].isEmpty()) {
981
                continue;
982
            }
983
            if (i == 0) {
984
                sb.append(Character.toUpperCase(parts[i].charAt(0))).append(parts[i].substring(1));
985
            } else {
986
                sb.append(' ').append(parts[i]);
987
            }
988
        }
989
        return sb.toString();
990
    }
991
 
992
    /** ISO yyyyww (YEARWEEK mode 3) → a short "w<week>" label. */
993
    private String weekLabel(int isoYearWeek) {
994
        int week = isoYearWeek % 100;
995
        return "W" + week;
996
    }
997
}