Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
36645 vikas 1
<section class="wrapper">
2
    <div class="row">
3
        <div class="col-lg-12">
4
            <h3 class="page-header"><i class="icon_document_alt"></i> $username - Visit Details ($reportDate)</h3>
5
            <ol class="breadcrumb">
6
                <li><i class="fa fa-home"></i><a href="${rc.contextPath}/dashboard">Home</a></li>
7
                <li><a href="javascript:void(0);" class="beat-report">Beat Report</a></li>
8
                <li><i class="fa fa-user"></i>$username</li>
9
            </ol>
10
        </div>
11
    </div>
12
    <br>
13
    <div class="row col-lg-12" style="float: right;">
36664 vikas 14
        <div class="col-lg-2">
15
            <label>Level</label>
16
            <select id="user-detail-level" class="form-control" data-selected="$!userLevel">
17
                <option value="">All Levels</option>
18
                #foreach($et in $escalationTypes)
19
                    <option value="$et" #if($et.name() == $userLevel)selected#end>$et</option>
20
                #end
21
            </select>
22
        </div>
36645 vikas 23
        <div class="col-lg-3">
36664 vikas 24
            <label>User</label>
25
            <select id="user-detail-user" class="form-control" data-selected-auth="$!authUserId">
26
                <option value="$!authUserId">$username</option>
27
            </select>
28
        </div>
29
        <div class="col-lg-3">
36645 vikas 30
            <label>Select Date</label>
31
            <div class="input-group">
32
                <input type="date" id="user-detail-date" class="form-control" value="$reportDate" data-userid="$userId">
33
                <span class="input-group-btn">
34
                    <button type="button" class="btn btn-info user-detail-refresh" data-userid="$userId" style="margin-left:10px;">
35
                        <i class="fa fa-refresh"></i> Refresh
36
                    </button>
36664 vikas 37
                    <button type="button" class="btn btn-success live-tracking-btn" data-userid="$userId" data-username="$username" style="margin-left:5px;">
38
                        <i class="fa fa-map-marker"></i> Live Tracking
39
                    </button>
36645 vikas 40
                </span>
41
            </div>
42
        </div>
43
    </div>
44
    <br><br><br>
45
 
46
    <div class="col-lg-12">
47
        <div class="row" style="margin-bottom:15px;">
48
            <div class="col-lg-3">
49
                <div class="panel panel-default" style="text-align:center; padding:10px;">
50
                    <h4 style="margin:0; color:#1abc9c; font-weight:bold;">$visits.size()</h4>
51
                    <small>Total Visits</small>
52
                </div>
53
            </div>
54
            #set($completedCount = 0)
55
            #set($pendingCount = 0)
56
            #set($deferredCount = 0)
57
            #foreach($v in $visits)
58
                #if($v.getMarkType() == "CHECKIN-CHECKOUT" || $v.getMarkType() == "CHECKOUT")
59
                    #set($completedCount = $completedCount + 1)
60
                #elseif($v.getMarkType() == "PENDING" || $v.getMarkType() == "CHECKIN")
61
                    #set($pendingCount = $pendingCount + 1)
62
                #elseif($v.getMarkType() == "DEFERRED")
63
                    #set($deferredCount = $deferredCount + 1)
64
                #end
65
            #end
66
            <div class="col-lg-3">
67
                <div class="panel panel-default" style="text-align:center; padding:10px;">
68
                    <h4 style="margin:0; color:#27ae60; font-weight:bold;">$completedCount</h4>
69
                    <small>Completed</small>
70
                </div>
71
            </div>
72
            <div class="col-lg-3">
73
                <div class="panel panel-default" style="text-align:center; padding:10px;">
74
                    <h4 style="margin:0; color:#e67e22; font-weight:bold;">$pendingCount</h4>
75
                    <small>Pending</small>
76
                </div>
77
            </div>
78
            <div class="col-lg-3">
79
                <div class="panel panel-default" style="text-align:center; padding:10px;">
80
                    <h4 style="margin:0; color:#e74c3c; font-weight:bold;">$deferredCount</h4>
81
                    <small>Deferred</small>
82
                </div>
83
            </div>
84
        </div>
85
 
86
        <table class="table table-border table-condensed table-bordered table-striped" id="userDetailTable" style="width:100%">
87
            <thead>
36656 vikas 88
            <tr >
36645 vikas 89
                <th>#</th>
36666 vikas 90
                <th>Agenda/Partner Name</th>
36645 vikas 91
                <th>Task Type</th>
92
                <th>Status</th>
93
                <th>Address</th>
94
                <th>Check In Time</th>
95
                <th>Check Out Time</th>
36666 vikas 96
                <th>Time Spent at Outlet</th>
36645 vikas 97
                <th>Transit Time</th>
98
                <th>Distance (km)</th>
36666 vikas 99
                <th>Estimated Time</th>
36645 vikas 100
            </tr>
101
            </thead>
102
            <tbody>
36656 vikas 103
            #if($punchIn)
104
                <tr style="background:#d5f5e3;">
105
                    <td>--</td>
106
                    <td><strong>PUNCH IN</strong></td>
107
                    <td>$!punchIn.getTaskType()</td>
36709 vikas 108
                    <td><span class="label label-info">PUNCHIN</span> #if($punchIn.getAttachment() && $punchIn.getAttachment() != "")<a href="javascript:void(0);" class="view-attachment-link" data-attachment="$punchIn.getAttachment()" data-checkin-latlng="$!punchIn.getCheckInLatLng()" data-visit-location="$!punchIn.getVisitLocation()" data-tracking-id="$punchIn.getId()" title="View Attachment"><i class="fa fa-paperclip" style="color:#e67e22; margin-left:5px;"></i></a>#end</td>
36656 vikas 109
                    <td>$!punchIn.getAddress()</td>
