Subversion Repositories SmartDukaan

Rev

Rev 36897 | Go to most recent revision | Details | 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
13
 * the caller's downline via the auth-id / dtr-id sets. Reuses the same cross-schema
14
 * patterns as {@link RouteAnalyticsServiceImpl}, adding {@code IN (:ids)} scope
15
 * filters and a few extra blocks (utilization, outcomes, findings).
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);
43
        Map<String, Object> deferral = deferral(s, start, end, auth);
44
        Map<String, Object> utilization = utilization(s, start, end, dtr);
45
        Map<String, Object> travel = travel(s, start, end, auth, dtr);
46
        Map<String, Object> outcomes = outcomes(s, start, end, auth);
47
        List<Map<String, Object>> scorecard = scorecard(s, start, end, auth, dtr);
48
        Map<String, Object> kpis = kpis(s, start, end, auth, dtr, coverage, funnel, deferral);
49
 
50
        out.put("kpis", kpis);
51
        out.put("funnel", funnel);
52
        out.put("coverageByLevel", coverage);
53
        out.put("scorecard", scorecard);
54
        out.put("utilization", utilization);
55
        out.put("deferral", deferral);
56
        out.put("travel", travel);
57
        out.put("outcomes", outcomes);
58
        out.put("findings", findings(kpis, funnel, deferral, utilization, travel, outcomes, coverage, scorecard));
59
        return out;
60
    }
61
 
62
    // ---- KPIs ---------------------------------------------------------------
63
 
64
    private Map<String, Object> kpis(Session s, String ms, String me, List<Integer> auth, List<Integer> dtr,
65
                                     List<Map<String, Object>> coverage, Map<String, Object> funnel, Map<String, Object> deferral) {
66
        Map<String, Object> m = new LinkedHashMap<>();
67
 
68
        long planned = asLong(funnel.get("plannedStops"));
69
        long done = asLong(funnel.get("checkedOut"));
70
        m.put("plannedStops", planned);
71
        m.put("doneStops", done);
72
        m.put("adherencePct", planned == 0 ? 0 : Math.round(100.0 * done / planned));
73
 
74
        // L1 coverage row
75
        long l1With = 0, l1Total = 0;
76
        for (Map<String, Object> c : coverage) {
77
            if ("L1".equalsIgnoreCase(asStr(c.get("level")))) {
78
                l1With = asLong(c.get("withPjp"));
79
                l1Total = asLong(c.get("totalUsers"));
80
            }
81
        }
82
        m.put("coverageL1With", l1With);
83
        m.put("coverageL1Total", l1Total);
84
        m.put("coverageL1Pct", l1Total == 0 ? 0 : Math.round(100.0 * l1With / l1Total));
85
 
86
        // avg visits / active (punched-in) day, and total punch-in days (journeys)
87
        NativeQuery<?> q = s.createNativeQuery(
88
            "SELECT COUNT(DISTINCT CONCAT(user_id,'-',task_date)) FROM auth.location_tracking" +
89
            " WHERE task_date>=:ms AND task_date<=:me AND mark_type='PUNCHIN' AND user_id IN (:dtr)");
90
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("dtr", dtr);
91
        long journeys = asLong(q.uniqueResult());
92
        m.put("journeys", journeys);
93
        m.put("avgVisitsPerActiveDay", journeys == 0 ? 0 : round1((double) asLong(funnel.get("checkedIn")) / journeys));
94
 
95
        // avg in-store discussion minutes
96
        NativeQuery<?> dq = s.createNativeQuery(
97
            "SELECT ROUND(AVG(NULLIF(TIME_TO_SEC(time_spent),0))/60,0) FROM auth.location_tracking" +
98
            " WHERE task_date>=:ms AND task_date<=:me AND task_type='franchisee-visit' AND mark_type LIKE '%CHECKOUT%' AND user_id IN (:dtr)");
99
        dq.setParameter("ms", ms).setParameter("me", me).setParameterList("dtr", dtr);
100
        m.put("avgDiscussionMin", asLong(dq.uniqueResult()));
101
 
102
        m.put("autoMissed", asLong(deferral.get("total")));
103
        m.put("autoMissedSystemPct", asLong(deferral.get("systemPct")));
104
 
105
        // leads created on route
106
        NativeQuery<?> lq = s.createNativeQuery(
107
            "SELECT COUNT(*) FROM `user`.lead WHERE created_timestamp>=:ms AND created_timestamp<=CONCAT(:me,' 23:59:59') AND auth_id IN (:auth)");
108
        lq.setParameter("ms", ms).setParameter("me", me).setParameterList("auth", auth);
109
        m.put("leadsCreated", asLong(lq.uniqueResult()));
110
        return m;
111
    }
