Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
36645 vikas 1
<script>
2
    if (!window.google || !window.google.maps) {
3
        var s = document.createElement('script');
36693 vikas 4
        s.src = 'https://maps.googleapis.com/maps/api/js?key=AIzaSyAckO0y4Z6WhBOuMjNjioWLSYZDhGEvGBc&libraries=geometry&v=weekly';
36645 vikas 5
        document.head.appendChild(s);
6
    }
7
</script>
8
 
9
<div class="col-lg-12">
36712 vikas 10
    <table class="table table-border table-condensed table-bordered table-hover" id="beatReportTable" style="width:100%">
36645 vikas 11
        <thead>
12
        <tr>
13
            <th>User Name</th>
36709 vikas 14
            <th>Punch In/Out</th>
36645 vikas 15
            <th>Total Visits</th>
16
            <th>Completed Visits</th>
17
            <th>Pending Visits</th>
18
            <th>Deferred</th>
36693 vikas 19
            <th>Map</th>
36645 vikas 20
        </tr>
21
        </thead>
22
        <tbody>
23
        #set($rowIndex = 0)
24
        #foreach($row in $reportRows)
25
            <tr>
26
                <td><a href="javascript:void(0);" class="beat-user-detail-link" data-userid="$row.get('userId')" style="color:#2c3e50; font-weight:bold; text-decoration:underline; cursor:pointer;">$row.get("username")</a></td>
36709 vikas 27
                <td>
28
                    #if($row.get("punchInTime") != "")<span class="label label-success">$row.get("punchInTime")</span>#else<span style="color:#ccc;">--</span>#end
29
                    #if($row.get("punchOutTime") != "")<span class="label label-danger">$row.get("punchOutTime")</span>#else<span style="color:#ccc;">--</span>#end
30
                </td>
36645 vikas 31
                <td><a href="javascript:void(0);" class="beat-detail-link" data-row="$rowIndex" data-type="total" style="color:#1abc9c; font-weight:bold; text-decoration:underline; cursor:pointer;">$row.get("total")</a></td>
32
                <td><a href="javascript:void(0);" class="beat-detail-link" data-row="$rowIndex" data-type="completed" style="color:#1abc9c; font-weight:bold; text-decoration:underline; cursor:pointer;">$row.get("completed")</a></td>
33
                <td><a href="javascript:void(0);" class="beat-detail-link" data-row="$rowIndex" data-type="pending" style="color:#e67e22; font-weight:bold; text-decoration:underline; cursor:pointer;">$row.get("pending")</a></td>
34
                <td><a href="javascript:void(0);" class="beat-detail-link" data-row="$rowIndex" data-type="deferred" style="color:#e74c3c; font-weight:bold; text-decoration:underline; cursor:pointer;">$row.get("deferred")</a></td>
35
                <td><a href="javascript:void(0);" class="beat-map-link" data-row="$rowIndex" style="cursor:pointer;"><i class="fa fa-map-marker" style="color:#1abc9c; font-size:18px;"></i></a></td>
36
            </tr>
37
 
38
            <script>
39
                window.beatReportData = window.beatReportData || {};
40
                window.beatReportData[$rowIndex] = {
41
                    username: "$row.get('username').replace('"', '\"')",
42
                    total: [
43
                        #foreach($lt in $row.get("totalList"))
44
                        { taskName: "$!lt.getTaskName().replace('"', '\"')", markType: "$!lt.getMarkType()", address: "$!lt.getAddress().replace('"', '\"').replace("'", "\'")", checkInTime: "$!lt.getCheckInTime()", checkOutTime: "$!lt.getCheckOutTime()", timeSpent: "$!lt.getTimeSpent()", taskType: "$!lt.getTaskType()", visitLocation: "$!lt.getVisitLocation()", checkInLatLng: "$!lt.getCheckInLatLng()", taskDescription: "$!lt.getTaskDescription().replace('"', '\"')", attachment: "$!lt.getAttachment()" },
45
                        #end
46
                    ],
47
                    completed: [
48
                        #foreach($lt in $row.get("completedList"))
49
                        { taskName: "$!lt.getTaskName().replace('"', '\"')", markType: "$!lt.getMarkType()", address: "$!lt.getAddress().replace('"', '\"').replace("'", "\'")", checkInTime: "$!lt.getCheckInTime()", checkOutTime: "$!lt.getCheckOutTime()", timeSpent: "$!lt.getTimeSpent()", taskType: "$!lt.getTaskType()", visitLocation: "$!lt.getVisitLocation()", checkInLatLng: "$!lt.getCheckInLatLng()", taskDescription: "$!lt.getTaskDescription().replace('"', '\"')", attachment: "$!lt.getAttachment()" },
50
                        #end
51
                    ],
52
                    pending: [
53
                        #foreach($lt in $row.get("pendingList"))
54
                        { taskName: "$!lt.getTaskName().replace('"', '\"')", markType: "$!lt.getMarkType()", address: "$!lt.getAddress().replace('"', '\"').replace("'", "\'")", checkInTime: "$!lt.getCheckInTime()", checkOutTime: "$!lt.getCheckOutTime()", timeSpent: "$!lt.getTimeSpent()", taskType: "$!lt.getTaskType()", visitLocation: "$!lt.getVisitLocation()", checkInLatLng: "$!lt.getCheckInLatLng()", taskDescription: "$!lt.getTaskDescription().replace('"', '\"')", attachment: "$!lt.getAttachment()" },
55
                        #end
56
                    ],
57
                    deferred: [
58
                        #foreach($lt in $row.get("deferredList"))
59
                        { taskName: "$!lt.getTaskName().replace('"', '\"')", markType: "$!lt.getMarkType()", address: "$!lt.getAddress().replace('"', '\"').replace("'", "\'")", checkInTime: "$!lt.getCheckInTime()", checkOutTime: "$!lt.getCheckOutTime()", timeSpent: "$!lt.getTimeSpent()", taskType: "$!lt.getTaskType()", visitLocation: "$!lt.getVisitLocation()", checkInLatLng: "$!lt.getCheckInLatLng()", taskDescription: "$!lt.getTaskDescription().replace('"', '\"')", attachment: "$!lt.getAttachment()" },
60
                        #end
61
                    ]
62
                };
