forked from rubyforgood/casa
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdashboard.js
More file actions
593 lines (552 loc) · 19.4 KB
/
dashboard.js
File metadata and controls
593 lines (552 loc) · 19.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
/* global alert */
const { Notifier } = require('./notifier')
let pageNotifier
const defineCaseContactsTable = function () {
$('table#case_contacts').DataTable({
scrollX: true,
searching: true,
processing: true,
serverSide: true,
order: [[2, 'desc']], // Sort by Date column (index 2, after bell and chevron)
ajax: {
url: $('table#case_contacts').data('source'),
type: 'POST',
error: function (xhr, error, code) {
console.error('DataTable error:', error, code)
},
dataType: 'json'
},
columnDefs: [
{ orderable: false, targets: [0, 1, 10] } // Bell, Chevron, and Ellipsis columns not orderable
],
columns: [
{ // Bell icon column (index 0)
data: 'has_followup',
orderable: false,
searchable: false,
render: (data, type, row) => {
return data === 'true'
? '<i class="fas fa-bell"></i>'
: '<i class="fas fa-bell" style="opacity: 0.3;"></i>'
}
},
{ // Chevron icon column (index 1)
data: null,
orderable: false,
searchable: false,
render: () => '<i class="fa-solid fa-chevron-down"></i>'
},
{ // Date column (index 2)
data: 'occurred_at',
name: 'occurred_at',
render: (data) => data || ''
},
{ // Case column (index 3)
data: 'casa_case',
orderable: false,
render: (data) => {
if (!data || !data.id) return ''
const a = document.createElement('a')
a.href = `/casa_cases/${data.id}`
a.textContent = data.case_number
return a.outerHTML
}
},
{ // Relationship (Contact Types) column (index 4)
data: 'contact_types',
orderable: false,
render: (data) => data || ''
},
{ // Medium column (index 5)
data: 'medium_type',
render: (data) => data || ''
},
{ // Created By column (index 6)
data: 'creator',
orderable: false,
render: (data) => {
if (!data) return ''
// Build edit link based on role
let editPath = ''
if (data.role === 'Supervisor') {
editPath = `/supervisors/${data.id}/edit`
} else if (data.role === 'Casa Admin') {
editPath = '/users/edit'
} else {
editPath = `/volunteers/${data.id}/edit`
}
return $('<a>')
.attr('href', editPath)
.attr('data-turbo', 'false')
.text(data.display_name)
.prop('outerHTML')
}
},
{ // Contacted column (index 7)
data: 'contact_made',
orderable: false,
render: (data, type, row) => {
const icon = data === 'true'
? '<i class="lni lni-checkmark-circle" style="color: green;"></i>'
: '<i class="lni lni-cross-circle" style="color: orange;"></i>'
let duration = ''
if (row.duration_minutes) {
const hours = Math.floor(row.duration_minutes / 60)
const minutes = row.duration_minutes % 60
duration = ` (${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')})`
}
return icon + duration
}
},
{ // Topics column (index 8)
data: 'contact_topics',
orderable: false,
render: (data) => data || ''
},
{ // Draft column (index 9)
data: 'is_draft',
orderable: false,
render: (data) => {
return (data === true || data === 'true')
? '<span class="badge badge-pill light-bg text-black" data-testid="draft-badge">Draft</span>'
: ''
}
},
{ // Ellipsis menu column (index 10)
data: null,
orderable: false,
searchable: false,
render: () => '<i class="fas fa-ellipsis-v"></i>'
}
]
})
}
$(() => { // JQuery's callback for the DOM loading
const notificationsElement = $('#notifications')
if (notificationsElement.length && ($('table#case_contacts').length || $('table#casa_cases').length || $('table#volunteers').length || $('table#supervisors').length)) {
pageNotifier = new Notifier(notificationsElement)
}
$.fn.dataTable.ext.search.push(
function (settings, data, dataIndex) {
if (settings.nTable.id !== 'casa-cases') {
return true
}
const statusArray = []
const assignedToVolunteerArray = []
const assignedToMoreThanOneVolunteerArray = []
const assignedToTransitionYouthArray = []
const caseNumberPrefixArray = []
$('.status-options').find('input[type="checkbox"]').each(function () {
if ($(this).is(':checked')) {
statusArray.push($(this).data('value'))
}
})
$('.assigned-to-volunteer-options').find('input[type="checkbox"]').each(function () {
if ($(this).is(':checked')) {
assignedToVolunteerArray.push($(this).data('value'))
}
})
$('.more-than-one-volunteer-options').find('input[type="checkbox"]').each(function () {
if ($(this).is(':checked')) {
assignedToMoreThanOneVolunteerArray.push($(this).data('value'))
}
})
$('.transition-youth-options').find('input[type="checkbox"]').each(function () {
if ($(this).is(':checked')) {
assignedToTransitionYouthArray.push($(this).data('value'))
}
})
$('.case-number-prefix-options').find('input[type="checkbox"]').each(function () {
if ($(this).is(':checked')) {
caseNumberPrefixArray.push($(this).data('value'))
}
})
const possibleCaseNumberPrefixes = ['CINA', 'TPR']
const status = data[3]
const assignedToVolunteer = (data[5] !== '' && data[5].split(',').length >= 1) ? 'Yes' : 'No'
const assignedToMoreThanOneVolunteer = (data[5] !== '' && data[5].split(',').length > 1) ? 'Yes' : 'No'
const assignedToTransitionYouth = data[4]
const caseNumberPrefix = possibleCaseNumberPrefixes.includes(data[0].split('-')[0]) ? data[0].split('-')[0] : 'None'
return statusArray.includes(status) &&
assignedToVolunteerArray.includes(assignedToVolunteer) &&
assignedToMoreThanOneVolunteerArray.includes(assignedToMoreThanOneVolunteer) &&
assignedToTransitionYouthArray.some(filterValue =>
assignedToTransitionYouth.toLowerCase().includes(filterValue.toLowerCase().replace(/[^a-zA-Z]/g, ''))
) &&
caseNumberPrefixArray.includes(caseNumberPrefix)
}
)
const handleAjaxError = e => {
console.error(e)
if (e.responseJSON && e.responseJSON.error) {
alert(e.responseJSON.error)
} else {
const responseErrorMessage = e.response.statusText
? `\n${e.response.statusText}\n`
: ''
alert(`Sorry, try that again?\n${responseErrorMessage}\nIf you're seeing a problem, please fill out the Report A Site Issue
link to the bottom left near your email address.`)
}
}
// Enable all data tables on dashboard but only filter on volunteers table
const editSupervisorPath = id => `/supervisors/${id}/edit`
const editVolunteerPath = id => `/volunteers/${id}/edit`
const impersonateVolunteerPath = id => `/volunteers/${id}/impersonate`
const casaCasePath = id => `/casa_cases/${id}`
const volunteersTable = $('table#volunteers').DataTable({
autoWidth: false,
stateSave: true,
initComplete: function (settings, json) {
this.api().columns().every(function (index) {
const columnVisible = this.visible()
return $('#visibleColumns input[data-column="' + index + '"]').prop('checked', columnVisible)
})
},
stateSaveCallback: function (settings, data) {
$.ajax({
url: '/preference_sets/table_state_update/' + settings.nTable.id + '_table',
data: {
table_state: JSON.stringify(data)
},
dataType: 'json',
type: 'POST',
error: function (jqXHR, textStatus, errorMessage) {
console.error(errorMessage)
pageNotifier.notify('Error while saving preferences', 'error')
}
})
},
stateSaveParams: function (settings, data) {
data.search.search = ''
return data
},
stateLoadCallback: function (settings, callback) {
$.ajax({
url: '/preference_sets/table_state/' + settings.nTable.id + '_table',
dataType: 'json',
type: 'GET',
success: function (json) {
callback(json)
}
})
},
order: [[7, 'desc']],
columns: [
{
data: 'id',
targets: 0,
searchable: false,
orderable: false,
render: (data, type, row, meta) => {
return `
<input type="checkbox" name="supervisor_volunteer[volunteer_ids][]" id="supervisor_volunteer_volunteer_ids_${row.id}" value="${row.id}" class="form-check-input" data-select-all-target="checkbox" data-action="select-all#toggleSingle">
`
}
},
{
name: 'display_name',
render: (data, type, row, meta) => {
return `
<span class="mobile-label">Name</span>
<a href="${editVolunteerPath(row.id)}">
${row.display_name || row.email}
</a>
`
}
},
{
name: 'email',
render: (data, type, row, meta) => row.email
},
{
className: 'supervisor-column',
name: 'supervisor_name',
render: (data, type, row, meta) => {
return row.supervisor.id
? `
<span class="mobile-label">Supervisor</span>
<a href="${editSupervisorPath(row.supervisor.id)}">
${row.supervisor.name}
</a>
`
: ''
}
},
{
name: 'active',
render: (data, type, row, meta) => {
return `
<span class="mobile-label">Status</span>
${row.active === 'true' ? 'Active' : 'Inactive'}
`
},
searchable: false
},
{
name: 'has_transition_aged_youth_cases',
render: (data, type, row, meta) => {
return `
<span class="mobile-label">Assigned to Transitioned Aged Youth</span>
${row.has_transition_aged_youth_cases === 'true' ? 'Yes 🦋' : 'No 🐛'}`
},
searchable: false
},
{
name: 'casa_cases',
render: (data, type, row, meta) => {
const links = row.casa_cases.map(casaCase => {
return `
<a href="${casaCasePath(casaCase.id)}">${casaCase.case_number}</a>
`
})
const caseNumbers = `
<span class="mobile-label">Case Number(s)</span>
${links.join(', ')}
`
return caseNumbers
},
orderable: false
},
{
name: 'most_recent_attempt_occurred_at',
render: (data, type, row, meta) => {
return row.most_recent_attempt.case_id
? `
<span class="mobile-label">Last Attempted Contact</span>
<a href="${casaCasePath(row.most_recent_attempt.case_id)}">
${row.most_recent_attempt.occurred_at}
</a>
`
: 'None ❌'
},
searchable: false
},
{
name: 'contacts_made_in_past_days',
render: (data, type, row, meta) => {
return `
<span class="mobile-label">Contacts</span>
${row.contacts_made_in_past_days}
`
},
searchable: false
},
{
name: 'hours_spent_in_days',
render: (data, type, row, meta) => {
return `
<span class="mobile-label">Hours spent in last 30 days</span>
${row.hours_spent_in_days}
`
},
searchable: false
},
{
name: 'has_any_extra_languages ',
render: (data, type, row, meta) => {
const languages = row.extra_languages.map(x => x.name).join(', ')
return row.extra_languages.length > 0 ? `<span class="language-icon" data-toggle="tooltip" title="${languages}">🌎</span>` : ''
},
searchable: false
},
{
name: 'actions',
orderable: false,
render: (data, type, row, meta) => {
return `
<span class="mobile-label">Actions</span>
<a href="${editVolunteerPath(row.id)}" class="btn btn-primary text-white">
Edit
</a>
<a href="${impersonateVolunteerPath(row.id)}" class="btn btn-secondary text-white">
Impersonate
</a>
`
},
searchable: false
}
],
processing: true,
serverSide: true,
ajax: {
url: $('table#volunteers').data('source'),
type: 'POST',
data: function (d) {
const supervisorOptions = $('.supervisor-options input:checked')
const supervisorFilter = Array.from(supervisorOptions).map(option => option.dataset.value)
const statusOptions = $('.status-options input:checked')
const statusFilter = Array.from(statusOptions).map(option => JSON.parse(option.dataset.value))
const transitionYouthOptions = $('.transition-youth-options input:checked')
const transitionYouthFilter = Array.from(transitionYouthOptions).map(option => JSON.parse(option.dataset.value))
const extraLanguageOptions = $('.extra-language-options input:checked')
const extraLanguageFilter = Array.from(extraLanguageOptions).map(option => JSON.parse(option.dataset.value))
return $.extend({}, d, {
additional_filters: {
supervisor: supervisorFilter,
active: statusFilter,
transition_aged_youth: transitionYouthFilter,
extra_languages: extraLanguageFilter
}
})
},
error: handleAjaxError,
dataType: 'json'
},
drawCallback: function (settings) {
$('[data-toggle=tooltip]').tooltip()
}
})
// Because the table saves state, we have to check/uncheck modal inputs based on what
// columns are visible
volunteersTable.columns().every(function (index) {
const columnVisible = this.visible()
$('#visibleColumns input[data-column="' + index + '"]').prop('checked', columnVisible)
return true
})
// Add Supervisors Table
const supervisorsTable = $('table#supervisors').DataTable({
autoWidth: false,
stateSave: false,
order: [[1, 'asc']], // order by cast contacts
columns: [
{
name: 'display_name',
className: 'min-width',
render: (data, type, row, meta) => {
return `
<a href="${editSupervisorPath(row.id)}">
${row.display_name || row.email}
</a>
`
}
},
{
name: '',
className: 'min-width',
render: (data, type, row, meta) => {
const noContactVolunteers = Number(row.no_attempt_for_two_weeks)
const transitionAgedCaseVolunteers = Number(row.transitions_volunteers)
const activeContactVolunteers = Number(row.volunteer_assignments) - noContactVolunteers
const activeContactElement = activeContactVolunteers
? (
`
<span class="attempted-contact supervisor-stat success-bg text-white pl-${activeContactVolunteers * 15} pr-${activeContactVolunteers * 15}" title="Number of Volunteers attempting contact (within 2 weeks)">
${activeContactVolunteers}
</span>
`
)
: ''
const noContactElement = noContactVolunteers > 0
? (
`
<span class="no-attempted-contact supervisor-stat danger-bg text-white pl-${noContactVolunteers * 15} pr-${noContactVolunteers * 15}" title="Number of Volunteers not attempting contact (within 2 weeks)">
${noContactVolunteers}
</span>
`
)
: ''
let volunteersCounterElement = ''
if (activeContactVolunteers <= 0 && noContactVolunteers <= 0) {
volunteersCounterElement = '<span class="no-volunteers" style="flex-grow: 1">No assigned volunteers</span>'
} else {
volunteersCounterElement = `<span class="supervisor-stat deactive-bg text-black pl-${transitionAgedCaseVolunteers * 15} pr-${transitionAgedCaseVolunteers * 15}" title="Count of Transition Aged Youth">${transitionAgedCaseVolunteers}</span>`
}
return `
<div class="supervisor_case_contact_stats">
${activeContactElement + noContactElement + volunteersCounterElement}
</div>
`
}
},
{
name: 'actions',
orderable: false,
render: (data, type, row, meta) => {
return `
<a href="${editSupervisorPath(row.id)}">
<div class="action">
<button class="text-danger">
<i class="lni lni-pencil-alt"></i>Edit
</button>
</div>
</a>
`
},
searchable: false
}
],
processing: true,
serverSide: true,
ajax: {
url: $('table#supervisors').data('source'),
type: 'POST',
data: function (d) {
const statusOptions = $('.status-options input:checked')
const statusFilter = Array.from(statusOptions).map(option => JSON.parse(option.dataset.value))
return $.extend({}, d, {
additional_filters: {
active: statusFilter
}
})
},
error: handleAjaxError,
dataType: 'json'
},
drawCallback: function (settings) {
$('[data-toggle=tooltip]').tooltip()
},
createdRow: function (row, data, dataIndex, cells) {
row.setAttribute('id', `supervisor-${data.id}-information`)
}
})
const casaCasesTable = $('table#casa-cases').DataTable({
autoWidth: false,
stateSave: false,
columnDefs: [],
language: {
emptyTable: 'No active cases'
}
})
casaCasesTable.columns().every(function (index) {
const columnVisible = this.visible()
if (columnVisible) {
$('#visibleColumns input[data-column="' + index + '"]').prop('checked', true)
} else {
$('#visibleColumns input[data-column="' + index + '"]').prop('checked', false)
}
return true
})
defineCaseContactsTable()
function filterOutUnassignedVolunteers (checked) {
$('.supervisor-options').find('input[type="checkbox"]').not('#unassigned-vol-filter').each(function () {
this.checked = checked
})
}
$('#unassigned-vol-filter').on('click', function () {
if ($('#unassigned-vol-filter').is(':checked')) {
filterOutUnassignedVolunteers(false)
} else {
filterOutUnassignedVolunteers(true)
}
volunteersTable.draw()
})
$('.volunteer-filters input[type="checkbox"]').not('#unassigned-vol-filter').on('click', function () {
volunteersTable.draw()
})
$('.supervisor-filters input[type="checkbox"]').on('click', function () {
supervisorsTable.draw()
})
$('.casa-case-filters input[type="checkbox"]').on('click', function () {
casaCasesTable.draw()
})
$('input.toggle-visibility').on('click', function (e) {
// Get the column API object and toggle the visibility
const column = volunteersTable.column($(this).attr('data-column'))
column.visible(!column.visible())
volunteersTable.columns.adjust().draw()
const caseColumn = casaCasesTable.column($(this).attr('data-column'))
caseColumn.visible(!caseColumn.visible())
casaCasesTable.columns.adjust().draw()
})
})
export { defineCaseContactsTable }