Subversion Repositories SmartDukaan

Rev

Rev 36736 | Rev 36783 | 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>
36761 ranu 14
            <th>Beat</th>
15
            <th>Day</th>
16
            <th>Planned</th>
36709 vikas 17
            <th>Punch In/Out</th>
36645 vikas 18
            <th>Total Visits</th>
19
            <th>Completed Visits</th>
20
            <th>Pending Visits</th>
21
            <th>Deferred</th>
36761 ranu 22
            <th>Action</th>
36645 vikas 23
        </tr>
24
        </thead>
25
        <tbody>
26
        #set($rowIndex = 0)
27
        #foreach($row in $reportRows)
28
            <tr>
29
                <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>
36761 ranu 30
                #set($userBeats = $row.get("beats"))
31
                #if($userBeats && $userBeats.size() > 0)
32
                    <td>
33
                        #foreach($b in $userBeats)
34
                            <span style="display:inline-block;width:8px;height:8px;border-radius:2px;background:#if($b.get(
35
                                'beatColor'))$b.get('beatColor')#else#3498db#end;margin-right:5px;"></span>$b.get(
36
                            "beatName")<br>
37
                        #end
38
                    </td>
39
                    <td>
40
                        #foreach($b in $userBeats)
41
                            $b.get("dayNumber")<br>
42
                        #end
43
                    </td>
44
                    <td>
45
                        #foreach($b in $userBeats)
46
                            <strong>$b.get("totalCount")</strong><br>
47
                        #end
48
                    </td>
49
                #else
50
                    <td colspan="3" style="color:#999; text-align:center; font-style:italic;">No beat scheduled</td>
51
                #end
36709 vikas 52
                <td>
53
                    #if($row.get("punchInTime") != "")<span class="label label-success">$row.get("punchInTime")</span>#else<span style="color:#ccc;">--</span>#end
54
                    #if($row.get("punchOutTime") != "")<span class="label label-danger">$row.get("punchOutTime")</span>#else<span style="color:#ccc;">--</span>#end
55
                </td>
36645 vikas 56
                <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>
57
                <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>
58
                <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>
59
                <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>
36761 ranu 60
                <td style="white-space:nowrap;">
61
                    <a href="javascript:void(0);" class="beat-map-link" data-row="$rowIndex" title="Map"
62
                       style="cursor:pointer; margin-right:6px;"><i class="fa fa-map-marker"
63
                                                                    style="color:#1abc9c; font-size:18px;"></i></a>
64
                    #if($userBeats && $userBeats.size() > 0)
65
                        #foreach($b in $userBeats)
66
                            <button class="btn btn-xs btn-info beat-view-calendar" title="View Calendar"
67
                                    data-userid="$b.get('authUserId')"
68
                                    data-username="$row.get('username').replace('"', '\"')"><i class="fa fa-eye"></i>
69
                            </button>
70
                            <button class="btn btn-xs btn-warning beat-edit-on-date" title="Edit Beat"
71
                                    data-userid="$b.get('authUserId')"
72
                                    data-username="$row.get('username').replace('"', '\"')"
73
                                    data-beatid="$b.get('beatId')"
74
                                    data-date="$b.get('scheduleDate')"><i class="fa fa-edit"></i></button>
75
                            <button class="btn btn-xs btn-success beat-assign-visit" title="Assign Visit"
76
                                    data-userid="$b.get('authUserId')"
77
                                    data-username="$row.get('username').replace('"', '\"')"
78
                                    data-beatid="$b.get('beatId')"
79
                                    data-date="$b.get('scheduleDate')"><i class="fa fa-plus-circle"></i></button>
80
                            <br>
81
                        #end
82
                    #end
83
                </td>
36645 vikas 84
            </tr>
85
 
86
            <script>
87
                window.beatReportData = window.beatReportData || {};