63
            </script>
64
            #set($rowIndex = $rowIndex + 1)
65
        #end
66
        </tbody>
67
    </table>
68
</div>
69
 
70
<!-- Map Modal -->
71
<div class="modal fade" id="beatMapModal" tabindex="-1" role="dialog">
72
    <div class="modal-dialog modal-lg" role="document" style="width:90%;">
73
        <div class="modal-content">
74
            <div class="modal-header" style="background:#1abc9c; color:white;">
75
                <button type="button" class="close" data-dismiss="modal" style="color:white;">&times;</button>
76
                <h4 class="modal-title" id="beatMapModalTitle">Visit Locations</h4>
77
            </div>
78
            <div class="modal-body" style="padding:0;">
79
                <div id="beatMapContainer" style="height:500px; width:100%;"></div>
80
                <div id="beatMapInfo" style="padding:6px 15px; background:#fff3cd; border-top:1px solid #ddd; color:#856404; display:none;"></div>
81
                <div style="padding:8px 15px; background:#f5f5f5; border-top:1px solid #ddd;">
82
                    <span style="margin-right:15px;"><i class="fa fa-circle" style="color:#4285F4;"></i> Check In</span>
83
                    <span style="margin-right:15px;"><i class="fa fa-circle" style="color:#0F9D58;"></i> Completed</span>
84
                    <span style="margin-right:15px;"><i class="fa fa-circle" style="color:#F4B400;"></i> Pending</span>
85
                    <span><i class="fa fa-circle" style="color:#DB4437;"></i> Deferred</span>
86
                </div>
87
            </div>
88
            <div class="modal-footer">
89
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
90
            </div>
91
        </div>
92
    </div>
93
</div>
94
 
95
<!-- Detail Popup Modal -->
96
<div class="modal fade" id="beatDetailModal" tabindex="-1" role="dialog">
97
    <div class="modal-dialog modal-lg" role="document">
98
        <div class="modal-content">
99
            <div class="modal-header" style="background:#1abc9c; color:white;">
100
                <button type="button" class="close" data-dismiss="modal" style="color:white;">&times;</button>
101
                <h4 class="modal-title" id="beatDetailModalTitle">Visit Details</h4>
102
            </div>
103
            <div class="modal-body">
104
                <table class="table table-bordered table-condensed table-striped" id="beatDetailTable" style="width:100%">
105
                    <thead>
106
                    <tr>
107
                        <th>#</th>
36669 vikas 108
                        <th>Agenda/Partner Name</th>
36645 vikas 109
                        <th>Type</th>
110
                        <th>Status</th>
111
                        <th>Address</th>
112
                        <th>Check In</th>
113
                        <th>Check Out</th>
114
                        <th>Time Spent</th>
115
                        <th>Description</th>
36666 vikas 116
                        <th>Extimated Time</th>
36645 vikas 117
                        <th>Attachment</th>
118
                    </tr>
119
                    </thead>
120
                    <tbody id="beatDetailTableBody"></tbody>
121
                </table>
122
            </div>
123
            <div class="modal-footer">
124
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
125
            </div>
126
        </div>
127
    </div>
128
</div>
129
 
130
<script>
131
    $('#beatReportTable').DataTable({
132
        "scrollX": true,
36685 vikas 133
        "pageLength": 50,
36645 vikas 134
        "bPaginate": true,
135
        "bLengthChange": true,
136
        "bFilter": true,
137
        "bInfo": true,
138
        "bAutoWidth": false
139
    });
140
 
141
    var beatMapMarkerColors = {
142
        'PENDING': '#F4B400',
143
        'DEFERRED': '#DB4437',
144
        'CHECKIN': '#4285F4',
145
        'CHECKIN-CHECKOUT': '#0F9D58',
146
        'CHECKOUT': '#0F9D58'
147
    };
148
 
149
    function getMarkerColor(markType) {
150
        return beatMapMarkerColors[markType] || '#999999';
151
    }
152
 