112
 
113
    // ---- Funnel -------------------------------------------------------------
114
 
115
    private Map<String, Object> funnel(Session s, String ms, String me, List<Integer> auth, List<Integer> dtr) {
116
        Map<String, Object> m = new LinkedHashMap<>();
117
 
118
        // planned stops = scheduled beat-days × their routed stops
119
        NativeQuery<?> pq = s.createNativeQuery(
120
            "SELECT COUNT(*) FROM `user`.beat_schedule sc" +
121
            " JOIN `user`.beat b ON b.id=sc.beat_id AND b.auth_user_id IN (:auth)" +
122
            " JOIN `user`.beat_route r ON r.beat_id=sc.beat_id AND r.day_number=sc.day_number AND r.active=1" +
123
            " WHERE sc.start_date>=:ms AND sc.start_date<=:me");
124
        pq.setParameter("ms", ms).setParameter("me", me).setParameterList("auth", auth);
125
        long planned = asLong(pq.uniqueResult());
126
 
127
        // planned stops that fall on a day the owner actually punched in
128
        NativeQuery<?> piq = s.createNativeQuery(
129
            "SELECT COUNT(*) FROM `user`.beat_schedule sc" +
130
            " JOIN `user`.beat b ON b.id=sc.beat_id AND b.auth_user_id IN (:auth)" +
131
            " JOIN `user`.beat_route r ON r.beat_id=sc.beat_id AND r.day_number=sc.day_number AND r.active=1" +
132
            " JOIN auth.auth_user au ON au.id=b.auth_user_id" +
133
            " JOIN dtr.users du ON du.email=au.email_id" +
134
            " JOIN (SELECT DISTINCT user_id, task_date FROM auth.location_tracking" +
135
            "       WHERE task_date>=:ms AND task_date<=:me AND mark_type='PUNCHIN' AND user_id IN (:dtr)) p" +
136
            "   ON p.user_id=du.id AND p.task_date=sc.start_date" +
137
            " WHERE sc.start_date>=:ms AND sc.start_date<=:me");
138
        piq.setParameter("ms", ms).setParameter("me", me).setParameterList("auth", auth).setParameterList("dtr", dtr);
139
        long punchedIn = asLong(piq.uniqueResult());
140
 
141
        long checkedIn = countVisits(s, ms, me, dtr, "mark_type LIKE 'CHECKIN%'");
142
        long checkedOut = countVisits(s, ms, me, dtr, "(mark_type LIKE '%CHECKOUT%')");
143
 
144
        m.put("plannedStops", planned);
145
        m.put("punchedIn", punchedIn);
146
        m.put("checkedIn", checkedIn);
147
        m.put("checkedOut", checkedOut);
148
        m.put("dropPunch", planned == 0 ? 0 : Math.round(100.0 * (planned - punchedIn) / planned));
149
        m.put("dropCheckin", punchedIn == 0 ? 0 : Math.round(100.0 * (punchedIn - checkedIn) / punchedIn));
150
        m.put("dropCheckout", checkedIn == 0 ? 0 : Math.round(100.0 * (checkedIn - checkedOut) / checkedIn));
151
        return m;
152
    }
153
 
154
    private long countVisits(Session s, String ms, String me, List<Integer> dtr, String markPredicate) {
155
        NativeQuery<?> q = s.createNativeQuery(
156
            "SELECT COUNT(*) FROM auth.location_tracking" +
157
            " WHERE task_date>=:ms AND task_date<=:me AND task_type='franchisee-visit' AND " + markPredicate +
158
            " AND user_id IN (:dtr)");
159
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("dtr", dtr);
160
        return asLong(q.uniqueResult());
161
    }
162
 
163
    // ---- Coverage by level --------------------------------------------------
164
 
