Subversion Repositories SmartDukaan

Rev

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