Subversion Repositories SmartDukaan

Rev

Rev 36954 | 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," +
37020 vikas 314
            " COALESCE(ld.leads,0) leads, du.id duid, COALESCE(acp.donep,0) donep," +
315
            // Active days + lead / franchisee check-ins, for the per-active-day
316
            // visit averages (same definitions as the Period KPI cards).
317
            " COALESCE(ad.days,0) act_days, COALESCE(lv.lvis,0) lvis, COALESCE(fv.fvis,0) fvis" +
36877 vikas 318
            " FROM (SELECT DISTINCT auth_user_id FROM `user`.beat WHERE active=1 AND auth_user_id IN (:auth)) o" +
319
            " JOIN auth.auth_user au ON au.id=o.auth_user_id" +
320
            " LEFT JOIN dtr.users du ON du.email=au.email_id" +
36954 vikas 321
            " 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 322
            " LEFT JOIN (SELECT b.auth_user_id uid, COUNT(*) planned FROM `user`.beat_schedule sc" +
36913 vikas 323
            "   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 324
            "   WHERE sc.start_date>=:ms AND sc.start_date<=:me GROUP BY b.auth_user_id) pl ON pl.uid=au.id" +
36913 vikas 325
            " LEFT JOIN (SELECT b.auth_user_id uid, COUNT(*) planned FROM `user`.beat_schedule sc" +
326
            "   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'" +
327
            "   WHERE sc.start_date>=:ms AND sc.start_date<=:me GROUP BY b.auth_user_id) plL ON plL.uid=au.id" +
36877 vikas 328
            " LEFT JOIN (SELECT user_id uid, COUNT(*) done FROM auth.location_tracking" +
36913 vikas 329
            "   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 330
            // Adherence numerator: completed PLANNED visits only (partner franchisee +
331
            // approved leads), excluding ad-hoc office/warehouse stops and self-assigned
332
            // stops (task_name carries a "… | SELF" marker, which aren't part of the plan).
333
            " LEFT JOIN (SELECT user_id uid, COUNT(*) donep FROM auth.location_tracking" +
334
            "   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 335
            " 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 336
            "   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 337
            " 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" +
338
            "   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" +
339
            " 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" +
37020 vikas 340
            // active (punched-in) days — same rule as the KPI 'journeys' count.
341
            " LEFT JOIN (SELECT user_id uid, COUNT(DISTINCT task_date) days FROM auth.location_tracking" +
342
            "   WHERE task_date>=:ms AND task_date<=:me AND (mark_type='PUNCHIN' OR (task_id=0 AND check_in_time IS NOT NULL AND check_in_time<>'00:00:00')) GROUP BY user_id) ad ON ad.uid=du.id" +
343
            " LEFT JOIN (SELECT user_id uid, COUNT(*) lvis FROM auth.location_tracking" +
344
            "   WHERE task_date>=:ms AND task_date<=:me AND task_id<>0 AND task_type='lead' AND mark_type LIKE 'CHECKIN%' GROUP BY user_id) lv ON lv.uid=du.id" +
345
            " LEFT JOIN (SELECT user_id uid, COUNT(*) fvis FROM auth.location_tracking" +
346
            "   WHERE task_date>=:ms AND task_date<=:me AND task_id<>0 AND task_type='franchisee-visit' AND mark_type LIKE 'CHECKIN%' GROUP BY user_id) fv ON fv.uid=du.id" +
36877 vikas 347
            " ORDER BY done DESC, planned DESC");
348
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("auth", auth);
349
 
350
        // Geofence-offsite check-ins per user are computed in Java (not SQL): the
351
        // coords are stored as "lat,lng" strings, and the inline parsing/haversine
352
        // expression trips Hibernate's native-query parameter parser.
353
        Map<Integer, Integer> geoByUser = geoOffsiteByUser(s, ms, me, dtr);
354
 
355
        List<Map<String, Object>> list = new ArrayList<>();