153
    function createColoredMarkerIcon(color, label) {
154
        var svg = '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="42" viewBox="0 0 32 42">' +
155
            '<path d="M16 0C7.2 0 0 7.2 0 16c0 12 16 26 16 26s16-14 16-26C32 7.2 24.8 0 16 0z" fill="' + color + '"/>' +
156
            '<circle cx="16" cy="15" r="10" fill="white"/>' +
157
            '<text x="16" y="20" text-anchor="middle" font-size="12" font-weight="bold" fill="' + color + '">' + label + '</text>' +
158
            '</svg>';
159
        return 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg);
160
    }
161
 
162
    function getLatLng(item) {
163
        var loc = item.visitLocation || item.checkInLatLng || '';
164
        if (!loc || loc === '0.0000,0.0000') return null;
165
        var parts = loc.split(',');
166
        if (parts.length !== 2) return null;
167
        var lat = parseFloat(parts[0].trim());
168
        var lng = parseFloat(parts[1].trim());
169
        if (isNaN(lat) || isNaN(lng) || (lat === 0 && lng === 0)) return null;
170
        return { lat: lat, lng: lng };
171
    }
172
 
173
    $(document).on('click', '.beat-map-link', function () {
174
        var rowIndex = $(this).data('row');
175
        var data = window.beatReportData[rowIndex];
176
        if (!data) return;
177
 
178
        var items = data.total || [];
179
        var username = data.username;
180
        $('#beatMapModalTitle').text(username + ' - Visit Locations (' + items.length + ')');
181
 
182
        if (typeof google === 'undefined' || !google.maps) {
183
            alert('Google Maps is still loading. Please try again in a moment.');
184
            return;
185
        }
186
 
187
        $('#beatMapModal').modal('show');
188
 
189
        setTimeout(function () {
190
            var mapDiv = document.getElementById('beatMapContainer');
191
            var bounds = new google.maps.LatLngBounds();
192
            var hasMarkers = false;
193
 
194
            var map = new google.maps.Map(mapDiv, {
195
                zoom: 10,
196
                center: { lat: 20.5937, lng: 78.9629 },
197
                mapTypeId: 'roadmap'
198
            });
199
 
200
            var infoWindow = new google.maps.InfoWindow();
201
 
202
            for (var i = 0; i < items.length; i++) {
203
                var item = items[i];
204
                var pos = getLatLng(item);
205
                if (!pos) continue;
206
 
207
                hasMarkers = true;
208
                bounds.extend(pos);
209
 
210
                var color = getMarkerColor(item.markType);
211
                var marker = new google.maps.Marker({
212
                    position: pos,
213
                    map: map,
214
                    title: item.taskName || item.markType,
215
                    icon: {
216
                        url: createColoredMarkerIcon(color, (i + 1)),
217
                        scaledSize: new google.maps.Size(32, 42),
218
                        anchor: new google.maps.Point(16, 42)
219
                    }
220
                });
221
 
222
                (function (m, itm, idx) {
223
                    google.maps.event.addListener(m, 'click', function () {
224
                        var content = '<div style="min-width:200px;">' +
225
                            '<strong>' + (idx + 1) + '. ' + (itm.taskName || '--') + '</strong><br>' +
226
                            '<b>Status:</b> ' + (itm.markType || '--') + '<br>' +
227
                            '<b>Address:</b> ' + (itm.address || '--') + '<br>' +
228
                            '<b>Check In:</b> ' + (itm.checkInTime || '--') + '<br>' +
229
                            '<b>Check Out:</b> ' + (itm.checkOutTime || '--') + '<br>' +
230
                            '<b>Time Spent:</b> ' + (itm.timeSpent || '--') +
231
                            '</div>';
232
                        infoWindow.setContent(content);
233
                        infoWindow.open(map, m);
234
                    });
235
                })(marker, item, i);
236
            }
237
 
238
            var markerCount = 0;
239
            for (var j = 0; j < items.length; j++) { if (getLatLng(items[j])) markerCount++; }
240
 
241
            var infoDiv = document.getElementById('beatMapInfo');
242
            if (markerCount < items.length) {
243
                infoDiv.innerHTML = '<i class="fa fa-exclamation-triangle"></i> Showing ' + markerCount + ' of ' + items.length + ' visits on map. ' + (items.length - markerCount) + ' visits have no location data.';
244
                infoDiv.style.display = 'block';
245
            } else {
246
                infoDiv.style.display = 'none';
247
            }
248
 
249
            if (hasMarkers) {
250
                map.fitBounds(bounds);
251
                if (markerCount === 1) {
252
                    map.setZoom(14);
253
                }
254
            }
255
        }, 400);
256
    });
257
 
