Subversion Repositories SmartDukaan

Rev

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