356
        for (Object o : q.getResultList()) {
357
            Object[] r = (Object[]) o;
36929 vikas 358
            long planned = asLong(r[3]), done = asLong(r[4]), donePlanned = asLong(r[9]);
36913 vikas 359
            Integer duid = (r[8] == null) ? null : ((Number) r[8]).intValue();
36877 vikas 360
            Map<String, Object> m = new LinkedHashMap<>();
36913 vikas 361
            m.put("authUserId", asLong(r[0]));
362
            m.put("userId", duid == null ? 0 : duid);
36877 vikas 363
            m.put("name", asStr(r[1]));
364
            m.put("level", r[2] == null ? "-" : asStr(r[2]));
365
            m.put("planned", planned);
366
            m.put("done", done);
36929 vikas 367
            // Adherence = completed PLANNED visits ÷ planned visits (not all visits).
368
            m.put("adherencePct", planned == 0 ? 0 : Math.round(100.0 * donePlanned / planned));
36877 vikas 369
            m.put("discussionMin", asLong(r[5]));
370
            m.put("workingHrs", round1(asDouble(r[6]) / 3600.0));
371
            m.put("leads", asLong(r[7]));
37020 vikas 372
            // avg lead / franchisee visits per active (punched-in) day
373
            long actDays = asLong(r[10]);
374
            m.put("avgLeadVisitsPerDay", actDays == 0 ? 0 : round1((double) asLong(r[11]) / actDays));
375
            m.put("avgFranchiseeVisitsPerDay", actDays == 0 ? 0 : round1((double) asLong(r[12]) / actDays));
36877 vikas 376
            m.put("geoFlags", duid == null ? 0 : geoByUser.getOrDefault(duid, 0));
377
            list.add(m);
378
        }
379
        return list;
380
    }
381
 
382
    // Per dtr-user count of check-ins recorded >50 m from the partner's saved
383
    // location. Pulls the raw "lat,lng" strings and does the haversine in Java.
384
    private Map<Integer, Integer> geoOffsiteByUser(Session s, String ms, String me, List<Integer> dtr) {
385
        NativeQuery<?> q = s.createNativeQuery(
386
            "SELECT user_id, checkin_lat_lng, visit_location FROM auth.location_tracking" +
387
            " WHERE task_date>=:ms AND task_date<=:me AND task_type='franchisee-visit' AND mark_type LIKE 'CHECKIN%'" +
388
            " AND checkin_lat_lng LIKE '%,%' AND visit_location LIKE '%,%' AND user_id IN (:dtr)");
389
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("dtr", dtr);
390
        Map<Integer, Integer> out = new HashMap<>();
391
        for (Object o : q.getResultList()) {
392
            Object[] r = (Object[]) o;
393
            if (r[0] == null) continue;
394
            double[] cin = parseLatLng(asStr(r[1]));
395
            double[] vis = parseLatLng(asStr(r[2]));
396
            if (cin == null || vis == null) continue;
397
            if (haversineMeters(cin[0], cin[1], vis[0], vis[1]) > 50.0) {
398
                int uid = ((Number) r[0]).intValue();
399
                out.merge(uid, 1, Integer::sum);
400
            }
401
        }
402
        return out;
403
    }
404
 
405
    private static double[] parseLatLng(String s) {
406
        if (s == null || !s.contains(",")) return null;
407
        String[] parts = s.split(",");
408
        if (parts.length != 2) return null;
409
        try {
410
            double a = Double.parseDouble(parts[0].trim());
411
            double b = Double.parseDouble(parts[1].trim());
412
            if (a == 0 && b == 0) return null;
413
            return new double[]{a, b};
414
        } catch (NumberFormatException e) {
415
            return null;
416
        }
417
    }
418
 
419
    private static double haversineMeters(double lat1, double lng1, double lat2, double lng2) {
420
        double R = 6371000d;
421
        double dLat = Math.toRadians(lat2 - lat1);
422
        double dLng = Math.toRadians(lng2 - lng1);
423
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
424
                + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
425
                * Math.sin(dLng / 2) * Math.sin(dLng / 2);
426
        return 2 * R * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
427
    }
428
 
429
    // ---- Working-hour utilization ------------------------------------------
430
 