258
    $(document).on('click', '.beat-detail-link', function () {
259
        var rowIndex = $(this).data('row');
260
        var type = $(this).data('type');
261
        var data = window.beatReportData[rowIndex];
262
        if (!data) return;
263
 
264
        var items = data[type] || [];
265
        var username = data.username;
266
 
267
        var typeLabel = type.charAt(0).toUpperCase() + type.slice(1);
268
        $('#beatDetailModalTitle').text(username + ' - ' + typeLabel + ' Visits (' + items.length + ')');
269
 
270
        var tbody = '';
271
        for (var i = 0; i < items.length; i++) {
272
            var item = items[i];
273
            tbody += '<tr>' +
274
                '<td>' + (i + 1) + '</td>' +
275
                '<td>' + (item.taskName || '--') + '</td>' +
276
                '<td>' + (item.taskType || '--') + '</td>' +
277
                '<td>' + (item.markType || '--') + '</td>' +
278
                '<td>' + (item.address || '--') + '</td>' +
279
                '<td>' + (item.checkInTime || '--') + '</td>' +
280
                '<td>' + (item.checkOutTime || '--') + '</td>' +
281
                '<td>' + (item.timeSpent || '--') + '</td>' +
282
                '<td>' + (item.taskDescription || '--') + '</td>' +
36666 vikas 283
                '<td>' + (item.estimatedTime || '--') + '</td>' +
36645 vikas 284
                '<td>' + (item.attachment ? '<a href="https://partners.smartdukaan.com/document/' + item.attachment + '" target="_blank"><i class="fa fa-paperclip"></i> View</a>' : '--') + '</td>' +
285
                '</tr>';
286
        }
287
        if (items.length === 0) {
288
            tbody = '<tr><td colspan="10" class="text-center">No records found</td></tr>';
289
        }
290
        $('#beatDetailTableBody').html(tbody);
291
        $('#beatDetailModal').modal('show');
292
    });
36693 vikas 293
 
36696 vikas 294
    // --- Live Tracking ---
295
    var dataLiveMap = null;
296
    var dataLiveUserId = null;
297
    var dataLiveUsername = '';
298
    var dataLiveInterval = null;
299
 
300
    function dataGetMarkerColor(markType) {
301
        if (markType === 'CHECKIN-CHECKOUT' || markType === 'CHECKOUT') return '#0F9D58';
302
        if (markType === 'PENDING' || markType === 'CHECKIN') return '#4285F4';
303
        if (markType === 'DEFERRED') return '#DB4437';
304
        if (markType === 'PUNCHIN') return '#1abc9c';
305
        if (markType === 'PUNCHOUT') return '#e74c3c';
306
        return '#F4B400';
307
    }
308
 
309
    function dataCreateMarkerIcon(color, label) {
310
        var svg = '<svg xmlns="http://www.w3.org/2000/svg" width="28" height="40" viewBox="0 0 28 40">' +
311
            '<path d="M14 0C6.268 0 0 6.268 0 14c0 10.5 14 26 14 26s14-15.5 14-26C28 6.268 21.732 0 14 0z" fill="' + color + '"/>' +
312
            '<circle cx="14" cy="14" r="7" fill="white"/>' +
313
            '<text x="14" y="18" text-anchor="middle" font-size="10" font-weight="bold" fill="' + color + '">' + label + '</text></svg>';
314
        return 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg);
315
    }
316
 
317
    function dataFormatEpoch(ts) {
318
        if (!ts) return 'N/A';
319
        var n = parseFloat(ts);
320
        if (isNaN(n)) return ts;
321
        if (n < 1e12) n = n * 1000;
322
        var d = new Date(n);
323
        return d.getHours().toString().padStart(2,'0') + ':' + d.getMinutes().toString().padStart(2,'0') + ':' + d.getSeconds().toString().padStart(2,'0');
324
    }
325
 
326
    function dataFormatDuration(ms) {
327
        var sec = Math.floor(ms / 1000);
328
        var h = Math.floor(sec / 3600);
329
        var m = Math.floor((sec % 3600) / 60);
330
        var s = sec % 60;
331
        if (h > 0) return h + 'h ' + m + 'm';
332
        if (m > 0) return m + 'm ' + s + 's';
333
        return s + 's';
334
    }
335
 
336
    function dataHaversine(lat1, lon1, lat2, lon2) {
337
        var R = 6371000;
338
        var dLat = (lat2 - lat1) * Math.PI / 180;
339
        var dLon = (lon2 - lon1) * Math.PI / 180;
340
        var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
341
                Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
342
                Math.sin(dLon/2) * Math.sin(dLon/2);
343
        return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
344
    }
345
 
346
    function dataDetectStops(points, radiusM, minTimeMs) {
347
        var stops = [];
348
        var i = 0;
349
        while (i < points.length) {
350
            var cluster = [points[i]];
351
            var cLat = points[i].lat, cLng = points[i].lng;
352
            var j = i + 1;
353
            while (j < points.length) {
354
                if (dataHaversine(cLat, cLng, points[j].lat, points[j].lng) <= radiusM) {
355
                    cluster.push(points[j]);
356
                    j++;
357
                } else {
358
                    break;
359
                }
360
            }
361
            if (cluster.length >= 2) {
362
                var t0 = parseFloat(cluster[0].ts);
363
                var t1 = parseFloat(cluster[cluster.length - 1].ts);
364
                if (t0 < 1e12) t0 *= 1000;
365
                if (t1 < 1e12) t1 *= 1000;
366
                var duration = t1 - t0;
367
                if (duration >= minTimeMs) {
368
                    var avgLat = 0, avgLng = 0;
369
                    cluster.forEach(function(p) { avgLat += p.lat; avgLng += p.lng; });
370
                    stops.push({
371
                        lat: avgLat / cluster.length, lng: avgLng / cluster.length,
372
                        startTime: t0, endTime: t1, duration: duration, pointCount: cluster.length
373
                    });
374
                }
375
            }
376
            i = j;
377
        }
378
        return stops;
379
    }