110
                    <td>$!punchIn.getCheckInTime()</td>
111
                    <td>--</td>
112
                    <td>--</td>
113
                    <td>--</td>
114
                    <td>$!punchIn.getTotalDistance()</td>
36666 vikas 115
                    <td>$!punchIn.getEstimatedTime()</td>
36656 vikas 116
                </tr>
117
            #end
36645 vikas 118
            #set($idx = 1)
119
            #foreach($v in $visits)
120
                <tr>
121
                    <td>$idx</td>
122
                    <td>$!v.getTaskName()</td>
123
                    <td>$!v.getTaskType()</td>
124
                    <td>
125
                        #if($v.getMarkType() == "CHECKIN-CHECKOUT" || $v.getMarkType() == "CHECKOUT")
126
                            <span class="label label-success">$v.getMarkType()</span>
127
                        #elseif($v.getMarkType() == "PENDING" || $v.getMarkType() == "CHECKIN")
128
                            <span class="label label-warning">$v.getMarkType()</span>
129
                        #elseif($v.getMarkType() == "DEFERRED")
130
                            <span class="label label-danger">$v.getMarkType()</span>
131
                        #else
132
                            <span class="label label-default">$!v.getMarkType()</span>
133
                        #end
36656 vikas 134
                        <a href="javascript:void(0);" class="beat-history-link" data-userid="$userId" data-taskid="$v.getTaskId()" data-tasktype="$!v.getTaskType()" data-taskname="$!v.getTaskName()" title="View History" style="margin-left:5px;"><i class="fa fa-history" style="color:#3498db; font-size:14px;"></i></a>
36709 vikas 135
                        #if($v.getAttachment() && $v.getAttachment() != "")<a href="javascript:void(0);" class="view-attachment-link" data-attachment="$v.getAttachment()" data-checkin-latlng="$!v.getCheckInLatLng()" data-visit-location="$!v.getVisitLocation()" data-tracking-id="$v.getId()" title="View Attachment"><i class="fa fa-paperclip" style="color:#e67e22; margin-left:3px; font-size:14px;"></i></a>#end
36645 vikas 136
                    </td>
137
                    <td>$!v.getAddress()</td>
138
                    <td>$!v.getCheckInTime()</td>
139
                    <td>$!v.getCheckOutTime()</td>
140
                    <td>$!v.getTimeSpent()</td>
141
                    <td>$!v.getTransitTime()</td>
142
                    <td>$!v.getTotalDistance()</td>
36666 vikas 143
                    <td>$!v.getEstimatedTime()</td>
36645 vikas 144
                </tr>
145
                #set($idx = $idx + 1)
146
            #end
36656 vikas 147
            #if($punchOut)
148
                <tr style="background:#fadbd8;">
149
                    <td>--</td>
150
                    <td><strong>PUNCH OUT</strong></td>
151
                    <td>$!punchOut.getTaskType()</td>
36709 vikas 152
                    <td><span class="label label-danger">PUNCHOUT</span> #if($punchOut.getAttachment() && $punchOut.getAttachment() != "")<a href="javascript:void(0);" class="view-attachment-link" data-attachment="$punchOut.getAttachment()" data-checkin-latlng="$!punchOut.getCheckInLatLng()" data-visit-location="$!punchOut.getVisitLocation()" data-tracking-id="$punchOut.getId()" title="View Attachment"><i class="fa fa-paperclip" style="color:#e67e22; margin-left:5px;"></i></a>#end</td>
36656 vikas 153
                    <td>$!punchOut.getAddress()</td>
154
                    <td>$!punchOut.getCheckInTime()</td>
155
                    <td>--</td>
156
                    <td>--</td>
157
                    <td>--</td>
158
                    <td>$!punchOut.getTotalDistance()</td>
36666 vikas 159
                    <td>$!punchOut.getEstimatedTime()</td>
36656 vikas 160
                </tr>
161
            #end
36645 vikas 162
            </tbody>
36656 vikas 163
            <tfoot>
164
                <tr style="background:#f2f3f4; font-weight:bold;">
165
                    <td colspan="5" style="text-align:right;">Totals</td>
166
                    <td>--</td>
167
                    <td>--</td>
168
                    <td>$totalTimeSpentStr</td>
169
                    <td>$totalTransitStr</td>
170
                    <td>$totalDistanceStr km | Visits: $visitCount | Leads: $leadCount</td>
36666 vikas 171
                    <td></td>
36656 vikas 172
                </tr>
173
            </tfoot>
36645 vikas 174
        </table>
175
    </div>
176
</section>
177
 
36656 vikas 178
<!-- Task History Modal -->
179
<div class="modal fade" id="taskHistoryModal" tabindex="-1" role="dialog">
180
    <div class="modal-dialog modal-lg" role="document" style="width:85%;">
181
        <div class="modal-content">
182
            <div class="modal-header" style="background:#3498db; color:white;">
183
                <button type="button" class="close" data-dismiss="modal" style="color:white;">&times;</button>
184
                <h4 class="modal-title" id="taskHistoryModalTitle">Task History</h4>
185
            </div>
186
            <div class="modal-body" id="taskHistoryModalBody">
187
                <div class="text-center"><i class="fa fa-spinner fa-spin fa-2x"></i> Loading...</div>
188
            </div>
189
            <div class="modal-footer">
190
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
191
            </div>
192
        </div>
193
    </div>
194
</div>
195
 
36664 vikas 196
<!-- Live Tracking Modal -->
197
<div class="modal fade" id="liveTrackingModal" tabindex="-1" role="dialog">
198
    <div class="modal-dialog modal-lg" role="document" style="width:90%;">
199
        <div class="modal-content">
200
            <div class="modal-header" style="background:#27ae60; color:white;">
201
                <button type="button" class="close" data-dismiss="modal" style="color:white;">&times;</button>