88
                window.beatReportData[$rowIndex] = {
89
                    username: "$row.get('username').replace('"', '\"')",
90
                    total: [
91
                        #foreach($lt in $row.get("totalList"))
92
                        { 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()" },
93
                        #end
94
                    ],
95
                    completed: [
96
                        #foreach($lt in $row.get("completedList"))
97
                        { 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()" },
98
                        #end
99
                    ],
100
                    pending: [
101
                        #foreach($lt in $row.get("pendingList"))
102
                        { 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()" },
103
                        #end
104
                    ],
105
                    deferred: [
106
                        #foreach($lt in $row.get("deferredList"))
107
                        { 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()" },
108
                        #end
109
                    ]
110
                };
111
            </script>
112
            #set($rowIndex = $rowIndex + 1)
113
        #end
114
        </tbody>
115
    </table>
116
</div>
117
 
118
<!-- Map Modal -->
119
<div class="modal fade" id="beatMapModal" tabindex="-1" role="dialog">
120
    <div class="modal-dialog modal-lg" role="document" style="width:90%;">
121
        <div class="modal-content">
122
            <div class="modal-header" style="background:#1abc9c; color:white;">
123
                <button type="button" class="close" data-dismiss="modal" style="color:white;">&times;</button>
124
                <h4 class="modal-title" id="beatMapModalTitle">Visit Locations</h4>
125
            </div>
126
            <div class="modal-body" style="padding:0;">
127
                <div id="beatMapContainer" style="height:500px; width:100%;"></div>
128
                <div id="beatMapInfo" style="padding:6px 15px; background:#fff3cd; border-top:1px solid #ddd; color:#856404; display:none;"></div>
129
                <div style="padding:8px 15px; background:#f5f5f5; border-top:1px solid #ddd;">
130
                    <span style="margin-right:15px;"><i class="fa fa-circle" style="color:#4285F4;"></i> Check In</span>
131
                    <span style="margin-right:15px;"><i class="fa fa-circle" style="color:#0F9D58;"></i> Completed</span>
132
                    <span style="margin-right:15px;"><i class="fa fa-circle" style="color:#F4B400;"></i> Pending</span>
133
                    <span><i class="fa fa-circle" style="color:#DB4437;"></i> Deferred</span>
134
                </div>
135
            </div>
136
            <div class="modal-footer">
137
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
138
            </div>
139
        </div>
140
    </div>
141
</div>
142
 
143
<!-- Detail Popup Modal -->
144
<div class="modal fade" id="beatDetailModal" tabindex="-1" role="dialog">
145
    <div class="modal-dialog modal-lg" role="document">
146
        <div class="modal-content">
147
            <div class="modal-header" style="background:#1abc9c; color:white;">
148
                <button type="button" class="close" data-dismiss="modal" style="color:white;">&times;</button>
149
                <h4 class="modal-title" id="beatDetailModalTitle">Visit Details</h4>
150
            </div>
151
            <div class="modal-body">
152
                <table class="table table-bordered table-condensed table-striped" id="beatDetailTable" style="width:100%">
153
                    <thead>
154
                    <tr>
155
                        <th>#</th>
36669 vikas 156
                        <th>Agenda/Partner Name</th>
36645 vikas 157
                        <th>Type</th>
158
                        <th>Status</th>
159
                        <th>Address</th>
160
                        <th>Check In</th>
161
                        <th>Check Out</th>
162
                        <th>Time Spent</th>
163
                        <th>Description</th>
36736 ranu 164
                        <th>ETA</th>
36645 vikas 165
                        <th>Attachment</th>
166
                    </tr>
167
                    </thead>
168
                    <tbody id="beatDetailTableBody"></tbody>
169
                </table>
170
            </div>
171
            <div class="modal-footer">
172
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
173
            </div>
174
        </div>
175
    </div>
176
</div>
177
 
178
<script>
179
    $('#beatReportTable').DataTable({
180
        "scrollX": true,
36685 vikas 181
        "pageLength": 50,
36645 vikas 182
        "bPaginate": true,
183
        "bLengthChange": true,
184
        "bFilter": true,
185
        "bInfo": true,
186
        "bAutoWidth": false
187
    });
188
 
189
    var beatMapMarkerColors = {
190
        'PENDING': '#F4B400',
191
        'DEFERRED': '#DB4437',
192
        'CHECKIN': '#4285F4',
193
        'CHECKIN-CHECKOUT': '#0F9D58',
194
        'CHECKOUT': '#0F9D58'
195
    };
196
 
197
    function getMarkerColor(markType) {
198
        return beatMapMarkerColors[markType] || '#999999';
199
    }
200
 
201
    function createColoredMarkerIcon(color, label) {
202
        var svg = '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="42" viewBox="0 0 32 42">' +
203
            '<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 + '"/>' +
204
            '<circle cx="16" cy="15" r="10" fill="white"/>' +
205
            '<text x="16" y="20" text-anchor="middle" font-size="12" font-weight="bold" fill="' + color + '">' + label + '</text>' +
206
            '</svg>';
207
        return 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg);
208
    }
209
 
210
    function getLatLng(item) {
211
        var loc = item.visitLocation || item.checkInLatLng || '';
212
        if (!loc || loc === '0.0000,0.0000') return null;
213
        var parts = loc.split(',');
214
        if (parts.length !== 2) return null;
215
        var lat = parseFloat(parts[0].trim());
216
        var lng = parseFloat(parts[1].trim());
217
        if (isNaN(lat) || isNaN(lng) || (lat === 0 && lng === 0)) return null;
218
        return { lat: lat, lng: lng };
219
    }
220
 
221
    $(document).on('click', '.beat-map-link', function () {
222
        var rowIndex = $(this).data('row');
223
        var data = window.beatReportData[rowIndex];
224
        if (!data) return;
225
 
226
        var items = data.total || [];
227
        var username = data.username;
228
        $('#beatMapModalTitle').text(username + ' - Visit Locations (' + items.length + ')');
229
 
230
        if (typeof google === 'undefined' || !google.maps) {
231
            alert('Google Maps is still loading. Please try again in a moment.');
232
            return;
233
        }
234
 
235
        $('#beatMapModal').modal('show');
236
 
237
        setTimeout(function () {
238
            var mapDiv = document.getElementById('beatMapContainer');
239
            var bounds = new google.maps.LatLngBounds();
240
            var hasMarkers = false;
241
 
242
            var map = new google.maps.Map(mapDiv, {
243
                zoom: 10,
244
                center: { lat: 20.5937, lng: 78.9629 },
245
                mapTypeId: 'roadmap'
246
            });
247
 
248
            var infoWindow = new google.maps.InfoWindow();
249
 
250
            for (var i = 0; i < items.length; i++) {
251
                var item = items[i];
252
                var pos = getLatLng(item);
253
                if (!pos) continue;
254
 
255
                hasMarkers = true;
256
                bounds.extend(pos);
257
 
258
                var color = getMarkerColor(item.markType);
259
                var marker = new google.maps.Marker({
260
                    position: pos,
261
                    map: map,
262
                    title: item.taskName || item.markType,
263
                    icon: {
264
                        url: createColoredMarkerIcon(color, (i + 1)),
265
                        scaledSize: new google.maps.Size(32, 42),
266
                        anchor: new google.maps.Point(16, 42)
267
                    }
268
                });
269
 
270
                (function (m, itm, idx) {
271
                    google.maps.event.addListener(m, 'click', function () {
272
                        var content = '<div style="min-width:200px;">' +
273
                            '<strong>' + (idx + 1) + '. ' + (itm.taskName || '--') + '</strong><br>' +
274
                            '<b>Status:</b> ' + (itm.markType || '--') + '<br>' +
275
                            '<b>Address:</b> ' + (itm.address || '--') + '<br>' +
276
                            '<b>Check In:</b> ' + (itm.checkInTime || '--') + '<br>' +
277
                            '<b>Check Out:</b> ' + (itm.checkOutTime || '--') + '<br>' +
278
                            '<b>Time Spent:</b> ' + (itm.timeSpent || '--') +
279
                            '</div>';
280
                        infoWindow.setContent(content);
281
                        infoWindow.open(map, m);
282
                    });
283
                })(marker, item, i);
284
            }
285
 
286
            var markerCount = 0;
287
            for (var j = 0; j < items.length; j++) { if (getLatLng(items[j])) markerCount++; }
288
 
289
            var infoDiv = document.getElementById('beatMapInfo');
290
            if (markerCount < items.length) {
291
                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.';
292
                infoDiv.style.display = 'block';
293
            } else {
294
                infoDiv.style.display = 'none';
295
            }
296
 
297
            if (hasMarkers) {
298
                map.fitBounds(bounds);
299
                if (markerCount === 1) {
300
                    map.setZoom(14);
301
                }
302
            }
303
        }, 400);
304
    });
305
 
306
    $(document).on('click', '.beat-detail-link', function () {
307
        var rowIndex = $(this).data('row');
308
        var type = $(this).data('type');
309
        var data = window.beatReportData[rowIndex];
310
        if (!data) return;
311
 
312
        var items = data[type] || [];
313
        var username = data.username;
314
 
315
        var typeLabel = type.charAt(0).toUpperCase() + type.slice(1);
316
        $('#beatDetailModalTitle').text(username + ' - ' + typeLabel + ' Visits (' + items.length + ')');
317
 
318
        var tbody = '';
319
        for (var i = 0; i < items.length; i++) {
320
            var item = items[i];
321
            tbody += '<tr>' +
322
                '<td>' + (i + 1) + '</td>' +
323
                '<td>' + (item.taskName || '--') + '</td>' +
324
                '<td>' + (item.taskType || '--') + '</td>' +
325
                '<td>' + (item.markType || '--') + '</td>' +
326
                '<td>' + (item.address || '--') + '</td>' +
327
                '<td>' + (item.checkInTime || '--') + '</td>' +
328
                '<td>' + (item.checkOutTime || '--') + '</td>' +
329
                '<td>' + (item.timeSpent || '--') + '</td>' +
330
                '<td>' + (item.taskDescription || '--') + '</td>' +
36666 vikas 331
                '<td>' + (item.estimatedTime || '--') + '</td>' +
36645 vikas 332
                '<td>' + (item.attachment ? '<a href="https://partners.smartdukaan.com/document/' + item.attachment + '" target="_blank"><i class="fa fa-paperclip"></i> View</a>' : '--') + '</td>' +
333
                '</tr>';
334
        }
335
        if (items.length === 0) {
336
            tbody = '<tr><td colspan="10" class="text-center">No records found</td></tr>';
337
        }
338
        $('#beatDetailTableBody').html(tbody);
339
        $('#beatDetailModal').modal('show');
340
    });
36693 vikas 341
 
36696 vikas 342
    // --- Live Tracking ---
343
    var dataLiveMap = null;
344
    var dataLiveUserId = null;
345
    var dataLiveUsername = '';
346
    var dataLiveInterval = null;
347
 
348
    function dataGetMarkerColor(markType) {
349
        if (markType === 'CHECKIN-CHECKOUT' || markType === 'CHECKOUT') return '#0F9D58';
350
        if (markType === 'PENDING' || markType === 'CHECKIN') return '#4285F4';
351
        if (markType === 'DEFERRED') return '#DB4437';
352
        if (markType === 'PUNCHIN') return '#1abc9c';
353
        if (markType === 'PUNCHOUT') return '#e74c3c';
354
        return '#F4B400';
355
    }
356
 
357
    function dataCreateMarkerIcon(color, label) {
358
        var svg = '<svg xmlns="http://www.w3.org/2000/svg" width="28" height="40" viewBox="0 0 28 40">' +
359
            '<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 + '"/>' +
360
            '<circle cx="14" cy="14" r="7" fill="white"/>' +
361
            '<text x="14" y="18" text-anchor="middle" font-size="10" font-weight="bold" fill="' + color + '">' + label + '</text></svg>';
362
        return 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg);
363
    }
364
 
365
    function dataFormatEpoch(ts) {
366
        if (!ts) return 'N/A';
367
        var n = parseFloat(ts);
368
        if (isNaN(n)) return ts;
369
        if (n < 1e12) n = n * 1000;
370
        var d = new Date(n);
371
        return d.getHours().toString().padStart(2,'0') + ':' + d.getMinutes().toString().padStart(2,'0') + ':' + d.getSeconds().toString().padStart(2,'0');
372
    }
373
 
374
    function dataFormatDuration(ms) {
375
        var sec = Math.floor(ms / 1000);
376
        var h = Math.floor(sec / 3600);
377
        var m = Math.floor((sec % 3600) / 60);
378
        var s = sec % 60;
379
        if (h > 0) return h + 'h ' + m + 'm';
380
        if (m > 0) return m + 'm ' + s + 's';
381
        return s + 's';
382
    }
383
 
384
    function dataHaversine(lat1, lon1, lat2, lon2) {
385
        var R = 6371000;
386
        var dLat = (lat2 - lat1) * Math.PI / 180;
387
        var dLon = (lon2 - lon1) * Math.PI / 180;
388
        var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
389
                Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
390
                Math.sin(dLon/2) * Math.sin(dLon/2);
391
        return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
392
    }
393
 
394
    function dataDetectStops(points, radiusM, minTimeMs) {
395
        var stops = [];
396
        var i = 0;
397
        while (i < points.length) {
398
            var cluster = [points[i]];
399
            var cLat = points[i].lat, cLng = points[i].lng;
400
            var j = i + 1;
401
            while (j < points.length) {
402
                if (dataHaversine(cLat, cLng, points[j].lat, points[j].lng) <= radiusM) {
403
                    cluster.push(points[j]);
404
                    j++;
405
                } else {
406
                    break;
407
                }
408
            }
409
            if (cluster.length >= 2) {
410
                var t0 = parseFloat(cluster[0].ts);
411
                var t1 = parseFloat(cluster[cluster.length - 1].ts);
412
                if (t0 < 1e12) t0 *= 1000;
413
                if (t1 < 1e12) t1 *= 1000;
414
                var duration = t1 - t0;
415
                if (duration >= minTimeMs) {
416
                    var avgLat = 0, avgLng = 0;
417
                    cluster.forEach(function(p) { avgLat += p.lat; avgLng += p.lng; });
418
                    stops.push({
419
                        lat: avgLat / cluster.length, lng: avgLng / cluster.length,
420
                        startTime: t0, endTime: t1, duration: duration, pointCount: cluster.length
421
                    });
422
                }
423
            }
424
            i = j;
425
        }
426
        return stops;
427
    }
428
 
429
    function dataClearOverlays() {
430
        if (!dataLiveMap) return;
431
        if (dataLiveMap._markers) dataLiveMap._markers.forEach(function(m) { m.setMap(null); });
432
        if (dataLiveMap._polyline) dataLiveMap._polyline.setMap(null);
433
        if (dataLiveMap._gpsDots) dataLiveMap._gpsDots.forEach(function(m) { m.setMap(null); });
434
        if (dataLiveMap._stopMarkers) dataLiveMap._stopMarkers.forEach(function(m) { m.setMap(null); });
435
        if (dataLiveMap._currentMarker) dataLiveMap._currentMarker.setMap(null);
436
        if (dataLiveMap._directionsRenderer) dataLiveMap._directionsRenderer.setMap(null);
437
        dataLiveMap._markers = [];
438
        dataLiveMap._gpsDots = [];
439
        dataLiveMap._stopMarkers = [];
440
    }
441
 
442
    function dataLoadLiveTracking(userId, username) {
443
        var selectedDate = $('#beat-report-date').val();
444
        $.ajax({
445
            url: context + "/beat-report/live-tracking",
446
            type: "GET", dataType: "json",
447
            data: { userId: userId, date: selectedDate },
448
            success: function(data) { dataRenderMap(data, username); },
449
            error: function() { $('#dataLiveInfo').html('<span style="color:red;">Failed to load tracking data.</span>'); }
450
        });
451
    }
452
 
453
    function dataRenderMap(data, username) {
454
        var visits = data.visits || [];
455
        var pathPoints = data.pathPoints || [];
456
 
457
        if (!dataLiveMap) {
458
            dataLiveMap = new google.maps.Map(document.getElementById('dataLiveMap'), {
459
                zoom: 12, center: { lat: 20.5937, lng: 78.9629 },
460
                mapTypeControl: true, streetViewControl: false
461
            });
462
        }
463
        dataClearOverlays();
464
 
465
        var bounds = new google.maps.LatLngBounds();
466
        var hasPoints = false;
467
        var visitIdx = 0;
468
        var visitCoords = [];
469
 
470
        for (var i = 0; i < visits.length; i++) {
471
            var v = visits[i];
472
            if (!v.lat || !v.lng) continue;
473
            var lat = parseFloat(v.lat), lng = parseFloat(v.lng);
474
            if (isNaN(lat) || isNaN(lng) || (lat === 0 && lng === 0)) continue;
475
            hasPoints = true;
476
            var pos = { lat: lat, lng: lng };
477
            bounds.extend(pos);
478
            visitCoords.push(pos);
479
            var label = v.markType === 'PUNCHIN' ? 'P' : (v.markType === 'PUNCHOUT' ? 'X' : String(++visitIdx));
480
            var marker = new google.maps.Marker({
481
                position: pos, map: dataLiveMap,
482
                icon: { url: dataCreateMarkerIcon(dataGetMarkerColor(v.markType), label), scaledSize: new google.maps.Size(28, 40), anchor: new google.maps.Point(14, 40) },
483
                title: v.taskName + ' (' + v.markType + ')', zIndex: 100
484
            });
485
            var infoContent = '<div style="font-size:13px; max-width:280px;">' +
486
                '<strong>' + (v.taskName || '') + '</strong><br>' +
487
                '<span class="label" style="background:' + dataGetMarkerColor(v.markType) + '; color:white;">' + v.markType + '</span>' +
488
                (v.taskType ? ' <span class="label label-default">' + v.taskType + '</span>' : '') + '<br>' +
489
                (v.checkInTime ? '<i class="fa fa-sign-in" style="color:#27ae60;"></i> In: <strong>' + v.checkInTime + '</strong><br>' : '') +
490
                (v.checkOutTime ? '<i class="fa fa-sign-out" style="color:#e74c3c;"></i> Out: <strong>' + v.checkOutTime + '</strong><br>' : '') +
491
                (v.timeSpent ? '<i class="fa fa-clock-o" style="color:#f39c12;"></i> Time Spent: <strong>' + v.timeSpent + '</strong><br>' : '') +
492
                (v.transitTime ? '<i class="fa fa-car" style="color:#3498db;"></i> Transit: <strong>' + v.transitTime + '</strong><br>' : '') +
493
                (v.totalDistance && v.totalDistance !== '0.0' ? '<i class="fa fa-road" style="color:#8e44ad;"></i> Distance: <strong>' + v.totalDistance + ' km</strong><br>' : '') +
494
                (v.address ? '<i class="fa fa-map-marker" style="color:#e74c3c;"></i> ' + v.address : '') + '</div>';
495
            (function(m, c) {
496
                var iw = new google.maps.InfoWindow({ content: c });
497
                m.addListener('click', function() { iw.open(dataLiveMap, m); });
498
            })(marker, infoContent);
499
            dataLiveMap._markers.push(marker);
500
        }
501
 
502
        if (visitCoords.length >= 2) {
503
            var origin = visitCoords[0], destination = visitCoords[visitCoords.length - 1];
504
            var waypoints = [];
505
            for (var wi = 1; wi < visitCoords.length - 1; wi++) waypoints.push({ location: visitCoords[wi], stopover: true });
506
            var ds = new google.maps.DirectionsService();
507
            var dr = new google.maps.DirectionsRenderer({
508
                map: dataLiveMap, suppressMarkers: true,
509
                polylineOptions: { strokeColor: '#8e44ad', strokeOpacity: 0.7, strokeWeight: 4 },
510
                preserveViewport: true
511
            });
512
            dataLiveMap._directionsRenderer = dr;
513
            ds.route({ origin: origin, destination: destination, waypoints: waypoints, travelMode: google.maps.TravelMode.DRIVING, optimizeWaypoints: false },
514
                function(result, status) { if (status === 'OK') dr.setDirections(result); });
515
        }
516
 
517
        var totalGpsDistanceM = 0, accuracySum = 0, accuracyCount = 0, stopsDetected = [];
518
        if (pathPoints.length > 0) {
519
            var validPoints = [];
520
            for (var j = 0; j < pathPoints.length; j++) {
521
                var pt = pathPoints[j];
522
                var pLat = parseFloat(pt.lat), pLng = parseFloat(pt.lng);
523
                if (isNaN(pLat) || isNaN(pLng) || (pLat === 0 && pLng === 0)) continue;
524
                var acc = parseFloat(pt.accuracy);
525
                if (!isNaN(acc)) { accuracySum += acc; accuracyCount++; }
526
                validPoints.push({ lat: pLat, lng: pLng, ts: pt.timestamp, accuracy: pt.accuracy });
527
                bounds.extend({ lat: pLat, lng: pLng });
528
                hasPoints = true;
529
            }
530
            for (var d = 1; d < validPoints.length; d++) {
531
                totalGpsDistanceM += dataHaversine(validPoints[d-1].lat, validPoints[d-1].lng, validPoints[d].lat, validPoints[d].lng);
532
            }
533
            if (validPoints.length > 0) {
534
                var pathCoords = validPoints.map(function(p) { return { lat: p.lat, lng: p.lng }; });
535
                dataLiveMap._polyline = new google.maps.Polyline({
536
                    path: pathCoords, geodesic: true, strokeColor: '#e74c3c', strokeOpacity: 0.7, strokeWeight: 3, zIndex: 50, map: dataLiveMap
537
                });
538
                dataLiveMap._gpsDots = [];
539
                for (var gi = 0; gi < validPoints.length; gi++) {
540
                    var gp = validPoints[gi];
541
                    var heading = 0;
542
                    if (gi < validPoints.length - 1) {
543
                        heading = google.maps.geometry.spherical.computeHeading(
544
                            new google.maps.LatLng(gp.lat, gp.lng), new google.maps.LatLng(validPoints[gi+1].lat, validPoints[gi+1].lng));
545
                    } else if (gi > 0) {
546
                        heading = google.maps.geometry.spherical.computeHeading(
547
                            new google.maps.LatLng(validPoints[gi-1].lat, validPoints[gi-1].lng), new google.maps.LatLng(gp.lat, gp.lng));
548
                    }
549
                    var dot = new google.maps.Marker({
550
                        position: { lat: gp.lat, lng: gp.lng }, map: dataLiveMap,
551
                        icon: { path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW, scale: 3, fillColor: '#e74c3c', fillOpacity: 1, strokeColor: '#b71c1c', strokeWeight: 1, rotation: heading },
552
                        zIndex: 80
553
                    });
554
                    (function(marker, point, idx) {
555
                        var iw = new google.maps.InfoWindow({
556
                            content: '<div style="font-size:12px;"><strong>GPS Point #' + (idx+1) + '</strong><br>' +
557
                                '<i class="fa fa-clock-o"></i> ' + dataFormatEpoch(point.ts) + '<br>' +
558
                                '<i class="fa fa-crosshairs"></i> Accuracy: ' + (point.accuracy || 'N/A') + 'm<br>' +
559
                                '<i class="fa fa-map-marker"></i> ' + point.lat.toFixed(6) + ', ' + point.lng.toFixed(6) + '</div>'
560
                        });
561
                        marker.addListener('click', function() { iw.open(dataLiveMap, marker); });
562
                    })(dot, gp, gi);
563
                    dataLiveMap._gpsDots.push(dot);
564
                }
565
                stopsDetected = dataDetectStops(validPoints, 50, 5 * 60 * 1000);
566
                dataLiveMap._stopMarkers = [];
567
                for (var si = 0; si < stopsDetected.length; si++) {
568
                    var stop = stopsDetected[si];
569
                    var sm = new google.maps.Marker({
570
                        position: { lat: stop.lat, lng: stop.lng }, map: dataLiveMap,
571
                        icon: { path: google.maps.SymbolPath.CIRCLE, scale: 14, fillColor: '#f39c12', fillOpacity: 0.9, strokeColor: '#e67e22', strokeWeight: 2 },
572
                        label: { text: dataFormatDuration(stop.duration), fontSize: '9px', fontWeight: 'bold', color: '#000' },
573
                        title: 'Stopped for ' + dataFormatDuration(stop.duration), zIndex: 200
574
                    });
575
                    (function(marker, s) {
576
                        var iw = new google.maps.InfoWindow({
577
                            content: '<div style="font-size:13px;"><strong><i class="fa fa-pause-circle" style="color:#f39c12;"></i> Stationary Stop</strong><br>' +
578
                                '<i class="fa fa-clock-o"></i> Duration: <strong>' + dataFormatDuration(s.duration) + '</strong><br>' +
579
                                '<i class="fa fa-sign-in"></i> From: <strong>' + new Date(s.startTime).toLocaleTimeString() + '</strong><br>' +
580
                                '<i class="fa fa-sign-out"></i> To: <strong>' + new Date(s.endTime).toLocaleTimeString() + '</strong><br>' +
581
                                '<i class="fa fa-map-marker"></i> ' + s.lat.toFixed(6) + ', ' + s.lng.toFixed(6) + '<br>' +
582
                                '<i class="fa fa-dot-circle-o"></i> Points in cluster: ' + s.pointCount + '</div>'
583
                        });
584
                        marker.addListener('click', function() { iw.open(dataLiveMap, marker); });
585
                    })(sm, stop);
586
                    dataLiveMap._stopMarkers.push(sm);
587
                }
588
                var lastPoint = pathCoords[pathCoords.length - 1];
589
                dataLiveMap._currentMarker = new google.maps.Marker({
590
                    position: lastPoint, map: dataLiveMap,
591
                    icon: { url: '${rc.contextPath}/resources/images/Bike-Icon-SD.png', scaledSize: new google.maps.Size(40, 40), anchor: new google.maps.Point(20, 20) },
592
                    title: 'Last Known Location', zIndex: 999
593
                });
594
                var lastGp = validPoints[validPoints.length - 1];
595
                var curIw = new google.maps.InfoWindow({
596
                    content: '<div style="font-size:13px;"><strong><i class="fa fa-crosshairs" style="color:#27ae60;"></i> Last Known Location</strong><br>' +
597
                        '<i class="fa fa-clock-o"></i> Time: ' + dataFormatEpoch(lastGp.ts) + '<br>' +
598
                        '<i class="fa fa-crosshairs"></i> Accuracy: ' + (lastGp.accuracy || 'N/A') + 'm</div>'
599
                });
600
                dataLiveMap._currentMarker.addListener('click', function() { curIw.open(dataLiveMap, dataLiveMap._currentMarker); });
601
            }
602
        }
603
 
604
        if (hasPoints) dataLiveMap.fitBounds(bounds);
605
 
606
        var totalVisits = visits.filter(function(v) { return v.markType !== 'PUNCHIN' && v.markType !== 'PUNCHOUT'; }).length;
607
        var completedVisits = visits.filter(function(v) { return v.markType === 'CHECKIN-CHECKOUT' || v.markType === 'CHECKOUT'; }).length;
608
        var now = new Date();
609
        var timeStr = now.getHours().toString().padStart(2,'0') + ':' + now.getMinutes().toString().padStart(2,'0') + ':' + now.getSeconds().toString().padStart(2,'0');
610
        var avgAccuracy = accuracyCount > 0 ? (accuracySum / accuracyCount).toFixed(0) : null;
611
        var accuracyLabel = '', accuracyBadge = '';
612
        if (avgAccuracy) {
613
            if (avgAccuracy <= 10) { accuracyLabel = 'High'; accuracyBadge = 'background:#27ae60;'; }
614
            else if (avgAccuracy <= 30) { accuracyLabel = 'Good'; accuracyBadge = 'background:#2ecc71;'; }
615
            else if (avgAccuracy <= 100) { accuracyLabel = 'Average'; accuracyBadge = 'background:#f39c12;'; }
616
            else { accuracyLabel = 'Low'; accuracyBadge = 'background:#e74c3c;'; }
617
        }
618
        var totalGpsKm = (totalGpsDistanceM / 1000).toFixed(2);
619
        var infoHtml = '<strong>' + username + '</strong> | Visits: <strong>' + totalVisits + '</strong> | Completed: <strong>' + completedVisits + '</strong>';
620
        if (pathPoints.length > 0) {
621
            infoHtml += ' | GPS Distance: <strong>' + totalGpsKm + ' km</strong>';
622
            infoHtml += ' | Points: <strong>' + pathPoints.length + '</strong>';
623
            if (accuracyLabel) infoHtml += ' | Accuracy: <span class="label" style="' + accuracyBadge + ' color:white; padding:2px 8px; border-radius:3px; font-size:11px;">' + accuracyLabel + '</span> (' + avgAccuracy + 'm)';
624
            if (stopsDetected.length > 0) infoHtml += ' | <span style="color:#f39c12;"><i class="fa fa-pause-circle"></i></span> Stops: <strong>' + stopsDetected.length + '</strong>';
625
            infoHtml += ' | <img src="${rc.contextPath}/resources/images/Bike-Icon-SD.png" style="height:16px; vertical-align:middle;"> Last Known';
626
        } else {
627
            infoHtml += ' | <span style="color:#999;"><i class="fa fa-exclamation-triangle"></i> No GPS data yet</span>';
628
        }
629
        infoHtml += ' | <span style="color:#e74c3c;"><i class="fa fa-arrow-right" style="font-size:10px;"></i></span> GPS Trail';
630
        if (visitCoords.length > 1) infoHtml += ' | <span style="background:#8e44ad; display:inline-block; width:14px; height:3px; vertical-align:middle; margin:0 2px;"></span> Route';
631
        var locToggle = data.locationToggleCount || 0;
632
        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>';
633
        infoHtml += ' | <span style="color:#999;">Updated: ' + timeStr + '</span>';
634
        $('#dataLiveInfo').html(infoHtml);
635
        if (pathPoints.length > 0 && pathPoints.length < 10) {
636
            $('#dataLiveInfo').append(
637
                '<div style="margin-top:4px; padding:4px 8px; background:#fff3cd; border:1px solid #ffc107; border-radius:3px; font-size:11px; color:#856404;">' +
638
                '<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>');
639
        }
640
    }
641
 
642
    function dataStartAutoRefresh() {
643
        dataStopAutoRefresh();
644
        if ($('#dataAutoRefresh').is(':checked') && dataLiveUserId) {
645
            dataLiveInterval = setInterval(function() { dataLoadLiveTracking(dataLiveUserId, dataLiveUsername); }, 30000);
646
        }
647
    }
648
    function dataStopAutoRefresh() {
649
        if (dataLiveInterval) { clearInterval(dataLiveInterval); dataLiveInterval = null; }
650
    }
651
 
652
    $(document).on('click', '.data-live-tracking-btn', function() {
653
        dataLiveUserId = $(this).data('userid');
654
        dataLiveUsername = $(this).data('username');
655
        $('#dataLiveTitle').html('<img src="${rc.contextPath}/resources/images/Bike-Icon-SD.png" style="height:24px; vertical-align:middle; margin-right:6px;"> Live Tracking - ' + dataLiveUsername);
656
        $('#dataLiveInfo').html('<div class="text-center"><i class="fa fa-spinner fa-spin"></i> Loading...</div>');
657
        $('#dataLiveModal').modal('show');
658
        setTimeout(function() {
659
            dataLiveMap = null;
660
            if (window.google && window.google.maps) {
661
                dataLoadLiveTracking(dataLiveUserId, dataLiveUsername);
662
                dataStartAutoRefresh();
663
            } else {
664
                var s = document.createElement('script');
665
                s.src = 'https://maps.googleapis.com/maps/api/js?key=AIzaSyAckO0y4Z6WhBOuMjNjioWLSYZDhGEvGBc&libraries=geometry&v=weekly';
666
                s.onload = function() { dataLoadLiveTracking(dataLiveUserId, dataLiveUsername); dataStartAutoRefresh(); };
667
                document.head.appendChild(s);
668
            }
669
        }, 300);
670
    });
671
 
672
    $(document).on('click', '#dataRefreshBtn', function() {
673
        if (dataLiveUserId) {
674
            $('#dataLiveInfo').html('<div class="text-center"><i class="fa fa-spinner fa-spin"></i> Refreshing...</div>');
675
            dataLoadLiveTracking(dataLiveUserId, dataLiveUsername);
676
        }
677
    });
678
    $(document).on('change', '#dataAutoRefresh', function() {
679
        $(this).is(':checked') ? dataStartAutoRefresh() : dataStopAutoRefresh();
680
    });
681
    $('#dataLiveModal').on('hidden.bs.modal', function() { dataStopAutoRefresh(); dataLiveUserId = null; });
36645 vikas 682
</script>
36696 vikas 683
 
684
<!-- Live Tracking Modal -->
685
<div class="modal fade" id="dataLiveModal" tabindex="-1" role="dialog">
686
    <div class="modal-dialog modal-lg" role="document" style="width:90%;">
687
        <div class="modal-content">
688
            <div class="modal-header" style="background:#27ae60; color:white;">
689
                <button type="button" class="close" data-dismiss="modal" style="color:white;">&times;</button>
690
                <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>
691
            </div>
692
            <div class="modal-body" style="padding:0;">
693
                <div id="dataLiveInfo" style="padding:8px 15px; background:#f8f9fa; border-bottom:1px solid #ddd; font-size:13px;"></div>
694
                <div id="dataLiveMap" style="height:500px; width:100%;"></div>
695
            </div>
696
            <div class="modal-footer">
697
                <label style="float:left; margin-top:7px; font-weight:normal; font-size:13px;">
698
                    <input type="checkbox" id="dataAutoRefresh" checked style="margin-right:5px;"> Auto-refresh (30s)
699
                </label>
700
                <button type="button" class="btn btn-primary" id="dataRefreshBtn"><i class="fa fa-refresh"></i> Refresh</button>
701
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
702
            </div>
703
        </div>
704
    </div>
705
</div>
36761 ranu 706
 
707
<!-- Beat calendar modal (iframe loads /beatPlanWindow with auto-selected user) -->
708
<div class="modal fade" id="reportBeatCalendarModal" tabindex="-1" style="overflow-y:auto;">
709
    <div class="modal-dialog" style="width:95%; max-width:1300px; margin-top:20px;">
710
        <div class="modal-content">
711
            <div class="modal-header">
712
                <button type="button" class="close" data-dismiss="modal"
713
                        onclick="$('#reportBeatCalendarFrame').attr('src','');">&times;
714
                </button>
715
                <h4 class="modal-title" id="reportBeatCalendarTitle">Calendar</h4>
716
            </div>
717
            <div class="modal-body" style="padding:0;">
718
                <iframe id="reportBeatCalendarFrame" style="width:100%; height:80vh; border:none;"></iframe>
719
            </div>
720
        </div>
721
    </div>
722
</div>
723
 
724
<script>
725
    $(document).on('click', '.beat-view-calendar', function () {
726
        var userId = $(this).data('userid');
727
        var userName = $(this).data('username') || '';
728
        var url = context + '/beatPlanWindow?autoUserId=' + userId
729
                + '&autoUserName=' + encodeURIComponent(userName);
730
        $('#reportBeatCalendarTitle').text('Calendar - ' + userName);
731
        $('#reportBeatCalendarFrame').attr('src', url);
732
        $('#reportBeatCalendarModal').modal('show');
733
    });
734
 
735
    $(document).on('click', '.beat-edit-on-date', function () {
736
        var userId = $(this).data('userid');
737
        var userName = $(this).data('username') || '';
738
        var beatId = $(this).data('beatid');
739
        var date = $(this).data('date');
740
        var url = context + '/beatPlanWindow?autoUserId=' + userId
741
                + '&autoUserName=' + encodeURIComponent(userName)
742
                + '&editBeatId=' + beatId + '&editDate=' + date;
743
        $('#reportBeatCalendarTitle').text('Edit Beat - ' + userName + ' on ' + date);
744
        $('#reportBeatCalendarFrame').attr('src', url);
745
        $('#reportBeatCalendarModal').modal('show');
746
    });
747
 
748
    // ---------- ASSIGN VISIT (mirrors Beat Day View; IDs/classes prefixed with `r` to avoid collisions) ----------
749
    var rAvContext = {authUserId: null, userName: '', date: '', beatId: null, allParties: [], agendaOptions: []};
750
 
751
    var R_AGENDA_MULTISELECT_OPTS = {
752
        includeSelectAllOption: false,
753
        maxHeight: 220,
754
        buttonWidth: '240px',
755
        numberDisplayed: 2,
756
        nonSelectedText: 'Pick agenda(s)',
757
        nSelectedText: ' agendas',
758
        allSelectedText: 'All agendas',
759
        enableFiltering: true,
760
        enableCaseInsensitiveFiltering: true
761
    };
762
 
763
    function rAgendaSelectHtml(p) {
764
        var preset = {};
765
        (p.existingAgendas || []).forEach(function (a) {
766
            preset[a] = true;
767
        });
768
        var html = '<select multiple class="r-av-party-agenda" data-fofoid="' + p.fofoStoreId + '">';
769
        rAvContext.agendaOptions.forEach(function (opt) {
770
            html += '<option value="' + opt + '"' + (preset[opt] ? ' selected' : '') + '>' + opt + '</option>';
771
        });
772
        html += '</select>';
773
        return html;
774
    }
775
 
776
    function rRebuildDefaultAgenda() {
777
        var $sel = $('#rAvDefaultAgenda');
778
        try {
779
                $sel.multiselect('destroy');
780
        } catch (e) {
781
        }
782
        var html = '';
783
        rAvContext.agendaOptions.forEach(function (opt) {
784
            html += '<option value="' + opt + '">' + opt + '</option>';
785
        });
786
            $sel.html(html);
787
        var defaultOpts = $.extend({}, R_AGENDA_MULTISELECT_OPTS);
788
        defaultOpts.nonSelectedText = 'Pick agenda(s) to apply';
789
            $sel.multiselect(defaultOpts);
790
    }
791
 
792
    function rInitRowMultiselects() {
793
        $('.r-av-party-agenda').each(function () {
794
            var $sel = $(this);
795
            try {
796
                    $sel.multiselect('destroy');
797
            } catch (e) {
798
            }
799
                $sel.multiselect(R_AGENDA_MULTISELECT_OPTS);
800
        });
801
    }
802
 
803
    function rUpdateAvSelectedCount() {
804
        var n = $('.r-av-party-chk:checked').length;
805
        $('#rAvSelectedCount').text(n + ' selected');
806
        $('#rAvSubmit').prop('disabled', n === 0);
807
    }
808
 
809
    function rRenderAvParties(list) {
810
        if (!list || list.length === 0) {
811
            $('#rAvPartyList').html('<div style="padding:20px; color:#999; text-align:center;">No parties found.</div>');
812
            return;
813
        }
814
        var html = '<table class="table table-condensed table-hover" style="margin-bottom:0; font-size:13px;">';
815
        html += '<thead><tr>'
816
                + '<th style="width:30px;"><input type="checkbox" id="rAvSelectAll" title="Select all"></th>'
817
                + '<th>Code</th><th>Outlet</th><th>City</th>'
818
                + '<th style="width:260px;">Agenda</th>'
819
                + '<th style="width:260px;">Description</th>'
820
                + '</tr></thead><tbody>';
821
        list.forEach(function (p) {
822
            var safeName = (p.outletName || '').replace(/"/g, '&quot;');
823
            var existingDesc = (p.existingDescription || '').replace(/"/g, '&quot;');
824
            html += '<tr>'
825
                    + '<td><input type="checkbox" class="r-av-party-chk" '
826
                    + 'data-fofoid="' + p.fofoStoreId + '" '
827
                    + 'data-name="' + safeName + '" '
828
                    + 'data-lat="' + (p.latitude || '') + '" '
829
                    + 'data-lng="' + (p.longitude || '') + '"></td>'
830
                    + '<td>' + (p.code || '') + '</td>'
831
                    + '<td>' + (p.outletName || '') + '</td>'
832
                    + '<td>' + (p.city || '') + '</td>'
833
                    + '<td>' + rAgendaSelectHtml(p) + '</td>'
834
                    + '<td><textarea class="form-control input-sm r-av-party-desc"'
835
                    + ' data-fofoid="' + p.fofoStoreId + '"'
836
                    + ' rows="2" placeholder="Optional notes..."'
837
                    + ' style="resize:vertical; min-height:34px;">' + existingDesc + '</textarea></td>'
838
                    + '</tr>';
839
        });
840
        html += '</tbody></table>';
841
        $('#rAvPartyList').html(html);
842
        rInitRowMultiselects();
843
        rUpdateAvSelectedCount();
844
    }
845
 
846
    $(document).on('click', '.beat-assign-visit', function () {
847
        rAvContext.authUserId = $(this).data('userid');
848
        rAvContext.userName = $(this).data('username') || '';
849
        rAvContext.date = $(this).data('date');
850
        rAvContext.beatId = $(this).data('beatid');
851
        rAvContext.allParties = [];
852
 
853
        $('#rAvTitle').text('Assign Visit - ' + rAvContext.userName + ' on ' + rAvContext.date);
854
        $('#rAvSearch').val('');
855
        $('#rAvPartyList').html('<div style="padding:20px; color:#999; text-align:center;">Loading parties...</div>');
856
        $('#rAvMsg').text('');
857
        $('#rAvSelectedCount').text('0 selected');
858
        $('#rAvSubmit').prop('disabled', true);
859
        $('#rAssignVisitModal').modal('show');
860
 
861
        $.get(context + '/beatPlan/assignVisit/parties', {
862
            authUserId: rAvContext.authUserId,
863
            date: rAvContext.date,
864
            beatId: rAvContext.beatId
865
        }).done(function (r) {
866
            var data = r.response || r;
867
            rAvContext.allParties = (data.parties || []).filter(function (p) {
868
                return !p.inBeat;
869
            });
870
            rAvContext.agendaOptions = data.agendaOptions || [];
871
            if (!data.dtrUserId) {
872
                $('#rAvPartyList').html('<div style="padding:20px; color:#c62828; text-align:center;">'
873
                        + 'This user has no dtr.users record (cannot create visit tasks).</div>');
874
                return;
875
            }
876
            rRebuildDefaultAgenda();
877
            rRenderAvParties(rAvContext.allParties);
878
        }).fail(function (xhr) {
879
            $('#rAvPartyList').html('<div style="padding:20px; color:#c62828; text-align:center;">'
880
                    + 'Error loading parties: ' + (xhr.responseText || xhr.statusText) + '</div>');
881
        });
882
    });
883
 
884
    $(document).on('input', '#rAvSearch', function () {
885
        var q = $(this).val().toLowerCase().trim();
886
        if (!q) {
887
            rRenderAvParties(rAvContext.allParties);
888
            return;
889
        }
890
        var filtered = rAvContext.allParties.filter(function (p) {
891
            return (p.code || '').toLowerCase().indexOf(q) !== -1
892
                    || (p.outletName || '').toLowerCase().indexOf(q) !== -1
893
                    || (p.city || '').toLowerCase().indexOf(q) !== -1;
894
        });
895
        rRenderAvParties(filtered);
896
    });
897
 
898
    $(document).on('change', '#rAvSelectAll', function () {
899
        $('.r-av-party-chk').prop('checked', this.checked);
900
        rUpdateAvSelectedCount();
901
    });
902
    $(document).on('change', '.r-av-party-chk', rUpdateAvSelectedCount);
903
 
904
    $(document).on('click', '#rAvApplyAgenda', function () {
905
        var defValues = $('#rAvDefaultAgenda').val() || [];
906
        if (defValues.length === 0) {
907
            alert('Pick at least one agenda above first');
908
            return;
909
        }
910
        $('.r-av-party-chk:checked').each(function () {
911
            var fid = $(this).data('fofoid');
912
            var $sel = $('.r-av-party-agenda[data-fofoid="' + fid + '"]');
913
            var existing = $sel.val() || [];
914
            var merged = existing.slice();
915
            defValues.forEach(function (v) {
916
                if (merged.indexOf(v) === -1) merged.push(v);
917
            });
918
                $sel.val(merged);
919
            try {
920
                    $sel.multiselect('refresh');
921
            } catch (e) {
922
            }
923
        });
924
    });
925
 
926
    $(document).on('click', '#rAvSubmit', function () {
927
        var picks = [];
928
        var missing = 0;
929
        $('.r-av-party-chk:checked').each(function () {
930
            var fid = parseInt($(this).data('fofoid'));
931
            var agendas = $('.r-av-party-agenda[data-fofoid="' + fid + '"]').val() || [];
932
            var description = ($('.r-av-party-desc[data-fofoid="' + fid + '"]').val() || '').trim();
933
            if (agendas.length === 0) missing++;
934
            picks.push({
935
                fofoStoreId: fid,
936
                outletName: $(this).data('name'),
937
                latitude: $(this).data('lat') ? String($(this).data('lat')) : null,
938
                longitude: $(this).data('lng') ? String($(this).data('lng')) : null,
939
                agendas: agendas,
940
                description: description
941
            });
942
        });
943
        if (picks.length === 0) return;
944
        if (missing > 0) {
945
            if (!confirm(missing + ' selected row(s) have no agenda. Submit anyway with default "Visit"?')) return;
946
        }
947
        var btn = $(this);
948
        btn.prop('disabled', true).text('Assigning...');
949
        $('#rAvMsg').text('');
950
        $.ajax({
951
            url: context + '/beatPlan/assignVisit/submit',
952
            type: 'POST',
953
            contentType: 'application/json',
954
            data: JSON.stringify({
955
                authUserId: rAvContext.authUserId,
956
                planDate: rAvContext.date,
957
                parties: picks
958
            }),
959
            success: function (r) {
960
                var d = r.response || r;
961
                $('#rAvMsg').html('<span style="color:#2e7d32;">' + (d.message || 'Saved') + '</span>');
962
                btn.prop('disabled', false).text('Save Assignments');
963
                setTimeout(function () {
964
                    $('#rAssignVisitModal').modal('hide');
965
                }, 1500);
966
            },
967
            error: function (xhr) {
968
                var msg = 'Failed';
969
                try {
970
                    msg = (JSON.parse(xhr.responseText).response.message) || msg;
971
                } catch (e) {
972
                }
973
                $('#rAvMsg').html('<span style="color:#c62828;">' + msg + '</span>');
974
                btn.prop('disabled', false).text('Save Assignments');
975
            }
976
        });
977
    });
978
</script>
979
 
980
<!-- Assign Visit Modal (mirrors Beat Day View; prefixed IDs to avoid collisions) -->
981
<div class="modal fade" id="rAssignVisitModal" tabindex="-1" style="overflow-y:auto;">
982
    <div class="modal-dialog" style="width:90%; max-width:900px; margin-top:30px;">
983
        <div class="modal-content">
984
            <div class="modal-header">
985
                <button type="button" class="close" data-dismiss="modal">&times;</button>
986
                <h4 class="modal-title" id="rAvTitle">Assign Visit</h4>
987
            </div>
988
            <div class="modal-body">
989
                <div style="display:flex; gap:10px; align-items:flex-start; margin-bottom:10px;">
990
                    <div style="flex:1;">
991
                        <label style="font-size:11px; color:#666; font-weight:normal; margin-bottom:2px;">
992
                            Agenda - applies to selected rows
993
                        </label>
994
                        <select id="rAvDefaultAgenda" multiple></select>
995
                    </div>
996
                    <button type="button" class="btn btn-default btn-sm" id="rAvApplyAgenda" style="margin-top:18px;"
997
                            title="Add the picked agendas into all selected rows (merges with existing)">
998
                        Apply to Selected
999
                    </button>
1000
                </div>
1001
                <div style="display:flex; gap:10px; align-items:center; margin-bottom:10px;">
1002
                    <input type="text" id="rAvSearch" class="form-control input-sm"
1003
                           placeholder="Search by code, outlet name or city..." style="flex:1;">
1004
                    <span id="rAvSelectedCount" style="font-size:12px; color:#666;">0 selected</span>
1005
                </div>
1006
                <div id="rAvPartyList"
1007
                     style="max-height:50vh; overflow-y:auto; border:1px solid #e5e5e5; border-radius:4px;"></div>
1008
                <div id="rAvMsg" style="margin-top:10px; font-size:12px;"></div>
1009
            </div>
1010
            <div class="modal-footer">
1011
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
1012
                <button type="button" class="btn btn-success" id="rAvSubmit" disabled>Save Assignments</button>
1013
            </div>
1014
        </div>
1015
    </div>
1016
</div>