380
 
381
    function dataClearOverlays() {
382
        if (!dataLiveMap) return;
383
        if (dataLiveMap._markers) dataLiveMap._markers.forEach(function(m) { m.setMap(null); });
384
        if (dataLiveMap._polyline) dataLiveMap._polyline.setMap(null);
385
        if (dataLiveMap._gpsDots) dataLiveMap._gpsDots.forEach(function(m) { m.setMap(null); });
386
        if (dataLiveMap._stopMarkers) dataLiveMap._stopMarkers.forEach(function(m) { m.setMap(null); });
387
        if (dataLiveMap._currentMarker) dataLiveMap._currentMarker.setMap(null);
388
        if (dataLiveMap._directionsRenderer) dataLiveMap._directionsRenderer.setMap(null);
389
        dataLiveMap._markers = [];
390
        dataLiveMap._gpsDots = [];
391
        dataLiveMap._stopMarkers = [];
392
    }
393
 
394
    function dataLoadLiveTracking(userId, username) {
395
        var selectedDate = $('#beat-report-date').val();
396
        $.ajax({
397
            url: context + "/beat-report/live-tracking",
398
            type: "GET", dataType: "json",
399
            data: { userId: userId, date: selectedDate },
400
            success: function(data) { dataRenderMap(data, username); },
401
            error: function() { $('#dataLiveInfo').html('<span style="color:red;">Failed to load tracking data.</span>'); }
402
        });
403
    }
404
 