431
    private Map<String, Object> utilization(Session s, String ms, String me, List<Integer> dtr) {
432
        NativeQuery<?> q = s.createNativeQuery(
433
            "SELECT" +
36913 vikas 434
            " (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," +
435
            " (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 436
            " (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");
437
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("dtr", dtr);
438
        Object[] r = (Object[]) q.uniqueResult();
439
        double instore = asDouble(r[0]), travel = asDouble(r[1]), working = asDouble(r[2]);
440
        if (working < instore + travel) working = instore + travel; // guard: working must cover its parts
441
        double idle = Math.max(working - instore - travel, 0);
442
        Map<String, Object> m = new LinkedHashMap<>();
443
        m.put("inStoreHrs", round1(instore / 3600.0));
444
        m.put("travelHrs", round1(travel / 3600.0));
445
        m.put("idleHrs", round1(idle / 3600.0));
446
        m.put("workingHrs", round1(working / 3600.0));
447
        m.put("inStorePct", working == 0 ? 0 : (int) Math.round(100.0 * instore / working));
448
        m.put("travelPct", working == 0 ? 0 : (int) Math.round(100.0 * travel / working));
449
        m.put("idlePct", working == 0 ? 0 : (int) Math.round(100.0 * idle / working));
450
        return m;
451
    }
452
 
453
    // ---- Deferrals & SLA ----------------------------------------------------
454
 
455
    private Map<String, Object> deferral(Session s, String ms, String me, List<Integer> auth) {
456
        NativeQuery<?> q = s.createNativeQuery(
457
            "SELECT COUNT(*) total," +
458
            " SUM(status='RESCHEDULED') rescheduled, SUM(status='CANCELLED') cancelled," +
459
            " SUM(action_by IS NOT NULL) actioned," +
460
            " SUM(reason LIKE 'Beat missed%' OR reason LIKE 'Not marked%') system_gen," +
461
            " ROUND(AVG(CASE WHEN action_by IS NOT NULL THEN TIMESTAMPDIFF(HOUR, created_timestamp, updated_timestamp)/24.0 END),1) avg_days" +
462
            " FROM `user`.beat_deferred_visit WHERE deferred_date>=:ms AND deferred_date<=:me AND auth_user_id IN (:auth)");
463
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("auth", auth);
464
        Object[] r = (Object[]) q.uniqueResult();
465
        long total = asLong(r[0]), system = asLong(r[4]);
466
        long human = total - system;
467
        Map<String, Object> m = new LinkedHashMap<>();
468
        m.put("total", total);
469
        m.put("rescheduled", asLong(r[1]));
470
        m.put("cancelled", asLong(r[2]));
471
        m.put("actioned", asLong(r[3]));
472
        m.put("systemGenerated", system);
473
        m.put("human", human);
474
        m.put("avgDaysToAction", asDouble(r[5]));
475
        m.put("systemPct", total == 0 ? 0 : Math.round(100.0 * system / total));
476
        m.put("humanPct", total == 0 ? 0 : Math.round(100.0 * human / total));
477
        return m;
478
    }
479
 
36929 vikas 480
    // ---- Auto "missed" breakdown -------------------------------------------
481
    // Three distinct execution gaps behind the "Auto missed" card:
482
    //   unscheduled    — executives (sales positions) with no PJP at all in range
483
    //   unfilledAgenda — scheduled beat-days whose agenda was never filled
484
    //   missedPunchin  — scheduled beat-days the owner never punched in on
