Subversion Repositories SmartDukaan

Rev

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