165
    private List<Map<String, Object>> coverageByLevel(Session s, String ms, String me, List<Integer> auth) {
166
        NativeQuery<?> q = s.createNativeQuery(
167
            "SELECT p.escalation_type lvl, COUNT(DISTINCT p.auth_user_id) total_users," +
168
            " COUNT(DISTINCT CASE WHEN sc.id IS NOT NULL THEN p.auth_user_id END) with_pjp" +
169
            " FROM cs.position p" +
170
            " LEFT JOIN `user`.beat b ON b.auth_user_id=p.auth_user_id AND b.active=1" +
171
            " LEFT JOIN `user`.beat_schedule sc ON sc.beat_id=b.id AND sc.start_date>=:ms AND sc.start_date<=:me" +
172
            " WHERE p.category_id=4 AND p.auth_user_id IN (:auth) GROUP BY p.escalation_type ORDER BY p.escalation_type");
173
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("auth", auth);
174
        List<Map<String, Object>> list = new ArrayList<>();
175
        for (Object o : q.getResultList()) {
176
            Object[] r = (Object[]) o;
177
            long total = asLong(r[1]), with = asLong(r[2]);
178
            Map<String, Object> m = new LinkedHashMap<>();
179
            m.put("level", asStr(r[0]));
180
            m.put("totalUsers", total);
181
            m.put("withPjp", with);
182
            m.put("coveragePct", total == 0 ? 0 : Math.round(100.0 * with / total));
183
            list.add(m);
184
        }
185
        return list;
186
    }
187
 
188
    // ---- Per-executive scorecard -------------------------------------------
189
 
190
    private List<Map<String, Object>> scorecard(Session s, String ms, String me, List<Integer> auth, List<Integer> dtr) {
191
        NativeQuery<?> q = s.createNativeQuery(
192
            "SELECT au.id uid, TRIM(CONCAT(au.first_name,' ',COALESCE(au.last_name,''))) nm, lvl.lvl," +
193
            " COALESCE(pl.planned,0) planned, COALESCE(ac.done,0) done," +
194
            " COALESCE(ds.disc_min,0) disc_min, COALESCE(wk.work_sec,0) work_sec," +
195
            " COALESCE(ld.leads,0) leads, du.id duid" +
196
            " FROM (SELECT DISTINCT auth_user_id FROM `user`.beat WHERE active=1 AND auth_user_id IN (:auth)) o" +
197
            " JOIN auth.auth_user au ON au.id=o.auth_user_id" +
198
            " LEFT JOIN dtr.users du ON du.email=au.email_id" +
199
            " LEFT JOIN (SELECT auth_user_id, MIN(escalation_type) lvl FROM cs.position WHERE category_id=4 GROUP BY auth_user_id) lvl ON lvl.auth_user_id=au.id" +
200
            " LEFT JOIN (SELECT b.auth_user_id uid, COUNT(*) planned FROM `user`.beat_schedule sc" +
201
            "   JOIN `user`.beat b ON b.id=sc.beat_id JOIN `user`.beat_route r ON r.beat_id=sc.beat_id AND r.day_number=sc.day_number AND r.active=1" +
202
            "   WHERE sc.start_date>=:ms AND sc.start_date<=:me GROUP BY b.auth_user_id) pl ON pl.uid=au.id" +
203
            " LEFT JOIN (SELECT user_id uid, COUNT(*) done FROM auth.location_tracking" +
204
            "   WHERE task_date>=:ms AND task_date<=:me AND task_type='franchisee-visit' AND mark_type LIKE 'CHECKIN%' GROUP BY user_id) ac ON ac.uid=du.id" +
205
            " LEFT JOIN (SELECT user_id uid, ROUND(AVG(NULLIF(TIME_TO_SEC(time_spent),0))/60,0) disc_min FROM auth.location_tracking" +
206
            "   WHERE task_date>=:ms AND task_date<=:me AND task_type='franchisee-visit' AND mark_type LIKE '%CHECKOUT%' GROUP BY user_id) ds ON ds.uid=du.id" +
207
            " 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" +
208
            "   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" +
209
            " 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" +
210
            " ORDER BY done DESC, planned DESC");
211
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("auth", auth);
212
 
213
        // Geofence-offsite check-ins per user are computed in Java (not SQL): the
214
        // coords are stored as "lat,lng" strings, and the inline parsing/haversine
215
        // expression trips Hibernate's native-query parameter parser.
216
        Map<Integer, Integer> geoByUser = geoOffsiteByUser(s, ms, me, dtr);
217
 
218
        List<Map<String, Object>> list = new ArrayList<>();
219
        for (Object o : q.getResultList()) {
220
            Object[] r = (Object[]) o;
221
            long planned = asLong(r[3]), done = asLong(r[4]);
222
            Map<String, Object> m = new LinkedHashMap<>();
223
            m.put("name", asStr(r[1]));
224
            m.put("level", r[2] == null ? "-" : asStr(r[2]));
225
            m.put("planned", planned);
226
            m.put("done", done);
227
            m.put("adherencePct", planned == 0 ? 0 : Math.round(100.0 * done / planned));
228
            m.put("discussionMin", asLong(r[5]));
229
            m.put("workingHrs", round1(asDouble(r[6]) / 3600.0));
230
            m.put("leads", asLong(r[7]));
231
            Integer duid = (r[8] == null) ? null : ((Number) r[8]).intValue();
232
            m.put("geoFlags", duid == null ? 0 : geoByUser.getOrDefault(duid, 0));
233
            list.add(m);
234
        }
235
        return list;
236
    }