485
    private Map<String, Object> missedBreakdown(Session s, String ms, String me,
486
                                                List<Integer> auth, List<Map<String, Object>> coverage) {
487
        // unscheduled execs: total at each level minus those with a plan (reuse coverage)
488
        long unscheduled = 0;
489
        for (Map<String, Object> c : coverage) {
490
            unscheduled += Math.max(asLong(c.get("totalUsers")) - asLong(c.get("withPjp")), 0);
491
        }
492
 
493
        NativeQuery<?> ua = s.createNativeQuery(
494
            "SELECT COUNT(*) FROM `user`.beat_schedule sc" +
495
            " JOIN `user`.beat b ON b.id=sc.beat_id AND b.active=1 AND b.auth_user_id IN (:auth)" +
496
            " WHERE sc.start_date>=:ms AND sc.start_date<=:me AND sc.agenda_filled_timestamp IS NULL");
497
        ua.setParameter("ms", ms).setParameter("me", me).setParameterList("auth", auth);
498
        long unfilledAgenda = asLong(ua.uniqueResult());
499
 
500
        NativeQuery<?> mp = s.createNativeQuery(
501
            "SELECT COUNT(*) FROM `user`.beat_schedule sc" +
502
            " JOIN `user`.beat b ON b.id=sc.beat_id AND b.active=1 AND b.auth_user_id IN (:auth)" +
503
            " JOIN auth.auth_user au ON au.id=b.auth_user_id" +
504
            " JOIN dtr.users du ON du.email=au.email_id" +
505
            " WHERE sc.start_date>=:ms AND sc.start_date<=:me AND NOT EXISTS (" +
506
            "   SELECT 1 FROM auth.location_tracking lt WHERE lt.user_id=du.id AND lt.task_date=sc.start_date" +
507
            "     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')))");
508
        mp.setParameter("ms", ms).setParameter("me", me).setParameterList("auth", auth);
509
        long missedPunchin = asLong(mp.uniqueResult());
510
 
511
        Map<String, Object> m = new LinkedHashMap<>();
512
        m.put("unscheduled", unscheduled);
513
        m.put("unfilledAgenda", unfilledAgenda);
514
        m.put("missedPunchin", missedPunchin);
515
        m.put("total", unscheduled + unfilledAgenda + missedPunchin);
516
        return m;
517
    }
518
 
36913 vikas 519
    // ---- Drill-down lists ---------------------------------------------------
520
 
521
    // Per-executive PJP coverage (with/without a plan in range) — powers the
522
    // PJP coverage KPI and the coverage-by-level bar drill-downs.
523
    private List<Map<String, Object>> coverageDetail(Session s, String ms, String me, List<Integer> auth) {
524
        NativeQuery<?> q = s.createNativeQuery(
525
            "SELECT au.id uid, TRIM(CONCAT(au.first_name,' ',COALESCE(au.last_name,''))) nm, p.lvl," +
526
            " MAX(CASE WHEN sc.id IS NOT NULL THEN 1 ELSE 0 END) has_plan" +
36954 vikas 527
            " 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 528
            " JOIN auth.auth_user au ON au.id=p.auth_user_id" +
529
            " LEFT JOIN `user`.beat b ON b.auth_user_id=p.auth_user_id AND b.active=1" +
530
            " LEFT JOIN `user`.beat_schedule sc ON sc.beat_id=b.id AND sc.start_date>=:ms AND sc.start_date<=:me" +
531
            " GROUP BY au.id, nm, p.lvl ORDER BY p.lvl, nm");
532
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("auth", auth);
533
        List<Map<String, Object>> list = new ArrayList<>();
534
        for (Object o : q.getResultList()) {
535
            Object[] r = (Object[]) o;
536
            Map<String, Object> m = new LinkedHashMap<>();
537
            m.put("authUserId", asLong(r[0]));
538
            m.put("name", asStr(r[1]));
539
            m.put("level", asStr(r[2]));
540
            m.put("hasPlan", asLong(r[3]) > 0);
541
            list.add(m);
542
        }
543
        return list;
544
    }
545
 
546
    // Every deferral in range (exec, partner, reason, date, status, system flag).
