-
Notifications
You must be signed in to change notification settings - Fork 246
Expand file tree
/
Copy pathProcess.php
More file actions
2175 lines (1971 loc) · 73.4 KB
/
Process.php
File metadata and controls
2175 lines (1971 loc) · 73.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
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
namespace ProcessMaker\Models;
use DOMElement;
use Exception;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Mustache_Engine;
use ProcessMaker\AssignmentRules\PreviousTaskAssignee;
use ProcessMaker\AssignmentRules\ProcessManagerAssigned;
use ProcessMaker\BpmnEngine;
use ProcessMaker\Contracts\ProcessModelInterface;
use ProcessMaker\Exception\InvalidUserAssignmentException;
use ProcessMaker\Exception\TaskDoesNotHaveRequesterException;
use ProcessMaker\Exception\TaskDoesNotHaveUsersException;
use ProcessMaker\Exception\ThereIsNoProcessManagerAssignedException;
use ProcessMaker\Facades\WorkflowUserManager;
use ProcessMaker\Managers\DataManager;
use ProcessMaker\Nayra\Bpmn\Models\Activity;
use ProcessMaker\Nayra\Contracts\Bpmn\ActivityInterface;
use ProcessMaker\Nayra\Contracts\Bpmn\ScriptTaskInterface;
use ProcessMaker\Nayra\Contracts\Bpmn\ServiceTaskInterface;
use ProcessMaker\Nayra\Contracts\Bpmn\StartEventInterface;
use ProcessMaker\Nayra\Contracts\Storage\BpmnDocumentInterface;
use ProcessMaker\Nayra\Managers\WorkflowManagerDefault;
use ProcessMaker\Nayra\Storage\BpmnDocument;
use ProcessMaker\Package\WebEntry\Models\WebentryRoute;
use ProcessMaker\Rules\BPMNValidation;
use ProcessMaker\Traits\Exportable;
use ProcessMaker\Traits\ExtendedPMQL;
use ProcessMaker\Traits\HasCategories;
use ProcessMaker\Traits\HasSelfServiceTasks;
use ProcessMaker\Traits\HasVersioning;
use ProcessMaker\Traits\HideSystemResources;
use ProcessMaker\Traits\ProcessStartEventAssignmentsTrait;
use ProcessMaker\Traits\ProcessTaskAssignmentsTrait;
use ProcessMaker\Traits\ProcessTimerEventsTrait;
use ProcessMaker\Traits\ProcessTrait;
use ProcessMaker\Traits\ProjectAssetTrait;
use ProcessMaker\Traits\SerializeToIso8601;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use Throwable;
/**
* Represents a business process definition.
*
* @property string $id
* @property string $process_category_id
* @property string $user_id
* @property string $bpmn
* @property string $description
* @property string $name
* @property string $case_title
* @property string $status
* @property array $start_events
* @property int $manager_id
* @property \Carbon\Carbon $updated_at
* @property \Carbon\Carbon $created_at
*
* @method static Process find(string $id)
*
* @OA\Schema(
* schema="ProcessEditable",
* @OA\Property(property="process_category_id", type="integer", format="id"),
* @OA\Property(property="name", type="string"),
* @OA\Property(property="case_title", type="string"),
* @OA\Property(property="description", type="string"),
* @OA\Property(property="status", type="string", enum={"ACTIVE", "INACTIVE", "ARCHIVED"}),
* @OA\Property(property="pause_timer_start", type="integer"),
* @OA\Property(property="cancel_screen_id", type="integer"),
* @OA\Property(property="has_timer_start_events", type="boolean"),
* @OA\Property(property="request_detail_screen_id", type="integer", format="id"),
* @OA\Property(property="is_valid", type="integer"),
* @OA\Property(property="package_key", type="string"),
* @OA\Property(property="start_events", type="array", @OA\Items(ref="#/components/schemas/ProcessStartEvents")),
* @OA\Property(property="warnings", type="string"),
* @OA\Property(property="self_service_tasks", type="object"),
* @OA\Property(property="signal_events", type="array", @OA\Items(type="object")),
* @OA\Property(property="category", type="object", @OA\Schema(ref="#/components/schemas/ProcessCategory")),
* @OA\Property(property="manager_id", type="array", @OA\Items(type="integer", format="id")),
* ),
* @OA\Schema(
* schema="Process",
* allOf={
* @OA\Schema(ref="#/components/schemas/ProcessEditable"),
* @OA\Schema(
* @OA\Property(property="user_id", type="integer", format="id"),
* @OA\Property(property="id", type="string", format="id"),
* @OA\Property(property="deleted_at", type="string", format="date-time"),
* @OA\Property(property="created_at", type="string", format="date-time"),
* @OA\Property(property="updated_at", type="string", format="date-time"),
* @OA\Property(property="notifications", type="object"),
* @OA\Property(property="task_notifications", type="object"),
* )
* }
* ),
* @OA\Schema(
* schema="ProcessStartEvents",
* @OA\Property(property="eventDefinitions", type="object"),
* @OA\Property(property="parallelMultiple", type="boolean"),
* @OA\Property(property="outgoing", type="object"),
* @OA\Property(property="incoming", type="object"),
* @OA\Property(property="id", type="string"),
* @OA\Property(property="name", type="string"),
* ),
* @OA\Schema(
* schema="ProcessWithStartEvents",
* allOf={
* @OA\Schema(ref="#/components/schemas/Process"),
* @OA\Schema(
* @OA\Property(
* property="events",
* type="array",
* @OA\Items(ref="#/components/schemas/ProcessStartEvents"),
* ))
* }
* ),
*
* @OA\Schema(
* schema="ProcessImport",
* allOf={
* @OA\Schema(ref="#/components/schemas/ProcessEditable"),
* @OA\Schema(
* @OA\Property(property="status", type="array", @OA\Items(type="object")),
* @OA\Property(property="assignable", type="array", @OA\Items(type="object")),
* @OA\Property(property="process", @OA\Schema(ref="#/components/schemas/Process"))
* )
* }
* ),
* @OA\Schema(
* schema="ProcessAssignments",
* @OA\Property(property="assignable", type="array", @OA\Items(type="object")),
* @OA\Property(property="cancel_request", type="object"),
* @OA\Property(property="edit_data", type="object"),
* )
*/
class Process extends ProcessMakerModel implements HasMedia, ProcessModelInterface
{
use InteractsWithMedia;
use SerializeToIso8601;
use SoftDeletes;
use ProcessTaskAssignmentsTrait;
use HasVersioning;
use ProcessTimerEventsTrait;
use ProcessStartEventAssignmentsTrait;
use HideSystemResources;
use ExtendedPMQL;
use HasCategories;
use HasSelfServiceTasks;
use ProcessTrait;
use Exportable;
use ProjectAssetTrait;
const categoryClass = ProcessCategory::class;
const ASSIGNMENT_PROCESS = 'Assignment process';
const NOT_ASSIGNABLE_USER_STATUS = ['INACTIVE', 'OUT_OF_OFFICE'];
protected $connection = 'processmaker';
/**
* The attributes that aren't mass assignable.
*
* @var array
*/
protected $guarded = [
'id',
'user_id',
'created_at',
'updated_at',
'updated_by',
'has_timer_start_events',
'warnings',
];
/**
* The attributes that are dates.
*
* @var array
*/
/**
* The attributes that should be hidden for serialization.
*
* BPMN data will be hidden. It will be able by its getter.
*
* @var array
*/
protected $hidden = [
'bpmn',
'svg',
];
public $requestNotifiableTypes = [
'requester',
'assignee',
'participants',
'manager',
];
public $requestNotificationTypes = [
'started',
'canceled',
'completed',
'error',
'comment',
];
public $taskNotifiableTypes = [
'requester',
'assignee',
'participants',
'manager',
];
public $taskNotificationTypes = [
'assigned',
'completed',
'due',
'default',
];
protected $appends = [
'has_timer_start_events',
'projects',
];
protected $casts = [
'start_events' => 'array',
'warnings' => 'array',
'self_service_tasks' => 'array',
'signal_events' => 'array',
'conditional_events' => 'array',
'properties' => 'array',
'stages' => 'array',
];
public static function boot()
{
parent::boot();
static::creating(function ($model) {
$user = Auth::user();
$model->updated_by = $user?->id;
});
static::updating(function ($model) {
$user = Auth::user();
$model->updated_by = $user?->id;
self::clearAndRebuildUserProjectAssetsCache();
});
}
/**
* Category of the process.
*
* @return BelongsTo
*/
public function category()
{
return $this->belongsTo(ProcessCategory::class, 'process_category_id')->withDefault();
}
/**
* Get the associated projects
*/
public function projects()
{
if (!class_exists('ProcessMaker\Package\Projects\Models\Project')) {
// return an empty collection
return new HasMany($this->newQuery(), $this, '', '');
}
return $this->belongsToMany('ProcessMaker\Package\Projects\Models\Project',
'project_assets',
'asset_id',
'project_id',
'id',
'id'
)->wherePivot('asset_type', static::class);
}
// Define the relationship with the ProjectAsset model
public function projectAssets()
{
return $this->belongsToMany('ProcessMaker\Package\Projects\Models\ProjectAsset',
'project_assets', 'asset_id', 'project_id')
->withPivot('asset_type')
->wherePivot('asset_type', static::class)->withTimestamps();
}
public function projectAsset()
{
return $this->belongsToMany('ProcessMaker\Package\Projects\Models\ProjectAsset',
'project_assets',
'asset_id',
'project_id',
)->withTimeStamps();
}
/**
* Returns a single record from the `Alternative` model
*/
public function alternativeInfo()
{
return $this->hasOne('ProcessMaker\Package\PackageABTesting\Models\Alternative', 'process_id', 'id');
}
/**
* Notification settings of the process.
*
* @return HasMany
*/
public function notification_settings()
{
return $this->hasMany(ProcessNotificationSetting::class);
}
/**
* Get the associated embed
*/
public function embed()
{
return $this->hasMany(Embed::class, 'model_id', 'id');
}
/**
* Notification settings of the process.
*
* @return object
*/
public function getNotificationsAttribute()
{
$array = [];
foreach ($this->requestNotifiableTypes as $notifiable) {
foreach ($this->requestNotificationTypes as $notification) {
$setting = $this->notification_settings()
->whereNull('element_id')
->where('notifiable_type', $notifiable)
->where('notification_type', $notification)->get();
if ($setting->count()) {
$value = true;
} else {
$value = false;
}
$array[$notifiable][$notification] = $value;
}
}
return (object) $array;
}
/**
* Task notification settings of the process.
*
* @return object
*/
public function getTaskNotificationsAttribute()
{
$array = [];
$elements = $this->notification_settings()
->whereNotNull('element_id')
->get();
foreach ($elements->groupBy('element_id') as $group) {
$elementId = $group->first()->element_id;
foreach ($this->taskNotifiableTypes as $notifiable) {
foreach ($this->taskNotificationTypes as $notification) {
$setting = $group->where('notifiable_type', $notifiable)
->where('notification_type', $notification);
if ($setting->count()) {
$value = true;
} else {
$value = false;
}
$array[$elementId][$notifiable][$notification] = $value;
}
}
}
return (object) $array;
}
/**
* Cancel Screen of the process.
*
* @return BelongsTo
*/
public function cancelScreen()
{
return $this->belongsTo(Screen::class, 'cancel_screen_id');
}
/**
* Validation rules.
*
* @param null $existing
*
* @return array
*/
public static function rules($existing = null)
{
$unique = Rule::unique('processes')->ignore($existing);
return [
'name' => ['required', $unique, 'alpha_spaces'],
'description' => 'required',
'status' => 'in:ACTIVE,INACTIVE,ARCHIVED',
'process_category_id' => 'exists:process_categories,id',
'bpmn' => 'nullable',
'case_title' => 'nullable|max:200',
'alternative' => 'nullable|in:A,B',
];
}
/**
* Get the creator/author of this process.
*/
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
/**
* Get the last user that updated the process
*/
public function updatedByUser()
{
return $this->belongsTo(User::class, 'updated_by');
}
/**
* Get the users who can start this process
*
* @param string|null $node If null get START from any node
*/
public function usersCanStart($node = null)
{
$relationship = $this->morphedByMany('ProcessMaker\Models\User', 'processable')
->wherePivot('method', 'START');
return $node === null ? $relationship : $relationship->wherePivot('node', $node);
}
/**
* Get the groups who can start this process
*
* @param string|null $node If null get START from any node
*/
public function groupsCanStart($node = null)
{
$relationship = $this->morphedByMany('ProcessMaker\Models\Group', 'processable')
->wherePivot('method', 'START');
return $node === null ? $relationship : $relationship->wherePivot('node', $node);
}
/**
* Scope a query to include only active and inactive but not archived processes
*/
public function scopeNotArchived($query)
{
return $query->whereIn('processes.status', ['ACTIVE', 'INACTIVE']);
}
/**
* Scope a query to include only active processes
*/
public function scopeActive($query)
{
return $query->where('processes.status', 'ACTIVE');
}
/**
* Scope a query to include only inactive processes
*/
public function scopeInactive($query)
{
return $query->where('processes.status', 'INACTIVE');
}
/**
* Scope a query to include only archived processes
*/
public function scopeArchived($query)
{
return $query->where('processes.status', 'ARCHIVED');
}
/**
* Scope a query to include a specific category
*/
public function scopeProcessCategory($query, int $id)
{
return $query->whereHas('categories', function ($query) use ($id) {
$query->where('process_categories.id', $id);
});
}
/**
* Scope a query to include a specific category
* @param string $status
*/
public function scopeCategoryStatus($query, $status)
{
if (!empty($status)) {
return $query->whereHas('categories', function ($query) use ($status) {
$query->where('process_categories.status', $status);
});
}
}
/**
* Load the collaborations if exists
*
* @deprecated Not used, does not have a process_version reference
*
* @return BpmnDocumentInterface
*/
public function getCollaborations()
{
$this->bpmnDefinitions = app(BpmnDocumentInterface::class, ['process' => $this]);
if ($this->bpmn) {
$this->bpmnDefinitions->loadXML($this->bpmn);
// Load the collaborations if exists
return $this->bpmnDefinitions->getElementsByTagNameNS(BpmnDocument::BPMN_MODEL, 'collaboration');
}
}
/**
* Get the path of the process templates.
*
* @return string
*/
public static function getProcessTemplatesPath()
{
return Storage::disk('process_templates')->path('');
}
/**
* Get a process template by name.
*
* @param string $name
*
* @return string
*/
public static function getProcessTemplate($name)
{
return Storage::disk('process_templates')->get($name);
}
/**
* Category of the process.
*
* @return BelongsTo
*/
public function requests()
{
return $this->hasMany(ProcessRequest::class);
}
/**
* Category of the process.
*
* @return BelongsTo
*/
public function collaborations()
{
return $this->hasMany(ProcessCollaboration::class);
}
/**
* Get the user to whom to assign a task.
*
* @param ActivityInterface $activity
* @param ProcessRequestToken $token
*
* @return User
*/
public function getNextUser(ActivityInterface $activity, ProcessRequestToken $token)
{
$default = $activity instanceof ScriptTaskInterface
|| $activity instanceof ServiceTaskInterface ? 'script' : 'requester';
$assignmentType = $activity->getProperty('assignment', $default);
$config = json_decode($activity->getProperty('config', '{}'), true);
$escalateToManager = $config['escalateToManager'] ?? false;
$definitions = $token->getInstance()->getVersionDefinitions();
$properties = $definitions->findElementById($activity->getId())->getBpmnElementInstance()->getProperties();
$assignmentLock = array_key_exists('assignmentLock', $properties ?? []) ? $properties['assignmentLock'] : false;
$config = array_key_exists('config', $properties ?? []) ? json_decode($properties['config'], true) : [];
$isSelfService = array_key_exists('selfService', $config ?? []) ? $config['selfService'] : false;
if ($assignmentType === 'rule_expression') {
$userByRule = $isSelfService ? null : $this->getNextUserByRule($activity, $token);
if ($userByRule !== null) {
$user = $this->scalateToManagerIfEnabled($userByRule->id, $activity, $token, $assignmentType);
return $this->checkAssignment($token->processRequest, $activity, $assignmentType, $escalateToManager, $user ? User::where('id', $user)->first() : null, $token);
}
}
if (filter_var($assignmentLock, FILTER_VALIDATE_BOOLEAN) === true) {
$user = $this->getLastUserAssignedToTask($activity->getId(), $token->getInstance()->getId());
if ($user) {
return $this->checkAssignment($token->processRequest, $activity, $assignmentType, $escalateToManager, User::where('id', $user)->first(), $token);
}
}
switch ($assignmentType) {
case 'user_group':
case 'group':
$user = $this->getNextUserFromGroupAssignment($activity->getId());
break;
case 'user':
$user = $this->getNextUserAssignment($activity->getId());
break;
case 'user_by_id':
$user = $this->getNextUserFromVariable($activity, $token);
break;
case 'process_variable':
$user = $this->getNextUserFromProcessVariable($activity, $token);
break;
case 'requester':
$user = $this->getRequester($activity, $token);
break;
case 'previous_task_assignee':
$rule = new PreviousTaskAssignee();
$user = $rule->getNextUser($activity, $token, $this, $token->getInstance());
break;
case 'process_manager':
$rule = new ProcessManagerAssigned();
$user = $rule->getNextUser($activity, $token, $this, $token->getInstance());
break;
case 'manual':
case 'self_service':
$user = null;
break;
case 'script':
default:
$user = null;
}
// If the self-service toggle is enabled the user must always be null
if ($isSelfService && in_array($assignmentType, ['user_group', 'process_variable', 'rule_expression'])) {
$user = null;
}
$user = $this->scalateToManagerIfEnabled($user, $activity, $token, $assignmentType);
return $this->checkAssignment($token->getInstance(), $activity, $assignmentType, $escalateToManager, $user ? User::where('id', $user)->first() : null, $token);
}
/**
* If user assignment is not valid reassign to Process Manager
*
* @param ProcessRequest $request
* @param ActivityInterface $activity
* @param string $assignmentType
* @param bool $escalateToManager
* @param User|null $user
* @param ProcessRequestToken $token
*
* @return User|null
*/
private function checkAssignment(ProcessRequest $request, ActivityInterface $activity, $assignmentType, $escalateToManager, User $user = null, ProcessRequestToken $token = null)
{
$config = $activity->getProperty('config') ? json_decode($activity->getProperty('config'), true) : [];
$selfServiceToggle = array_key_exists('selfService', $config ?? []) ? $config['selfService'] : false;
$isSelfService = $selfServiceToggle || $assignmentType === 'self_service';
if ($activity instanceof ScriptTaskInterface
|| $activity instanceof ServiceTaskInterface) {
return $user;
}
if ($user === null) {
if ($isSelfService && !$escalateToManager) {
return null;
}
$rule = new ProcessManagerAssigned();
if ($token === null) {
throw new ThereIsNoProcessManagerAssignedException($activity);
}
$user = $rule->getNextUser($activity, $token, $this, $request);
if (!$user) {
throw new ThereIsNoProcessManagerAssignedException($activity);
}
$user = User::find($user);
}
return $user;
}
private function scalateToManagerIfEnabled($user, $activity, $token, $assignmentType)
{
if ($user) {
$assignmentProcess = self::where('name', self::ASSIGNMENT_PROCESS)->first();
if (app()->bound('workflow.UserManager') && $assignmentProcess) {
$config = json_decode($activity->getProperty('config', '{}'), true);
$escalateToManager = $config['escalateToManager'] ?? false;
if ($escalateToManager) {
$user = WorkflowUserManager::escalateToManager($token, $user);
} else {
$res = (new WorkflowManagerDefault)->runProcess($assignmentProcess, 'assign', [
'user_id' => $user,
'process_id' => $this->id,
'request_id' => $token->getInstance()->getId(),
]);
$user = $res['assign_to'];
}
}
}
return $user;
}
/**
* If the assignment type is user_by_id, we need to parse
* mustache syntax with the current data to get the user
* that should be assigned
*
* @param ProcessRequestToken $token
* @return User $user
* @throws InvalidUserAssignmentException
*/
private function getNextUserFromVariable($activity, $token)
{
try {
$userExpression = $activity->getProperty('assignedUsers');
$dataManager = new DataManager();
$instanceData = $dataManager->getData($token);
$mustache = new Mustache_Engine();
$userId = $mustache->render($userExpression, $instanceData);
$user = User::find($userId);
if (!$user) {
throw new InvalidUserAssignmentException($userExpression, $userId);
}
return $user->id;
} catch (Exception $exception) {
return null;
}
}
/*
* Used to assign a user when the task is assigned by variables that have lists
* of users and groups
*/
private function getNextUserFromProcessVariable($activity, $token)
{
// self service tasks should not have a next user
if ($token->getSelfServiceAttribute()) {
return null;
}
$usersVariable = $activity->getProperty('assignedUsers');
$groupsVariable = $activity->getProperty('assignedGroups');
$dataManager = new DataManager();
$instanceData = $dataManager->getData($token);
$assignedUsers = $usersVariable ? feelExpression($usersVariable, $instanceData) : [];
$assignedGroups = $groupsVariable ? feelExpression($groupsVariable, $instanceData) : [];
if (!is_array($assignedUsers)) {
$assignedUsers = [$assignedUsers];
}
if (!is_array($assignedGroups)) {
$assignedGroups = [$assignedGroups];
}
// We need to remove inactive users.
$users = User::whereIn('id', array_unique($assignedUsers))->where('status', 'ACTIVE')->pluck('id')->toArray();
// user in OUT_OF_OFFICE
$outOfOffice = User::whereIn('id', array_unique($assignedUsers))->where('status', 'OUT_OF_OFFICE')->get();
foreach ($outOfOffice as $user) {
$delegation = $user->delegationUser()->pluck('id')->toArray();
if ($delegation) {
$users[] = $delegation[0];
}
}
foreach ($assignedGroups as $groupId) {
// getConsolidatedUsers already removes inactive users
$this->getConsolidatedUsers($groupId, $users);
}
return $this->getNextUserFromGroupAssignment($activity->getId(), $users);
}
/**
* Get the next user in a cyclical assignment.
*
* @param string $processTaskUuid
*
* @return binary
* @throws TaskDoesNotHaveUsersException
*/
private function getNextUserFromGroupAssignment($processTaskUuid, $users = null)
{
$last = ProcessRequestToken::where('process_id', $this->id)
->where('element_id', $processTaskUuid)
->orderBy('created_at', 'desc')
->orderBy('id', 'desc')
->first();
if ($users === null) {
$users = $this->getAssignableUsers($processTaskUuid);
}
if (empty($users)) {
return null;
}
sort($users);
if ($last) {
foreach ($users as $user) {
if ($user > $last->user_id) {
return $user;
}
}
}
return $users[0];
}
/**
* Given a request, returns the last user assigned to a task. If it is the
* first time that the task is assigned, null is returned.
*
* @param string $processTaskUuid
*
* @return binary
* @throws TaskDoesNotHaveUsersException
*/
private function getLastUserAssignedToTask($processTaskUuid, $processRequestId)
{
$last = ProcessRequestToken::where('process_id', $this->id)
->where('element_id', $processTaskUuid)
->where('process_request_id', $processRequestId)
->orderBy('created_at', 'desc')
->first();
return $last ? $last->user_id : null;
}
/**
* Get the next user in a user assignment.
*
* @param string $processTaskUuid
*
* @return binary
* @throws TaskDoesNotHaveUsersException
*/
private function getNextUserAssignment($processTaskUuid, $users = null)
{
$last = ProcessRequestToken::where('process_id', $this->id)
->where('element_id', $processTaskUuid)
->orderBy('created_at', 'desc')
->first();
if ($users === null) {
$users = $this->getAssignableUsers($processTaskUuid);
}
if (empty($users)) {
return null;
}
sort($users);
if ($last) {
foreach ($users as $user) {
if ($user > $last->user_id) {
return $user;
}
}
}
return $users[0];
}
/**
* Get the next user if some special assignment is true
*
* @param string $processTaskUuid
*
* @return binary
* @throws TaskDoesNotHaveUsersException
*/
private function getNextUserByRule($activity, $token)
{
$assignmentRules = $activity->getProperty('assignmentRules', null);
$instanceData = $token->getInstance()->getDataStore()->getData();
if ($assignmentRules && $instanceData) {
$list = json_decode($assignmentRules);
$list = ($list === null) ? [] : $list;
foreach ($list as $item) {
$formalExp = new FormalExpression();
$formalExp->setLanguage('FEEL');
$formalExp->setBody($item->expression);
$eval = $formalExp($instanceData);
if ($eval) {
switch ($item->type) {
case 'user_group':
$users = [];
foreach ($item->assignee->users as $user) {
$users[$user] = $user;
}
foreach ($item->assignee->groups as $group) {
$this->getConsolidatedUsers($group, $users);
}
$user = $this->getNextUserFromGroupAssignment(
$activity->getId(),
$users
);
break;
case 'group':
$users = [];
$user = $this->getNextUserFromGroupAssignment(
$activity->getId(),
$this->getConsolidatedUsers($item->assignee, $users)
);
break;
case 'user':
$user = $item->assignee;
break;
case 'requester':
$user = $this->getRequester($activity, $token);
break;
case 'manual':
case 'self_service':
$user = null;
break;
case 'user_by_id':
$mustache = new Mustache_Engine();
$assigneeId = $mustache->render($item->assignee, $instanceData);
$user = $assigneeId;
break;
case 'script':
default:
$user = null;
}
return $user ? User::where('id', $user)->first() : null;
}
}
}
return null;
}
/**
* Evaluates each expression rule and returns the list of groups and users
* that can be assigned to
*
* @param $activity
* @param $token
* @return array
*/
public function getAssigneesFromExpressionRules($activity, $token)
{
$assignmentRules = $activity->getProperty('assignmentRules', null);
$instanceData = $token->getInstance()->getDataStore()->getData();
$groups = [];
$users = [];
$default = [];
if ($assignmentRules && $instanceData) {
$list = json_decode($assignmentRules);
$list = ($list === null) ? [] : $list;
foreach ($list as $item) {
if (is_null($item->expression)) {
$default[] = $item;
continue;
}
$formalExp = new FormalExpression();
$formalExp->setLanguage('FEEL');
$formalExp->setBody($item->expression);
$eval = $formalExp($instanceData);
if ($eval) {
if ($item->type === 'group') {
$groups[] = $item->assignee;