237
 
238
    // Per dtr-user count of check-ins recorded >50 m from the partner's saved
239
    // location. Pulls the raw "lat,lng" strings and does the haversine in Java.
240
    private Map<Integer, Integer> geoOffsiteByUser(Session s, String ms, String me, List<Integer> dtr) {
241
        NativeQuery<?> q = s.createNativeQuery(
242
            "SELECT user_id, checkin_lat_lng, visit_location FROM auth.location_tracking" +
243
            " WHERE task_date>=:ms AND task_date<=:me AND task_type='franchisee-visit' AND mark_type LIKE 'CHECKIN%'" +
244
            " AND checkin_lat_lng LIKE '%,%' AND visit_location LIKE '%,%' AND user_id IN (:dtr)");
245
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("dtr", dtr);
246
        Map<Integer, Integer> out = new HashMap<>();
247
        for (Object o : q.getResultList()) {
248
            Object[] r = (Object[]) o;
249
            if (r[0] == null) continue;
250
            double[] cin = parseLatLng(asStr(r[1]));
251
            double[] vis = parseLatLng(asStr(r[2]));
252
            if (cin == null || vis == null) continue;
253
            if (haversineMeters(cin[0], cin[1], vis[0], vis[1]) > 50.0) {
254
                int uid = ((Number) r[0]).intValue();
255
                out.merge(uid, 1, Integer::sum);
256
            }
257
        }
258
        return out;
259
    }
260
 
261
    private static double[] parseLatLng(String s) {
262
        if (s == null || !s.contains(",")) return null;
263
        String[] parts = s.split(",");
264
        if (parts.length != 2) return null;
265
        try {
266
            double a = Double.parseDouble(parts[0].trim());
267
            double b = Double.parseDouble(parts[1].trim());
268
            if (a == 0 && b == 0) return null;
269
            return new double[]{a, b};
270
        } catch (NumberFormatException e) {
271
            return null;
272
        }
273
    }
274
 
275
    private static double haversineMeters(double lat1, double lng1, double lat2, double lng2) {
276
        double R = 6371000d;
277
        double dLat = Math.toRadians(lat2 - lat1);
278
        double dLng = Math.toRadians(lng2 - lng1);
279
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
280
                + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
281
                * Math.sin(dLng / 2) * Math.sin(dLng / 2);
282
        return 2 * R * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
283
    }
284
 
285
    // ---- Working-hour utilization ------------------------------------------
286
 