547
    private List<Map<String, Object>> deferralsList(Session s, String ms, String me, List<Integer> auth) {
548
        NativeQuery<?> q = s.createNativeQuery(
549
            "SELECT TRIM(CONCAT(au.first_name,' ',COALESCE(au.last_name,''))) nm, d.display_name, d.reason," +
550
            " d.deferred_date, d.status, d.task_type," +
551
            " (d.reason LIKE 'Beat missed%' OR d.reason LIKE 'Not marked%') sys" +
552
            " FROM `user`.beat_deferred_visit d JOIN auth.auth_user au ON au.id=d.auth_user_id" +
553
            " WHERE d.deferred_date>=:ms AND d.deferred_date<=:me AND d.auth_user_id IN (:auth)" +
554
            " ORDER BY d.deferred_date, nm");
555
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("auth", auth);
556
        List<Map<String, Object>> list = new ArrayList<>();
557
        for (Object o : q.getResultList()) {
558
            Object[] r = (Object[]) o;
559
            Map<String, Object> m = new LinkedHashMap<>();
560
            m.put("exec", asStr(r[0]));
561
            m.put("partner", asStr(r[1]));
562
            m.put("reason", asStr(r[2]));
563
            m.put("date", asStr(r[3]));
564
            m.put("status", asStr(r[4]));
565
            m.put("taskType", asStr(r[5]));
566
            m.put("system", asLong(r[6]) > 0);
567
            list.add(m);
568
        }
569
        return list;
570
    }
571
 
572
    // Every lead created in range (exec, outlet, city, date, status).
573
    private List<Map<String, Object>> leadsList(Session s, String ms, String me, List<Integer> auth) {
574
        NativeQuery<?> q = s.createNativeQuery(
575
            "SELECT TRIM(CONCAT(au.first_name,' ',COALESCE(au.last_name,''))) nm," +
576
            " COALESCE(NULLIF(l.outlet_name,''), TRIM(CONCAT(COALESCE(l.first_name,''),' ',COALESCE(l.last_name,'')))) lead," +
577
            " l.city, DATE(l.created_timestamp) dt, l.status" +
578
            " FROM `user`.lead l JOIN auth.auth_user au ON au.id=l.auth_id" +
579
            " WHERE l.created_timestamp>=:ms AND l.created_timestamp<=CONCAT(:me,' 23:59:59') AND l.auth_id IN (:auth)" +
580
            " ORDER BY dt, nm");
581
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("auth", auth);
582
        List<Map<String, Object>> list = new ArrayList<>();
583
        for (Object o : q.getResultList()) {
584
            Object[] r = (Object[]) o;
585
            Map<String, Object> m = new LinkedHashMap<>();
586
            m.put("exec", asStr(r[0]));
587
            m.put("lead", asStr(r[1]));
588
            m.put("city", asStr(r[2]));
589
            m.put("date", asStr(r[3]));
590
            m.put("status", asStr(r[4]));
591
            list.add(m);
592
        }
593
        return list;
594
    }
595
 
36877 vikas 596
    // ---- Travel & route quality --------------------------------------------
597
 
