| 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 |
|
| 37743 |
vikas |
61 |
/** Cap on rows returned to a drill-down drawer. Public so the drawer can say it is showing a slice. */
|
|
|
62 |
public static final int DRILL_LIMIT = 100;
|
| 37125 |
vikas |
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) {
|
| 37743 |
vikas |
621 |
String type = bucketType == null ? "" : bucketType.trim().toUpperCase();
|
|
|
622 |
String key = bucketKey;
|
|
|
623 |
// The funnel asks for a stage cumulatively -- "reached CONTACTED" means CONTACTED or anything
|
|
|
624 |
// beyond it, which is exactly how the bar was counted. Expand it here, where the happy path
|
|
|
625 |
// already lives, rather than teaching the repository the order of the lifecycle.
|
|
|
626 |
if ("STAGE_REACHED".equals(type)) {
|
|
|
627 |
type = "STAGE_IN";
|
|
|
628 |
key = stagesFrom(bucketKey);
|
|
|
629 |
}
|
| 37125 |
vikas |
630 |
LocalDateTime now = LocalDateTime.now();
|
| 37743 |
vikas |
631 |
List<Integer> ids = leadRepository.selectLeadIdsForBucket(type, key, regionId,
|
| 37125 |
vikas |
632 |
now, now.plusHours(1), from, to, DRILL_LIMIT);
|
|
|
633 |
List<Map<String, Object>> out = new ArrayList<>();
|
|
|
634 |
if (ids == null || ids.isEmpty()) {
|
|
|
635 |
return out;
|
|
|
636 |
}
|
|
|
637 |
// selectAllByIds returns id-desc; preserve the bucket's newest-first order.
|
|
|
638 |
Map<Integer, Lead> leadById = new HashMap<>();
|
|
|
639 |
for (Lead l : leadRepository.selectAllByIds(ids)) {
|
|
|
640 |
leadById.put(l.getId(), l);
|
|
|
641 |
}
|
| 37651 |
vikas |
642 |
List<Lead> ordered = new ArrayList<>(ids.size());
|
|
|
643 |
for (Integer id : ids) {
|
|
|
644 |
Lead l = leadById.get(id);
|
|
|
645 |
if (l != null) {
|
|
|
646 |
ordered.add(l);
|
|
|
647 |
}
|
|
|
648 |
}
|
|
|
649 |
return toRows(ordered);
|
|
|
650 |
}
|
|
|
651 |
|
|
|
652 |
/**
|
| 37743 |
vikas |
653 |
* The given stage and every stage after it on the happy path, comma-separated -- the set the
|
|
|
654 |
* cumulative funnel bar counted. An unrecognised stage (a terminal one such as NOT_INTERESTED,
|
|
|
655 |
* which is not on the path) passes through unchanged and matches only itself.
|
|
|
656 |
*/
|
|
|
657 |
private String stagesFrom(String stage) {
|
|
|
658 |
String wanted = stage == null ? "" : stage.trim();
|
|
|
659 |
int idx = -1;
|
|
|
660 |
for (int i = 0; i < FUNNEL.length; i++) {
|
|
|
661 |
if (FUNNEL[i].name().equalsIgnoreCase(wanted)) {
|
|
|
662 |
idx = i;
|
|
|
663 |
break;
|
|
|
664 |
}
|
|
|
665 |
}
|
|
|
666 |
if (idx < 0) {
|
|
|
667 |
return wanted;
|
|
|
668 |
}
|
|
|
669 |
StringBuilder sb = new StringBuilder();
|
|
|
670 |
for (int i = idx; i < FUNNEL.length; i++) {
|
|
|
671 |
if (sb.length() > 0) {
|
|
|
672 |
sb.append(',');
|
|
|
673 |
}
|
|
|
674 |
sb.append(FUNNEL[i].name());
|
|
|
675 |
}
|
|
|
676 |
return sb.toString();
|
|
|
677 |
}
|
|
|
678 |
|
|
|
679 |
/**
|
| 37692 |
vikas |
680 |
* The Lead-pipeline table: every matching lead, not a client-side slice of the first page.
|
|
|
681 |
*
|
|
|
682 |
* <p>Returns the page plus the true total, so the table can report "50 of 229" rather than
|
|
|
683 |
* implying the twelve rows it drew are all there are. A non-empty {@code q} searches across all
|
|
|
684 |
* leads and ignores the date window — see {@code LeadRepository.selectPipeline}.
|
|
|
685 |
*/
|
|
|
686 |
public Map<String, Object> pipeline(String q, Integer regionId, LocalDateTime from, LocalDateTime to,
|
|
|
687 |
String sort, String dir, int page, int pageSize) {
|
|
|
688 |
int size = Math.min(Math.max(pageSize, 1), MAX_PAGE_SIZE);
|
|
|
689 |
int p = Math.max(page, 1);
|
|
|
690 |
boolean searching = q != null && !q.trim().isEmpty();
|
|
|
691 |
|
|
|
692 |
long total = leadRepository.countPipeline(q, regionId, from, to);
|
|
|
693 |
List<Lead> leads = leadRepository.selectPipeline(q, regionId, from, to, sort, dir, (p - 1) * size, size);
|
|
|
694 |
|
|
|
695 |
Map<String, Object> out = new LinkedHashMap<>();
|
|
|
696 |
out.put("rows", toRows(leads));
|
|
|
697 |
out.put("total", total);
|
|
|
698 |
out.put("page", p);
|
|
|
699 |
out.put("pageSize", size);
|
|
|
700 |
out.put("pages", (int) Math.ceil(total / (double) size));
|
|
|
701 |
out.put("sort", sort);
|
|
|
702 |
out.put("dir", dir);
|
|
|
703 |
// The caller renders a different caption when the date filter is not in play, so it has to
|
|
|
704 |
// be told which mode the server actually used rather than inferring it.
|
|
|
705 |
out.put("searching", searching);
|
|
|
706 |
return out;
|
|
|
707 |
}
|
|
|
708 |
|
|
|
709 |
/**
|
| 37651 |
vikas |
710 |
* Free-text lookup for the dashboard search box: LMS id / retailer / business / mobile / city.
|
|
|
711 |
* Same row shape as {@link #drill}, so results render in the same drawer table.
|
|
|
712 |
*/
|
|
|
713 |
public List<Map<String, Object>> search(String term) {
|
|
|
714 |
if (term == null || term.trim().isEmpty()) {
|
|
|
715 |
return new ArrayList<>();
|
|
|
716 |
}
|
|
|
717 |
return toRows(leadRepository.selectByGlobalSearch(term.trim(), DRILL_LIMIT));
|
|
|
718 |
}
|
|
|
719 |
|
|
|
720 |
/** Shared drawer-row mapping for {@link #drill} and {@link #search}; owner names fetched in one batch. */
|
|
|
721 |
private List<Map<String, Object>> toRows(List<Lead> leads) {
|
|
|
722 |
List<Map<String, Object>> out = new ArrayList<>();
|
|
|
723 |
if (leads == null || leads.isEmpty()) {
|
|
|
724 |
return out;
|
|
|
725 |
}
|
| 37125 |
vikas |
726 |
// Owner names in one batch.
|
|
|
727 |
java.util.Set<Integer> ownerIds = new java.util.HashSet<>();
|
| 37651 |
vikas |
728 |
for (Lead l : leads) {
|
| 37125 |
vikas |
729 |
if (l.getAssignTo() > 0) {
|
|
|
730 |
ownerIds.add(l.getAssignTo());
|
|
|
731 |
}
|
|
|
732 |
}
|
|
|
733 |
Map<Integer, AuthUser> owners = new HashMap<>();
|
|
|
734 |
if (!ownerIds.isEmpty()) {
|
|
|
735 |
for (AuthUser u : authRepository.selectByIds(new ArrayList<>(ownerIds))) {
|
|
|
736 |
owners.put(u.getId(), u);
|
|
|
737 |
}
|
|
|
738 |
}
|
|
|
739 |
|
| 37651 |
vikas |
740 |
for (Lead l : leads) {
|
| 37125 |
vikas |
741 |
LeadStage eff = l.getEffectiveStage();
|
|
|
742 |
AuthUser owner = owners.get(l.getAssignTo());
|
|
|
743 |
Map<String, Object> r = new LinkedHashMap<>();
|
|
|
744 |
r.put("id", l.getId());
|
|
|
745 |
r.put("lmsCode", l.getLmsCode() != null ? l.getLmsCode() : ("Lead #" + l.getId()));
|
|
|
746 |
r.put("name", trimName(l.getFirstName(), l.getLastName()));
|
|
|
747 |
r.put("outlet", l.getOutLetName());
|
|
|
748 |
r.put("path", l.getCreationPath());
|
|
|
749 |
r.put("stage", eff != null ? eff.name() : null);
|
|
|
750 |
r.put("stageLabel", pretty(eff));
|
|
|
751 |
r.put("owner", owner != null ? owner.getFullName() : (l.getAssignTo() > 0 ? "#" + l.getAssignTo() : "—"));
|
|
|
752 |
r.put("slaState", lmsAssignmentService.slaState(l));
|
|
|
753 |
r.put("value", l.getPotential());
|
| 37692 |
vikas |
754 |
// Both are sortable columns on the pipeline table, so the row has to carry them.
|
|
|
755 |
r.put("city", l.getCity());
|
|
|
756 |
r.put("createdBy", l.getCreatedBy());
|
| 37737 |
vikas |
757 |
// Lets the assign picker surface whoever covers this lead's region first.
|
|
|
758 |
r.put("regionId", l.getRegionId());
|
| 37125 |
vikas |
759 |
out.add(r);
|
|
|
760 |
}
|
|
|
761 |
return out;
|
|
|
762 |
}
|
|
|
763 |
|
|
|
764 |
// ---- Lead Record (native, sts-mockup styled — read-only JSON) ---------------------------
|
|
|
765 |
|
|
|
766 |
/** Full record for one lead: details + derived stage + SLA + append-only trail. Null if not found. */
|
|
|
767 |
public Map<String, Object> record(int leadId) {
|
|
|
768 |
Lead l = leadRepository.selectById(leadId);
|
|
|
769 |
if (l == null) {
|
|
|
770 |
return null;
|
|
|
771 |
}
|
|
|
772 |
LeadStage eff = l.getEffectiveStage();
|
|
|
773 |
int stageIndex = -1;
|
|
|
774 |
for (int i = 0; i < FUNNEL.length; i++) {
|
|
|
775 |
if (FUNNEL[i] == eff) {
|
|
|
776 |
stageIndex = i;
|
|
|
777 |
}
|
|
|
778 |
}
|
|
|
779 |
boolean terminal = eff == LeadStage.NOT_INTERESTED || eff == LeadStage.DROPPED;
|
|
|
780 |
|
|
|
781 |
AuthUser owner = l.getAssignTo() > 0 ? authRepository.selectById(l.getAssignTo()) : null;
|
|
|
782 |
AuthUser bm = (l.getOwnerBmId() != null && l.getOwnerBmId() > 0) ? authRepository.selectById(l.getOwnerBmId()) : null;
|
|
|
783 |
|
|
|
784 |
// Append-only trail, newest first.
|
|
|
785 |
List<LeadActivity> acts = leadActivityRepository.selectBYLeadId(leadId);
|
|
|
786 |
acts.sort((a, b) -> {
|
|
|
787 |
LocalDateTime ta = a.getCreatedTimestamp(), tb = b.getCreatedTimestamp();
|
|
|
788 |
if (ta == null && tb == null) return 0;
|
|
|
789 |
if (ta == null) return 1;
|
|
|
790 |
if (tb == null) return -1;
|
|
|
791 |
return tb.compareTo(ta);
|
|
|
792 |
});
|
|
|
793 |
// Actor names in one batch.
|
|
|
794 |
java.util.Set<Integer> ids = new java.util.HashSet<>();
|
|
|
795 |
for (LeadActivity a : acts) {
|
|
|
796 |
if (a.getAuthId() > 0) ids.add(a.getAuthId());
|
|
|
797 |
}
|
|
|
798 |
Map<Integer, AuthUser> actors = new HashMap<>();
|
|
|
799 |
if (!ids.isEmpty()) {
|
|
|
800 |
for (AuthUser u : authRepository.selectByIds(new ArrayList<>(ids))) {
|
|
|
801 |
actors.put(u.getId(), u);
|
|
|
802 |
}
|
|
|
803 |
}
|
| 37692 |
vikas |
804 |
// Calls keyed by id, so a disposition in the trail can carry the recording of the call it came
|
|
|
805 |
// from. A disposition is the agent's account of the conversation; having to hunt for the audio
|
|
|
806 |
// in a separate list to check it against the recording is the friction worth removing.
|
|
|
807 |
Map<Integer, LeadCall> callById = new HashMap<>();
|
|
|
808 |
List<LeadCall> calls = leadCallRepository.selectByLeadId(leadId);
|
|
|
809 |
if (calls != null) {
|
|
|
810 |
for (LeadCall c : calls) {
|
|
|
811 |
callById.put(c.getId(), c);
|
|
|
812 |
}
|
|
|
813 |
}
|
|
|
814 |
|
| 37125 |
vikas |
815 |
List<Map<String, Object>> trail = new ArrayList<>();
|
|
|
816 |
for (LeadActivity a : acts) {
|
|
|
817 |
AuthUser act = actors.get(a.getAuthId());
|
|
|
818 |
Map<String, Object> t = new LinkedHashMap<>();
|
|
|
819 |
t.put("when", a.getCreatedTimestamp() == null ? null : a.getCreatedTimestamp().toString());
|
|
|
820 |
t.put("actor", act != null ? act.getFullName() : (a.getAuthId() > 0 ? "#" + a.getAuthId() : "System"));
|
|
|
821 |
t.put("type", a.getCommunicationType() == null ? null : a.getCommunicationType().name());
|
|
|
822 |
t.put("body", a.getRemark());
|
|
|
823 |
t.put("scheduled", a.getSchelduleTimestamp() == null ? null : a.getSchelduleTimestamp().toString());
|
| 37692 |
vikas |
824 |
|
|
|
825 |
// Either handle is enough to play: the gated endpoint serves our archived copy when there
|
|
|
826 |
// is one and proxies the vendor's otherwise, so an agent is not made to wait on the
|
|
|
827 |
// archival sweep to hear a call. The URL is never the raw vendor one — playback goes
|
|
|
828 |
// through /lms/recording/{id}, which enforces the §15 matrix and logs the open.
|
|
|
829 |
LeadCall call = a.getLeadCallId() == null ? null : callById.get(a.getLeadCallId());
|
|
|
830 |
if (call != null && (call.getRecordingObjectKey() != null || call.getRecordingUuid() != null)) {
|
|
|
831 |
t.put("callId", call.getId());
|
|
|
832 |
t.put("durationSeconds", call.getDurationSeconds());
|
|
|
833 |
t.put("archived", call.getRecordingObjectKey() != null);
|
|
|
834 |
}
|
| 37125 |
vikas |
835 |
trail.add(t);
|
|
|
836 |
}
|
|
|
837 |
|
|
|
838 |
Map<String, Object> m = new LinkedHashMap<>();
|
|
|
839 |
m.put("id", l.getId());
|
|
|
840 |
m.put("lmsCode", l.getLmsCode());
|
|
|
841 |
m.put("name", trimName(l.getFirstName(), l.getLastName()));
|
|
|
842 |
m.put("outlet", l.getOutLetName());
|
|
|
843 |
m.put("stage", eff != null ? eff.name() : null);
|
|
|
844 |
m.put("stageLabel", pretty(eff));
|
|
|
845 |
m.put("stageIndex", stageIndex);
|
|
|
846 |
m.put("terminal", terminal);
|
|
|
847 |
m.put("created", l.getCreatedTimestamp() == null ? null : l.getCreatedTimestamp().toString());
|
|
|
848 |
m.put("createdBy", owner != null ? owner.getFullName() : null); // best-effort
|
|
|
849 |
m.put("path", l.getCreationPath());
|
|
|
850 |
m.put("contact", l.getLeadMobile());
|
|
|
851 |
m.put("location", joinLoc(l.getAddress(), l.getCity(), l.getState()));
|
|
|
852 |
m.put("regionCode", l.getRegionCode());
|
|
|
853 |
m.put("value", l.getPotential());
|
|
|
854 |
m.put("source", l.getSource());
|
|
|
855 |
m.put("disposition", l.getDisposition() == null ? null : l.getDisposition().name());
|
|
|
856 |
m.put("ownerBm", bm != null ? bm.getFullName() : null);
|
|
|
857 |
m.put("owner", owner != null ? owner.getFullName() : null);
|
|
|
858 |
m.put("assignmentStatus", l.getAssignmentStatus());
|
|
|
859 |
m.put("slaState", lmsAssignmentService.slaState(l));
|
|
|
860 |
m.put("firstContactDue", l.getFirstContactDue() == null ? null : l.getFirstContactDue().toString());
|
|
|
861 |
m.put("firstContactedAt", l.getFirstContactedAt() == null ? null : l.getFirstContactedAt().toString());
|
|
|
862 |
m.put("unreachableCount", l.getUnreachableCount());
|
| 37692 |
vikas |
863 |
|
|
|
864 |
// The dashboard's record tab acts on the lead rather than only displaying it, so it needs
|
|
|
865 |
// the same three things the in-app screen reads before it offers a control:
|
|
|
866 |
// - the parts of the address, not just the joined string, or an edit would have to
|
|
|
867 |
// re-split "addr, city, state" and would corrupt any value containing a comma;
|
|
|
868 |
// - the region id, so the edit form can preselect it (regionCode alone cannot);
|
|
|
869 |
// - whether the number is blocked and whether the geo-pin is approved, so the call and
|
|
|
870 |
// beat controls can say why they are unavailable instead of failing on submit.
|
|
|
871 |
m.put("regionId", l.getRegionId());
|
|
|
872 |
m.put("address", l.getAddress());
|
|
|
873 |
m.put("city", l.getCity());
|
|
|
874 |
m.put("state", l.getState());
|
|
|
875 |
|
|
|
876 |
LeadDnd dnd = leadDndRepository.selectByMobile(l.getLeadMobile());
|
|
|
877 |
m.put("dnd", dnd != null);
|
|
|
878 |
m.put("dndReason", dnd == null ? null : dnd.getReason());
|
|
|
879 |
|
|
|
880 |
// The pin itself, not just a yes/no: the record card offers a map link when it is approved
|
|
|
881 |
// and pre-fills the manual-verify form with the existing coords when it is not, so nudging
|
|
|
882 |
// a slightly-off pin does not mean typing it from scratch.
|
|
|
883 |
LeadLiveLocation geo = leadLiveLocationRepository.selectByLeadId(leadId);
|
|
|
884 |
m.put("geoApproved", geo != null && geo.getStatus() != null
|
|
|
885 |
&& "APPROVED".equalsIgnoreCase(geo.getStatus().toString()));
|
|
|
886 |
m.put("geoStatus", geo == null || geo.getStatus() == null ? null : geo.getStatus().toString());
|
|
|
887 |
if (geo != null && (geo.getLatitude() != 0 || geo.getLongitude() != 0)) {
|
|
|
888 |
m.put("geoLat", geo.getLatitude());
|
|
|
889 |
m.put("geoLng", geo.getLongitude());
|
|
|
890 |
}
|
|
|
891 |
m.put("geoPhotoId", geo == null ? 0 : geo.getImageDocumentId());
|
|
|
892 |
|
| 37125 |
vikas |
893 |
m.put("trail", trail);
|
|
|
894 |
return m;
|
|
|
895 |
}
|
|
|
896 |
|
|
|
897 |
private String joinLoc(String a, String c, String s) {
|
|
|
898 |
StringBuilder sb = new StringBuilder();
|
|
|
899 |
for (String p : new String[]{a, c, s}) {
|
|
|
900 |
if (p != null && !p.trim().isEmpty()) {
|
|
|
901 |
if (sb.length() > 0) sb.append(", ");
|
|
|
902 |
sb.append(p.trim());
|
|
|
903 |
}
|
|
|
904 |
}
|
|
|
905 |
return sb.toString();
|
|
|
906 |
}
|
|
|
907 |
|
|
|
908 |
// ---- helpers ----------------------------------------------------------------------------
|
|
|
909 |
|
|
|
910 |
private long reachedAtLeast(Map<String, Long> stage, LeadStage at) {
|
|
|
911 |
long sum = 0;
|
|
|
912 |
boolean counting = false;
|
|
|
913 |
for (LeadStage s : FUNNEL) {
|
|
|
914 |
if (s == at) {
|
|
|
915 |
counting = true;
|
|
|
916 |
}
|
|
|
917 |
if (counting) {
|
|
|
918 |
sum += stage.getOrDefault(s.name(), 0L);
|
|
|
919 |
}
|
|
|
920 |
}
|
|
|
921 |
return sum;
|
|
|
922 |
}
|
|
|
923 |
|
|
|
924 |
private Map<String, Long> toCountMap(List<Object[]> rows) {
|
|
|
925 |
Map<String, Long> m = new HashMap<>();
|
|
|
926 |
for (Object[] r : rows) {
|
|
|
927 |
if (r[0] == null) {
|
|
|
928 |
continue;
|
|
|
929 |
}
|
|
|
930 |
m.merge(String.valueOf(r[0]), ((Number) r[1]).longValue(), Long::sum);
|
|
|
931 |
}
|
|
|
932 |
return m;
|
|
|
933 |
}
|
|
|
934 |
|
|
|
935 |
private Map<String, Double> toSumMap(List<Object[]> rows) {
|
|
|
936 |
Map<String, Double> m = new HashMap<>();
|
|
|
937 |
for (Object[] r : rows) {
|
|
|
938 |
if (r[0] == null) {
|
|
|
939 |
continue;
|
|
|
940 |
}
|
|
|
941 |
double v = r[1] == null ? 0d : ((Number) r[1]).doubleValue();
|
|
|
942 |
m.merge(String.valueOf(r[0]), v, Double::sum);
|
|
|
943 |
}
|
|
|
944 |
return m;
|
|
|
945 |
}
|
|
|
946 |
|
|
|
947 |
private long num(Object[] row, int i) {
|
|
|
948 |
if (row == null || i >= row.length || row[i] == null) {
|
|
|
949 |
return 0L;
|
|
|
950 |
}
|
|
|
951 |
return ((Number) row[i]).longValue();
|
|
|
952 |
}
|
|
|
953 |
|
|
|
954 |
private long pct(long part, long whole) {
|
|
|
955 |
if (whole <= 0) {
|
|
|
956 |
return 0;
|
|
|
957 |
}
|
|
|
958 |
return Math.round((part * 100.0) / whole);
|
|
|
959 |
}
|
|
|
960 |
|
|
|
961 |
private String str(Object o) {
|
|
|
962 |
return o == null ? "" : String.valueOf(o);
|
|
|
963 |
}
|
|
|
964 |
|
|
|
965 |
private Map<String, Object> kpi(String key, String label, long value, String foot, String tone) {
|
|
|
966 |
Map<String, Object> m = new LinkedHashMap<>();
|
|
|
967 |
m.put("key", key);
|
|
|
968 |
m.put("label", label);
|
|
|
969 |
m.put("value", value);
|
|
|
970 |
m.put("foot", foot);
|
|
|
971 |
m.put("tone", tone);
|
|
|
972 |
return m;
|
|
|
973 |
}
|
|
|
974 |
|
|
|
975 |
private Map<String, Object> funnelStep(String stage, String label, long count, long pct) {
|
|
|
976 |
Map<String, Object> m = new LinkedHashMap<>();
|
|
|
977 |
m.put("stage", stage);
|
|
|
978 |
m.put("label", label);
|
|
|
979 |
m.put("count", count);
|
|
|
980 |
m.put("pct", pct);
|
|
|
981 |
return m;
|
|
|
982 |
}
|
|
|
983 |
|
|
|
984 |
private Map<String, Object> attn(String key, String title, String detail, long count, String tone) {
|
|
|
985 |
Map<String, Object> m = new LinkedHashMap<>();
|
|
|
986 |
m.put("key", key);
|
|
|
987 |
m.put("title", title);
|
|
|
988 |
m.put("detail", detail);
|
|
|
989 |
m.put("count", count);
|
|
|
990 |
m.put("tone", tone);
|
|
|
991 |
return m;
|
|
|
992 |
}
|
|
|
993 |
|
|
|
994 |
private String trimName(String first, String last) {
|
|
|
995 |
String f = first == null ? "" : first.trim();
|
|
|
996 |
String l = last == null ? "" : last.trim();
|
|
|
997 |
return (f + " " + l).trim();
|
|
|
998 |
}
|
|
|
999 |
|
|
|
1000 |
private LeadStage safeStage(String s) {
|
|
|
1001 |
try {
|
|
|
1002 |
return LeadStage.valueOf(s);
|
|
|
1003 |
} catch (Exception e) {
|
|
|
1004 |
return null;
|
|
|
1005 |
}
|
|
|
1006 |
}
|
|
|
1007 |
|
|
|
1008 |
/** "NEW" → "New", "BEAT_PLANNED" → "Beat planned". */
|
|
|
1009 |
private String pretty(LeadStage s) {
|
|
|
1010 |
if (s == null) {
|
|
|
1011 |
return "—";
|
|
|
1012 |
}
|
|
|
1013 |
String[] parts = s.name().toLowerCase().split("_");
|
|
|
1014 |
StringBuilder sb = new StringBuilder();
|
|
|
1015 |
for (int i = 0; i < parts.length; i++) {
|
|
|
1016 |
if (parts[i].isEmpty()) {
|
|
|
1017 |
continue;
|
|
|
1018 |
}
|
|
|
1019 |
if (i == 0) {
|
|
|
1020 |
sb.append(Character.toUpperCase(parts[i].charAt(0))).append(parts[i].substring(1));
|
|
|
1021 |
} else {
|
|
|
1022 |
sb.append(' ').append(parts[i]);
|
|
|
1023 |
}
|
|
|
1024 |
}
|
|
|
1025 |
return sb.toString();
|
|
|
1026 |
}
|
|
|
1027 |
|
|
|
1028 |
/** ISO yyyyww (YEARWEEK mode 3) → a short "w<week>" label. */
|
|
|
1029 |
private String weekLabel(int isoYearWeek) {
|
|
|
1030 |
int week = isoYearWeek % 100;
|
|
|
1031 |
return "W" + week;
|
|
|
1032 |
}
|
|
|
1033 |
}
|