405
    function dataRenderMap(data, username) {
406
        var visits = data.visits || [];
407
        var pathPoints = data.pathPoints || [];
408
 
409
        if (!dataLiveMap) {
410
            dataLiveMap = new google.maps.Map(document.getElementById('dataLiveMap'), {
411
                zoom: 12, center: { lat: 20.5937, lng: 78.9629 },
412
                mapTypeControl: true, streetViewControl: false
413
            });
414
        }
415
        dataClearOverlays();
416
 
417
        var bounds = new google.maps.LatLngBounds();
418
        var hasPoints = false;
419
        var visitIdx = 0;
420
        var visitCoords = [];
421
 
422
        for (var i = 0; i < visits.length; i++) {
423
            var v = visits[i];
424
            if (!v.lat || !v.lng) continue;
425
            var lat = parseFloat(v.lat), lng = parseFloat(v.lng);
426
            if (isNaN(lat) || isNaN(lng) || (lat === 0 && lng === 0)) continue;
427
            hasPoints = true;
428
            var pos = { lat: lat, lng: lng };
429
            bounds.extend(pos);
430
            visitCoords.push(pos);
431
            var label = v.markType === 'PUNCHIN' ? 'P' : (v.markType === 'PUNCHOUT' ? 'X' : String(++visitIdx));
432
            var marker = new google.maps.Marker({
433
                position: pos, map: dataLiveMap,
434
                icon: { url: dataCreateMarkerIcon(dataGetMarkerColor(v.markType), label), scaledSize: new google.maps.Size(28, 40), anchor: new google.maps.Point(14, 40) },
435
                title: v.taskName + ' (' + v.markType + ')', zIndex: 100
436
            });
437
            var infoContent = '<div style="font-size:13px; max-width:280px;">' +
438
                '<strong>' + (v.taskName || '') + '</strong><br>' +
439
                '<span class="label" style="background:' + dataGetMarkerColor(v.markType) + '; color:white;">' + v.markType + '</span>' +
440
                (v.taskType ? ' <span class="label label-default">' + v.taskType + '</span>' : '') + '<br>' +
441
                (v.checkInTime ? '<i class="fa fa-sign-in" style="color:#27ae60;"></i> In: <strong>' + v.checkInTime + '</strong><br>' : '') +
442
                (v.checkOutTime ? '<i class="fa fa-sign-out" style="color:#e74c3c;"></i> Out: <strong>' + v.checkOutTime + '</strong><br>' : '') +
443
                (v.timeSpent ? '<i class="fa fa-clock-o" style="color:#f39c12;"></i> Time Spent: <strong>' + v.timeSpent + '</strong><br>' : '') +
444
                (v.transitTime ? '<i class="fa fa-car" style="color:#3498db;"></i> Transit: <strong>' + v.transitTime + '</strong><br>' : '') +
445
                (v.totalDistance && v.totalDistance !== '0.0' ? '<i class="fa fa-road" style="color:#8e44ad;"></i> Distance: <strong>' + v.totalDistance + ' km</strong><br>' : '') +
446
                (v.address ? '<i class="fa fa-map-marker" style="color:#e74c3c;"></i> ' + v.address : '') + '</div>';
447
            (function(m, c) {
448
                var iw = new google.maps.InfoWindow({ content: c });
449
                m.addListener('click', function() { iw.open(dataLiveMap, m); });
450
            })(marker, infoContent);
451
            dataLiveMap._markers.push(marker);
452
        }
453
 
454
        if (visitCoords.length >= 2) {
455
            var origin = visitCoords[0], destination = visitCoords[visitCoords.length - 1];
456
            var waypoints = [];
457
            for (var wi = 1; wi < visitCoords.length - 1; wi++) waypoints.push({ location: visitCoords[wi], stopover: true });
458
            var ds = new google.maps.DirectionsService();
459
            var dr = new google.maps.DirectionsRenderer({
460
                map: dataLiveMap, suppressMarkers: true,
461
                polylineOptions: { strokeColor: '#8e44ad', strokeOpacity: 0.7, strokeWeight: 4 },
462
                preserveViewport: true
463
            });
464
            dataLiveMap._directionsRenderer = dr;
465
            ds.route({ origin: origin, destination: destination, waypoints: waypoints, travelMode: google.maps.TravelMode.DRIVING, optimizeWaypoints: false },
466
                function(result, status) { if (status === 'OK') dr.setDirections(result); });
467
        }
468
 
469
        var totalGpsDistanceM = 0, accuracySum = 0, accuracyCount = 0, stopsDetected = [];
470
        if (pathPoints.length > 0) {
471
            var validPoints = [];
472
            for (var j = 0; j < pathPoints.length; j++) {
473
                var pt = pathPoints[j];
474
                var pLat = parseFloat(pt.lat), pLng = parseFloat(pt.lng);
475
                if (isNaN(pLat) || isNaN(pLng) || (pLat === 0 && pLng === 0)) continue;
476
                var acc = parseFloat(pt.accuracy);
477
                if (!isNaN(acc)) { accuracySum += acc; accuracyCount++; }
478
                validPoints.push({ lat: pLat, lng: pLng, ts: pt.timestamp, accuracy: pt.accuracy });
479
                bounds.extend({ lat: pLat, lng: pLng });
480
                hasPoints = true;
481
            }
482
            for (var d = 1; d < validPoints.length; d++) {
483
                totalGpsDistanceM += dataHaversine(validPoints[d-1].lat, validPoints[d-1].lng, validPoints[d].lat, validPoints[d].lng);
484
            }
485
            if (validPoints.length > 0) {
486
                var pathCoords = validPoints.map(function(p) { return { lat: p.lat, lng: p.lng }; });
487
                dataLiveMap._polyline = new google.maps.Polyline({
488
                    path: pathCoords, geodesic: true, strokeColor: '#e74c3c', strokeOpacity: 0.7, strokeWeight: 3, zIndex: 50, map: dataLiveMap
489
                });
490
                dataLiveMap._gpsDots = [];
491
                for (var gi = 0; gi < validPoints.length; gi++) {
492
                    var gp = validPoints[gi];
493
                    var heading = 0;
494
                    if (gi < validPoints.length - 1) {
495
                        heading = google.maps.geometry.spherical.computeHeading(
496
                            new google.maps.LatLng(gp.lat, gp.lng), new google.maps.LatLng(validPoints[gi+1].lat, validPoints[gi+1].lng));
497
                    } else if (gi > 0) {
498
                        heading = google.maps.geometry.spherical.computeHeading(
499
                            new google.maps.LatLng(validPoints[gi-1].lat, validPoints[gi-1].lng), new google.maps.LatLng(gp.lat, gp.lng));
500
                    }
501
                    var dot = new google.maps.Marker({
502
                        position: { lat: gp.lat, lng: gp.lng }, map: dataLiveMap,
503
                        icon: { path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW, scale: 3, fillColor: '#e74c3c', fillOpacity: 1, strokeColor: '#b71c1c', strokeWeight: 1, rotation: heading },
504
                        zIndex: 80
505
                    });
506
                    (function(marker, point, idx) {
507
                        var iw = new google.maps.InfoWindow({
508
                            content: '<div style="font-size:12px;"><strong>GPS Point #' + (idx+1) + '</strong><br>' +
509
                                '<i class="fa fa-clock-o"></i> ' + dataFormatEpoch(point.ts) + '<br>' +
510
                                '<i class="fa fa-crosshairs"></i> Accuracy: ' + (point.accuracy || 'N/A') + 'm<br>' +
511
                                '<i class="fa fa-map-marker"></i> ' + point.lat.toFixed(6) + ', ' + point.lng.toFixed(6) + '</div>'
512
                        });
513
                        marker.addListener('click', function() { iw.open(dataLiveMap, marker); });
514
                    })(dot, gp, gi);
515
                    dataLiveMap._gpsDots.push(dot);
516
                }
517
                stopsDetected = dataDetectStops(validPoints, 50, 5 * 60 * 1000);
518
                dataLiveMap._stopMarkers = [];
519
                for (var si = 0; si < stopsDetected.length; si++) {
520
                    var stop = stopsDetected[si];
521
                    var sm = new google.maps.Marker({
522
                        position: { lat: stop.lat, lng: stop.lng }, map: dataLiveMap,
523
                        icon: { path: google.maps.SymbolPath.CIRCLE, scale: 14, fillColor: '#f39c12', fillOpacity: 0.9, strokeColor: '#e67e22', strokeWeight: 2 },
524
                        label: { text: dataFormatDuration(stop.duration), fontSize: '9px', fontWeight: 'bold', color: '#000' },
525
                        title: 'Stopped for ' + dataFormatDuration(stop.duration), zIndex: 200
526
                    });
527
                    (function(marker, s) {
528
                        var iw = new google.maps.InfoWindow({
529
                            content: '<div style="font-size:13px;"><strong><i class="fa fa-pause-circle" style="color:#f39c12;"></i> Stationary Stop</strong><br>' +
530
                                '<i class="fa fa-clock-o"></i> Duration: <strong>' + dataFormatDuration(s.duration) + '</strong><br>' +
531
                                '<i class="fa fa-sign-in"></i> From: <strong>' + new Date(s.startTime).toLocaleTimeString() + '</strong><br>' +
532
                                '<i class="fa fa-sign-out"></i> To: <strong>' + new Date(s.endTime).toLocaleTimeString() + '</strong><br>' +
533
                                '<i class="fa fa-map-marker"></i> ' + s.lat.toFixed(6) + ', ' + s.lng.toFixed(6) + '<br>' +
534
                                '<i class="fa fa-dot-circle-o"></i> Points in cluster: ' + s.pointCount + '</div>'
535
                        });
536
                        marker.addListener('click', function() { iw.open(dataLiveMap, marker); });
537
                    })(sm, stop);
538
                    dataLiveMap._stopMarkers.push(sm);
539
                }
540
                var lastPoint = pathCoords[pathCoords.length - 1];
541
                dataLiveMap._currentMarker = new google.maps.Marker({
542
                    position: lastPoint, map: dataLiveMap,
543
                    icon: { url: '${rc.contextPath}/resources/images/Bike-Icon-SD.png', scaledSize: new google.maps.Size(40, 40), anchor: new google.maps.Point(20, 20) },
544
                    title: 'Last Known Location', zIndex: 999
545
                });
546
                var lastGp = validPoints[validPoints.length - 1];
547
                var curIw = new google.maps.InfoWindow({
548
                    content: '<div style="font-size:13px;"><strong><i class="fa fa-crosshairs" style="color:#27ae60;"></i> Last Known Location</strong><br>' +
549
                        '<i class="fa fa-clock-o"></i> Time: ' + dataFormatEpoch(lastGp.ts) + '<br>' +
550
                        '<i class="fa fa-crosshairs"></i> Accuracy: ' + (lastGp.accuracy || 'N/A') + 'm</div>'
551
                });
552
                dataLiveMap._currentMarker.addListener('click', function() { curIw.open(dataLiveMap, dataLiveMap._currentMarker); });
553
            }
554
        }
555
 
556
        if (hasPoints) dataLiveMap.fitBounds(bounds);
557
 
558
        var totalVisits = visits.filter(function(v) { return v.markType !== 'PUNCHIN' && v.markType !== 'PUNCHOUT'; }).length;
559
        var completedVisits = visits.filter(function(v) { return v.markType === 'CHECKIN-CHECKOUT' || v.markType === 'CHECKOUT'; }).length;
560
        var now = new Date();
561
        var timeStr = now.getHours().toString().padStart(2,'0') + ':' + now.getMinutes().toString().padStart(2,'0') + ':' + now.getSeconds().toString().padStart(2,'0');
562
        var avgAccuracy = accuracyCount > 0 ? (accuracySum / accuracyCount).toFixed(0) : null;
563
        var accuracyLabel = '', accuracyBadge = '';
564
        if (avgAccuracy) {
565
            if (avgAccuracy <= 10) { accuracyLabel = 'High'; accuracyBadge = 'background:#27ae60;'; }
566
            else if (avgAccuracy <= 30) { accuracyLabel = 'Good'; accuracyBadge = 'background:#2ecc71;'; }
567
            else if (avgAccuracy <= 100) { accuracyLabel = 'Average'; accuracyBadge = 'background:#f39c12;'; }
568
            else { accuracyLabel = 'Low'; accuracyBadge = 'background:#e74c3c;'; }
569
        }
570
        var totalGpsKm = (totalGpsDistanceM / 1000).toFixed(2);
571
        var infoHtml = '<strong>' + username + '</strong> | Visits: <strong>' + totalVisits + '</strong> | Completed: <strong>' + completedVisits + '</strong>';
572
        if (pathPoints.length > 0) {
573
            infoHtml += ' | GPS Distance: <strong>' + totalGpsKm + ' km</strong>';
574
            infoHtml += ' | Points: <strong>' + pathPoints.length + '</strong>';
575
            if (accuracyLabel) infoHtml += ' | Accuracy: <span class="label" style="' + accuracyBadge + ' color:white; padding:2px 8px; border-radius:3px; font-size:11px;">' + accuracyLabel + '</span> (' + avgAccuracy + 'm)';
576
            if (stopsDetected.length > 0) infoHtml += ' | <span style="color:#f39c12;"><i class="fa fa-pause-circle"></i></span> Stops: <strong>' + stopsDetected.length + '</strong>';
577
            infoHtml += ' | <img src="${rc.contextPath}/resources/images/Bike-Icon-SD.png" style="height:16px; vertical-align:middle;"> Last Known';
578
        } else {
579
            infoHtml += ' | <span style="color:#999;"><i class="fa fa-exclamation-triangle"></i> No GPS data yet</span>';
580
        }
581
        infoHtml += ' | <span style="color:#e74c3c;"><i class="fa fa-arrow-right" style="font-size:10px;"></i></span> GPS Trail';
582
        if (visitCoords.length > 1) infoHtml += ' | <span style="background:#8e44ad; display:inline-block; width:14px; height:3px; vertical-align:middle; margin:0 2px;"></span> Route';
583
        var locToggle = data.locationToggleCount || 0;
584
        if (locToggle > 0) 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>';
585
        infoHtml += ' | <span style="color:#999;">Updated: ' + timeStr + '</span>';
586
        $('#dataLiveInfo').html(infoHtml);
587
        if (pathPoints.length > 0 && pathPoints.length < 10) {
588
            $('#dataLiveInfo').append(
589
                '<div style="margin-top:4px; padding:4px 8px; background:#fff3cd; border:1px solid #ffc107; border-radius:3px; font-size:11px; color:#856404;">' +
590
                '<i class="fa fa-exclamation-triangle"></i> Received less data points from device due to: Low Battery level, GPS/location switched off, or phone automatically switched off the location service.</div>');
591
        }
592
    }