598
    private Map<String, Object> travel(Session s, String ms, String me, List<Integer> auth, List<Integer> dtr) {
599
        Map<String, Object> m = new LinkedHashMap<>();
600
 
601
        String legFrom =
602
            " FROM `user`.beat_route a" +
603
            " JOIN `user`.beat bt ON bt.id=a.beat_id AND bt.auth_user_id IN (:auth)" +
604
            " 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" +
605
            " 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" +
606
            " 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" +
607
            " WHERE a.active=1";
608
        String legKm =
609
            "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)))";
610
 
611
        NativeQuery<?> bq = s.createNativeQuery(
612
            "SELECT bucket, COUNT(*) n FROM (" +
613
            "  SELECT CASE WHEN km<2 THEN '0-2 km' WHEN km<5 THEN '2-5 km' WHEN km<15 THEN '5-15 km'" +
614
            "    WHEN km<50 THEN '15-50 km' ELSE '50 km+' END bucket," +
615
            "  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" +
616
            "  FROM (SELECT " + legKm + " km" + legFrom + ") l" +
617
            " ) z GROUP BY bucket, ord ORDER BY ord");
618
        bq.setParameterList("auth", auth);
619
        List<Map<String, Object>> buckets = new ArrayList<>();
620
        for (Object o : bq.getResultList()) {
621
            Object[] r = (Object[]) o;
622
            Map<String, Object> b = new LinkedHashMap<>();
623
            b.put("bucket", asStr(r[0]));
624
            b.put("count", asLong(r[1]));
625
            buckets.add(b);
626
        }
627
        m.put("legBuckets", buckets);
628
 
629
        NativeQuery<?> sq = s.createNativeQuery(
630
            "SELECT ROUND(AVG(km),1) avg_leg, ROUND(MAX(km),0) max_leg, SUM(km>15) over15, COUNT(*) total" +
631
            " FROM (SELECT " + legKm + " km" + legFrom + ") l");
632
        sq.setParameterList("auth", auth);
633
        Object[] sr = (Object[]) sq.uniqueResult();
634
        long totalLegs = asLong(sr[3]), over15 = asLong(sr[2]);
635
        m.put("avgLegKm", asDouble(sr[0]));
636
        m.put("maxLegKm", asDouble(sr[1]));
637
        m.put("pctOver15", totalLegs == 0 ? 0 : Math.round(100.0 * over15 / totalLegs));
638
 
639
        NativeQuery<?> tq = s.createNativeQuery(
640
            "SELECT ROUND(SUM(TIME_TO_SEC(transit_time))/3600,1) transit_hrs, ROUND(SUM(TIME_TO_SEC(estimated_time))/3600,1) est_hrs" +
641
            " FROM auth.location_tracking WHERE task_date>=:ms AND task_date<=:me AND task_type='franchisee-visit' AND user_id IN (:dtr)");
642
        tq.setParameter("ms", ms).setParameter("me", me).setParameterList("dtr", dtr);
643
        Object[] tr = (Object[]) tq.uniqueResult();
644
        double transit = asDouble(tr[0]), est = asDouble(tr[1]);
645
        m.put("actualVsEstimateRatio", est == 0 ? 0 : round1(transit / est));
646
        return m;
647
    }
648
 
649
    // ---- Outcomes & visit quality ------------------------------------------
650
 
651
    private Map<String, Object> outcomes(Session s, String ms, String me, List<Integer> auth) {
652
        NativeQuery<?> q = s.createNativeQuery(
653
            "SELECT COUNT(*) total," +
654
            " SUM(partner_remark IS NOT NULL AND TRIM(partner_remark)<>'') remark," +
655
            " ROUND(AVG(NULLIF(rbm_rating,0)),1) avg_rating," +
656
            " SUM(instore_visibility IS NOT NULL AND TRIM(instore_visibility)<>'') audit," +
657
            " SUM(franchise_activity_id>0) nextv" +
658
            " FROM `user`.my_franchisee_visit" +
659
            " WHERE auth_id IN (:auth) AND COALESCE(visit_timestamp, created_timestamp)>=:ms" +
660
            " AND COALESCE(visit_timestamp, created_timestamp)<=CONCAT(:me,' 23:59:59')");
661
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("auth", auth);
662
        Object[] r = (Object[]) q.uniqueResult();
663
        long total = asLong(r[0]);
664
        Map<String, Object> m = new LinkedHashMap<>();
665
        m.put("completedVisits", total);
666
        m.put("remarkFilledPct", total == 0 ? 0 : Math.round(100.0 * asLong(r[1]) / total));
667
        m.put("avgRating", asDouble(r[2]));
668
        m.put("auditDonePct", total == 0 ? 0 : Math.round(100.0 * asLong(r[3]) / total));
669
        m.put("nextVisitPct", total == 0 ? 0 : Math.round(100.0 * asLong(r[4]) / total));
670
        return m;
671
    }
672
 
673
    // ---- "What to fix" findings (computed in Java) --------------------------
674
 
