-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCallLog.php
More file actions
779 lines (691 loc) · 33.1 KB
/
Copy pathCallLog.php
File metadata and controls
779 lines (691 loc) · 33.1 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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
<?php
namespace UWMadison\CallLog;
use ExternalModules\AbstractExternalModule;
use REDCap;
use Project;
use Throwable;
use Piping;
use UWMadison\CallLog\Services\ConfigService;
use UWMadison\CallLog\Services\DateMathService;
use UWMadison\CallLog\Services\CallGeneratorService;
use UWMadison\CallLog\Services\CallQueryService;
use UWMadison\CallLog\Services\InstrumentDeploymentService;
use UWMadison\CallLog\Services\ApiService;
use UWMadison\CallLog\Services\LoggingService;
use UWMadison\CallLog\Services\ReportService;
use UWMadison\CallLog\CallMetadataRepository;
spl_autoload_register(function ($class) {
$prefix = 'UWMadison\\CallLog\\';
$baseDir = __DIR__ . '/src/';
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) return;
$relativeClass = substr($class, $len);
$file = $baseDir . str_replace('\\', '/', $relativeClass) . '.php';
if (file_exists($file)) require_once $file;
});
/**
* DEPENDENCY NOTE:
* REDCap 17.4.0 supplies DataTables v1.13.11.
* This module includes DataTables ColReorder v1.7.0 (js/dataTables.colReorder.min.js & css/colReorder.dataTables.min.css).
* These are manually managed dependencies. If REDCap is upgraded to a version using DataTables 2.0+,
* ColReorder must be manually updated to v2.x to maintain compatibility.
*/
class CallLog extends AbstractExternalModule
{
public array $tabsConfig = [];
private string $instrumentCall = "call_log";
private string $instrumentMeta = "call_log_metadata";
private string $metadataField = "call_metadata";
private int $startedCallGrace = 30;
public function __construct()
{
parent::__construct();
$this->disableUserBasedSettingPermissions();
}
private ?ConfigService $configService = null;
private ?CallMetadataRepository $metadataRepo = null;
private ?DateMathService $dateMathService = null;
private ?CallGeneratorService $generatorService = null;
private ?CallQueryService $queryService = null;
private ?InstrumentDeploymentService $deploymentService = null;
private ?ApiService $apiService = null;
private ?LoggingService $loggingService = null;
public function getConfigService(): ConfigService
{
return $this->configService ??= new ConfigService($this);
}
public function getLoggingService(): LoggingService
{
return $this->loggingService ??= new LoggingService($this);
}
public function getMetadataRepo(): CallMetadataRepository
{
return $this->metadataRepo ??= new CallMetadataRepository();
}
public function getDateMathService(): DateMathService
{
return $this->dateMathService ??= new DateMathService();
}
public function getGeneratorService(): CallGeneratorService
{
return $this->generatorService ??= new CallGeneratorService(
$this,
$this->getConfigService(),
$this->getMetadataRepo(),
$this->getDateMathService(),
$this->getLoggingService()
);
}
public function getQueryService(): CallQueryService
{
return $this->queryService ??= new CallQueryService(
$this,
$this->getConfigService(),
$this->getMetadataRepo()
);
}
public function getDeploymentService(): InstrumentDeploymentService
{
return $this->deploymentService ??= new InstrumentDeploymentService();
}
public function getApiService(): ApiService
{
return $this->apiService ??= new ApiService(
$this,
$this->getConfigService(),
$this->getGeneratorService(),
$this->getMetadataRepo(),
$this->getLoggingService()
);
}
private ?ReportService $reportService = null;
public function getReportService(): ReportService
{
return $this->reportService ??= new ReportService(
$this,
$this->getConfigService(),
$this->getMetadataRepo()
);
}
public function redcap_save_record($project_id, $record, $instrument, $event_id = null, $group_id = null, $survey_hash = null, $response_id = null, $repeat_instance = 1)
{
// Skip call generation evaluation when saving internal module metadata
if ($instrument === $this->instrumentMeta) return;
$project_id = (int)$project_id;
$record = (string)$record;
if ($instrument === $this->instrumentCall) {
$this->syncMetadataWithCallInstances($project_id, $record);
$this->markCallEndedOnSave($project_id, $record, $event_id, $repeat_instance);
}
$this->getGeneratorService()->evaluateAndGenerateForRecord($project_id, $record, $instrument, 'save_record');
}
public function redcap_every_page_top($project_id)
{
if (!defined("USERID") || empty($project_id)) return;
$cfg = $this->getConfigService();
$showCallLogInstrument = $cfg->isSettingEnabled((int)$project_id, 'show_call_log_instrument', false);
$showMetadataInstrument = $cfg->isSettingEnabled((int)$project_id, 'show_metadata_instrument', false);
$hidingCss = [];
if (!$showMetadataInstrument) {
$hidingCss[] = '.rc-form-menu-item[data-form="' . $this->instrumentMeta . '"],
div.formMenuList:has(a[id="form[' . $this->instrumentMeta . ']"]),
div.formMenuList:has(a[href*="page=' . $this->instrumentMeta . '"]),
#event_grid_table tr:has([data-mlm-name="' . $this->instrumentMeta . '"]),
#event_grid_table tr:has(a[href*="page=' . $this->instrumentMeta . '"]),
.sysManTable tr:has([data-mlm-name="' . $this->instrumentMeta . '"]),
#record_status_table tr:has([data-mlm-name="' . $this->instrumentMeta . '"]),
#record_status_table tr:has(a[href*="page=' . $this->instrumentMeta . '"]),
div[id*="repeat_instrument_table"][id*="' . $this->instrumentMeta . '"] { display: none !important; }';
}
if (!$showCallLogInstrument) {
$hidingCss[] = '.rc-form-menu-item[data-form="' . $this->instrumentCall . '"],
div.formMenuList:has(a[id="form[' . $this->instrumentCall . ']"]),
div.formMenuList:has(a[href*="page=' . $this->instrumentCall . '"]),
#event_grid_table tr:has([data-mlm-name="' . $this->instrumentCall . '"]),
#event_grid_table tr:has(a[href*="page=' . $this->instrumentCall . '"]),
.sysManTable tr:has([data-mlm-name="' . $this->instrumentCall . '"]),
#record_status_table tr:has([data-mlm-name="' . $this->instrumentCall . '"]),
#record_status_table tr:has(a[href*="page=' . $this->instrumentCall . '"]),
div[id*="repeat_instrument_table"][id*="' . $this->instrumentCall . '"] { display: none !important; }';
}
if (!empty($hidingCss)) echo "<style id='callLogVisibilityHider'>" . implode("\n", $hidingCss) . "</style>";
$isRelevantPage = $this->isPage('ExternalModules/')
|| $this->isPage('DataEntry/record_home.php')
|| $this->isPage('DataEntry/index.php')
|| $this->isPage('ExternalModules/manager/project.php');
if ($isRelevantPage) {
try {
$this->initGlobal((int)$project_id);
} catch (Throwable $e) {
return;
}
$this->includeJs('js/dayjs.min.js');
$this->includeJs('js/utils.js');
$this->includeJs('js/templates.js');
}
if ($this->isPage('ExternalModules/') && ($_GET['prefix'] ?? '') === 'call_log') {
$page = $_GET['page'] ?? 'index';
if ($page === 'config') {
$this->passArgument('rawConfig', $this->getConfigService()->getRawProjectSettings((int)$project_id));
$this->passArgument('metaInfo', $this->getConfigService()->getProjectMetadataInfo((int)$project_id));
$this->includeCss('css/config.css');
$this->includeCss('css/swal.css');
echo "<script type='text/javascript' src='" . APP_PATH_WEBROOT . "Resources/webpack/css/tinymce/tinymce.min.js'></script>\n";
$this->includeJs('js/config.js', true);
$this->includeJs('js/alpine.min.js', true);
} else {
// Dependency: ColReorder v1.7.0 paired with REDCap built-in DataTables v1.13.11
$this->includeCss('css/colReorder.dataTables.min.css');
$this->includeCss('css/list.css');
$this->includeCss('css/swal.css');
$this->includeJs('js/dataTables.colReorder.min.js', true);
$this->includeJs('js/call_list.js', true);
$this->includeJs('js/alpine.min.js', true);
$this->tabsConfig = $this->getConfigService()->getTabConfig((int)$project_id);
$this->passArgument('tabs', $this->tabsConfig);
$rawSettings = $this->getConfigService()->getRawProjectSettings((int)$project_id);
$this->passArgument('dateTimeFormat', $rawSettings['datetime_format'][0] ?? 'm/d/Y g:i A');
$userSettingsRaw = $this->getUserSetting('user-settings');
$userSettings = (!empty($userSettingsRaw) && is_string($userSettingsRaw))
? json_decode($userSettingsRaw, true)
: (is_array($userSettingsRaw) ? $userSettingsRaw : []);
$this->passArgument('userSettings', $userSettings ?: (object)[]);
}
} elseif ($this->isPage('DataEntry/record_home.php') && !empty($_GET['id'])) {
$this->includeJs('js/record_home_page.js', 'defer');
} elseif ($this->isPage('ExternalModules/manager/project.php') && $project_id) {
$this->includeJs('js/config_modal.js', 'defer');
}
}
public function redcap_data_entry_form($project_id, $record, $instrument)
{
$project_id = (int)$project_id;
$record = (string)$record;
$rawSummary = $this->getConfigService()->getRawProjectSettings($project_id)['call_summary'] ?? [];
$summary = is_array($rawSummary) ? $rawSummary : (!empty($rawSummary) ? [$rawSummary] : []);
$this->passArgument('recentCaller', $this->recentCallStarted($project_id, $record));
$this->includeJs('js/data_entry.js', true);
$rawSettings = $this->getConfigService()->getRawProjectSettings($project_id);
$callNames = [];
$callScripts = [];
$callDurations = [];
$callTemplates = [];
foreach ($rawSettings['call_id'] ?? [] as $i => $cid) {
if (!empty($cid)) {
$callNames[$cid] = $rawSettings['call_name'][$i] ?? $cid;
$script = $rawSettings['call_script'][$i] ?? '';
if (is_array($script)) $script = reset($script);
$duration = $rawSettings['call_expected_duration'][$i] ?? 30;
if (is_array($duration)) $duration = reset($duration);
$callDurations[$cid] = (int)($duration ?: 30);
$callTemplates[$cid] = $rawSettings['call_template'][$i] ?? 'new';
$pipedScript = (string)$script;
if (!empty($pipedScript) && class_exists('Piping')) {
$pipedScript = Piping::replaceVariablesInLabel($pipedScript, $record, null, null, [], false, $project_id);
}
$callScripts[$cid] = $pipedScript;
}
}
$this->passArgument('callNames', $callNames);
$this->passArgument('callScripts', $callScripts);
$this->passArgument('callDurations', $callDurations);
$this->passArgument('callTemplates', $callTemplates);
$rawDateTimeFormat = $rawSettings['datetime_format'][0] ?? ($rawSettings['datetime_format'] ?? 'm/d/Y g:i A');
if (is_array($rawDateTimeFormat)) $rawDateTimeFormat = reset($rawDateTimeFormat);
$this->passArgument('dateTimeFormat', $rawDateTimeFormat ?: 'm/d/Y g:i A');
// Pass event context for client-side call_event_name / call_event population
try {
$proj = new Project($project_id);
$uniqueEventNames = $proj->getUniqueEventNames() ?: [];
$currentEventId = (int)(
(isset($event_id) && $event_id > 0) ? $event_id :
(!empty($_GET['event_id']) ? $_GET['event_id'] : $proj->firstEventId)
);
$currentEventName = (string)($proj->getUniqueEventNames($currentEventId) ?: '');
} catch (Throwable $e) {
$uniqueEventNames = [];
$currentEventId = 0;
$currentEventName = '';
}
$this->passArgument('uniqueEventNames', (object)$uniqueEventNames);
$this->passArgument('currentEventName', $currentEventName);
$this->passArgument('currentEventId', $currentEventId);
$displayNameField = $rawSettings['display_name_field'] ?? '';
if (is_array($displayNameField)) $displayNameField = reset($displayNameField);
$participantName = '';
if (!empty($displayNameField)) {
$recData = REDCap::getData($project_id, 'array', $record, [$displayNameField]);
if (is_array($recData[$record] ?? null)) {
foreach ($recData[$record] as $evData) {
if (is_array($evData) && !empty($evData[$displayNameField])) {
$participantName = (string)$evData[$displayNameField];
break;
}
}
}
}
$this->passArgument('participantName', $participantName);
if (!empty($_GET['call_id'])) {
$callId = (string)$_GET['call_id'];
$metaRepo = $this->getMetadataRepo();
$metaData = $metaRepo->getMetadata($project_id, $record);
if (!isset($metaData[$callId]) || !is_array($metaData[$callId])) {
$metaData[$callId] = ['id' => $callId, 'status' => 'incomplete'];
}
if (empty($metaData[$callId]['name'])) {
$baseId = explode('|', explode('||', $callId)[0])[0];
foreach ($rawSettings['call_id'] ?? [] as $i => $cid) {
if ($cid === $baseId || $cid === $callId) {
$metaData[$callId]['name'] = $rawSettings['call_name'][$i] ?? $callId;
$metaData[$callId]['template'] = $rawSettings['call_template'][$i] ?? 'new';
break;
}
}
}
$user = defined('USERID') ? USERID : '';
$metaData[$callId]['callStarted'] = date("Y-m-d H:i:s");
$metaData[$callId]['callStartedBy'] = $user;
$saved = $metaRepo->saveMetadata($project_id, $record, $metaData);
if ($saved) {
$this->getLoggingService()->logCallStarted($project_id, $record, $callId, $user);
}
}
$cfgService = $this->getConfigService();
$showPhoneBanner = $cfgService->isSettingEnabled($project_id, 'show_phone_banner', true);
$phoneBannerData = [];
if ($showPhoneBanner && !empty($record)) {
try {
$projObj = new Project($project_id);
$phoneFields = [];
foreach ($projObj->metadata as $fName => $fAttr) {
if (strpos($fName, 'phone') !== false || strpos($fName, 'cell') !== false || strpos($fName, 'mobile') !== false) {
$phoneFields[] = $fName;
}
}
if (!empty($phoneFields)) {
$phoneRec = REDCap::getData($project_id, 'array', $record, $phoneFields);
if (is_array($phoneRec[$record] ?? null)) {
foreach ($phoneRec[$record] as $evData) {
if (is_array($evData)) {
foreach ($phoneFields as $pf) {
$numVal = trim((string)($evData[$pf] ?? ''));
if (!empty($numVal) && !isset($phoneBannerData[$pf])) {
$label = $projObj->metadata[$pf]['element_label'] ?? $pf;
$phoneBannerData[$pf] = [
'field' => $pf,
'label' => strip_tags($label),
'number' => $numVal
];
}
}
}
}
}
}
} catch (Throwable $e) {}
}
$this->passArgument('autoCaptureTimestamps', $cfgService->isSettingEnabled($project_id, 'auto_capture_timestamps', true));
$this->passArgument('requireCallOutcome', $cfgService->isSettingEnabled($project_id, 'require_call_outcome', true));
$this->passArgument('showPhoneBanner', $showPhoneBanner);
$this->passArgument('phoneBannerData', array_values($phoneBannerData));
$this->passArgument('enableCallTimer', $cfgService->isSettingEnabled($project_id, 'enable_call_timer', false));
if ($instrument === $this->instrumentCall) {
$this->passArgument('adhoc', $this->getConfigService()->getAdhocTemplateConfig($project_id));
$this->passArgument('callListUrl', $this->getUrl('index.php'));
$this->passArgument('recordId', (string)$record);
$this->includeJs('js/call_log.js', true);
}
if (in_array($instrument, array_merge($summary, [$this->instrumentCall]), true)) {
$this->syncMetadataWithCallInstances($project_id, $record);
$metadata = $this->getMetadataRepo()->getMetadata($project_id, $record);
foreach ($metadata as $k => &$item) {
if (is_array($item)) {
$baseId = explode('|', explode('||', $k)[0])[0];
if (empty($item['name'])) {
$item['name'] = $callNames[$baseId] ?? ($callNames[$k] ?? ($item['template'] ?? $k));
}
if (empty($item['template'])) {
$item['template'] = $callTemplates[$baseId]
?? ($callTemplates[$k]
?? (strpos($k, '||') !== false ? 'adhoc' : 'new'));
}
if (!isset($item['instances']) || !is_array($item['instances'])) {
$item['instances'] = [];
}
if (empty($item['status'])) {
$item['status'] = 'incomplete';
}
}
}
unset($item);
$this->passArgument('metadata', $metadata);
$this->passArgument('data', $this->getAllCallData($project_id, $record));
$this->includeCss('css/log.css');
$this->includeCss('css/swal.css');
$this->includeJs('js/call_history.js', true);
}
}
public function redcap_module_ajax($action, $payload, $project_id, $record)
{
return $this->getApiService()->handleAjaxRequest(
(string)$action,
is_array($payload) ? $payload : [],
(int)$project_id,
(string)($record ?: '')
);
}
public function redcap_module_api($action, $payload, $project_id, $user_id, $template_id)
{
$projectId = (int)$project_id;
$payload['action'] = $action;
$payload['user_id'] = $user_id;
return $this->getApiService()->handleApiRequest($projectId, $payload);
}
public function cronTemporalLifecycle($cronInfo): string
{
$projects = $this->getProjectsWithModuleEnabled();
$totalChanged = 0;
foreach ($projects as $projectId) {
$totalChanged += $this->getGeneratorService()->evaluateTemporalLifecyclesForProject((int)$projectId);
}
return "Temporal lifecycle cron completed successfully. Processed updates for " . count($projects) . " projects.";
}
public function cronDailySync($cronInfo): string
{
$projects = $this->getProjectsWithModuleEnabled();
$totalGenerated = 0;
foreach ($projects as $projectId) {
$totalGenerated += $this->getGeneratorService()->evaluateAndGenerateForProject((int)$projectId, 'cron_daily');
}
return "Daily sync cron completed successfully. Processed calls for " . count($projects) . " projects.";
}
// Backward-compatibility aliases for REDCap scheduled cron registry
public function cronGenerateAllCalls($cronInfo): string
{
return $this->cronDailySync($cronInfo);
}
public function cronNewEntry($cronInfo): string
{
return $this->cronTemporalLifecycle($cronInfo);
}
private function initGlobal(int $projectId): void
{
$this->initializeJavascriptModuleObject();
$callEvent = $this->getMetadataRepo()->getEventOfInstrument($projectId, $this->instrumentCall);
$metaEvent = $this->getMetadataRepo()->getEventOfInstrument($projectId, $this->instrumentMeta);
$username = $this->getUser()->getUsername();
$cfg = $this->getConfigService();
$showRecordHomeButton = $cfg->isSettingEnabled($projectId, 'show_record_home_button', true);
$showCallLogInstrument = $cfg->isSettingEnabled($projectId, 'show_call_log_instrument', false);
$showMetadataInstrument = $cfg->isSettingEnabled($projectId, 'show_metadata_instrument', false);
$data = json_encode([
"eventNameMap" => $this->getConfigService()->getEventNameMap($projectId),
"prefix" => $this->getPrefix(),
"user" => $username,
"userNameMap" => $this->getUserNameMap($projectId),
"format" => $this->getUserDateFormat($username),
"dateTimeFormat" => $this->getConfigService()->getRawProjectSettings($projectId)['datetime_format'][0] ?? 'm/d/Y g:i A',
"static" => [
"instrument" => $this->instrumentCall,
"instrumentMeta" => $this->instrumentMeta,
"instrumentEvent" => $callEvent,
"metaEvent" => $metaEvent,
"record_id" => REDCap::getRecordIdField()
],
"workflow" => [
"showRecordHomeButton" => $showRecordHomeButton,
"showCallLogInstrument" => $showCallLogInstrument,
"showMetadataInstrument" => $showMetadataInstrument
],
"configError" => !($callEvent && $metaEvent)
]);
echo "<script>Object.assign({$this->getJavascriptModuleObjectName()}, {$data});</script>";
}
public function parseTimeTo24(?string $time): string
{
return $this->getDateMathService()->parseTimeTo24($time);
}
/**
* Synchronizes metadata with all logged call instances for the record.
* Ensures every metadata entry has an 'instances' array and 'status' string,
* merges instance numbers from saved call logs, and marks complete if call_outcome was 1.
*/
public function syncMetadataWithCallInstances(int $projectId, string $record, ?array &$metadata = null): bool
{
$metadataRepo = $this->getMetadataRepo();
$passedRef = ($metadata !== null);
if ($metadata === null) {
$metadata = $metadataRepo->getMetadata($projectId, $record);
}
$allCallData = $this->getAllCallData($projectId, $record);
$changed = false;
$rawSettings = $this->getConfigService()->getRawProjectSettings($projectId);
$callNames = [];
$callTemplates = [];
foreach ($rawSettings['call_id'] ?? [] as $i => $cid) {
if (!empty($cid)) {
$callNames[$cid] = $rawSettings['call_name'][$i] ?? $cid;
$callTemplates[$cid] = $rawSettings['call_template'][$i] ?? 'new';
}
}
// Map existing call instances by call_id
$instancesByCallId = [];
$completeByCallId = [];
foreach ($allCallData as $instId => $instData) {
$callId = trim((string)($instData['call_id'] ?? ''));
if ($callId === '') continue;
$instNum = (int)$instId;
if ($instNum > 0) {
$instancesByCallId[$callId][] = $instNum;
}
$outcome = (string)($instData['call_outcome'] ?? '');
if ($outcome === '1') {
$completeByCallId[$callId] = true;
}
}
// 1. Ensure all existing metadata entries have required fields and sync instances/status
foreach ($metadata as $callId => &$item) {
if (!is_array($item)) continue;
if (empty($item['id'])) {
$item['id'] = (string)$callId;
$changed = true;
}
if (!isset($item['instances']) || !is_array($item['instances'])) {
$item['instances'] = [];
$changed = true;
}
if (empty($item['status'])) {
$item['status'] = 'incomplete';
$changed = true;
}
// Sync instances from logged calls
if (isset($instancesByCallId[$callId])) {
$merged = array_values(array_unique(array_merge($item['instances'], $instancesByCallId[$callId])));
sort($merged, SORT_NUMERIC);
if ($merged !== $item['instances']) {
$item['instances'] = $merged;
$changed = true;
}
}
// Sync complete status if logged call outcome was completed
if (!empty($completeByCallId[$callId]) && $item['status'] !== 'complete') {
$item['status'] = 'complete';
$changed = true;
}
}
unset($item);
// 2. Add any calls that have logged instances but were missing from metadata
foreach ($instancesByCallId as $callId => $instList) {
if (!isset($metadata[$callId])) {
$baseId = explode('|', explode('||', $callId)[0])[0];
$merged = array_values(array_unique($instList));
sort($merged, SORT_NUMERIC);
$metadata[$callId] = [
'id' => $callId,
'name' => $callNames[$baseId] ?? ($callNames[$callId] ?? (strpos($callId, '||') !== false ? 'Adhoc Call' : $callId)),
'template' => $callTemplates[$baseId] ?? ($callTemplates[$callId] ?? (strpos($callId, '||') !== false ? 'adhoc' : 'new')),
'event_id' => strpos($callId, '|') !== false && strpos($callId, '||') === false ? (explode('|', $callId)[1] ?? '') : '',
'instances' => $merged,
'voiceMails' => 0,
'hideAfterAttempt' => 9999,
'status' => !empty($completeByCallId[$callId]) ? 'complete' : 'incomplete',
'load' => date('Y-m-d H:i')
];
$changed = true;
}
}
if ($changed) {
$metadataRepo->saveMetadata($projectId, $record, $metadata);
}
return $changed;
}
public function markCallEndedOnSave(int $projectId, string $record, $eventId = null, $repeatInstance = 1): void
{
$metaRepo = $this->getMetadataRepo();
$metadata = $metaRepo->getMetadata($projectId, $record);
if (empty($metadata)) {
return;
}
$user = defined('USERID') ? USERID : '';
$callId = '';
if (!empty($_POST['call_id'])) {
$callId = trim((string)$_POST['call_id']);
} elseif (!empty($_GET['call_id'])) {
$callId = trim((string)$_GET['call_id']);
}
if (empty($callId)) {
$callEvent = $eventId ?: $metaRepo->getEventOfInstrument($projectId, $this->instrumentCall);
$data = REDCap::getData($projectId, 'array', $record, ['call_id'], $callEvent);
$callId = trim((string)($data[$record]['repeat_instances'][$callEvent][$this->instrumentCall][$repeatInstance]['call_id']
?? ($data[$record][$callEvent]['call_id'] ?? '')));
}
$changed = false;
$endedCallId = '';
if (!empty($callId)) {
$targetKey = isset($metadata[$callId]) ? $callId : null;
if (!$targetKey) {
foreach ($metadata as $k => $v) {
if ($k === $callId || ($v['id'] ?? '') === $callId || strpos($k, $callId . '|') === 0 || strpos($callId, $k . '|') === 0) {
$targetKey = $k;
break;
}
}
}
if ($targetKey && isset($metadata[$targetKey])) {
if (!empty($metadata[$targetKey]['callStarted']) || !empty($metadata[$targetKey]['callStartedBy'])) {
$metadata[$targetKey]['callStarted'] = '';
$metadata[$targetKey]['callStartedBy'] = '';
$changed = true;
$endedCallId = (string)$targetKey;
}
}
}
if (!empty($user)) {
foreach ($metadata as $k => &$item) {
if (is_array($item) && ($item['callStartedBy'] ?? '') === $user && !empty($item['callStarted'])) {
$item['callStarted'] = '';
$item['callStartedBy'] = '';
$changed = true;
if (empty($endedCallId)) {
$endedCallId = (string)$k;
}
}
}
unset($item);
}
// Safety fallback: if user or specific call was not matched, clear any active ongoing call on this record
if (!$changed) {
foreach ($metadata as $k => &$item) {
if (is_array($item) && !empty($item['callStarted'])) {
$item['callStarted'] = '';
$item['callStartedBy'] = '';
$changed = true;
if (empty($endedCallId)) {
$endedCallId = (string)$k;
}
}
}
unset($item);
}
if ($changed) {
$metaRepo->saveMetadata($projectId, $record, $metadata);
if (!empty($endedCallId)) {
$this->getLoggingService()->logCallEnded($projectId, $record, $endedCallId, $user);
}
}
}
private function getAllCallData(int $projectId, string $record): array
{
$event = $this->getMetadataRepo()->getEventOfInstrument($projectId, $this->instrumentCall);
$data = REDCap::getData($projectId, 'array', $record, null, $event);
$callData = $data[$record]['repeat_instances'][$event][$this->instrumentCall] ?? [];
return empty($callData) ? [1 => ($data[$record][$event] ?? [])] : $callData;
}
private function recentCallStarted(int $projectId, string $record): string
{
$meta = $this->getMetadataRepo()->getMetadata($projectId, $record);
if (empty($meta)) return '';
try {
$userObj = $this->getUser();
$user = $userObj ? $userObj->getUsername() : (defined('USERID') ? USERID : '');
} catch (Throwable $e) {
$user = defined('USERID') ? USERID : '';
}
foreach ($meta as $call) {
if (
(($call['status'] ?? '') !== 'complete') &&
(($call['callStartedBy'] ?? '') !== $user) &&
!empty($call['callStarted']) &&
((time() - strtotime($call['callStarted'])) / 60 < $this->startedCallGrace)
) {
return $call['callStartedBy'];
}
}
return '';
}
public function getUserNameMap(int $projectId): array
{
$map = [];
$sql = "
SELECT u.username, u.full_name FROM redcap_user_rights ur
LEFT JOIN (SELECT
lower(trim(i.username)) AS username,
trim(concat(i.user_firstname, ' ', i.user_lastname)) AS full_name
FROM redcap_user_information i
WHERE i.username != '') u ON ur.username = u.username
WHERE project_id = ?";
$result = $this->query($sql, [$projectId]);
while ($row = $result->fetch_assoc()) {
$map[$row['username']] = $row['full_name'];
}
return $map;
}
private function getUserDateFormat(string $username): array
{
$sql = "SELECT datetime_format FROM redcap_user_information WHERE username = ?";
$result = $this->query($sql, [$username]);
$row = $result->fetch_assoc();
$format = $row['datetime_format'] ?? 'Y-M-D_24';
[$date, $time] = array_pad(explode('_', $format), 2, '24');
$time = $time === '12' ? 'hh:mma' : 'HH:mm';
$date = str_replace(['Y', 'M', 'D'], ['y', 'MM', 'dd'], $date);
return [
'date' => $date,
'dateTime' => "{$date} {$time}"
];
}
public function includeJs(string $path, bool $defer = false, bool $module = false): void
{
$defer = $defer ? "defer " : "";
$module = $module ? "type=\"module\" " : "";
echo '<script ' . $module . $defer . 'src="' . $this->getUrl($path) . '"></script>';
}
public function includeCss(string $path): void
{
echo '<link rel="stylesheet" href="' . $this->getUrl($path) . '"/>';
}
private function passArgument(string $name, $value): void
{
echo "<script>" . $this->getJavascriptModuleObjectName() . "." . $name . " = " . json_encode($value) . ";</script>";
}
}