287
    private Map<String, Object> utilization(Session s, String ms, String me, List<Integer> dtr) {
288
        NativeQuery<?> q = s.createNativeQuery(
289
            "SELECT" +
290
            " (SELECT COALESCE(SUM(TIME_TO_SEC(time_spent)),0) FROM auth.location_tracking WHERE task_date>=:ms AND task_date<=:me AND task_type='franchisee-visit' AND user_id IN (:dtr)) instore," +
291
            " (SELECT COALESCE(SUM(TIME_TO_SEC(transit_time)),0) FROM auth.location_tracking WHERE task_date>=:ms AND task_date<=:me AND task_type='franchisee-visit' AND user_id IN (:dtr)) travel," +
292
            " (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");
293
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("dtr", dtr);
294
        Object[] r = (Object[]) q.uniqueResult();
295
        double instore = asDouble(r[0]), travel = asDouble(r[1]), working = asDouble(r[2]);
296
        if (working < instore + travel) working = instore + travel; // guard: working must cover its parts
297
        double idle = Math.max(working - instore - travel, 0);
298
        Map<String, Object> m = new LinkedHashMap<>();
299
        m.put("inStoreHrs", round1(instore / 3600.0));
300
        m.put("travelHrs", round1(travel / 3600.0));
301
        m.put("idleHrs", round1(idle / 3600.0));
302
        m.put("workingHrs", round1(working / 3600.0));
303
        m.put("inStorePct", working == 0 ? 0 : (int) Math.round(100.0 * instore / working));
304
        m.put("travelPct", working == 0 ? 0 : (int) Math.round(100.0 * travel / working));
305
        m.put("idlePct", working == 0 ? 0 : (int) Math.round(100.0 * idle / working));
306
        return m;
307
    }
308
 
309
    // ---- Deferrals & SLA ----------------------------------------------------
310
 
311
    private Map<String, Object> deferral(Session s, String ms, String me, List<Integer> auth) {
312
        NativeQuery<?> q = s.createNativeQuery(
313
            "SELECT COUNT(*) total," +
314
            " SUM(status='RESCHEDULED') rescheduled, SUM(status='CANCELLED') cancelled," +
315
            " SUM(action_by IS NOT NULL) actioned," +
316
            " SUM(reason LIKE 'Beat missed%' OR reason LIKE 'Not marked%') system_gen," +
317
            " ROUND(AVG(CASE WHEN action_by IS NOT NULL THEN TIMESTAMPDIFF(HOUR, created_timestamp, updated_timestamp)/24.0 END),1) avg_days" +
318
            " FROM `user`.beat_deferred_visit WHERE deferred_date>=:ms AND deferred_date<=:me AND auth_user_id IN (:auth)");
319
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("auth", auth);
320
        Object[] r = (Object[]) q.uniqueResult();
321
        long total = asLong(r[0]), system = asLong(r[4]);
322
        long human = total - system;
323
        Map<String, Object> m = new LinkedHashMap<>();
324
        m.put("total", total);
325
        m.put("rescheduled", asLong(r[1]));
326
        m.put("cancelled", asLong(r[2]));
327
        m.put("actioned", asLong(r[3]));
328
        m.put("systemGenerated", system);
329
        m.put("human", human);
330
        m.put("avgDaysToAction", asDouble(r[5]));
331
        m.put("systemPct", total == 0 ? 0 : Math.round(100.0 * system / total));
332
        m.put("humanPct", total == 0 ? 0 : Math.round(100.0 * human / total));
333
        return m;
334
    }
335
 
336
    // ---- Travel & route quality --------------------------------------------
337
 
