Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
36877 vikas 1
package com.spice.profitmandi.dao.service;
2
 
3
import org.hibernate.Session;
4
import org.hibernate.SessionFactory;
5
import org.hibernate.query.NativeQuery;
6
import org.springframework.beans.factory.annotation.Autowired;
7
import org.springframework.stereotype.Service;
8
 
9
import java.util.*;
10
 
11
/**
12
 * Period analytics for the Beat Journey console — read-only native SQL, scoped to
36897 vikas 13
 * the caller's downline via the auth-id / dtr-id sets, with {@code IN (:ids)} scope
14
 * filters and blocks for KPIs, funnel, scorecard, coverage, utilization, deferrals,
15
 * travel, outcomes, and findings.
36877 vikas 16
 *
17
 * Empty scope is handled by substituting a sentinel id (-1) so every {@code IN}
18
 * clause is valid and simply returns zeros rather than throwing.
19
 */
20
@Service
21
public class BeatJourneyServiceImpl implements BeatJourneyService {
22
 
23
    @Autowired
24
    private SessionFactory sessionFactory;
25
 
26
    @Override
27
    public Map<String, Object> periodAnalytics(String start, String end, String today,
28
                                               List<Integer> authIds, List<Integer> dtrIds) {
29
        Session s = sessionFactory.getCurrentSession();
30
        List<Integer> auth = safeIds(authIds);
31
        List<Integer> dtr = safeIds(dtrIds);
32
 
33
        Map<String, Object> out = new LinkedHashMap<>();
34
        Map<String, Object> range = new LinkedHashMap<>();
35
        range.put("start", start);
36
        range.put("end", end);
37
        range.put("today", today);
38
        out.put("range", range);
39
        out.put("scopeCount", authIds == null ? 0 : authIds.size());
40
 
41
        List<Map<String, Object>> coverage = coverageByLevel(s, start, end, auth);
42
        Map<String, Object> funnel = funnel(s, start, end, auth, dtr);
36929 vikas 43
        Map<String, Object> summary = journeySummary(s, start, end, dtr, funnel);
36877 vikas 44
        Map<String, Object> deferral = deferral(s, start, end, auth);
45
        Map<String, Object> utilization = utilization(s, start, end, dtr);
46
        Map<String, Object> travel = travel(s, start, end, auth, dtr);
47
        Map<String, Object> outcomes = outcomes(s, start, end, auth);
48
        List<Map<String, Object>> scorecard = scorecard(s, start, end, auth, dtr);
49
        Map<String, Object> kpis = kpis(s, start, end, auth, dtr, coverage, funnel, deferral);
50
 
51
        out.put("kpis", kpis);
52
        out.put("funnel", funnel);
36929 vikas 53
        out.put("summary", summary);
36877 vikas 54
        out.put("coverageByLevel", coverage);
55
        out.put("scorecard", scorecard);
56
        out.put("utilization", utilization);
57
        out.put("deferral", deferral);
58
        out.put("travel", travel);
59
        out.put("outcomes", outcomes);
60
        out.put("findings", findings(kpis, funnel, deferral, utilization, travel, outcomes, coverage, scorecard));
36913 vikas 61
        // drill-down lists
62
        out.put("coverageDetail", coverageDetail(s, start, end, auth));
63
        out.put("deferralsList", deferralsList(s, start, end, auth));
64
        out.put("leadsList", leadsList(s, start, end, auth));
36877 vikas 65
        return out;
66
    }
67
 
68
    // ---- KPIs ---------------------------------------------------------------
69
 
70
    private Map<String, Object> kpis(Session s, String ms, String me, List<Integer> auth, List<Integer> dtr,
71
                                     List<Map<String, Object>> coverage, Map<String, Object> funnel, Map<String, Object> deferral) {
72
        Map<String, Object> m = new LinkedHashMap<>();
73
 
74
        long planned = asLong(funnel.get("plannedStops"));
36929 vikas 75
        // Adherence is planned-visit completion: the numerator counts only completed
76
        // PLANNED visits (partner franchisee + approved leads), not every check-out
77
        // (ad-hoc office/warehouse stops don't count toward planned-visit adherence).
78
        // Self-assigned stops are excluded: task_name is pipe-delimited and ends with
79
        // a "… | SELF" marker for self-assigned visits, which aren't part of the plan.
80
        long done = countVisits(s, ms, me, dtr, "task_type IN ('franchisee-visit','lead') AND COALESCE(task_name,'') NOT LIKE '%SELF%' AND mark_type LIKE '%CHECKOUT%'");
36877 vikas 81
        m.put("plannedStops", planned);
82
        m.put("doneStops", done);
83
        m.put("adherencePct", planned == 0 ? 0 : Math.round(100.0 * done / planned));
84
 
85
        // L1 coverage row
86
        long l1With = 0, l1Total = 0;
87
        for (Map<String, Object> c : coverage) {
88
            if ("L1".equalsIgnoreCase(asStr(c.get("level")))) {
89
                l1With = asLong(c.get("withPjp"));
90
                l1Total = asLong(c.get("totalUsers"));
91
            }
92
        }
93
        m.put("coverageL1With", l1With);
94
        m.put("coverageL1Total", l1Total);
95
        m.put("coverageL1Pct", l1Total == 0 ? 0 : Math.round(100.0 * l1With / l1Total));
96
 
97
        // avg visits / active (punched-in) day, and total punch-in days (journeys)
36913 vikas 98
        // A "punch-in day" is the attendance row (task_id=0) with a real check-in
99
        // time, matching the Today lens. (Literal mark_type='PUNCHIN' rows barely
100
        // exist in the data, so relying on them under-counts drastically.)
36877 vikas 101
        NativeQuery<?> q = s.createNativeQuery(
102
            "SELECT COUNT(DISTINCT CONCAT(user_id,'-',task_date)) FROM auth.location_tracking" +
36913 vikas 103
            " WHERE task_date>=:ms AND task_date<=:me AND user_id IN (:dtr)" +
104
            "   AND (mark_type='PUNCHIN' OR (task_id=0 AND check_in_time IS NOT NULL AND check_in_time<>'00:00:00'))");
36877 vikas 105
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("dtr", dtr);
106
        long journeys = asLong(q.uniqueResult());
107
        m.put("journeys", journeys);
108
        m.put("avgVisitsPerActiveDay", journeys == 0 ? 0 : round1((double) asLong(funnel.get("checkedIn")) / journeys));
36929 vikas 109
        // partner (franchisee) visits per active day — the subset that are partner
110
        // store visits, shown alongside the all-types visit average.
111
        long partnerCheckins = countVisits(s, ms, me, dtr, "task_type='franchisee-visit' AND mark_type LIKE 'CHECKIN%'");
112
        m.put("avgPartnersPerActiveDay", journeys == 0 ? 0 : round1((double) partnerCheckins / journeys));
36941 vikas 113
        // lead visits per active day — planned (on the PJP / lead_route) and unplanned
114
        // (self-assigned ad-hoc) leads combined.
115
        long leadCheckins = countVisits(s, ms, me, dtr, "task_type='lead' AND mark_type LIKE 'CHECKIN%'");
116
        m.put("avgLeadsPerActiveDay", journeys == 0 ? 0 : round1((double) leadCheckins / journeys));
36877 vikas 117
 
36929 vikas 118
        // avg in-store discussion minutes — overall, plus partner (franchisee) and
119
        // lead split so the card can show each separately.
120
        m.put("avgDiscussionMin", avgDiscussionMin(s, ms, me, dtr, null));
121
        m.put("avgDiscussionPartnerMin", avgDiscussionMin(s, ms, me, dtr, "franchisee-visit"));
122
        m.put("avgDiscussionLeadMin", avgDiscussionMin(s, ms, me, dtr, "lead"));
36877 vikas 123
 
36929 vikas 124
        // Auto "missed" = situations where planned execution broke down, split into
125
        // three causes: execs with no PJP at all, scheduled beat-days with the agenda
126
        // left unfilled, and scheduled beat-days the owner never punched in on.
127
        Map<String, Object> mb = missedBreakdown(s, ms, me, auth, coverage);
128
        m.put("autoMissedUnscheduled", mb.get("unscheduled"));
129
        m.put("autoMissedUnfilledAgenda", mb.get("unfilledAgenda"));
130
        m.put("autoMissedMissedPunchin", mb.get("missedPunchin"));
131
        m.put("autoMissed", mb.get("total"));
36877 vikas 132
        m.put("autoMissedSystemPct", asLong(deferral.get("systemPct")));
133
 
134
        // leads created on route
135
        NativeQuery<?> lq = s.createNativeQuery(
136
            "SELECT COUNT(*) FROM `user`.lead WHERE created_timestamp>=:ms AND created_timestamp<=CONCAT(:me,' 23:59:59') AND auth_id IN (:auth)");
137
        lq.setParameter("ms", ms).setParameter("me", me).setParameterList("auth", auth);
138
        m.put("leadsCreated", asLong(lq.uniqueResult()));
139
        return m;
140
    }
141
 
142
    // ---- Funnel -------------------------------------------------------------
143
 
144
    private Map<String, Object> funnel(Session s, String ms, String me, List<Integer> auth, List<Integer> dtr) {
145
        Map<String, Object> m = new LinkedHashMap<>();
146
 
36913 vikas 147
        // Planned stops = partner stops (beat_route) + lead stops (lead_route, APPROVED)
148
        // on each scheduled beat-day, over active beats — exactly how the Today lens
149
        // (getAllScheduledBeats) counts, so Period reconciles with the day views.
150
        long planned = plannedCount(s, ms, me, auth, dtr, false, false)
151
                     + plannedCount(s, ms, me, auth, dtr, true, false);
152
        // ...of those, the planned stops that fall on a day the owner punched in
153
        long punchedIn = plannedCount(s, ms, me, auth, dtr, false, true)
154
                       + plannedCount(s, ms, me, auth, dtr, true, true);
36877 vikas 155
 
156
        long checkedIn = countVisits(s, ms, me, dtr, "mark_type LIKE 'CHECKIN%'");
157
        long checkedOut = countVisits(s, ms, me, dtr, "(mark_type LIKE '%CHECKOUT%')");
158
 
159
        m.put("plannedStops", planned);
160
        m.put("punchedIn", punchedIn);
161
        m.put("checkedIn", checkedIn);
162
        m.put("checkedOut", checkedOut);
163
        m.put("dropPunch", planned == 0 ? 0 : Math.round(100.0 * (planned - punchedIn) / planned));
164
        m.put("dropCheckin", punchedIn == 0 ? 0 : Math.round(100.0 * (punchedIn - checkedIn) / punchedIn));
165
        m.put("dropCheckout", checkedIn == 0 ? 0 : Math.round(100.0 * (checkedIn - checkedOut) / checkedIn));
166
        return m;
167
    }
168
 
36913 vikas 169
    // Planned stop count over scheduled beat-days of active beats. lead=false counts
170
    // partner stops (beat_route by day_number); lead=true counts approved lead stops
171
    // (lead_route by schedule_date). onlyPunchInDays restricts to days the owner
172
    // actually punched in (the funnel's "planned on punch-in days" stage).
173
    private long plannedCount(Session s, String ms, String me, List<Integer> auth,
174
                              List<Integer> dtr, boolean lead, boolean onlyPunchInDays) {
175
        String stopJoin = lead
176
            ? " JOIN `user`.lead_route x ON x.beat_id=sc.beat_id AND x.schedule_date=sc.start_date AND x.status='APPROVED'"
177
            : " JOIN `user`.beat_route x ON x.beat_id=sc.beat_id AND x.day_number=sc.day_number";
178
        String punchJoin = onlyPunchInDays
179
            ? " JOIN auth.auth_user au ON au.id=b.auth_user_id" +
180
              " JOIN dtr.users du ON du.email=au.email_id" +
181
              " JOIN (SELECT DISTINCT user_id, task_date FROM auth.location_tracking" +
182
              "        WHERE task_date>=:ms AND task_date<=:me AND user_id IN (:dtr)" +
183
              "          AND (mark_type='PUNCHIN' OR (task_id=0 AND check_in_time IS NOT NULL AND check_in_time<>'00:00:00'))) p" +
184
              "   ON p.user_id=du.id AND p.task_date=sc.start_date"
185
            : "";
186
        NativeQuery<?> q = s.createNativeQuery(
187
            "SELECT COUNT(*) FROM `user`.beat_schedule sc" +
188
            " JOIN `user`.beat b ON b.id=sc.beat_id AND b.active=1 AND b.auth_user_id IN (:auth)" +
189
            stopJoin + punchJoin +
190
            " WHERE sc.start_date>=:ms AND sc.start_date<=:me");
191
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("auth", auth);
192
        if (onlyPunchInDays) q.setParameterList("dtr", dtr);
193
        return asLong(q.uniqueResult());
194
    }
195
 
196
    // Counts visits across ALL task types (franchisee + lead + office) — task_id<>0
197
    // excludes the attendance/punch row — matching the Today lens, which tallies
198
    // every check-in/out regardless of type.
36877 vikas 199
    private long countVisits(Session s, String ms, String me, List<Integer> dtr, String markPredicate) {
200
        NativeQuery<?> q = s.createNativeQuery(
201
            "SELECT COUNT(*) FROM auth.location_tracking" +
36913 vikas 202
            " WHERE task_date>=:ms AND task_date<=:me AND task_id<>0 AND " + markPredicate +
36877 vikas 203
            " AND user_id IN (:dtr)");
204
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("dtr", dtr);
205
        return asLong(q.uniqueResult());
206
    }
207
 
36929 vikas 208
    // Avg in-store discussion minutes over checked-out visits. taskType null =
209
    // all visit types; otherwise restricted to that task_type (e.g. franchisee / lead).
210
    private long avgDiscussionMin(Session s, String ms, String me, List<Integer> dtr, String taskType) {
211
        NativeQuery<?> q = s.createNativeQuery(
212
            "SELECT ROUND(AVG(TIME_TO_SEC(check_out_time)-TIME_TO_SEC(check_in_time))/60,0) FROM auth.location_tracking" +
213
            " WHERE task_date>=:ms AND task_date<=:me AND task_id<>0 AND mark_type LIKE '%CHECKOUT%'" +
214
            " AND check_in_time IS NOT NULL AND check_in_time<>'00:00:00'" +
215
            " AND check_out_time IS NOT NULL AND check_out_time<>'00:00:00'" +
216
            " AND TIME_TO_SEC(check_out_time) > TIME_TO_SEC(check_in_time)" +
217
            (taskType != null ? " AND task_type=:tt" : "") +
218
            " AND user_id IN (:dtr)");
219
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("dtr", dtr);
220
        if (taskType != null) q.setParameter("tt", taskType);
221
        return asLong(q.uniqueResult());
222
    }
223
 
224
    // ---- Journey summary table ---------------------------------------------
225
    // A flat per-period scorecard split into Planned (on the PJP / lead_route, no
226
    // SELF marker) vs Self Assigned (the ad-hoc "… | SELF" visits the exec added):
227
    //   Total Visits   — planned = scheduled planned stops; self = self-assigned check-ins
228
    //   Avg Time Spent — avg (check-out − check-in) minutes, each side
229
    //   Idle/Break     — average idle minutes per active day (single value)
230
    //   Deferred       — total − completed, each side (what was never closed out)
231
    //   Completed      — checkouts, each side
232
    private Map<String, Object> journeySummary(Session s, String ms, String me, List<Integer> dtr,
233
                                               Map<String, Object> funnel) {
234
        long plannedVisits   = asLong(funnel.get("plannedStops"));
235
        long completedPlanned = countVisits(s, ms, me, dtr, "task_type IN ('franchisee-visit','lead') AND COALESCE(task_name,'') NOT LIKE '%SELF%' AND mark_type LIKE '%CHECKOUT%'");
236
        long selfVisits      = countVisits(s, ms, me, dtr, "COALESCE(task_name,'') LIKE '%SELF%' AND mark_type LIKE 'CHECKIN%'");
237
        long completedSelf   = countVisits(s, ms, me, dtr, "COALESCE(task_name,'') LIKE '%SELF%' AND mark_type LIKE '%CHECKOUT%'");
238
 
239
        // idle = working − in-store − travel, averaged over active (punch-in) days
240
        NativeQuery<?> uq = s.createNativeQuery(
241
            "SELECT" +
242
            " (SELECT COALESCE(SUM(TIME_TO_SEC(time_spent)),0) FROM auth.location_tracking WHERE task_date>=:ms AND task_date<=:me AND task_id<>0 AND user_id IN (:dtr)) instore," +
243
            " (SELECT COALESCE(SUM(TIME_TO_SEC(transit_time)),0) FROM auth.location_tracking WHERE task_date>=:ms AND task_date<=:me AND task_id<>0 AND user_id IN (:dtr)) travel," +
244
            " (SELECT COALESCE(SUM(GREATEST(TIME_TO_SEC(check_out_time)-TIME_TO_SEC(check_in_time),0)),0) FROM auth.location_tracking WHERE task_date>=:ms AND task_date<=:me AND task_id=0 AND check_out_time IS NOT NULL AND check_out_time<>'00:00:00' AND check_in_time IS NOT NULL AND check_in_time<>'00:00:00' AND user_id IN (:dtr)) working," +
245
            " (SELECT COUNT(DISTINCT CONCAT(user_id,'-',task_date)) FROM auth.location_tracking WHERE task_date>=:ms AND task_date<=:me AND user_id IN (:dtr) AND (mark_type='PUNCHIN' OR (task_id=0 AND check_in_time IS NOT NULL AND check_in_time<>'00:00:00'))) journeys");
246
        uq.setParameter("ms", ms).setParameter("me", me).setParameterList("dtr", dtr);
247
        Object[] ur = (Object[]) uq.uniqueResult();
248
        double instore = asDouble(ur[0]), travel = asDouble(ur[1]), working = asDouble(ur[2]);
249
        long journeys = asLong(ur[3]);
250
        if (working < instore + travel) working = instore + travel;
251
        double idle = Math.max(working - instore - travel, 0);
252
        long idleAvgMin = journeys == 0 ? 0 : Math.round(idle / journeys / 60.0);
253
 
254
        Map<String, Object> m = new LinkedHashMap<>();
255
        m.put("plannedVisits", plannedVisits);
256
        m.put("selfVisits", selfVisits);
36941 vikas 257
        m.put("avgTimeAllMin", avgTimeSpentMin(s, ms, me, dtr, null));   // planned + self combined
36929 vikas 258
        m.put("idleAvgMin", idleAvgMin);
259
        m.put("deferredPlanned", Math.max(plannedVisits - completedPlanned, 0));
260
        m.put("deferredSelf", Math.max(selfVisits - completedSelf, 0));
261
        m.put("completedPlanned", completedPlanned);
262
        m.put("completedSelf", completedSelf);
263
        return m;
264
    }
265
 
36941 vikas 266
    // Avg (check-out − check-in) minutes over checked-out visits. self==null covers
267
    // all visits (planned + self); true/false restricts to the pipe-delimited
268
    // "… | SELF" self-assigned visits or the planned ones respectively.
269
    private long avgTimeSpentMin(Session s, String ms, String me, List<Integer> dtr, Boolean self) {
36929 vikas 270
        NativeQuery<?> q = s.createNativeQuery(
271
            "SELECT ROUND(AVG(TIME_TO_SEC(check_out_time)-TIME_TO_SEC(check_in_time))/60,0) FROM auth.location_tracking" +
272
            " WHERE task_date>=:ms AND task_date<=:me AND task_id<>0 AND mark_type LIKE '%CHECKOUT%'" +
273
            " AND check_in_time IS NOT NULL AND check_in_time<>'00:00:00'" +
274
            " AND check_out_time IS NOT NULL AND check_out_time<>'00:00:00'" +
275
            " AND TIME_TO_SEC(check_out_time) > TIME_TO_SEC(check_in_time)" +
36941 vikas 276
            (self == null ? "" : self ? " AND COALESCE(task_name,'') LIKE '%SELF%'" : " AND COALESCE(task_name,'') NOT LIKE '%SELF%'") +
36929 vikas 277
            " AND user_id IN (:dtr)");
278
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("dtr", dtr);
279
        return asLong(q.uniqueResult());
280
    }
281
 
36877 vikas 282
    // ---- Coverage by level --------------------------------------------------
283
 
284
    private List<Map<String, Object>> coverageByLevel(Session s, String ms, String me, List<Integer> auth) {
285
        NativeQuery<?> q = s.createNativeQuery(
286
            "SELECT p.escalation_type lvl, COUNT(DISTINCT p.auth_user_id) total_users," +
287
            " COUNT(DISTINCT CASE WHEN sc.id IS NOT NULL THEN p.auth_user_id END) with_pjp" +
288
            " FROM cs.position p" +
289
            " LEFT JOIN `user`.beat b ON b.auth_user_id=p.auth_user_id AND b.active=1" +
290
            " LEFT JOIN `user`.beat_schedule sc ON sc.beat_id=b.id AND sc.start_date>=:ms AND sc.start_date<=:me" +
36954 vikas 291
            " WHERE p.category_id=4 AND p.auth_user_id IN (:auth) AND LOWER(p.escalation_type) NOT IN ('l4','l5','final') GROUP BY p.escalation_type ORDER BY p.escalation_type");
36877 vikas 292
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("auth", auth);
293
        List<Map<String, Object>> list = new ArrayList<>();
294
        for (Object o : q.getResultList()) {
295
            Object[] r = (Object[]) o;
296
            long total = asLong(r[1]), with = asLong(r[2]);
297
            Map<String, Object> m = new LinkedHashMap<>();
298
            m.put("level", asStr(r[0]));
299
            m.put("totalUsers", total);
300
            m.put("withPjp", with);
301
            m.put("coveragePct", total == 0 ? 0 : Math.round(100.0 * with / total));
302
            list.add(m);
303
        }
304
        return list;
305
    }
306
 
307
    // ---- Per-executive scorecard -------------------------------------------
308
 
309
    private List<Map<String, Object>> scorecard(Session s, String ms, String me, List<Integer> auth, List<Integer> dtr) {
310
        NativeQuery<?> q = s.createNativeQuery(
311
            "SELECT au.id uid, TRIM(CONCAT(au.first_name,' ',COALESCE(au.last_name,''))) nm, lvl.lvl," +
36913 vikas 312
            " COALESCE(pl.planned,0)+COALESCE(plL.planned,0) planned, COALESCE(ac.done,0) done," +
36877 vikas 313
            " COALESCE(ds.disc_min,0) disc_min, COALESCE(wk.work_sec,0) work_sec," +
36929 vikas 314
            " COALESCE(ld.leads,0) leads, du.id duid, COALESCE(acp.donep,0) donep" +
36877 vikas 315
            " FROM (SELECT DISTINCT auth_user_id FROM `user`.beat WHERE active=1 AND auth_user_id IN (:auth)) o" +
316
            " JOIN auth.auth_user au ON au.id=o.auth_user_id" +
317
            " LEFT JOIN dtr.users du ON du.email=au.email_id" +
36954 vikas 318
            " LEFT JOIN (SELECT auth_user_id, MIN(escalation_type) lvl FROM cs.position WHERE category_id=4 AND LOWER(escalation_type) NOT IN ('l4','l5','final') GROUP BY auth_user_id) lvl ON lvl.auth_user_id=au.id" +
36877 vikas 319
            " LEFT JOIN (SELECT b.auth_user_id uid, COUNT(*) planned FROM `user`.beat_schedule sc" +
36913 vikas 320
            "   JOIN `user`.beat b ON b.id=sc.beat_id AND b.active=1 JOIN `user`.beat_route r ON r.beat_id=sc.beat_id AND r.day_number=sc.day_number" +
36877 vikas 321
            "   WHERE sc.start_date>=:ms AND sc.start_date<=:me GROUP BY b.auth_user_id) pl ON pl.uid=au.id" +
36913 vikas 322
            " LEFT JOIN (SELECT b.auth_user_id uid, COUNT(*) planned FROM `user`.beat_schedule sc" +
323
            "   JOIN `user`.beat b ON b.id=sc.beat_id AND b.active=1 JOIN `user`.lead_route lr ON lr.beat_id=sc.beat_id AND lr.schedule_date=sc.start_date AND lr.status='APPROVED'" +
324
            "   WHERE sc.start_date>=:ms AND sc.start_date<=:me GROUP BY b.auth_user_id) plL ON plL.uid=au.id" +
36877 vikas 325
            " LEFT JOIN (SELECT user_id uid, COUNT(*) done FROM auth.location_tracking" +
36913 vikas 326
            "   WHERE task_date>=:ms AND task_date<=:me AND task_id<>0 AND mark_type LIKE 'CHECKIN%' GROUP BY user_id) ac ON ac.uid=du.id" +
36929 vikas 327
            // Adherence numerator: completed PLANNED visits only (partner franchisee +
328
            // approved leads), excluding ad-hoc office/warehouse stops and self-assigned
329
            // stops (task_name carries a "… | SELF" marker, which aren't part of the plan).
330
            " LEFT JOIN (SELECT user_id uid, COUNT(*) donep FROM auth.location_tracking" +
331
            "   WHERE task_date>=:ms AND task_date<=:me AND task_id<>0 AND task_type IN ('franchisee-visit','lead') AND COALESCE(task_name,'') NOT LIKE '%SELF%' AND mark_type LIKE '%CHECKOUT%' GROUP BY user_id) acp ON acp.uid=du.id" +
36877 vikas 332
            " LEFT JOIN (SELECT user_id uid, ROUND(AVG(NULLIF(TIME_TO_SEC(time_spent),0))/60,0) disc_min FROM auth.location_tracking" +
36913 vikas 333
            "   WHERE task_date>=:ms AND task_date<=:me AND task_id<>0 AND mark_type LIKE '%CHECKOUT%' GROUP BY user_id) ds ON ds.uid=du.id" +
36877 vikas 334
            " LEFT JOIN (SELECT user_id uid, SUM(GREATEST(TIME_TO_SEC(check_out_time)-TIME_TO_SEC(check_in_time),0)) work_sec FROM auth.location_tracking" +
335
            "   WHERE task_date>=:ms AND task_date<=:me AND task_id=0 AND check_out_time IS NOT NULL AND check_out_time<>'00:00:00' AND check_in_time IS NOT NULL AND check_in_time<>'00:00:00' GROUP BY user_id) wk ON wk.uid=du.id" +
336
            " LEFT JOIN (SELECT auth_id uid, COUNT(*) leads FROM `user`.lead WHERE created_timestamp>=:ms AND created_timestamp<=CONCAT(:me,' 23:59:59') GROUP BY auth_id) ld ON ld.uid=au.id" +
337
            " ORDER BY done DESC, planned DESC");
338
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("auth", auth);
339
 
340
        // Geofence-offsite check-ins per user are computed in Java (not SQL): the
341
        // coords are stored as "lat,lng" strings, and the inline parsing/haversine
342
        // expression trips Hibernate's native-query parameter parser.
343
        Map<Integer, Integer> geoByUser = geoOffsiteByUser(s, ms, me, dtr);
344
 
345
        List<Map<String, Object>> list = new ArrayList<>();
346
        for (Object o : q.getResultList()) {
347
            Object[] r = (Object[]) o;
36929 vikas 348
            long planned = asLong(r[3]), done = asLong(r[4]), donePlanned = asLong(r[9]);
36913 vikas 349
            Integer duid = (r[8] == null) ? null : ((Number) r[8]).intValue();
36877 vikas 350
            Map<String, Object> m = new LinkedHashMap<>();
36913 vikas 351
            m.put("authUserId", asLong(r[0]));
352
            m.put("userId", duid == null ? 0 : duid);
36877 vikas 353
            m.put("name", asStr(r[1]));
354
            m.put("level", r[2] == null ? "-" : asStr(r[2]));
355
            m.put("planned", planned);
356
            m.put("done", done);
36929 vikas 357
            // Adherence = completed PLANNED visits ÷ planned visits (not all visits).
358
            m.put("adherencePct", planned == 0 ? 0 : Math.round(100.0 * donePlanned / planned));
36877 vikas 359
            m.put("discussionMin", asLong(r[5]));
360
            m.put("workingHrs", round1(asDouble(r[6]) / 3600.0));
361
            m.put("leads", asLong(r[7]));
362
            m.put("geoFlags", duid == null ? 0 : geoByUser.getOrDefault(duid, 0));
363
            list.add(m);
364
        }
365
        return list;
366
    }
367
 
368
    // Per dtr-user count of check-ins recorded >50 m from the partner's saved
369
    // location. Pulls the raw "lat,lng" strings and does the haversine in Java.
370
    private Map<Integer, Integer> geoOffsiteByUser(Session s, String ms, String me, List<Integer> dtr) {
371
        NativeQuery<?> q = s.createNativeQuery(
372
            "SELECT user_id, checkin_lat_lng, visit_location FROM auth.location_tracking" +
373
            " WHERE task_date>=:ms AND task_date<=:me AND task_type='franchisee-visit' AND mark_type LIKE 'CHECKIN%'" +
374
            " AND checkin_lat_lng LIKE '%,%' AND visit_location LIKE '%,%' AND user_id IN (:dtr)");
375
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("dtr", dtr);
376
        Map<Integer, Integer> out = new HashMap<>();
377
        for (Object o : q.getResultList()) {
378
            Object[] r = (Object[]) o;
379
            if (r[0] == null) continue;
380
            double[] cin = parseLatLng(asStr(r[1]));
381
            double[] vis = parseLatLng(asStr(r[2]));
382
            if (cin == null || vis == null) continue;
383
            if (haversineMeters(cin[0], cin[1], vis[0], vis[1]) > 50.0) {
384
                int uid = ((Number) r[0]).intValue();
385
                out.merge(uid, 1, Integer::sum);
386
            }
387
        }
388
        return out;
389
    }
390
 
391
    private static double[] parseLatLng(String s) {
392
        if (s == null || !s.contains(",")) return null;
393
        String[] parts = s.split(",");
394
        if (parts.length != 2) return null;
395
        try {
396
            double a = Double.parseDouble(parts[0].trim());
397
            double b = Double.parseDouble(parts[1].trim());
398
            if (a == 0 && b == 0) return null;
399
            return new double[]{a, b};
400
        } catch (NumberFormatException e) {
401
            return null;
402
        }
403
    }
404
 
405
    private static double haversineMeters(double lat1, double lng1, double lat2, double lng2) {
406
        double R = 6371000d;
407
        double dLat = Math.toRadians(lat2 - lat1);
408
        double dLng = Math.toRadians(lng2 - lng1);
409
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
410
                + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
411
                * Math.sin(dLng / 2) * Math.sin(dLng / 2);
412
        return 2 * R * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
413
    }
414
 
415
    // ---- Working-hour utilization ------------------------------------------
416
 
417
    private Map<String, Object> utilization(Session s, String ms, String me, List<Integer> dtr) {
418
        NativeQuery<?> q = s.createNativeQuery(
419
            "SELECT" +
36913 vikas 420
            " (SELECT COALESCE(SUM(TIME_TO_SEC(time_spent)),0) FROM auth.location_tracking WHERE task_date>=:ms AND task_date<=:me AND task_id<>0 AND user_id IN (:dtr)) instore," +
421
            " (SELECT COALESCE(SUM(TIME_TO_SEC(transit_time)),0) FROM auth.location_tracking WHERE task_date>=:ms AND task_date<=:me AND task_id<>0 AND user_id IN (:dtr)) travel," +
36877 vikas 422
            " (SELECT COALESCE(SUM(GREATEST(TIME_TO_SEC(check_out_time)-TIME_TO_SEC(check_in_time),0)),0) FROM auth.location_tracking WHERE task_date>=:ms AND task_date<=:me AND task_id=0 AND check_out_time IS NOT NULL AND check_out_time<>'00:00:00' AND check_in_time IS NOT NULL AND check_in_time<>'00:00:00' AND user_id IN (:dtr)) working");
423
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("dtr", dtr);
424
        Object[] r = (Object[]) q.uniqueResult();
425
        double instore = asDouble(r[0]), travel = asDouble(r[1]), working = asDouble(r[2]);
426
        if (working < instore + travel) working = instore + travel; // guard: working must cover its parts
427
        double idle = Math.max(working - instore - travel, 0);
428
        Map<String, Object> m = new LinkedHashMap<>();
429
        m.put("inStoreHrs", round1(instore / 3600.0));
430
        m.put("travelHrs", round1(travel / 3600.0));
431
        m.put("idleHrs", round1(idle / 3600.0));
432
        m.put("workingHrs", round1(working / 3600.0));
433
        m.put("inStorePct", working == 0 ? 0 : (int) Math.round(100.0 * instore / working));
434
        m.put("travelPct", working == 0 ? 0 : (int) Math.round(100.0 * travel / working));
435
        m.put("idlePct", working == 0 ? 0 : (int) Math.round(100.0 * idle / working));
436
        return m;
437
    }
438
 
439
    // ---- Deferrals & SLA ----------------------------------------------------
440
 
441
    private Map<String, Object> deferral(Session s, String ms, String me, List<Integer> auth) {
442
        NativeQuery<?> q = s.createNativeQuery(
443
            "SELECT COUNT(*) total," +
444
            " SUM(status='RESCHEDULED') rescheduled, SUM(status='CANCELLED') cancelled," +
445
            " SUM(action_by IS NOT NULL) actioned," +
446
            " SUM(reason LIKE 'Beat missed%' OR reason LIKE 'Not marked%') system_gen," +
447
            " ROUND(AVG(CASE WHEN action_by IS NOT NULL THEN TIMESTAMPDIFF(HOUR, created_timestamp, updated_timestamp)/24.0 END),1) avg_days" +
448
            " FROM `user`.beat_deferred_visit WHERE deferred_date>=:ms AND deferred_date<=:me AND auth_user_id IN (:auth)");
449
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("auth", auth);
450
        Object[] r = (Object[]) q.uniqueResult();
451
        long total = asLong(r[0]), system = asLong(r[4]);
452
        long human = total - system;
453
        Map<String, Object> m = new LinkedHashMap<>();
454
        m.put("total", total);
455
        m.put("rescheduled", asLong(r[1]));
456
        m.put("cancelled", asLong(r[2]));
457
        m.put("actioned", asLong(r[3]));
458
        m.put("systemGenerated", system);
459
        m.put("human", human);
460
        m.put("avgDaysToAction", asDouble(r[5]));
461
        m.put("systemPct", total == 0 ? 0 : Math.round(100.0 * system / total));
462
        m.put("humanPct", total == 0 ? 0 : Math.round(100.0 * human / total));
463
        return m;
464
    }
465
 
36929 vikas 466
    // ---- Auto "missed" breakdown -------------------------------------------
467
    // Three distinct execution gaps behind the "Auto missed" card:
468
    //   unscheduled    — executives (sales positions) with no PJP at all in range
469
    //   unfilledAgenda — scheduled beat-days whose agenda was never filled
470
    //   missedPunchin  — scheduled beat-days the owner never punched in on
471
    private Map<String, Object> missedBreakdown(Session s, String ms, String me,
472
                                                List<Integer> auth, List<Map<String, Object>> coverage) {
473
        // unscheduled execs: total at each level minus those with a plan (reuse coverage)
474
        long unscheduled = 0;
475
        for (Map<String, Object> c : coverage) {
476
            unscheduled += Math.max(asLong(c.get("totalUsers")) - asLong(c.get("withPjp")), 0);
477
        }
478
 
479
        NativeQuery<?> ua = s.createNativeQuery(
480
            "SELECT COUNT(*) FROM `user`.beat_schedule sc" +
481
            " JOIN `user`.beat b ON b.id=sc.beat_id AND b.active=1 AND b.auth_user_id IN (:auth)" +
482
            " WHERE sc.start_date>=:ms AND sc.start_date<=:me AND sc.agenda_filled_timestamp IS NULL");
483
        ua.setParameter("ms", ms).setParameter("me", me).setParameterList("auth", auth);
484
        long unfilledAgenda = asLong(ua.uniqueResult());
485
 
486
        NativeQuery<?> mp = s.createNativeQuery(
487
            "SELECT COUNT(*) FROM `user`.beat_schedule sc" +
488
            " JOIN `user`.beat b ON b.id=sc.beat_id AND b.active=1 AND b.auth_user_id IN (:auth)" +
489
            " JOIN auth.auth_user au ON au.id=b.auth_user_id" +
490
            " JOIN dtr.users du ON du.email=au.email_id" +
491
            " WHERE sc.start_date>=:ms AND sc.start_date<=:me AND NOT EXISTS (" +
492
            "   SELECT 1 FROM auth.location_tracking lt WHERE lt.user_id=du.id AND lt.task_date=sc.start_date" +
493
            "     AND (lt.mark_type='PUNCHIN' OR (lt.task_id=0 AND lt.check_in_time IS NOT NULL AND lt.check_in_time<>'00:00:00')))");
494
        mp.setParameter("ms", ms).setParameter("me", me).setParameterList("auth", auth);
495
        long missedPunchin = asLong(mp.uniqueResult());
496
 
497
        Map<String, Object> m = new LinkedHashMap<>();
498
        m.put("unscheduled", unscheduled);
499
        m.put("unfilledAgenda", unfilledAgenda);
500
        m.put("missedPunchin", missedPunchin);
501
        m.put("total", unscheduled + unfilledAgenda + missedPunchin);
502
        return m;
503
    }
504
 
36913 vikas 505
    // ---- Drill-down lists ---------------------------------------------------
506
 
507
    // Per-executive PJP coverage (with/without a plan in range) — powers the
508
    // PJP coverage KPI and the coverage-by-level bar drill-downs.
509
    private List<Map<String, Object>> coverageDetail(Session s, String ms, String me, List<Integer> auth) {
510
        NativeQuery<?> q = s.createNativeQuery(
511
            "SELECT au.id uid, TRIM(CONCAT(au.first_name,' ',COALESCE(au.last_name,''))) nm, p.lvl," +
512
            " MAX(CASE WHEN sc.id IS NOT NULL THEN 1 ELSE 0 END) has_plan" +
36954 vikas 513
            " FROM (SELECT auth_user_id, MIN(escalation_type) lvl FROM cs.position WHERE category_id=4 AND auth_user_id IN (:auth) AND LOWER(escalation_type) NOT IN ('l4','l5','final') GROUP BY auth_user_id) p" +
36913 vikas 514
            " JOIN auth.auth_user au ON au.id=p.auth_user_id" +
515
            " LEFT JOIN `user`.beat b ON b.auth_user_id=p.auth_user_id AND b.active=1" +
516
            " LEFT JOIN `user`.beat_schedule sc ON sc.beat_id=b.id AND sc.start_date>=:ms AND sc.start_date<=:me" +
517
            " GROUP BY au.id, nm, p.lvl ORDER BY p.lvl, nm");
518
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("auth", auth);
519
        List<Map<String, Object>> list = new ArrayList<>();
520
        for (Object o : q.getResultList()) {
521
            Object[] r = (Object[]) o;
522
            Map<String, Object> m = new LinkedHashMap<>();
523
            m.put("authUserId", asLong(r[0]));
524
            m.put("name", asStr(r[1]));
525
            m.put("level", asStr(r[2]));
526
            m.put("hasPlan", asLong(r[3]) > 0);
527
            list.add(m);
528
        }
529
        return list;
530
    }
531
 
532
    // Every deferral in range (exec, partner, reason, date, status, system flag).
533
    private List<Map<String, Object>> deferralsList(Session s, String ms, String me, List<Integer> auth) {
534
        NativeQuery<?> q = s.createNativeQuery(
535
            "SELECT TRIM(CONCAT(au.first_name,' ',COALESCE(au.last_name,''))) nm, d.display_name, d.reason," +
536
            " d.deferred_date, d.status, d.task_type," +
537
            " (d.reason LIKE 'Beat missed%' OR d.reason LIKE 'Not marked%') sys" +
538
            " FROM `user`.beat_deferred_visit d JOIN auth.auth_user au ON au.id=d.auth_user_id" +
539
            " WHERE d.deferred_date>=:ms AND d.deferred_date<=:me AND d.auth_user_id IN (:auth)" +
540
            " ORDER BY d.deferred_date, nm");
541
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("auth", auth);
542
        List<Map<String, Object>> list = new ArrayList<>();
543
        for (Object o : q.getResultList()) {
544
            Object[] r = (Object[]) o;
545
            Map<String, Object> m = new LinkedHashMap<>();
546
            m.put("exec", asStr(r[0]));
547
            m.put("partner", asStr(r[1]));
548
            m.put("reason", asStr(r[2]));
549
            m.put("date", asStr(r[3]));
550
            m.put("status", asStr(r[4]));
551
            m.put("taskType", asStr(r[5]));
552
            m.put("system", asLong(r[6]) > 0);
553
            list.add(m);
554
        }
555
        return list;
556
    }
557
 
558
    // Every lead created in range (exec, outlet, city, date, status).
559
    private List<Map<String, Object>> leadsList(Session s, String ms, String me, List<Integer> auth) {
560
        NativeQuery<?> q = s.createNativeQuery(
561
            "SELECT TRIM(CONCAT(au.first_name,' ',COALESCE(au.last_name,''))) nm," +
562
            " COALESCE(NULLIF(l.outlet_name,''), TRIM(CONCAT(COALESCE(l.first_name,''),' ',COALESCE(l.last_name,'')))) lead," +
563
            " l.city, DATE(l.created_timestamp) dt, l.status" +
564
            " FROM `user`.lead l JOIN auth.auth_user au ON au.id=l.auth_id" +
565
            " WHERE l.created_timestamp>=:ms AND l.created_timestamp<=CONCAT(:me,' 23:59:59') AND l.auth_id IN (:auth)" +
566
            " ORDER BY dt, nm");
567
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("auth", auth);
568
        List<Map<String, Object>> list = new ArrayList<>();
569
        for (Object o : q.getResultList()) {
570
            Object[] r = (Object[]) o;
571
            Map<String, Object> m = new LinkedHashMap<>();
572
            m.put("exec", asStr(r[0]));
573
            m.put("lead", asStr(r[1]));
574
            m.put("city", asStr(r[2]));
575
            m.put("date", asStr(r[3]));
576
            m.put("status", asStr(r[4]));
577
            list.add(m);
578
        }
579
        return list;
580
    }
581
 
36877 vikas 582
    // ---- Travel & route quality --------------------------------------------
583
 
584
    private Map<String, Object> travel(Session s, String ms, String me, List<Integer> auth, List<Integer> dtr) {
585
        Map<String, Object> m = new LinkedHashMap<>();
586
 
587
        String legFrom =
588
            " FROM `user`.beat_route a" +
589
            " JOIN `user`.beat bt ON bt.id=a.beat_id AND bt.auth_user_id IN (:auth)" +
590
            " JOIN `user`.beat_route b ON b.beat_id=a.beat_id AND b.day_number=a.day_number AND b.sequence_order=a.sequence_order+1 AND b.active=1" +
591
            " JOIN (SELECT id, CAST(latitude AS DECIMAL(10,7)) lat, CAST(longitude AS DECIMAL(10,7)) lng FROM fofo.fofo_store WHERE latitude REGEXP '^[0-9.]+$') al ON al.id=a.fofo_id" +
592
            " JOIN (SELECT id, CAST(latitude AS DECIMAL(10,7)) lat, CAST(longitude AS DECIMAL(10,7)) lng FROM fofo.fofo_store WHERE latitude REGEXP '^[0-9.]+$') bl ON bl.id=b.fofo_id" +
593
            " WHERE a.active=1";
594
        String legKm =
595
            "6371*2*ASIN(SQRT(POWER(SIN(RADIANS(bl.lat-al.lat)/2),2)+COS(RADIANS(al.lat))*COS(RADIANS(bl.lat))*POWER(SIN(RADIANS(bl.lng-al.lng)/2),2)))";
596
 
597
        NativeQuery<?> bq = s.createNativeQuery(
598
            "SELECT bucket, COUNT(*) n FROM (" +
599
            "  SELECT CASE WHEN km<2 THEN '0-2 km' WHEN km<5 THEN '2-5 km' WHEN km<15 THEN '5-15 km'" +
600
            "    WHEN km<50 THEN '15-50 km' ELSE '50 km+' END bucket," +
601
            "  CASE WHEN km<2 THEN 1 WHEN km<5 THEN 2 WHEN km<15 THEN 3 WHEN km<50 THEN 4 ELSE 5 END ord" +
602
            "  FROM (SELECT " + legKm + " km" + legFrom + ") l" +
603
            " ) z GROUP BY bucket, ord ORDER BY ord");
604
        bq.setParameterList("auth", auth);
605
        List<Map<String, Object>> buckets = new ArrayList<>();
606
        for (Object o : bq.getResultList()) {
607
            Object[] r = (Object[]) o;
608
            Map<String, Object> b = new LinkedHashMap<>();
609
            b.put("bucket", asStr(r[0]));
610
            b.put("count", asLong(r[1]));
611
            buckets.add(b);
612
        }
613
        m.put("legBuckets", buckets);
614
 
615
        NativeQuery<?> sq = s.createNativeQuery(
616
            "SELECT ROUND(AVG(km),1) avg_leg, ROUND(MAX(km),0) max_leg, SUM(km>15) over15, COUNT(*) total" +
617
            " FROM (SELECT " + legKm + " km" + legFrom + ") l");
618
        sq.setParameterList("auth", auth);
619
        Object[] sr = (Object[]) sq.uniqueResult();
620
        long totalLegs = asLong(sr[3]), over15 = asLong(sr[2]);
621
        m.put("avgLegKm", asDouble(sr[0]));
622
        m.put("maxLegKm", asDouble(sr[1]));
623
        m.put("pctOver15", totalLegs == 0 ? 0 : Math.round(100.0 * over15 / totalLegs));
624
 
625
        NativeQuery<?> tq = s.createNativeQuery(
626
            "SELECT ROUND(SUM(TIME_TO_SEC(transit_time))/3600,1) transit_hrs, ROUND(SUM(TIME_TO_SEC(estimated_time))/3600,1) est_hrs" +
627
            " FROM auth.location_tracking WHERE task_date>=:ms AND task_date<=:me AND task_type='franchisee-visit' AND user_id IN (:dtr)");
628
        tq.setParameter("ms", ms).setParameter("me", me).setParameterList("dtr", dtr);
629
        Object[] tr = (Object[]) tq.uniqueResult();
630
        double transit = asDouble(tr[0]), est = asDouble(tr[1]);
631
        m.put("actualVsEstimateRatio", est == 0 ? 0 : round1(transit / est));
632
        return m;
633
    }
634
 
635
    // ---- Outcomes & visit quality ------------------------------------------
636
 
637
    private Map<String, Object> outcomes(Session s, String ms, String me, List<Integer> auth) {
638
        NativeQuery<?> q = s.createNativeQuery(
639
            "SELECT COUNT(*) total," +
640
            " SUM(partner_remark IS NOT NULL AND TRIM(partner_remark)<>'') remark," +
641
            " ROUND(AVG(NULLIF(rbm_rating,0)),1) avg_rating," +
642
            " SUM(instore_visibility IS NOT NULL AND TRIM(instore_visibility)<>'') audit," +
643
            " SUM(franchise_activity_id>0) nextv" +
644
            " FROM `user`.my_franchisee_visit" +
645
            " WHERE auth_id IN (:auth) AND COALESCE(visit_timestamp, created_timestamp)>=:ms" +
646
            " AND COALESCE(visit_timestamp, created_timestamp)<=CONCAT(:me,' 23:59:59')");
647
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("auth", auth);
648
        Object[] r = (Object[]) q.uniqueResult();
649
        long total = asLong(r[0]);
650
        Map<String, Object> m = new LinkedHashMap<>();
651
        m.put("completedVisits", total);
652
        m.put("remarkFilledPct", total == 0 ? 0 : Math.round(100.0 * asLong(r[1]) / total));
653
        m.put("avgRating", asDouble(r[2]));
654
        m.put("auditDonePct", total == 0 ? 0 : Math.round(100.0 * asLong(r[3]) / total));
655
        m.put("nextVisitPct", total == 0 ? 0 : Math.round(100.0 * asLong(r[4]) / total));
656
        return m;
657
    }
658
 
659
    // ---- "What to fix" findings (computed in Java) --------------------------
660
 
661
    private List<Map<String, Object>> findings(Map<String, Object> kpis, Map<String, Object> funnel,
662
                                               Map<String, Object> deferral, Map<String, Object> util,
663
                                               Map<String, Object> travel, Map<String, Object> outcomes,
664
                                               List<Map<String, Object>> coverage, List<Map<String, Object>> scorecard) {
665
        List<Map<String, Object>> f = new ArrayList<>();
666
 
667
        long avgDisc = asLong(kpis.get("avgDiscussionMin"));
668
        long rushed = scorecard.stream().filter(r -> asLong(r.get("discussionMin")) > 0 && asLong(r.get("discussionMin")) < 10).count();
669
        if (avgDisc > 0 && (avgDisc < 30 || rushed > 0)) {
670
            f.add(finding("high", "Rushed partner visits",
671
                "Avg discussion is " + avgDisc + " min vs a 30–45 min target" + (rushed > 0 ? ", and " + rushed + " executive(s) average under 10 min" : "") + " — too short for a real outlet conversation.",
672
                "Set a minimum on-store time and review visit quality."));
673
        }
674
 
675
        long geo = scorecard.stream().mapToLong(r -> asLong(r.get("geoFlags"))).sum();
676
        if (geo > 0) {
677
            f.add(finding("high", "Fake-visit risk",
678
                geo + " check-in(s) were >50 m from the store (check-in GPS vs the partner's saved location).",
679
                "Enforce geofenced check-in and flag these journeys for audit."));
680
        }
681
 
682
        for (Map<String, Object> c : coverage) {
683
            if ("L1".equalsIgnoreCase(asStr(c.get("level")))) {
684
                long total = asLong(c.get("totalUsers")), with = asLong(c.get("withPjp"));
685
                if (total - with > 0) {
686
                    f.add(finding("med", "Coverage gap",
687
                        (total - with) + " of " + total + " L1 executives have no monthly PJP — they run no planned beat this period.",
688
                        "Make a monthly PJP mandatory and approved before month start."));
689
                }
690
            }
691
        }
692
 
693
        long sysPct = asLong(deferral.get("systemPct"));
694
        double sla = asDouble(deferral.get("avgDaysToAction"));
695
        if (asLong(deferral.get("total")) > 0 && (sysPct >= 50 || sla >= 2)) {
696
            f.add(finding("med", "Deferral leakage",
697
                sysPct + "% of deferrals are system auto-flags" + (sla > 0 ? ", and genuine deferrals sit " + sla + " days before a head acts" : "") + ".",
698
                "Require a reason on real deferrals and add a manager-action SLA."));
699
        }
700
 
701
        long idlePct = asLong(util.get("idlePct"));
702
        if (idlePct >= 20) {
703
            f.add(finding("med", "A large part of the day is idle",
704
                idlePct + "% of the working day (" + util.get("idleHrs") + " h) is neither travel nor in-store.",
705
                "Investigate idle windows; tighten beat sequencing to cut dead time."));
706
        }
707
 
708
        long over15 = asLong(travel.get("pctOver15"));
709
        if (over15 >= 15) {
710
            f.add(finding("med", "Route inefficiency",
711
                over15 + "% of legs exceed 15 km — consecutive stops aren't geographically clustered.",
712
                "Re-sequence beats by proximity and cap daily travel."));
713
        }
714
 
715
        long journeys = asLong(kpis.get("journeys")), leads = asLong(kpis.get("leadsCreated"));
716
        if (journeys > 0 && leads < journeys * 0.25) {
717
            f.add(finding("low", "Lead capture is low",
718
                "Only " + leads + " leads across " + journeys + " journeys — executives aren't logging the new shops they pass.",
719
                "Add a per-beat lead nudge; recognise top loggers."));
720
        }
721
        return f;
722
    }
723
 
724
    private static Map<String, Object> finding(String sev, String title, String detail, String action) {
725
        Map<String, Object> m = new LinkedHashMap<>();
726
        m.put("severity", sev);
727
        m.put("title", title);
728
        m.put("detail", detail);
729
        m.put("action", action);
730
        return m;
731
    }
732
 
733
    // ---- helpers ------------------------------------------------------------
734
 
735
    private static List<Integer> safeIds(List<Integer> ids) {
736
        if (ids == null || ids.isEmpty()) return Collections.singletonList(-1);
737
        return ids;
738
    }
739
 
740
    private static long asLong(Object o) {
741
        return o == null ? 0L : ((Number) o).longValue();
742
    }
743
 
744
    private static double asDouble(Object o) {
745
        return o == null ? 0.0 : ((Number) o).doubleValue();
746
    }
747
 
748
    private static String asStr(Object o) {
749
        return o == null ? "" : o.toString();
750
    }
751
 
752
    private static double round1(double v) {
753
        return Math.round(v * 10.0) / 10.0;
754
    }
755
}