593
 
594
    function dataStartAutoRefresh() {
595
        dataStopAutoRefresh();
596
        if ($('#dataAutoRefresh').is(':checked') && dataLiveUserId) {
597
            dataLiveInterval = setInterval(function() { dataLoadLiveTracking(dataLiveUserId, dataLiveUsername); }, 30000);
598
        }
599
    }
600
    function dataStopAutoRefresh() {
601
        if (dataLiveInterval) { clearInterval(dataLiveInterval); dataLiveInterval = null; }
602
    }
603
 
604
    $(document).on('click', '.data-live-tracking-btn', function() {
605
        dataLiveUserId = $(this).data('userid');
606
        dataLiveUsername = $(this).data('username');
607
        $('#dataLiveTitle').html('<img src="${rc.contextPath}/resources/images/Bike-Icon-SD.png" style="height:24px; vertical-align:middle; margin-right:6px;"> Live Tracking - ' + dataLiveUsername);
608
        $('#dataLiveInfo').html('<div class="text-center"><i class="fa fa-spinner fa-spin"></i> Loading...</div>');
609
        $('#dataLiveModal').modal('show');
610
        setTimeout(function() {
611
            dataLiveMap = null;
612
            if (window.google && window.google.maps) {
613
                dataLoadLiveTracking(dataLiveUserId, dataLiveUsername);
614
                dataStartAutoRefresh();
615
            } else {
616
                var s = document.createElement('script');
617
                s.src = 'https://maps.googleapis.com/maps/api/js?key=AIzaSyAckO0y4Z6WhBOuMjNjioWLSYZDhGEvGBc&libraries=geometry&v=weekly';
618
                s.onload = function() { dataLoadLiveTracking(dataLiveUserId, dataLiveUsername); dataStartAutoRefresh(); };
619
                document.head.appendChild(s);
620
            }
621
        }, 300);
622
    });