338
    private Map<String, Object> travel(Session s, String ms, String me, List<Integer> auth, List<Integer> dtr) {
339
        Map<String, Object> m = new LinkedHashMap<>();
340
 
341
        String legFrom =
342
            " FROM `user`.beat_route a" +
343
            " JOIN `user`.beat bt ON bt.id=a.beat_id AND bt.auth_user_id IN (:auth)" +
344
            " 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" +
345
            " 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" +
346
            " 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" +
347
            " WHERE a.active=1";
348
        String legKm =
349
            "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)))";
350
 
351
        NativeQuery<?> bq = s.createNativeQuery(
352
            "SELECT bucket, COUNT(*) n FROM (" +
353
            "  SELECT CASE WHEN km<2 THEN '0-2 km' WHEN km<5 THEN '2-5 km' WHEN km<15 THEN '5-15 km'" +
354
            "    WHEN km<50 THEN '15-50 km' ELSE '50 km+' END bucket," +
355
            "  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" +
356
            "  FROM (SELECT " + legKm + " km" + legFrom + ") l" +
357
            " ) z GROUP BY bucket, ord ORDER BY ord");
358
        bq.setParameterList("auth", auth);
359
        List<Map<String, Object>> buckets = new ArrayList<>();
360
        for (Object o : bq.getResultList()) {
361
            Object[] r = (Object[]) o;
362
            Map<String, Object> b = new LinkedHashMap<>();
363
            b.put("bucket", asStr(r[0]));
364
            b.put("count", asLong(r[1]));
365
            buckets.add(b);
366
        }
367
        m.put("legBuckets", buckets);
368
 
369
        NativeQuery<?> sq = s.createNativeQuery(
370
            "SELECT ROUND(AVG(km),1) avg_leg, ROUND(MAX(km),0) max_leg, SUM(km>15) over15, COUNT(*) total" +
371
            " FROM (SELECT " + legKm + " km" + legFrom + ") l");
372
        sq.setParameterList("auth", auth);
373
        Object[] sr = (Object[]) sq.uniqueResult();
374
        long totalLegs = asLong(sr[3]), over15 = asLong(sr[2]);
375
        m.put("avgLegKm", asDouble(sr[0]));
376
        m.put("maxLegKm", asDouble(sr[1]));
377
        m.put("pctOver15", totalLegs == 0 ? 0 : Math.round(100.0 * over15 / totalLegs));
378
 
379
        NativeQuery<?> tq = s.createNativeQuery(
380
            "SELECT ROUND(SUM(TIME_TO_SEC(transit_time))/3600,1) transit_hrs, ROUND(SUM(TIME_TO_SEC(estimated_time))/3600,1) est_hrs" +
381
            " FROM auth.location_tracking WHERE task_date>=:ms AND task_date<=:me AND task_type='franchisee-visit' AND user_id IN (:dtr)");
382
        tq.setParameter("ms", ms).setParameter("me", me).setParameterList("dtr", dtr);
383
        Object[] tr = (Object[]) tq.uniqueResult();
384
        double transit = asDouble(tr[0]), est = asDouble(tr[1]);
385
        m.put("actualVsEstimateRatio", est == 0 ? 0 : round1(transit / est));
386
        return m;
387
    }
388
 
389
    // ---- Outcomes & visit quality ------------------------------------------
390
 
391
    private Map<String, Object> outcomes(Session s, String ms, String me, List<Integer> auth) {
392
        NativeQuery<?> q = s.createNativeQuery(
393
            "SELECT COUNT(*) total," +
394
            " SUM(partner_remark IS NOT NULL AND TRIM(partner_remark)<>'') remark," +
395
            " ROUND(AVG(NULLIF(rbm_rating,0)),1) avg_rating," +
396
            " SUM(instore_visibility IS NOT NULL AND TRIM(instore_visibility)<>'') audit," +
397
            " SUM(franchise_activity_id>0) nextv" +
398
            " FROM `user`.my_franchisee_visit" +
399
            " WHERE auth_id IN (:auth) AND COALESCE(visit_timestamp, created_timestamp)>=:ms" +
400
            " AND COALESCE(visit_timestamp, created_timestamp)<=CONCAT(:me,' 23:59:59')");
401
        q.setParameter("ms", ms).setParameter("me", me).setParameterList("auth", auth);
402
        Object[] r = (Object[]) q.uniqueResult();
403
        long total = asLong(r[0]);
404
        Map<String, Object> m = new LinkedHashMap<>();
405
        m.put("completedVisits", total);
406
        m.put("remarkFilledPct", total == 0 ? 0 : Math.round(100.0 * asLong(r[1]) / total));
407
        m.put("avgRating", asDouble(r[2]));
408
        m.put("auditDonePct", total == 0 ? 0 : Math.round(100.0 * asLong(r[3]) / total));
409
        m.put("nextVisitPct", total == 0 ? 0 : Math.round(100.0 * asLong(r[4]) / total));
410
        return m;
411
    }
412
 
413
    // ---- "What to fix" findings (computed in Java) --------------------------
414
 