36690 vikas 202
                <h4 class="modal-title" id="liveTrackingModalTitle"><img src="${rc.contextPath}/resources/images/Bike-Icon-SD.png" style="height:24px; vertical-align:middle; margin-right:6px;"> Live Tracking</h4>
36664 vikas 203
            </div>
204
            <div class="modal-body" style="padding:0;">
205
                <div id="liveTrackingInfo" style="padding:8px 15px; background:#f8f9fa; border-bottom:1px solid #ddd; font-size:13px;"></div>
206
                <div id="liveTrackingMap" style="height:500px; width:100%;"></div>
207
            </div>
208
            <div class="modal-footer">
36709 vikas 209
                #*<label style="float:left; margin-top:7px; font-weight:normal; font-size:13px;">
210
                    <input type="checkbox" id="autoRefreshToggle" style="margin-right:5px;"> Auto-refresh (30s)
211
                </label>*#
36664 vikas 212
                <button type="button" class="btn btn-primary" id="refreshTrackingBtn"><i class="fa fa-refresh"></i> Refresh</button>
213
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
214
            </div>
215
        </div>
216
    </div>
217
</div>
218
 
36709 vikas 219
<!-- Attachment Viewer Modal -->
220
<div class="modal fade" id="attachmentViewerModal" tabindex="-1" role="dialog">
221
    <div class="modal-dialog" role="document" style="width:600px;">
222
        <div class="modal-content">
223
            <div class="modal-header" style="background:#e67e22; color:white;">
224
                <button type="button" class="close" data-dismiss="modal" style="color:white;">&times;</button>
225
                <h4 class="modal-title"><i class="fa fa-paperclip"></i> Attachment</h4>
226
            </div>
227
            <div class="modal-body" style="text-align:center; padding:15px;">
228
                <img id="attachmentImage" src="" style="max-width:100%; max-height:450px; border:1px solid #ddd; border-radius:4px;" />
229
                <div id="attachmentDistanceInfo" style="margin-top:10px; font-size:13px;"></div>
230
            </div>
231
            <div class="modal-footer">
232
                <button type="button" class="btn btn-success" id="approveCheckinBtn" style="display:none;">
233
                    <i class="fa fa-check"></i> Approve
234
                </button>
235
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
236
            </div>
237
        </div>
238
    </div>
239
</div>
240
 
36645 vikas 241
<script>
242
    $('#userDetailTable').DataTable({
243
        "scrollX": true,
36685 vikas 244
        "pageLength": 50,
36645 vikas 245
        "bPaginate": true,
246
        "bLengthChange": true,
247
        "bFilter": true,
248
        "bInfo": true,
36709 vikas 249
        "bAutoWidth": false,
250
        "ordering": false
36645 vikas 251
    });
36656 vikas 252
 
36664 vikas 253
    (function () {
254
        var level = $('#user-detail-level').data('selected');
255
        var selectedAuth = $('#user-detail-user').data('selected-auth');
256
        if (level && selectedAuth) {
257
            $.ajax({
258
                url: context + "/beatPlan/getAuthUsers", type: "GET", dataType: "json",
259
                data: { categoryId: 4, escalationType: level },
260
                success: function (r) {
261
                    var data = r.response || r;
262
                    var html = '<option value="">Select User</option>';
263
                    data.forEach(function (u) {
264
                        html += '<option value="' + u.id + '"' + (u.id == selectedAuth ? ' selected' : '') + '>' + u.name + '</option>';
265
                    });
266
                    $('#user-detail-user').html(html);
267
                }
268
            });
269
        }
270
    })();
271
 
272
    $(document).off('click.beatdetail').off('click.livetrack');
273
 
274
    $(document).on('click.beatdetail', '.beat-history-link', function () {
36656 vikas 275
        var userId = $(this).data('userid');
276
        var taskId = $(this).data('taskid');
277
        var taskType = $(this).data('tasktype');
278
        var taskName = $(this).data('taskname');
279
 
280
        $('#taskHistoryModalTitle').text('History - ' + taskName);
281
        $('#taskHistoryModalBody').html('<div class="text-center"><i class="fa fa-spinner fa-spin fa-2x"></i> Loading...</div>');
282
        $('#taskHistoryModal').modal('show');
283
 
284
        doGetAjaxRequestHandler(context + "/beat-report/task-history?userId=" + userId + "&taskId=" + taskId + "&taskType=" + encodeURIComponent(taskType),
285
            function (response) {
286
                $('#taskHistoryModalBody').html(response);
287
            });
288
    });
36664 vikas 289
 
290
    var liveTrackingMap = null;
291
    var liveTrackingUserId = null;
292
    var liveTrackingInterval = null;
293
 
294
    function getMarkerColor(markType) {
295
        if (markType === 'CHECKIN-CHECKOUT' || markType === 'CHECKOUT') return '#0F9D58';
296
        if (markType === 'PENDING' || markType === 'CHECKIN') return '#4285F4';
297
        if (markType === 'DEFERRED') return '#DB4437';
298
        if (markType === 'PUNCHIN') return '#1abc9c';
299
        if (markType === 'PUNCHOUT') return '#e74c3c';
300
        return '#F4B400';
301
    }
302
 
303
    function createTrackingMarkerIcon(color, label) {
36709 vikas 304
        var svg = '<svg xmlns="http://www.w3.org/2000/svg" width="42" height="60" viewBox="0 0 42 60">' +
305
            '<path d="M21 0C9.402 0 0 9.402 0 21c0 15.75 21 39 21 39s21-23.25 21-39C42 9.402 32.598 0 21 0z" fill="' + color + '"/>' +
306
            '<circle cx="21" cy="21" r="10" fill="white"/>' +
307
            '<text x="21" y="26" text-anchor="middle" font-size="14" font-weight="bold" fill="' + color + '">' + label + '</text></svg>';
36664 vikas 308
        return 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg);