675
    private List<Map<String, Object>> findings(Map<String, Object> kpis, Map<String, Object> funnel,
676
                                               Map<String, Object> deferral, Map<String, Object> util,
677
                                               Map<String, Object> travel, Map<String, Object> outcomes,
678
                                               List<Map<String, Object>> coverage, List<Map<String, Object>> scorecard) {
679
        List<Map<String, Object>> f = new ArrayList<>();
680
 
681
        long avgDisc = asLong(kpis.get("avgDiscussionMin"));
682
        long rushed = scorecard.stream().filter(r -> asLong(r.get("discussionMin")) > 0 && asLong(r.get("discussionMin")) < 10).count();
683
        if (avgDisc > 0 && (avgDisc < 30 || rushed > 0)) {
684
            f.add(finding("high", "Rushed partner visits",
685
                "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.",
686
                "Set a minimum on-store time and review visit quality."));
687
        }
688
 
689
        long geo = scorecard.stream().mapToLong(r -> asLong(r.get("geoFlags"))).sum();
690
        if (geo > 0) {
691
            f.add(finding("high", "Fake-visit risk",
692
                geo + " check-in(s) were >50 m from the store (check-in GPS vs the partner's saved location).",
693
                "Enforce geofenced check-in and flag these journeys for audit."));
694
        }
695
 
696
        for (Map<String, Object> c : coverage) {
697
            if ("L1".equalsIgnoreCase(asStr(c.get("level")))) {
698
                long total = asLong(c.get("totalUsers")), with = asLong(c.get("withPjp"));
699
                if (total - with > 0) {
700
                    f.add(finding("med", "Coverage gap",
701
                        (total - with) + " of " + total + " L1 executives have no monthly PJP — they run no planned beat this period.",
702
                        "Make a monthly PJP mandatory and approved before month start."));
703
                }
704
            }
705
        }
706
 
707
        long sysPct = asLong(deferral.get("systemPct"));
708
        double sla = asDouble(deferral.get("avgDaysToAction"));
709
        if (asLong(deferral.get("total")) > 0 && (sysPct >= 50 || sla >= 2)) {
710
            f.add(finding("med", "Deferral leakage",
711
                sysPct + "% of deferrals are system auto-flags" + (sla > 0 ? ", and genuine deferrals sit " + sla + " days before a head acts" : "") + ".",
712
                "Require a reason on real deferrals and add a manager-action SLA."));
713
        }
714
 
715
        long idlePct = asLong(util.get("idlePct"));
716
        if (idlePct >= 20) {
717
            f.add(finding("med", "A large part of the day is idle",
718
                idlePct + "% of the working day (" + util.get("idleHrs") + " h) is neither travel nor in-store.",
719
                "Investigate idle windows; tighten beat sequencing to cut dead time."));
720
        }
721
 
722
        long over15 = asLong(travel.get("pctOver15"));
723
        if (over15 >= 15) {
724
            f.add(finding("med", "Route inefficiency",
725
                over15 + "% of legs exceed 15 km — consecutive stops aren't geographically clustered.",
726
                "Re-sequence beats by proximity and cap daily travel."));
727
        }
728
 
729
        long journeys = asLong(kpis.get("journeys")), leads = asLong(kpis.get("leadsCreated"));
730
        if (journeys > 0 && leads < journeys * 0.25) {
731
            f.add(finding("low", "Lead capture is low",
732
                "Only " + leads + " leads across " + journeys + " journeys — executives aren't logging the new shops they pass.",
733
                "Add a per-beat lead nudge; recognise top loggers."));
734
        }
735
        return f;
736
    }
737
 
738
    private static Map<String, Object> finding(String sev, String title, String detail, String action) {
739
        Map<String, Object> m = new LinkedHashMap<>();
740
        m.put("severity", sev);
741
        m.put("title", title);
742
        m.put("detail", detail);
743
        m.put("action", action);
744
        return m;
745
    }
746
 
747
    // ---- helpers ------------------------------------------------------------
748
 
749
    private static List<Integer> safeIds(List<Integer> ids) {
750
        if (ids == null || ids.isEmpty()) return Collections.singletonList(-1);
751
        return ids;
752
    }
753
 
754
    private static long asLong(Object o) {
755
        return o == null ? 0L : ((Number) o).longValue();
756
    }
757
 
758
    private static double asDouble(Object o) {
759
        return o == null ? 0.0 : ((Number) o).doubleValue();
760
    }
761
 
762
    private static String asStr(Object o) {
763
        return o == null ? "" : o.toString();
764
    }
765
 
766
    private static double round1(double v) {
767
        return Math.round(v * 10.0) / 10.0;
768
    }
769
}