-
-
Notifications
You must be signed in to change notification settings - Fork 824
/
Copy pathCase.php
3183 lines (2839 loc) · 110 KB
/
Case.php
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
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC. All rights reserved. |
| |
| This work is published under the GNU AGPLv3 license with some |
| permitted exceptions and without any warranty. For full license |
| and copyright information, see https://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC https://civicrm.org/licensing
*/
use Civi\Api4\Activity;
/**
* This class contains the functions for Case Management.
*/
class CRM_Case_BAO_Case extends CRM_Case_DAO_Case implements \Civi\Core\HookInterface {
/**
* Static field for all the case information that we can potentially export.
*
* @var array
*/
public static $_exportableFields = NULL;
/**
* Is CiviCase enabled?
* @deprecated
* @return bool
*/
public static function enabled() {
CRM_Core_Error::deprecatedFunctionWarning('isComponentEnabled');
return CRM_Core_Component::isEnabled('CiviCase');
}
/**
* Create a case object.
*
* The function extracts all the params it needs to initialize the create a
* case object. the params array could contain additional unused name/value
* pairs
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
*
* @return CRM_Case_DAO_Case
*/
public static function add(&$params) {
$caseDAO = new CRM_Case_DAO_Case();
$caseDAO->copyValues($params);
$result = $caseDAO->save();
// Get other case values (required by XML processor), this adds to $result array
$caseDAO->find(TRUE);
return $result;
}
/**
* @param \Civi\Core\Event\PostEvent $e
*/
public static function on_hook_civicrm_post(\Civi\Core\Event\PostEvent $e): void {
// FIXME: The EventScanner ought to skip over disabled components when registering HookInterface
if (!CRM_Core_Component::isEnabled('CiviCase')) {
return;
}
if ($e->entity === 'Activity' && in_array($e->action, ['create', 'edit'])) {
/** @var CRM_Activity_DAO_Activity $activity */
$activity = $e->object;
$params = $e->params;
// If subject contains a ‘[case #…]’ string, file activity on the related case (CRM-5916)
$matches = [];
if (!isset($params['case_id'])) {
$subjectToMatch = $activity->subject ?? '';
if (preg_match('/\[case #([0-9a-h]{7})\]/', $subjectToMatch, $matches)) {
$key = CRM_Core_DAO::escapeString(CIVICRM_SITE_KEY);
$query = "SELECT id FROM civicrm_case WHERE SUBSTR(SHA1(CONCAT('$key', id)), 1, 7) = %1";
}
elseif (preg_match('/\[case #(\d+)\]/', $subjectToMatch, $matches)) {
$query = "SELECT id FROM civicrm_case WHERE id = %1";
}
}
if (!empty($matches)) {
$params['case_id'] = CRM_Core_DAO::singleValueQuery($query, [1 => [$matches[1], 'String']]) ?: NULL;
if (!$params['case_id']) {
CRM_Activity_BAO_Activity::logActivityAction($activity, "Case details for {$matches[1]} not found while recording an activity on case.");
}
}
// Add CaseActivity record (or remove if $params['case_id'] is falsey)
if (isset($params['case_id'])) {
CRM_Case_BAO_Case::updateCaseActivity($activity->id, $params['case_id']);
}
}
if ($e->entity === 'RelationshipType') {
CRM_Case_XMLProcessor::flushStaticCaches();
}
}
/**
* Takes an associative array and creates a case object.
*
* @param array $params
* (reference) an assoc array of name/value pairs.
*
* @return CRM_Case_DAO_Case
*/
public static function &create(&$params) {
// CRM-20958 - These fields are managed by MySQL triggers. Watch out for clients resaving stale timestamps.
unset($params['created_date']);
unset($params['modified_date']);
$caseStatus = CRM_Case_PseudoConstant::caseStatus('name');
// for resolved case the end date should set to now
if (!empty($params['status_id']) && $params['status_id'] == array_search('Closed', $caseStatus)) {
$params['end_date'] = date("Ymd");
}
$transaction = new CRM_Core_Transaction();
if (!empty($params['id'])) {
CRM_Utils_Hook::pre('edit', 'Case', $params['id'], $params);
}
else {
CRM_Utils_Hook::pre('create', 'Case', NULL, $params);
}
$case = self::add($params);
if (!empty($params['custom']) &&
is_array($params['custom'])
) {
CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_case', $case->id);
}
if (is_a($case, 'CRM_Core_Error')) {
$transaction->rollback();
return $case;
}
if (!empty($params['id'])) {
CRM_Utils_Hook::post('edit', 'Case', $case->id, $case);
}
else {
CRM_Utils_Hook::post('create', 'Case', $case->id, $case);
}
$transaction->commit();
//we are not creating log for case
//since case log can be tracked using log for activity.
return $case;
}
/**
* Add a CaseActivity record (skip if already exists).
*
* @param array{activity_id: int, case_id: int} $params
*/
public static function processCaseActivity(array $params): void {
$caseActivityDAO = new CRM_Case_DAO_CaseActivity();
$caseActivityDAO->activity_id = $params['activity_id'];
$caseActivityDAO->case_id = $params['case_id'];
$caseActivityDAO->find(TRUE);
$caseActivityDAO->save();
}
/**
* Associate an activity with 0 or more cases.
*
* @param int $activityId
* @param array|int $caseIds
*/
public static function updateCaseActivity(int $activityId, $caseIds): void {
$actionName = empty($caseIds) ? 'delete' : 'replace';
$action = \Civi\Api4\CaseActivity::$actionName(FALSE)
->addWhere('activity_id', '=', $activityId);
if (!empty($caseIds)) {
foreach ((array) $caseIds as $caseId) {
$action->addRecord(['case_id' => $caseId]);
}
}
$action->execute();
}
/**
* Get the case subject for Activity.
*
* @param int $activityId
* Activity id.
*
* @return string|null
*/
public static function getCaseSubject($activityId) {
$caseActivity = new CRM_Case_DAO_CaseActivity();
$caseActivity->activity_id = $activityId;
if ($caseActivity->find(TRUE)) {
return CRM_Core_DAO::getFieldValue('CRM_Case_BAO_Case', $caseActivity->case_id, 'subject');
}
return NULL;
}
/**
* Get the case type.
*
* @param int $caseId
* @param string $colName
*
* @return string
* case type
*/
public static function getCaseType($caseId, $colName = 'title') {
$query = "
SELECT civicrm_case_type.{$colName} FROM civicrm_case
LEFT JOIN civicrm_case_type ON
civicrm_case.case_type_id = civicrm_case_type.id
WHERE civicrm_case.id = %1";
$queryParams = [1 => [$caseId, 'Integer']];
return CRM_Core_DAO::singleValueQuery($query, $queryParams);
}
/**
* Delete the record that are associated with this case.
* record are deleted from case
*
* @param int $caseId
* Id of the case to delete.
*
* @param bool $moveToTrash
*
* @return bool
* is successful
*/
public static function deleteCase($caseId, $moveToTrash = FALSE) {
CRM_Utils_Hook::pre('delete', 'Case', $caseId);
//delete activities
$activities = self::getCaseActivityDates($caseId);
if ($activities) {
foreach ($activities as $value) {
CRM_Activity_BAO_Activity::deleteActivity($value, $moveToTrash);
}
}
if (!$moveToTrash) {
$transaction = new CRM_Core_Transaction();
}
$case = new CRM_Case_DAO_Case();
$case->id = $caseId;
if (!$moveToTrash) {
$result = $case->delete();
$transaction->commit();
}
else {
$result = $case->is_deleted = 1;
$case->save();
}
if ($result) {
// CRM-7364, disable relationships
self::enableDisableCaseRelationships($caseId, FALSE);
CRM_Utils_Hook::post('delete', 'Case', $caseId, $case);
return TRUE;
}
return FALSE;
}
/**
* @param int $id
* @return bool
*/
public static function del($id) {
return self::deleteCase($id);
}
/**
* Enable disable case related relationships.
*
* @param int $caseId
* Case id.
* @param bool $enable
* Action.
*/
public static function enableDisableCaseRelationships($caseId, $enable) {
$contactIds = self::retrieveContactIdsByCaseId($caseId);
if (!empty($contactIds)) {
foreach ($contactIds as $cid) {
$roles = self::getCaseRoles($cid, $caseId);
if (!empty($roles)) {
$relationshipIds = implode(',', array_keys($roles));
$enable = (int) $enable;
$query = "UPDATE civicrm_relationship SET is_active = {$enable}
WHERE id IN ( {$relationshipIds} )";
CRM_Core_DAO::executeQuery($query);
}
}
}
}
/**
* Retrieve contact_id by case_id.
*
* @param int $caseId
* ID of the case.
*
* @param int $contactID
* @param int $startArrayAt This is to support legacy calls to Case.Get API which may rely on the first array index being set to 1
*
* @return array
*/
public static function retrieveContactIdsByCaseId($caseId, $contactID = NULL, $startArrayAt = 0) {
$caseContact = new CRM_Case_DAO_CaseContact();
$caseContact->case_id = $caseId;
$caseContact->find();
$contactArray = [];
$count = $startArrayAt;
while ($caseContact->fetch()) {
if ($contactID != $caseContact->contact_id) {
$contactArray[$count] = $caseContact->contact_id;
$count++;
}
}
return $contactArray;
}
/**
* Look up a case using an activity ID.
*
* @param int $activityId
* @param bool $getSingle
*
* @return array|int|null
*/
public static function getCaseIdByActivityId($activityId, $getSingle = TRUE) {
$originalId = CRM_Core_DAO::singleValueQuery(
'SELECT original_id FROM civicrm_activity WHERE id = %1',
['1' => [$activityId, 'Integer']]
);
$caseIds = [];
$query = CRM_Core_DAO::executeQuery(
'SELECT case_id FROM civicrm_case_activity WHERE activity_id in (%1,%2)',
[
'1' => [$activityId, 'Integer'],
'2' => [$originalId ?: $activityId, 'Integer'],
]
);
while ($query->fetch()) {
$caseIds[] = $query->case_id;
}
return $getSingle ? CRM_Utils_Array::first($caseIds) : $caseIds;
}
/**
* Retrieve contact names by caseId.
*
* @param int $caseId
* ID of the case.
*
* @return array
*/
public static function getContactNames($caseId) {
$contactNames = [];
if (!$caseId) {
return $contactNames;
}
$query = "
SELECT contact_a.sort_name name,
contact_a.display_name as display_name,
contact_a.id cid,
contact_a.birth_date as birth_date,
ce.email as email,
cp.phone as phone
FROM civicrm_contact contact_a
LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
LEFT JOIN civicrm_email ce ON ( ce.contact_id = contact_a.id AND ce.is_primary = 1)
LEFT JOIN civicrm_phone cp ON ( cp.contact_id = contact_a.id AND cp.is_primary = 1)
WHERE contact_a.is_deleted = 0 AND civicrm_case_contact.case_id = %1
ORDER BY civicrm_case_contact.id";
$dao = CRM_Core_DAO::executeQuery($query,
[1 => [$caseId, 'Integer']]
);
while ($dao->fetch()) {
$contactNames[$dao->cid]['contact_id'] = $dao->cid;
$contactNames[$dao->cid]['sort_name'] = $dao->name;
$contactNames[$dao->cid]['display_name'] = $dao->display_name;
$contactNames[$dao->cid]['email'] = $dao->email;
$contactNames[$dao->cid]['phone'] = $dao->phone;
$contactNames[$dao->cid]['birth_date'] = $dao->birth_date;
$contactNames[$dao->cid]['role'] = ts('Client');
}
return $contactNames;
}
/**
* Retrieve case_id by contact_id.
*
* @param int $contactID
* @param bool $includeDeleted
* Include the deleted cases in result.
* @param null $caseType
*
* @return array
*/
public static function retrieveCaseIdsByContactId($contactID, $includeDeleted = FALSE, $caseType = NULL) {
$query = "
SELECT ca.id as id
FROM civicrm_case_contact cc
INNER JOIN civicrm_case ca ON cc.case_id = ca.id
";
if (isset($caseType)) {
$query .=
"INNER JOIN civicrm_case_type ON civicrm_case_type.id = ca.case_type_id
WHERE cc.contact_id = %1 AND civicrm_case_type.name = '{$caseType}'";
}
if (!isset($caseType)) {
$query .= "WHERE cc.contact_id = %1";
}
if (!$includeDeleted) {
$query .= " AND ca.is_deleted = 0";
}
$params = [1 => [$contactID, 'Integer']];
$dao = CRM_Core_DAO::executeQuery($query, $params);
$caseArray = [];
while ($dao->fetch()) {
$caseArray[] = $dao->id;
}
return $caseArray;
}
/**
* @param string $type
* @param int $userID
* @param string $condition
*
* @return string
*/
public static function getCaseActivityCountQuery($type, $userID, $condition = NULL) {
return sprintf(" SELECT COUNT(*) FROM (%s) temp ", self::getCaseActivityQuery($type, $userID, $condition));
}
/**
* @param string $type
* @param int $userID
* @param string $condition
* @param string $limit
* @param string $order
*
* @return string
*/
public static function getCaseActivityQuery($type, $userID, $condition = NULL, $limit = NULL, $order = NULL) {
$selectClauses = [
'civicrm_case.id as case_id',
'civicrm_case.subject as case_subject',
'civicrm_contact.id as contact_id',
'civicrm_contact.sort_name as sort_name',
'civicrm_phone.phone as phone',
'civicrm_contact.contact_type as contact_type',
'civicrm_contact.contact_sub_type as contact_sub_type',
't_act.activity_type_id as activity_type_id',
'civicrm_case.case_type_id as case_type_id',
'civicrm_case.status_id as case_status_id',
't_act.status_id as status_id',
'civicrm_case.start_date as case_start_date',
"GROUP_CONCAT(DISTINCT IF(case_relationship.contact_id_b = $userID, case_relation_type.label_a_b, case_relation_type.label_b_a) SEPARATOR ', ') as case_role",
't_act.activity_date_time as activity_date_time',
't_act.id as activity_id',
'case_status.label AS case_status',
'civicrm_case_type.title AS case_type',
];
$query = CRM_Contact_BAO_Query::appendAnyValueToSelect($selectClauses, 'case_id');
$query .= <<<HERESQL
FROM civicrm_case
INNER JOIN civicrm_case_contact ON civicrm_case.id = civicrm_case_contact.case_id
INNER JOIN civicrm_contact ON civicrm_case_contact.contact_id = civicrm_contact.id
LEFT JOIN civicrm_case_type ON civicrm_case.case_type_id = civicrm_case_type.id
LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
AND option_group_case_status.id = case_status.option_group_id )
HERESQL;
// 'upcoming' and 'recent' show the next scheduled and most recent
// not-scheduled activity on each case, respectively.
$scheduled_id = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Scheduled');
switch ($type) {
case 'upcoming':
$query .= <<<HERESQL
INNER JOIN (SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
FROM civicrm_case_activity ca
INNER JOIN civicrm_activity a ON ca.activity_id=a.id
WHERE a.id =
(SELECT b.id FROM civicrm_case_activity bca
INNER JOIN civicrm_activity b ON bca.activity_id=b.id
WHERE b.activity_date_time <= DATE_ADD( NOW(), INTERVAL 14 DAY )
AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id = $scheduled_id
AND bca.case_id = ca.case_id ORDER BY b.activity_date_time ASC LIMIT 1)) t_act
ON t_act.case_id = civicrm_case.id
HERESQL;
break;
case 'recent':
$query .= <<<HERESQL
INNER JOIN (SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
FROM civicrm_case_activity ca
INNER JOIN civicrm_activity a ON ca.activity_id=a.id
WHERE a.id =
(SELECT b.id FROM civicrm_case_activity bca
INNER JOIN civicrm_activity b ON bca.activity_id=b.id
WHERE b.activity_date_time >= DATE_SUB( NOW(), INTERVAL 14 DAY )
AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id <> $scheduled_id
AND bca.case_id = ca.case_id ORDER BY b.activity_date_time DESC LIMIT 1)) t_act
ON t_act.case_id = civicrm_case.id
HERESQL;
break;
case 'any':
$query .= <<<HERESQL
LEFT JOIN civicrm_case_activity ca4
ON civicrm_case.id = ca4.case_id
LEFT JOIN civicrm_activity t_act
ON t_act.id = ca4.activity_id
AND t_act.is_current_revision = 1
HERESQL;
}
$query .= <<<HERESQL
LEFT JOIN civicrm_phone
ON civicrm_phone.contact_id = civicrm_contact.id
AND civicrm_phone.is_primary = 1
LEFT JOIN civicrm_relationship case_relationship
ON ((case_relationship.contact_id_a = civicrm_case_contact.contact_id AND case_relationship.contact_id_b = {$userID})
OR (case_relationship.contact_id_b = civicrm_case_contact.contact_id AND case_relationship.contact_id_a = {$userID}))
AND case_relationship.is_active
AND case_relationship.case_id = civicrm_case.id
LEFT JOIN civicrm_relationship_type case_relation_type
ON case_relation_type.id = case_relationship.relationship_type_id
AND case_relation_type.id = case_relationship.relationship_type_id
HERESQL;
if ($condition) {
// CRM-8749 backwards compatibility - callers of this function expect to start $condition with "AND"
$query .= " WHERE (1) AND $condition ";
}
$query .= " GROUP BY case_id ";
$query .= ($order) ?: ' ORDER BY activity_date_time ASC';
if ($limit) {
$query .= $limit;
}
return $query;
}
/**
* Retrieve cases related to particular contact or whole contact used in Dashboard and Tab.
*
* @param bool $allCases
* @param array $params
* @param string $context
* @param bool $getCount
*
* @return array
* Array of Cases
*/
public static function getCases($allCases = TRUE, $params = [], $context = 'dashboard', $getCount = FALSE) {
$condition = NULL;
$casesList = [];
// validate access for own cases.
if (!self::accessCiviCase()) {
return $getCount ? 0 : $casesList;
}
$type = $params['type'] ?? 'upcoming';
// Return cached value instead of re-running query
if (isset(Civi::$statics[__CLASS__]['totalCount'][$type]) && $getCount) {
return Civi::$statics[__CLASS__]['totalCount'][$type];
}
$userID = CRM_Core_Session::getLoggedInContactID();
// validate access for all cases.
if ($allCases && !CRM_Core_Permission::check('access all cases and activities')) {
$allCases = FALSE;
}
$whereClauses = ['civicrm_case.is_deleted = 0 AND civicrm_contact.is_deleted <> 1'];
if (!$allCases) {
$whereClauses[] = "(case_relationship.contact_id_b = {$userID} OR case_relationship.contact_id_a = {$userID})";
$whereClauses[] = 'case_relationship.is_active';
}
if (empty($params['status_id']) && $type == 'upcoming') {
$whereClauses[] = "civicrm_case.status_id != " . CRM_Core_PseudoConstant::getKey('CRM_Case_BAO_Case', 'case_status_id', 'Closed');
}
foreach (['case_type_id', 'status_id'] as $column) {
if (!empty($params[$column])) {
$whereClauses[] = sprintf("civicrm_case.%s IN (%s)", $column, $params[$column]);
}
}
$condition = implode(' AND ', $whereClauses);
Civi::$statics[__CLASS__]['totalCount'][$type] = $totalCount = CRM_Core_DAO::singleValueQuery(self::getCaseActivityCountQuery($type, $userID, $condition));
if ($getCount) {
return $totalCount;
}
$casesList['total'] = $totalCount;
$limit = '';
if (!empty($params['rp'])) {
$params['offset'] = ($params['page'] - 1) * $params['rp'];
$params['rowCount'] = $params['rp'];
if (!empty($params['rowCount']) && $params['rowCount'] > 0) {
$limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
}
}
$order = NULL;
if (!empty($params['sortBy'])) {
if (str_contains($params['sortBy'], 'date ')) {
$params['sortBy'] = str_replace('date', 'activity_date_time', $params['sortBy']);
}
$order = "ORDER BY " . $params['sortBy'];
}
$query = self::getCaseActivityQuery($type, $userID, $condition, $limit, $order);
$result = CRM_Core_DAO::executeQuery($query);
// we're going to use the usual actions, so doesn't make sense to duplicate definitions
$actions = CRM_Case_Selector_Search::links();
// check is the user has view/edit signer permission
$permissions = [CRM_Core_Permission::VIEW];
if (CRM_Core_Permission::check('access all cases and activities') ||
(!$allCases && CRM_Core_Permission::check('access my cases and activities'))
) {
$permissions[] = CRM_Core_Permission::EDIT;
}
if (CRM_Core_Permission::check('delete in CiviCase')) {
$permissions[] = CRM_Core_Permission::DELETE;
}
$mask = CRM_Core_Action::mask($permissions);
// Pseudoconstants to populate labels
$caseStatuses = CRM_Case_PseudoConstant::caseStatus('label', FALSE);
$caseTypes = CRM_Case_PseudoConstant::caseType('name');
$caseTypeTitles = CRM_Case_PseudoConstant::caseType('title', FALSE);
$activityTypeLabels = CRM_Activity_BAO_Activity::buildOptions('activity_type_id');
foreach ($result->fetchAll() as $case) {
$key = $case['case_id'];
$casesList[$key] = [];
$casesList[$key]['DT_RowId'] = $case['case_id'];
$casesList[$key]['DT_RowAttr'] = ['data-entity' => 'case', 'data-id' => $case['case_id']];
$casesList[$key]['DT_RowClass'] = "crm-entity";
$casesList[$key]['activity_list'] = sprintf('<a title="%s" class="crm-expand-row" href="%s"></a>',
ts('Activities'),
CRM_Utils_System::url('civicrm/case/details', ['caseId' => $case['case_id'], 'cid' => $case['contact_id'], 'type' => $type])
);
$phone = empty($case['phone']) ? '' : '<br /><span class="description">' . $case['phone'] . '</span>';
$casesList[$key]['sort_name'] = sprintf('<a href="%s">%s</a>%s<br /><span class="description">%s: %d</span>',
CRM_Utils_System::url('civicrm/contact/view', ['cid' => $case['contact_id']]),
$case['sort_name'],
$phone,
ts('Case ID'),
$case['case_id']
);
$casesList[$key]['subject'] = $case['case_subject'];
$casesList[$key]['case_status'] = $caseStatuses[$case['case_status_id']] ?? NULL;
if ($case['case_status_id'] == CRM_Case_PseudoConstant::getKey('CRM_Case_BAO_Case', 'case_status_id', 'Urgent')) {
$casesList[$key]['case_status'] = sprintf('<strong>%s</strong>', strtoupper($casesList[$key]['case_status']));
}
$casesList[$key]['case_type'] = $caseTypeTitles[$case['case_type_id']] ?? NULL;
$casesList[$key]['case_role'] = CRM_Utils_Array::value('case_role', $case, '---');
$casesList[$key]['manager'] = self::getCaseManagerContact($caseTypes[$case['case_type_id']], $case['case_id']);
$casesList[$key]['date'] = $activityTypeLabels[$case['activity_type_id']] ?? NULL;
$actId = $case['activity_id'] ?? NULL;
if ($actId) {
if (self::checkPermission($actId, 'view', $case['activity_type_id'], $userID)) {
if ($type == 'recent') {
$casesList[$key]['date'] = sprintf('<a class="action-item crm-hover-button" href="%s" title="%s">%s</a>',
CRM_Utils_System::url('civicrm/case/activity/view', ['reset' => 1, 'cid' => $case['contact_id'], 'aid' => $case['activity_id']]),
ts('View activity'),
$activityTypeLabels[$case['activity_type_id']] ?? ''
);
}
else {
$status = CRM_Utils_Date::overdue($case['activity_date_time']) ? 'status-overdue' : 'status-scheduled';
$casesList[$key]['date'] = sprintf('<a class="crm-popup %s" href="%s" title="%s">%s</a> ',
$status,
CRM_Utils_System::url('civicrm/case/activity/view', ['reset' => 1, 'cid' => $case['contact_id'], 'aid' => $case['activity_id']]),
ts('View activity'),
$activityTypeLabels[$case['activity_type_id']] ?? ''
);
}
}
if (isset($case['activity_type_id']) && self::checkPermission($actId, 'edit', $case['activity_type_id'], $userID)) {
$casesList[$key]['date'] .= sprintf('<a class="action-item crm-hover-button" href="%s" title="%s"><i class="crm-i fa-pencil" aria-hidden="true"></i></a>',
CRM_Utils_System::url('civicrm/case/activity', ['reset' => 1, 'cid' => $case['contact_id'], 'caseid' => $case['case_id'], 'action' => 'update', 'id' => $actId]),
ts('Edit activity')
);
}
}
$casesList[$key]['date'] .= "<br/>" . CRM_Utils_Date::customFormat($case['activity_date_time']);
$casesList[$key]['links'] = CRM_Core_Action::formLink($actions['primaryActions'], $mask,
[
'id' => $case['case_id'],
'cid' => $case['contact_id'],
'cxt' => $context,
],
ts('more'),
FALSE,
'case.actions.primary',
'Case',
$case['case_id']
);
}
return $casesList;
}
/**
* Get the summary of cases counts by type and status.
*
* @param bool $allCases
*
* @return array
*/
public static function getCasesSummary($allCases = TRUE) {
$caseSummary = [];
//validate access for civicase.
if (!self::accessCiviCase()) {
return $caseSummary;
}
$userID = CRM_Core_Session::getLoggedInContactID();
//validate access for all cases.
if ($allCases && !CRM_Core_Permission::check('access all cases and activities')) {
$allCases = FALSE;
}
$caseTypes = CRM_Case_PseudoConstant::caseType();
$caseStatuses = CRM_Case_PseudoConstant::caseStatus();
// get statuses as headers for the table
$url = CRM_Utils_System::url('civicrm/case/search', "reset=1&force=1&all=1&case_status_id=");
$rows = [];
foreach ($caseStatuses as $key => $caseStatusLabel) {
$caseSummary['headers'][$key]['status'] = $caseStatusLabel;
$caseSummary['headers'][$key]['url'] = $url . $key;
foreach ($caseTypes as $caseTypeLabel) {
$rows[$caseTypeLabel][$caseStatusLabel] = ['count' => NULL, 'url' => NULL];
}
}
// build rows with actual data
$myGroupByClause = $mySelectClause = $myCaseFromClause = $myCaseWhereClauseA = $myCaseWhereClauseB = '';
if ($allCases) {
$userID = 'null';
$all = 1;
$case_owner = 1;
$myGroupByClauseB = ' GROUP BY civicrm_case.id';
}
else {
$all = 0;
$case_owner = 2;
$myCaseWhereClauseA = " AND case_relationship.contact_id_a = {$userID} AND case_relationship.is_active ";
$myGroupByClauseA = " GROUP BY CONCAT(civicrm_case.id,'-',case_relationship.contact_id_a)";
$myCaseWhereClauseB = " AND case_relationship.contact_id_b = {$userID} AND case_relationship.is_active ";
$myGroupByClauseB = " GROUP BY CONCAT(civicrm_case.id,'-',case_relationship.contact_id_b)";
}
$myGroupByClauseB .= ", case_status.label, status_id, case_type_id, civicrm_case.id";
$myGroupByClauseA = $myGroupByClauseB;
// FIXME: This query could be a lot more efficient if it used COUNT() instead of returning all rows and then counting them with php
$query = "
SELECT civicrm_case.id, case_status.label AS case_status, status_id, civicrm_case_type.title AS case_type,
case_type_id, case_relationship.contact_id_b as case_contact
FROM civicrm_case
INNER JOIN civicrm_case_contact cc on cc.case_id = civicrm_case.id
LEFT JOIN civicrm_case_type ON civicrm_case.case_type_id = civicrm_case_type.id
LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
AND option_group_case_status.id = case_status.option_group_id )
LEFT JOIN civicrm_relationship case_relationship ON ( case_relationship.case_id = civicrm_case.id
AND case_relationship.contact_id_b = {$userID} AND case_relationship.is_active )
WHERE is_deleted = 0 AND cc.contact_id IN (SELECT id FROM civicrm_contact WHERE is_deleted <> 1)
{$myCaseWhereClauseB} {$myGroupByClauseB}
UNION
SELECT civicrm_case.id, case_status.label AS case_status, status_id, civicrm_case_type.title AS case_type,
case_type_id, case_relationship.contact_id_a as case_contact
FROM civicrm_case
INNER JOIN civicrm_case_contact cc on cc.case_id = civicrm_case.id
LEFT JOIN civicrm_case_type ON civicrm_case.case_type_id = civicrm_case_type.id
LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
AND option_group_case_status.id = case_status.option_group_id )
LEFT JOIN civicrm_relationship case_relationship ON ( case_relationship.case_id = civicrm_case.id
AND case_relationship.contact_id_a = {$userID})
WHERE is_deleted = 0 AND cc.contact_id IN (SELECT id FROM civicrm_contact WHERE is_deleted <> 1)
{$myCaseWhereClauseA} {$myGroupByClauseA}";
$res = CRM_Core_DAO::executeQuery($query);
while ($res->fetch()) {
if (!empty($rows[$res->case_type][$res->case_status]['count'])) {
$rows[$res->case_type][$res->case_status]['count'] = $rows[$res->case_type][$res->case_status]['count'] + 1;
}
else {
$rows[$res->case_type][$res->case_status] = [
'count' => 1,
'url' => CRM_Utils_System::url('civicrm/case/search',
"reset=1&force=1&case_status_id={$res->status_id}&case_type_id={$res->case_type_id}&case_owner={$case_owner}"
),
];
}
}
$caseSummary['rows'] = $rows;
return $caseSummary;
}
/**
* Get Case roles.
*
* @param int $contactID
* Contact id.
* @param int $caseID
* Case id.
* @param int $relationshipID
* @param bool $activeOnly
*
* @return array
* case role / relationships
*
*/
public static function getCaseRoles($contactID, $caseID, $relationshipID = NULL, $activeOnly = TRUE) {
$query = '
SELECT rel.id as civicrm_relationship_id,
con.sort_name as sort_name,
civicrm_email.email as email,
civicrm_phone.phone as phone,
con.id as civicrm_contact_id,
rel.is_active as is_active,
rel.end_date as end_date,
IF(rel.contact_id_a = %1, civicrm_relationship_type.label_a_b, civicrm_relationship_type.label_b_a) as relation,
civicrm_relationship_type.id as relation_type,
IF(rel.contact_id_a = %1, "a_b", "b_a") as relationship_direction
FROM civicrm_relationship rel
INNER JOIN civicrm_relationship_type ON rel.relationship_type_id = civicrm_relationship_type.id
INNER JOIN civicrm_contact con ON ((con.id <> %1 AND con.id IN (rel.contact_id_a, rel.contact_id_b)) OR (con.id = %1 AND rel.contact_id_b = rel.contact_id_a AND rel.contact_id_a = %1 AND rel.is_active))
LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = con.id AND civicrm_phone.is_primary = 1)
LEFT JOIN civicrm_email ON (civicrm_email.contact_id = con.id AND civicrm_email.is_primary = 1)
WHERE (rel.contact_id_a = %1 OR rel.contact_id_b = %1) AND rel.case_id = %2
AND con.is_deleted = 0';
if ($activeOnly) {
$query .= ' AND rel.is_active = 1 AND (rel.end_date IS NULL OR rel.end_date > NOW())';
}
$params = [
1 => [$contactID, 'Positive'],
2 => [$caseID, 'Positive'],
];
if ($relationshipID) {
$query .= ' AND rel.id = %3 ';
$params[3] = [$relationshipID, 'Integer'];
}
$dao = CRM_Core_DAO::executeQuery($query, $params);
$values = [];
while ($dao->fetch()) {
$rid = $dao->civicrm_relationship_id;
$values[$rid]['cid'] = $dao->civicrm_contact_id;
$values[$rid]['relation'] = $dao->relation;
$values[$rid]['sort_name'] = $dao->sort_name;
$values[$rid]['email'] = $dao->email;
$values[$rid]['phone'] = $dao->phone;
$values[$rid]['is_active'] = $dao->is_active;
$values[$rid]['end_date'] = $dao->end_date;
$values[$rid]['relation_type'] = $dao->relation_type;
$values[$rid]['rel_id'] = $dao->civicrm_relationship_id;
$values[$rid]['client_id'] = $contactID;
$values[$rid]['relationship_direction'] = $dao->relationship_direction;
}
return $values;
}
/**
* Get Case Activities.
*
* @param int $caseID
* Case id.
* @param array $params
* Posted params.
* @param int $contactID
* Contact id.
*
* @param null $context
* @param int $userID
* @param null $type (deprecated)
*
* @return array
* Array of case activities
*
*/
public static function getCaseActivity($caseID, &$params, $contactID, $context = NULL, $userID = NULL, $type = NULL) {
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
$targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
// CRM-5081 - formatting the dates to omit seconds.
// Note the 00 in the date format string is needed otherwise later on it thinks scheduled ones are overdue.
$select = "
SELECT SQL_CALC_FOUND_ROWS COUNT(ca.id) AS ismultiple,
ca.id AS id,
ca.activity_type_id AS type,
ca.activity_type_id AS activity_type_id,
tcc.sort_name AS target_contact_name,
tcc.id AS target_contact_id,
scc.sort_name AS source_contact_name,
scc.id AS source_contact_id,
acc.sort_name AS assignee_contact_name,
acc.id AS assignee_contact_id,
DATE_FORMAT(
IF(ca.activity_date_time < NOW() AND ca.status_id=ov.value,
ca.activity_date_time,
DATE_ADD(NOW(), INTERVAL 1 YEAR)
), '%Y%m%d%H%i00') AS overdue_date,
DATE_FORMAT(ca.activity_date_time, '%Y%m%d%H%i00') AS display_date,
ca.status_id AS status,
ca.subject AS subject,
ca.is_deleted AS deleted,
ca.priority_id AS priority,
ca.weight AS weight,
GROUP_CONCAT(ef.file_id) AS attachment_ids ";
$from = "
FROM civicrm_case_activity cca
INNER JOIN civicrm_activity ca
ON ca.id = cca.activity_id
INNER JOIN civicrm_activity_contact cas
ON cas.activity_id = ca.id
AND cas.record_type_id = {$sourceID}
INNER JOIN civicrm_contact scc
ON scc.id = cas.contact_id
LEFT JOIN civicrm_activity_contact caa
ON caa.activity_id = ca.id
AND caa.record_type_id = {$assigneeID}
LEFT JOIN civicrm_contact acc
ON acc.id = caa.contact_id
LEFT JOIN civicrm_activity_contact cat
ON cat.activity_id = ca.id
AND cat.record_type_id = {$targetID}
LEFT JOIN civicrm_contact tcc
ON tcc.id = cat.contact_id
INNER JOIN civicrm_option_group cog
ON cog.name = 'activity_type'
INNER JOIN civicrm_option_value cov
ON cov.option_group_id = cog.id
AND cov.value = ca.activity_type_id
AND cov.is_active = 1
LEFT JOIN civicrm_entity_file ef
ON ef.entity_table = 'civicrm_activity'
AND ef.entity_id = ca.id
LEFT OUTER JOIN civicrm_option_group og
ON og.name = 'activity_status'
LEFT OUTER JOIN civicrm_option_value ov
ON ov.option_group_id=og.id
AND ov.name = 'Scheduled'";