309
    }
310
 
311
    function loadLiveTracking(userId, username) {
312
        var selectedDate = $('#user-detail-date').val();
313
        $.ajax({
314
            url: context + "/beat-report/live-tracking",
315
            type: "GET",
316
            dataType: "json",
317
            data: { userId: userId, date: selectedDate },
318
            success: function (data) {
319
                renderLiveTrackingMap(data, username);
320
            },
321
            error: function () {
322
                $('#liveTrackingInfo').html('<span style="color:red;">Failed to load tracking data.</span>');
323
            }
324
        });
325
    }
326
 
36685 vikas 327
    function clearMapOverlays() {
328
        if (!liveTrackingMap) return;
329
        if (liveTrackingMap._markers) {
330
            liveTrackingMap._markers.forEach(function (m) { m.setMap(null); });
331
        }
332
        if (liveTrackingMap._polyline) {
333
            liveTrackingMap._polyline.setMap(null);
334
        }
335
        if (liveTrackingMap._gpsDots) {
336
            liveTrackingMap._gpsDots.forEach(function (m) { m.setMap(null); });
337
        }
338
        if (liveTrackingMap._stopMarkers) {
339
            liveTrackingMap._stopMarkers.forEach(function (m) { m.setMap(null); });
340
        }
341
        if (liveTrackingMap._currentMarker) {
342
            liveTrackingMap._currentMarker.setMap(null);
343
        }
344
        if (liveTrackingMap._directionsRenderer) {
345
            liveTrackingMap._directionsRenderer.setMap(null);
346
        }
347
        liveTrackingMap._markers = [];
348
        liveTrackingMap._gpsDots = [];
349
        liveTrackingMap._stopMarkers = [];
350
    }
351
 
352
    function formatEpoch(ts) {
353
        if (!ts) return 'N/A';
354
        var n = parseFloat(ts);
355
        if (isNaN(n)) return ts;
356
        if (n < 1e12) n = n * 1000;
357
        var d = new Date(n);
358
        return d.getHours().toString().padStart(2,'0') + ':' + d.getMinutes().toString().padStart(2,'0') + ':' + d.getSeconds().toString().padStart(2,'0');
359
    }
360
 
361
    function formatDuration(ms) {
362
        var sec = Math.floor(ms / 1000);
363
        var h = Math.floor(sec / 3600);
364
        var m = Math.floor((sec % 3600) / 60);
365
        var s = sec % 60;
366
        if (h > 0) return h + 'h ' + m + 'm';
367
        if (m > 0) return m + 'm ' + s + 's';
368
        return s + 's';
369
    }
370
 
371
    function haversineMeters(lat1, lon1, lat2, lon2) {
372
        var R = 6371000;
373
        var dLat = (lat2 - lat1) * Math.PI / 180;
374
        var dLon = (lon2 - lon1) * Math.PI / 180;
375
        var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
376
                Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
377
                Math.sin(dLon/2) * Math.sin(dLon/2);
378
        return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
379
    }
380
 
381
    function detectStops(points, radiusM, minTimeMs) {
382
        var stops = [];
383
        var i = 0;
384
        while (i < points.length) {
385
            var cluster = [points[i]];
386
            var cLat = points[i].lat, cLng = points[i].lng;
387
            var j = i + 1;
388
            while (j < points.length) {
389
                if (haversineMeters(cLat, cLng, points[j].lat, points[j].lng) <= radiusM) {
390
                    cluster.push(points[j]);
391
                    j++;
392
                } else {
393
                    break;
394
                }
395
            }
396
            if (cluster.length >= 2) {
397
                var t0 = parseFloat(cluster[0].ts);
398
                var t1 = parseFloat(cluster[cluster.length - 1].ts);
399
                if (t0 < 1e12) t0 *= 1000;
400
                if (t1 < 1e12) t1 *= 1000;
401
                var duration = t1 - t0;
402
                if (duration >= minTimeMs) {
403
                    var avgLat = 0, avgLng = 0;
404
                    cluster.forEach(function(p) { avgLat += p.lat; avgLng += p.lng; });
405
                    stops.push({
406
                        lat: avgLat / cluster.length,
407
                        lng: avgLng / cluster.length,
408
                        startTime: t0,
409
                        endTime: t1,
410
                        duration: duration,
411
                        pointCount: cluster.length
412
                    });
413
                }
414
            }
415
            i = j;
416
        }
417
        return stops;
418
    }
419
 