415
    private List<Map<String, Object>> findings(Map<String, Object> kpis, Map<String, Object> funnel,
416
                                               Map<String, Object> deferral, Map<String, Object> util,
417
                                               Map<String, Object> travel, Map<String, Object> outcomes,
418
                                               List<Map<String, Object>> coverage, List<Map<String, Object>> scorecard) {
419
        List<Map<String, Object>> f = new ArrayList<>();
420
 
421
        long avgDisc = asLong(kpis.get("avgDiscussionMin"));
422
        long rushed = scorecard.stream().filter(r -> asLong(r.get("discussionMin")) > 0 && asLong(r.get("discussionMin")) < 10).count();
423
        if (avgDisc > 0 && (avgDisc < 30 || rushed > 0)) {
424
            f.add(finding("high", "Rushed partner visits",
425
                "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.",
426
                "Set a minimum on-store time and review visit quality."));
427
        }
428
 
429
        long geo = scorecard.stream().mapToLong(r -> asLong(r.get("geoFlags"))).sum();
430
        if (geo > 0) {
431
            f.add(finding("high", "Fake-visit risk",
432
                geo + " check-in(s) were >50 m from the store (check-in GPS vs the partner's saved location).",
433
                "Enforce geofenced check-in and flag these journeys for audit."));
434
        }
435
 
436
        for (Map<String, Object> c : coverage) {
437
            if ("L1".equalsIgnoreCase(asStr(c.get("level")))) {
438
                long total = asLong(c.get("totalUsers")), with = asLong(c.get("withPjp"));
439
                if (total - with > 0) {
440
                    f.add(finding("med", "Coverage gap",
441
                        (total - with) + " of " + total + " L1 executives have no monthly PJP — they run no planned beat this period.",
442
                        "Make a monthly PJP mandatory and approved before month start."));
443
                }
444
            }
445
        }
446
 
447
        long sysPct = asLong(deferral.get("systemPct"));
448
        double sla = asDouble(deferral.get("avgDaysToAction"));
449
        if (asLong(deferral.get("total")) > 0 && (sysPct >= 50 || sla >= 2)) {
450
            f.add(finding("med", "Deferral leakage",
451
                sysPct + "% of deferrals are system auto-flags" + (sla > 0 ? ", and genuine deferrals sit " + sla + " days before a head acts" : "") + ".",
452
                "Require a reason on real deferrals and add a manager-action SLA."));
453
        }
454
 
455
        long idlePct = asLong(util.get("idlePct"));
456
        if (idlePct >= 20) {
457
            f.add(finding("med", "A large part of the day is idle",
458
                idlePct + "% of the working day (" + util.get("idleHrs") + " h) is neither travel nor in-store.",
459
                "Investigate idle windows; tighten beat sequencing to cut dead time."));
460
        }
461
 
462
        long over15 = asLong(travel.get("pctOver15"));
463
        if (over15 >= 15) {
464
            f.add(finding("med", "Route inefficiency",
465
                over15 + "% of legs exceed 15 km — consecutive stops aren't geographically clustered.",
466
                "Re-sequence beats by proximity and cap daily travel."));
467
        }
468
 
469
        long journeys = asLong(kpis.get("journeys")), leads = asLong(kpis.get("leadsCreated"));
470
        if (journeys > 0 && leads < journeys * 0.25) {
471
            f.add(finding("low", "Lead capture is low",
472
                "Only " + leads + " leads across " + journeys + " journeys — executives aren't logging the new shops they pass.",
473
                "Add a per-beat lead nudge; recognise top loggers."));
474
        }
475
        return f;
476
    }
477
 
478
    private static Map<String, Object> finding(String sev, String title, String detail, String action) {
479
        Map<String, Object> m = new LinkedHashMap<>();
480
        m.put("severity", sev);
481
        m.put("title", title);
482
        m.put("detail", detail);
483
        m.put("action", action);
484
        return m;
485
    }
486
 
487
    // ---- helpers ------------------------------------------------------------
488
 
489
    private static List<Integer> safeIds(List<Integer> ids) {
490
        if (ids == null || ids.isEmpty()) return Collections.singletonList(-1);
491
        return ids;
492
    }
493
 
494
    private static long asLong(Object o) {
495
        return o == null ? 0L : ((Number) o).longValue();
496
    }
497
 
498
    private static double asDouble(Object o) {
499
        return o == null ? 0.0 : ((Number) o).doubleValue();
500
    }
501
 
502
    private static String asStr(Object o) {
503
        return o == null ? "" : o.toString();
504
    }
505
 
506
    private static double round1(double v) {
507
        return Math.round(v * 10.0) / 10.0;
508
    }
509
}