forked from ProcessMaker/processmaker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProcessRequest.php
More file actions
583 lines (527 loc) · 15 KB
/
ProcessRequest.php
File metadata and controls
583 lines (527 loc) · 15 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
<?php
namespace ProcessMaker\Models;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Validation\Rule;
use Log;
use ProcessMaker\Nayra\Contracts\Bpmn\FlowElementInterface;
use ProcessMaker\Nayra\Contracts\Engine\ExecutionInstanceInterface;
use ProcessMaker\Nayra\Engine\ExecutionInstanceTrait;
use ProcessMaker\Traits\ExtendedPMQL;
use ProcessMaker\Traits\SerializeToIso8601;
use ProcessMaker\Traits\SqlsrvSupportTrait;
use Spatie\MediaLibrary\HasMedia\HasMedia;
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
use Throwable;
/**
* Represents an Eloquent model of a Request which is an instance of a Process.
*
* @property string $id
* @property string $process_id
* @property string $user_id
* @property string $process_collaboration_id
* @property string $participant_id
* @property string $name
* @property string $status
* @property string $data
* @property \Carbon\Carbon $initiated_at
* @property \Carbon\Carbon $completed_at
* @property \Carbon\Carbon $updated_at
* @property \Carbon\Carbon $created_at
* @property Process $process
*
* @OA\Schema(
* schema="processRequestEditable",
* @OA\Property(property="user_id", type="string", format="id"),
* @OA\Property(property="callable_id", type="string", format="id"),
* @OA\Property(property="data", type="object"),
* @OA\Property(property="status", type="string", enum={"ACTIVE", "COMPLETED", "ERROR", "CANCELED"}),
* @OA\Property(property="name", type="string"),
* @OA\Property(property="process_id", type="integer"),
* @OA\Property(property="process", type="object"),
* ),
* @OA\Schema(
* schema="processRequest",
* allOf={
* @OA\Schema(ref="#/components/schemas/processRequestEditable"),
* @OA\Schema(
* type="object",
* @OA\Property(property="id", type="string", format="id"),
* @OA\Property(property="process_id", type="string", format="id"),
* @OA\Property(property="process_collaboration_id", type="string", format="id"),
* @OA\Property(property="participant_id", type="string", format="id"),
* @OA\Property(property="process_category_id", type="string", format="id"),
* @OA\Property(property="created_at", type="string", format="date-time"),
* @OA\Property(property="updated_at", type="string", format="date-time"),
* )
* },
* )
*/
class ProcessRequest extends Model implements ExecutionInstanceInterface, HasMedia
{
use ExecutionInstanceTrait;
use SerializeToIso8601;
use HasMediaTrait;
use ExtendedPMQL;
use SqlsrvSupportTrait;
protected $connection = 'data';
/**
* The attributes that aren't mass assignable.
*
* @var array
*/
protected $guarded = [
'id',
'created_at',
'updated_at',
];
/**
* The attributes that should be hidden for serialization.
*
* BPMN data will be hidden. It will be able by its getter.
*
* @var array
*/
protected $hidden = [
'data'
];
/**
* The binary UUID attributes that should be converted to text.
*
* @var array
*/
protected $ids = [
'process_id',
'process_collaboration_id',
'user_id',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'completed_at' => 'datetime:c',
'initiated_at' => 'datetime:c',
'data' => 'array',
'errors' => 'array',
];
/**
* Associated records that can be included with this model
*
* @var array
*/
public static $allowedIncludes = [
'assigned',
'process',
'participants',
];
/**
* Boot the model as a process instance.
*
* @param array $argument
*/
public function __construct(array $argument = [])
{
parent::__construct($argument);
$this->bootElement([]);
}
/**
* Validation rules.
*
* @param null $existing
*
* @return array
*/
public static function rules($existing = null)
{
$self = new self();
$unique = Rule::unique($self->getConnectionName() . '.process_requests')->ignore($existing);
return [
'name' => ['required', 'string', 'max:100', $unique, 'alpha_spaces'],
'data' => 'required',
'status' => 'in:ACTIVE,COMPLETED,ERROR,CANCELED',
'process_id' => 'required|exists:processes,id',
'process_collaboration_id' => 'nullable|exists:process_collaborations,id',
'user_id' => 'exists:users,id',
];
}
/**
* Notification settings of the process.
*
* @param string $entity
* @param string $notificationType
*
* @return array
*/
public function getNotifiables($notificationType)
{
$userIds = collect([]);
$process = $this->process()->first();
$notifiableTypes = $process->notification_settings()
->where('notification_type', $notificationType)
->whereNull('element_id')
->get()->pluck('notifiable_type');
foreach ($notifiableTypes as $notifiableType) {
$userIds = $userIds->merge($this->getNotifiableUserIds($notifiableType));
}
$userIds = $userIds->unique();
$notifiables = $notifiableTypes->implode(', ');
$users = $userIds->implode(', ');
Log::debug("Sending request $notificationType notification to $notifiables (users: $users)");
return User::whereIn('id', $userIds)->get();
}
public function getNotifiableUserIds($notifiableType)
{
switch ($notifiableType) {
case 'requester':
return collect([$this->user_id]);
break;
case 'participants':
return $this->participants()->get()->pluck('id');
break;
default:
return collect([]);
}
}
/**
* Determines if a user has participated in this application. This is done by checking if any delegations
* match this application and passed in user.
*
* @param User $user User to check
*
* @return boolean True if the user participated in this Case in some way
*/
public function hasUserParticipated(User $user)
{
return $this->tokens()
->where('user_id', $user->id)
->exists();
}
/**
* Returns the id of the summary screen that is associated with the end event in which the request
* finished
*
* @return null
*/
public function getSummaryScreen()
{
$endEvents = $this->tokens()->where('element_type', 'end_event')->get();
if ($endEvents->count(0) === 0) {
return null;
}
//get the first token that is and end event to get the summary screen
$definition = $endEvents->first()->getDefinition();
$screen = empty($definition['screenRef']) ? null : Screen::find($definition['screenRef']);
return $screen;
}
/**
* Get screen requested
*
* @return array of screens
*/
public function getScreensRequested()
{
$tokens = $this->tokens()
->whereNotIn('element_type', ['startEvent', 'end_event'])
->where('status', 'CLOSED')
->get();
$screens = [];
foreach ($tokens as $token) {
$definition = $token->getDefinition();
if (array_key_exists('screenRef', $definition)) {
$screen = $token->getScreenVersion();
if ($screen) {
$screen->element_name = $token->element_name;
$screen->element_type = $token->element_type;
$screen->data = $token->data;
$screen->screen_id = $screen->id;
$screen->id = $token->id;
$screens[] = $screen;
}
}
}
return $screens;
}
/**
* Get tokens of the request.
*
*/
public function tokens()
{
return $this->hasMany(ProcessRequestToken::class);
}
/**
* Get the creator/author of this request.
*
*/
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
/**
* Get collaboration of this request.
*
*/
public function collaboration()
{
return $this->belongsTo(
ProcessCollaboration::class,
'process_collaboration_id'
);
}
/**
* Get the creator/author of this request.
*
*/
public function process()
{
return $this->belongsTo(Process::class, 'process_id');
}
/**
* Get users of the request.
*
*/
public function assigned()
{
return $this->hasMany(ProcessRequestToken::class)
->with('user')
->whereNotIn('element_type', ['scriptTask']);
}
/**
* Filter process started with user
*
* @param $query
*
* @param $id User id
*/
public function scopeStartedMe($query, $id)
{
$query->where('user_id', '=', $id);
}
/**
* Filter process not completed
*
* @param $query
*/
public function scopeInProgress($query)
{
$query->where('status', '=', 'ACTIVE');
}
/**
* Filter process completed
*
* @param $query
*/
public function scopeCompleted($query)
{
$query->where(function ($query) {
$query->where('status', '=', 'COMPLETED');
});
}
/**
* Filter process not completed
*
* @param $query
*/
public function scopeNotCompleted($query)
{
$query->where('status', '!=', 'COMPLETED');
$query->where('status', '!=', 'CANCELED');
}
/**
* Returns the list of users that have participated in the request
*
* @return \Illuminate\Database\Eloquent\Relations\HasManyThrough
*/
public function participants()
{
return $this->hasManyThrough(
User::class,
ProcessRequestToken::class,
'process_request_id',
'id',
$this->getKeyName(),
'user_id'
)
->distinct();
}
/**
* Returns the summary data in an array key/value
*/
public function summary()
{
$result = [];
if (is_array($this->data)) {
foreach ($this->data as $key => $value) {
$result[] = [
'key' => $key,
'value' => $value
];
}
}
return $result;
}
/**
* Records an error occurred during the execution of the process.
*
* @param Throwable $exception
* @param FlowElementInterface $element
*/
public function logError(Throwable $exception, FlowElementInterface $element = null)
{
// Get the first line of the message
$array = explode("\n", $exception->getMessage());
$message = '';
$body = '';
while ($array) {
$message = array_shift($array);
if (trim($message)) {
$body = implode("\n", $array);
break;
}
}
$error = [
'message' => $message,
'body' => $body,
'element_id' => $element ? $element->getId() : null,
'element_name' => $element ? $element->getName() : null,
'created_at' => Carbon::now('UTC')->format('c'),
];
$errors = $this->errors ?: [];
$errors[] = $error;
$this->errors = $errors;
$this->status = 'ERROR';
$this->save();
}
public function childRequests()
{
return $this->hasMany(ProcessRequest::class, 'parent_request_id');
}
public function parentRequest()
{
return $this->belongsTo(ProcessRequest::class, 'parent_request_id');
}
/**
* Scheduled task of the request.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function scheduledTasks()
{
return $this->hasMany(ScheduledTask::class, 'process_request_id');
}
/**
* PMQL field alias (created = created_at)
*
* @return string
*/
public function fieldAliasCreated()
{
return 'created_at';
}
/**
* PMQL field alias (modified = updated_at)
*
* @return string
*/
public function fieldAliasModified()
{
return 'updated_at';
}
/**
* PMQL field alias (started = initiated_at)
*
* @return string
*/
public function fieldAliasStarted()
{
return 'initiated_at';
}
/**
* PMQL field alias (completed = completed_at)
*
* @return string
*/
public function fieldAliasCompleted()
{
return 'completed_at';
}
/**
* PMQL value alias for request field
*
* @param string $value
*
* @return callback
*/
public function valueAliasRequest($value)
{
return function($query) use ($value) {
$processes = Process::where('name', $value)->get();
$query->whereIn('process_id', $processes->pluck('id'));
};
}
/**
* PMQL value alias for status field
*
* @param string $value
*
* @return callback
*/
public function valueAliasStatus($value)
{
$statusMap = [
'in progress' => 'ACTIVE',
'completed' => 'COMPLETED',
'error' => 'ERROR',
'canceled' => 'CANCELED',
];
$value = mb_strtolower($value);
return function($query) use ($value, $statusMap) {
if (array_key_exists($value, $statusMap)) {
$query->where('status', $statusMap[$value]);
} else {
$query->where('status', $value);
}
};
}
/**
* PMQL value alias for requester field
*
* @param string $value
*
* @return callback
*/
private function valueAliasRequester($value)
{
$user = User::where('username', $value)->get()->first();
$requests = ProcessRequest::where('user_id', $user->id)->get();
return function($query) use ($requests) {
$query->whereIn('id', $requests->pluck('id'));
};
}
/**
* PMQL value alias for participant field
*
* @param string $value
*
* @return callback
*/
private function valueAliasParticipant($value)
{
$user = User::where('username', $value)->get()->first();
$tokens = ProcessRequestToken::where('user_id', $user->id)->get();
return function($query) use ($tokens) {
$query->whereIn('id', $tokens->pluck('process_request_id'));
};
}
/**
* Get the process version used by this request
*
* @return ProcessVersion
*/
public function processVersion()
{
return $this->belongsTo(ProcessVersion::class, 'process_version_id');
}
}