36664 vikas 420
    function renderLiveTrackingMap(data, username) {
421
        var visits = data.visits || [];
422
        var pathPoints = data.pathPoints || [];
423
 
424
        if (!liveTrackingMap) {
425
            liveTrackingMap = new google.maps.Map(document.getElementById('liveTrackingMap'), {
426
                zoom: 12,
427
                center: { lat: 20.5937, lng: 78.9629 },
428
                mapTypeControl: true,
429
                streetViewControl: false
430
            });
431
        }
432
 
36685 vikas 433
        clearMapOverlays();
36664 vikas 434
 
435
        var bounds = new google.maps.LatLngBounds();
436
        var hasPoints = false;
437
        var visitIdx = 0;
36685 vikas 438
        var visitCoords = [];
36664 vikas 439
 
440
        for (var i = 0; i < visits.length; i++) {
441
            var v = visits[i];
442
            if (!v.lat || !v.lng) continue;
443
            var lat = parseFloat(v.lat);
444
            var lng = parseFloat(v.lng);
445
            if (isNaN(lat) || isNaN(lng) || (lat === 0 && lng === 0)) continue;
446
 
447
            hasPoints = true;
448
            var pos = { lat: lat, lng: lng };
449
            bounds.extend(pos);
36685 vikas 450
            visitCoords.push(pos);
36664 vikas 451
 
452
            var label = v.markType === 'PUNCHIN' ? 'P' : (v.markType === 'PUNCHOUT' ? 'X' : String(++visitIdx));
453
            var marker = new google.maps.Marker({
454
                position: pos,
455
                map: liveTrackingMap,
456
                icon: {
457
                    url: createTrackingMarkerIcon(getMarkerColor(v.markType), label),
36709 vikas 458
                    scaledSize: new google.maps.Size(42, 60),
459
                    anchor: new google.maps.Point(21, 60)
36664 vikas 460
                },
36685 vikas 461
                title: v.taskName + ' (' + v.markType + ')',
462
                zIndex: 100
36664 vikas 463
            });
464
 
36685 vikas 465
            var infoContent = '<div style="font-size:13px; max-width:280px;">' +
36664 vikas 466
                '<strong>' + (v.taskName || '') + '</strong><br>' +
36685 vikas 467
                '<span class="label" style="background:' + getMarkerColor(v.markType) + '; color:white;">' + v.markType + '</span>' +
468
                (v.taskType ? ' <span class="label label-default">' + v.taskType + '</span>' : '') + '<br>' +
469
                (v.checkInTime ? '<i class="fa fa-sign-in" style="color:#27ae60;"></i> In: <strong>' + v.checkInTime + '</strong><br>' : '') +
470
                (v.checkOutTime ? '<i class="fa fa-sign-out" style="color:#e74c3c;"></i> Out: <strong>' + v.checkOutTime + '</strong><br>' : '') +
471
                (v.timeSpent ? '<i class="fa fa-clock-o" style="color:#f39c12;"></i> Time Spent: <strong>' + v.timeSpent + '</strong><br>' : '') +
472
                (v.transitTime ? '<i class="fa fa-car" style="color:#3498db;"></i> Transit: <strong>' + v.transitTime + '</strong><br>' : '') +
473
                (v.totalDistance && v.totalDistance !== '0.0' ? '<i class="fa fa-road" style="color:#8e44ad;"></i> Distance: <strong>' + v.totalDistance + ' km</strong><br>' : '') +
474
                (v.address ? '<i class="fa fa-map-marker" style="color:#e74c3c;"></i> ' + v.address : '') +
36664 vikas 475
                '</div>';
476
            (function (m, c) {
477
                var iw = new google.maps.InfoWindow({ content: c });
478
                m.addListener('click', function () { iw.open(liveTrackingMap, m); });
479
            })(marker, infoContent);
480
 
481
            liveTrackingMap._markers.push(marker);
482
        }
483
 
36685 vikas 484
        // Draw actual road path between visits using Directions API
485
        if (visitCoords.length >= 2) {
486
            var origin = visitCoords[0];
487
            var destination = visitCoords[visitCoords.length - 1];
488
            var waypoints = [];
489
            for (var wi = 1; wi < visitCoords.length - 1; wi++) {
490
                waypoints.push({ location: visitCoords[wi], stopover: true });
491
            }
492
 
493
            var directionsService = new google.maps.DirectionsService();
494
            var directionsRenderer = new google.maps.DirectionsRenderer({
495
                map: liveTrackingMap,
496
                suppressMarkers: true,
497
                polylineOptions: {
498
                    strokeColor: '#8e44ad',
499
                    strokeOpacity: 0.7,
500
                    strokeWeight: 4
501
                },
502
                preserveViewport: true
36682 vikas 503
            });
36685 vikas 504
            liveTrackingMap._directionsRenderer = directionsRenderer;
505
 
506
            directionsService.route({
507
                origin: origin,
508
                destination: destination,
509
                waypoints: waypoints,
510
                travelMode: google.maps.TravelMode.DRIVING,
511
                optimizeWaypoints: false
512
            }, function (result, status) {
513
                if (status === 'OK') {
514
                    directionsRenderer.setDirections(result);
515
                }
516
            });
36682 vikas 517
        }
518
 
36685 vikas 519
        // Draw GPS tracked path with red dots + connecting line
520
        var totalGpsDistanceM = 0;
521
        var accuracySum = 0;
522
        var accuracyCount = 0;
523
        var stopsDetected = [];
524
 
36664 vikas 525
        if (pathPoints.length > 0) {
36685 vikas 526
            var validPoints = [];
36664 vikas 527
            for (var j = 0; j < pathPoints.length; j++) {
528
                var pt = pathPoints[j];
529
                var pLat = parseFloat(pt.lat);
530
                var pLng = parseFloat(pt.lng);
531
                if (isNaN(pLat) || isNaN(pLng) || (pLat === 0 && pLng === 0)) continue;
36685 vikas 532
                var acc = parseFloat(pt.accuracy);
533
                if (!isNaN(acc)) { accuracySum += acc; accuracyCount++; }
534
                validPoints.push({ lat: pLat, lng: pLng, ts: pt.timestamp, accuracy: pt.accuracy });
36664 vikas 535
                bounds.extend({ lat: pLat, lng: pLng });
536
                hasPoints = true;
537
            }
538
 
36685 vikas 539
            // Calculate total GPS distance
540
            for (var d = 1; d < validPoints.length; d++) {
541
                totalGpsDistanceM += haversineMeters(validPoints[d-1].lat, validPoints[d-1].lng, validPoints[d].lat, validPoints[d].lng);
542
            }
543
 
544
            if (validPoints.length > 0) {
545
                var pathCoords = validPoints.map(function(p) { return { lat: p.lat, lng: p.lng }; });
546
 
547
                // Blue connecting line
36664 vikas 548
                liveTrackingMap._polyline = new google.maps.Polyline({
549
                    path: pathCoords,
550
                    geodesic: true,
36685 vikas 551
                    strokeColor: '#e74c3c',
552
                    strokeOpacity: 0.7,
36664 vikas 553
                    strokeWeight: 3,
36685 vikas 554
                    zIndex: 50,
36664 vikas 555
                    map: liveTrackingMap
556
                });
557
 
36688 vikas 558
                // Direction arrows for each GPS point
36685 vikas 559
                liveTrackingMap._gpsDots = [];
560
                for (var gi = 0; gi < validPoints.length; gi++) {
561
                    var gp = validPoints[gi];
36688 vikas 562
                    var heading = 0;
563
                    if (gi < validPoints.length - 1) {
564
                        heading = google.maps.geometry.spherical.computeHeading(
565
                            new google.maps.LatLng(gp.lat, gp.lng),
566
                            new google.maps.LatLng(validPoints[gi + 1].lat, validPoints[gi + 1].lng)
567
                        );
568
                    } else if (gi > 0) {
569
                        heading = google.maps.geometry.spherical.computeHeading(
570
                            new google.maps.LatLng(validPoints[gi - 1].lat, validPoints[gi - 1].lng),
571
                            new google.maps.LatLng(gp.lat, gp.lng)
572
                        );
573
                    }
36685 vikas 574
                    var dot = new google.maps.Marker({
575
                        position: { lat: gp.lat, lng: gp.lng },
576
                        map: liveTrackingMap,
577
                        icon: {
36688 vikas 578
                            path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
579
                            scale: 3,
36685 vikas 580
                            fillColor: '#e74c3c',
581
                            fillOpacity: 1,
582
                            strokeColor: '#b71c1c',
36688 vikas 583
                            strokeWeight: 1,
584
                            rotation: heading
36685 vikas 585
                        },
586
                        zIndex: 80
587
                    });
588
                    (function(marker, point, idx) {
589
                        var iw = new google.maps.InfoWindow({
590
                            content: '<div style="font-size:12px;">' +
591
                                '<strong>GPS Point #' + (idx + 1) + '</strong><br>' +
592
                                '<i class="fa fa-clock-o"></i> ' + formatEpoch(point.ts) + '<br>' +
593
                                '<i class="fa fa-crosshairs"></i> Accuracy: ' + (point.accuracy || 'N/A') + 'm<br>' +
594
                                '<i class="fa fa-map-marker"></i> ' + point.lat.toFixed(6) + ', ' + point.lng.toFixed(6) +
595
                                '</div>'
596
                        });
597
                        marker.addListener('click', function() { iw.open(liveTrackingMap, marker); });
598
                    })(dot, gp, gi);
599
                    liveTrackingMap._gpsDots.push(dot);
600
                }
601
 
602
                // Detect stationary stops (within 50m for >5 min)
603
                stopsDetected = detectStops(validPoints, 50, 5 * 60 * 1000);
604
                liveTrackingMap._stopMarkers = [];
605
                for (var si = 0; si < stopsDetected.length; si++) {
606
                    var stop = stopsDetected[si];
607
                    var stopMarker = new google.maps.Marker({
608
                        position: { lat: stop.lat, lng: stop.lng },
609
                        map: liveTrackingMap,
610
                        icon: {
611
                            path: google.maps.SymbolPath.CIRCLE,
36709 vikas 612
                            scale: 20,
36685 vikas 613
                            fillColor: '#f39c12',
614
                            fillOpacity: 0.9,
615
                            strokeColor: '#e67e22',
616
                            strokeWeight: 2
617
                        },
36709 vikas 618
                        label: { text: formatDuration(stop.duration), fontSize: '12px', fontWeight: 'bold', color: '#000' },
36685 vikas 619
                        title: 'Stopped for ' + formatDuration(stop.duration),
620
                        zIndex: 200
621
                    });
622
                    (function(marker, s) {
623
                        var iw = new google.maps.InfoWindow({
624
                            content: '<div style="font-size:13px;">' +
625
                                '<strong><i class="fa fa-pause-circle" style="color:#f39c12;"></i> Stationary Stop</strong><br>' +
626
                                '<i class="fa fa-clock-o"></i> Duration: <strong>' + formatDuration(s.duration) + '</strong><br>' +
627
                                '<i class="fa fa-sign-in"></i> From: <strong>' + new Date(s.startTime).toLocaleTimeString() + '</strong><br>' +
628
                                '<i class="fa fa-sign-out"></i> To: <strong>' + new Date(s.endTime).toLocaleTimeString() + '</strong><br>' +
629
                                '<i class="fa fa-map-marker"></i> ' + s.lat.toFixed(6) + ', ' + s.lng.toFixed(6) + '<br>' +
630
                                '<i class="fa fa-dot-circle-o"></i> Points in cluster: ' + s.pointCount +
631
                                '</div>'
632
                        });
633
                        marker.addListener('click', function() { iw.open(liveTrackingMap, marker); });
634
                    })(stopMarker, stop);
635
                    liveTrackingMap._stopMarkers.push(stopMarker);
636
                }
637
 
36688 vikas 638
                // Last known location marker (bike icon)
36664 vikas 639
                var lastPoint = pathCoords[pathCoords.length - 1];
640
                liveTrackingMap._currentMarker = new google.maps.Marker({
641
                    position: lastPoint,
642
                    map: liveTrackingMap,
643
                    icon: {
36690 vikas 644
                        url: '${rc.contextPath}/resources/images/Bike-Icon-SD.png',
36709 vikas 645
                        scaledSize: new google.maps.Size(56, 56),
646
                        anchor: new google.maps.Point(28, 28)
36664 vikas 647
                    },
648
                    title: 'Last Known Location',
649
                    zIndex: 999
650
                });
36685 vikas 651
                var lastGp = validPoints[validPoints.length - 1];
36664 vikas 652
                var currentIw = new google.maps.InfoWindow({
36685 vikas 653
                    content: '<div style="font-size:13px;"><strong><i class="fa fa-crosshairs" style="color:#27ae60;"></i> Last Known Location</strong><br>' +
654
                        '<i class="fa fa-clock-o"></i> Time: ' + formatEpoch(lastGp.ts) + '<br>' +
655
                        '<i class="fa fa-crosshairs"></i> Accuracy: ' + (lastGp.accuracy || 'N/A') + 'm</div>'
36664 vikas 656
                });
657
                liveTrackingMap._currentMarker.addListener('click', function () {
658
                    currentIw.open(liveTrackingMap, liveTrackingMap._currentMarker);
659
                });
660
            }
661
        }
662
 
663
        if (hasPoints) {
664
            liveTrackingMap.fitBounds(bounds);
665
        }
666
 
36685 vikas 667
        // Info bar
36664 vikas 668
        var totalVisits = visits.filter(function (v) { return v.markType !== 'PUNCHIN' && v.markType !== 'PUNCHOUT'; }).length;
669
        var completedVisits = visits.filter(function (v) { return v.markType === 'CHECKIN-CHECKOUT' || v.markType === 'CHECKOUT'; }).length;
36682 vikas 670
        var now = new Date();
671
        var timeStr = now.getHours().toString().padStart(2, '0') + ':' + now.getMinutes().toString().padStart(2, '0') + ':' + now.getSeconds().toString().padStart(2, '0');
36685 vikas 672
 
673
        var avgAccuracy = accuracyCount > 0 ? (accuracySum / accuracyCount).toFixed(0) : null;
674
        var accuracyLabel = '';
675
        var accuracyBadge = '';
676
        if (avgAccuracy) {
677
            if (avgAccuracy <= 10) { accuracyLabel = 'High'; accuracyBadge = 'background:#27ae60;'; }
678
            else if (avgAccuracy <= 30) { accuracyLabel = 'Good'; accuracyBadge = 'background:#2ecc71;'; }
679
            else if (avgAccuracy <= 100) { accuracyLabel = 'Average'; accuracyBadge = 'background:#f39c12;'; }
680
            else { accuracyLabel = 'Low'; accuracyBadge = 'background:#e74c3c;'; }
681
        }
682
 
683
        var totalGpsKm = (totalGpsDistanceM / 1000).toFixed(2);
684
 
685
        var infoHtml = '<strong>' + username + '</strong> | ' +
36664 vikas 686
            'Visits: <strong>' + totalVisits + '</strong> | ' +
36685 vikas 687
            'Completed: <strong>' + completedVisits + '</strong>';
688
 
689
        if (pathPoints.length > 0) {
690
            infoHtml += ' | GPS Distance: <strong>' + totalGpsKm + ' km</strong>';
691
            infoHtml += ' | Points: <strong>' + pathPoints.length + '</strong>';
692
            if (accuracyLabel) {
693
                infoHtml += ' | Accuracy: <span class="label" style="' + accuracyBadge + ' color:white; padding:2px 8px; border-radius:3px; font-size:11px;">' + accuracyLabel + '</span> (' + avgAccuracy + 'm)';
694
            }
695
            if (stopsDetected.length > 0) {
696
                infoHtml += ' | <span style="color:#f39c12;"><i class="fa fa-pause-circle"></i></span> Stops: <strong>' + stopsDetected.length + '</strong>';
697
            }
36690 vikas 698
            infoHtml += ' | <img src="${rc.contextPath}/resources/images/Bike-Icon-SD.png" style="height:16px; vertical-align:middle;"> Last Known';
36685 vikas 699
        } else {
700
            infoHtml += ' | <span style="color:#999;"><i class="fa fa-exclamation-triangle"></i> No GPS data yet</span>';
701
        }
702
 
36688 vikas 703
        infoHtml += ' | <span style="color:#e74c3c;"><i class="fa fa-arrow-right" style="font-size:10px;"></i></span> GPS Trail';
36685 vikas 704
        if (visitCoords.length > 1) {
705
            infoHtml += ' | <span style="background:#8e44ad; display:inline-block; width:14px; height:3px; vertical-align:middle; margin:0 2px;"></span> Route';
706
        }
36690 vikas 707
        var locToggle = data.locationToggleCount || 0;
708
        if (locToggle > 0) {
709
            infoHtml += ' | <span class="label" style="background:#e74c3c; color:white; padding:2px 8px; border-radius:3px; font-size:11px;"><i class="fa fa-power-off"></i> Loc Off: ' + locToggle + '</span>';
710
        }
711
 
36685 vikas 712
        infoHtml += ' | <span style="color:#999;">Updated: ' + timeStr + '</span>';
713
 
714
        $('#liveTrackingInfo').html(infoHtml);
715
 
716
        // Low data warning
717
        if (pathPoints.length > 0 && pathPoints.length < 10) {
718
            $('#liveTrackingInfo').append(
719
                '<div style="margin-top:4px; padding:4px 8px; background:#fff3cd; border:1px solid #ffc107; border-radius:3px; font-size:11px; color:#856404;">' +
720
                '<i class="fa fa-exclamation-triangle"></i> Received less data points from device due to: Low Battery level, ' +
721
                'GPS/location switched off, or phone automatically switched off the location service.' +
722
                '</div>'
723
            );
724
        }
36664 vikas 725
    }