623
 
624
    $(document).on('click', '#dataRefreshBtn', function() {
625
        if (dataLiveUserId) {
626
            $('#dataLiveInfo').html('<div class="text-center"><i class="fa fa-spinner fa-spin"></i> Refreshing...</div>');
627
            dataLoadLiveTracking(dataLiveUserId, dataLiveUsername);
628
        }
629
    });
630
    $(document).on('change', '#dataAutoRefresh', function() {
631
        $(this).is(':checked') ? dataStartAutoRefresh() : dataStopAutoRefresh();
632
    });
633
    $('#dataLiveModal').on('hidden.bs.modal', function() { dataStopAutoRefresh(); dataLiveUserId = null; });
36645 vikas 634
</script>
36696 vikas 635
 
636
<!-- Live Tracking Modal -->
637
<div class="modal fade" id="dataLiveModal" tabindex="-1" role="dialog">
638
    <div class="modal-dialog modal-lg" role="document" style="width:90%;">
639
        <div class="modal-content">
640
            <div class="modal-header" style="background:#27ae60; color:white;">
641
                <button type="button" class="close" data-dismiss="modal" style="color:white;">&times;</button>
642
                <h4 class="modal-title" id="dataLiveTitle"><img src="${rc.contextPath}/resources/images/Bike-Icon-SD.png" style="height:24px; vertical-align:middle; margin-right:6px;"> Live Tracking</h4>
643
            </div>
644
            <div class="modal-body" style="padding:0;">
645
                <div id="dataLiveInfo" style="padding:8px 15px; background:#f8f9fa; border-bottom:1px solid #ddd; font-size:13px;"></div>
646
                <div id="dataLiveMap" style="height:500px; width:100%;"></div>
647
            </div>
648
            <div class="modal-footer">
649
                <label style="float:left; margin-top:7px; font-weight:normal; font-size:13px;">
650
                    <input type="checkbox" id="dataAutoRefresh" checked style="margin-right:5px;"> Auto-refresh (30s)
651
                </label>
652
                <button type="button" class="btn btn-primary" id="dataRefreshBtn"><i class="fa fa-refresh"></i> Refresh</button>
653
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
654
            </div>
655
        </div>
656
    </div>
657
</div>