726
 
727
    function ensureGoogleMaps(callback) {
728
        if (window.google && window.google.maps) {
729
            callback();
730
            return;
731
        }
732
        var s = document.createElement('script');
36688 vikas 733
        s.src = 'https://maps.googleapis.com/maps/api/js?key=AIzaSyAckO0y4Z6WhBOuMjNjioWLSYZDhGEvGBc&libraries=geometry&v=weekly';
36664 vikas 734
        s.onload = callback;
735
        document.head.appendChild(s);
736
    }
737
 
36682 vikas 738
    var liveTrackingUsername = '';
739
 
36709 vikas 740
    /*function startAutoRefresh() {
36682 vikas 741
        stopAutoRefresh();
742
        if ($('#autoRefreshToggle').is(':checked') && liveTrackingUserId) {
743
            liveTrackingInterval = setInterval(function () {
744
                loadLiveTracking(liveTrackingUserId, liveTrackingUsername);
745
            }, 30000);
746
        }
747
    }
748
 
749
    function stopAutoRefresh() {
750
        if (liveTrackingInterval) {
751
            clearInterval(liveTrackingInterval);
752
            liveTrackingInterval = null;
753
        }
36709 vikas 754
    }*/
36682 vikas 755
 
36664 vikas 756
    $(document).on('click.livetrack', '.live-tracking-btn', function () {
757
        liveTrackingUserId = $(this).data('userid');
36682 vikas 758
        liveTrackingUsername = $(this).data('username');
36690 vikas 759
        $('#liveTrackingModalTitle').html('<img src="${rc.contextPath}/resources/images/Bike-Icon-SD.png" style="height:24px; vertical-align:middle; margin-right:6px;"> Live Tracking - ' + liveTrackingUsername);
36664 vikas 760
        $('#liveTrackingInfo').html('<div class="text-center"><i class="fa fa-spinner fa-spin"></i> Loading...</div>');
761
        $('#liveTrackingModal').modal('show');
762
 
763
        setTimeout(function () {
764
            liveTrackingMap = null;
765
            ensureGoogleMaps(function () {
36682 vikas 766
                loadLiveTracking(liveTrackingUserId, liveTrackingUsername);
767
                startAutoRefresh();
36664 vikas 768
            });
769
        }, 300);
770
    });
771
 
772
    $(document).on('click.livetrack', '#refreshTrackingBtn', function () {
773
        if (liveTrackingUserId) {
774
            $('#liveTrackingInfo').html('<div class="text-center"><i class="fa fa-spinner fa-spin"></i> Refreshing...</div>');
36682 vikas 775
            loadLiveTracking(liveTrackingUserId, liveTrackingUsername);
36664 vikas 776
        }
777
    });
778
 
36682 vikas 779
    $(document).on('change', '#autoRefreshToggle', function () {
780
        if ($(this).is(':checked')) {
781
            startAutoRefresh();
782
        } else {
783
            stopAutoRefresh();
36664 vikas 784
        }
785
    });
36682 vikas 786
 
787
    $('#liveTrackingModal').on('hidden.bs.modal', function () {
788
        stopAutoRefresh();
789
        liveTrackingUserId = null;
790
    });
36709 vikas 791
 
792
    // Attachment Viewer
793
    $(document).on('click', '.view-attachment-link', function () {
794
        var attachment = $(this).data('attachment');
795
        var checkinLatLng = $(this).data('checkin-latlng') || '';
796
        var visitLocation = $(this).data('visit-location') || '';
797
        var trackingId = $(this).data('tracking-id');
798
 
36710 vikas 799
        var imgUrl = context + '/download-attachment?documentId=' + attachment;
36709 vikas 800
        $('#attachmentImage').attr('src', imgUrl);
801
        $('#approveCheckinBtn').hide().removeData('tracking-id');
802
        $('#attachmentDistanceInfo').html('');
803
 
804
        var distanceM = -1;
805
        if (checkinLatLng && visitLocation && checkinLatLng.indexOf(',') > 0 && visitLocation.indexOf(',') > 0) {
806
            var cParts = checkinLatLng.toString().split(',');
807
            var vParts = visitLocation.toString().split(',');
808
            var cLat = parseFloat(cParts[0]);
809
            var cLng = parseFloat(cParts[1]);
810
            var vLat = parseFloat(vParts[0]);
811
            var vLng = parseFloat(vParts[1]);
812
            if (!isNaN(cLat) && !isNaN(cLng) && !isNaN(vLat) && !isNaN(vLng) && !(cLat === 0 && cLng === 0) && !(vLat === 0 && vLng === 0)) {
813
                distanceM = haversineMeters(cLat, cLng, vLat, vLng);
814
            }
815
        }
816
 
817
        if (distanceM > 50) {
818
            $('#attachmentDistanceInfo').html(
819
                '<span class="label label-danger" style="font-size:12px; padding:4px 10px;">' +
820
                '<i class="fa fa-exclamation-triangle"></i> Checkin Distance: ' + Math.round(distanceM) + 'm (exceeds 50m radius)</span>'
821
            );
822
            $('#approveCheckinBtn').show().data('tracking-id', trackingId);
823
        } else if (distanceM >= 0) {
824
            $('#attachmentDistanceInfo').html(
825
                '<span class="label label-success" style="font-size:12px; padding:4px 10px;">' +
826
                '<i class="fa fa-check-circle"></i> Checkin Distance: ' + Math.round(distanceM) + 'm (within 50m radius)</span>'
827
            );
828
        }
829
 
830
        $('#attachmentViewerModal').modal('show');
831
    });
832
 
833
    $(document).on('click', '#approveCheckinBtn', function () {
834
        var btn = $(this);
835
        var trackingId = btn.data('tracking-id');
836
        if (!trackingId) return;
837
 
838
        btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Approving...');
839
 
840
        $.ajax({
841
            url: context + '/beat-report/approve-checkin',
842
            type: 'POST',
843
            data: { trackingId: trackingId },
844
            success: function () {
845
                btn.html('<i class="fa fa-check"></i> Approved').removeClass('btn-success').addClass('btn-default').prop('disabled', true);
846
                alert('Checkin approved successfully');
847
            },
848
            error: function () {
849
                btn.prop('disabled', false).html('<i class="fa fa-check"></i> Approve');
850
                alert('Failed to approve checkin');
851
            }
852
        });
853
    });
36645 vikas 854
</script>