-
Notifications
You must be signed in to change notification settings - Fork 243
Expand file tree
/
Copy pathProcessTrait.php
More file actions
343 lines (299 loc) · 9.97 KB
/
ProcessTrait.php
File metadata and controls
343 lines (299 loc) · 9.97 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
<?php
namespace ProcessMaker\Traits;
use ProcessMaker\Models\Group;
use ProcessMaker\Models\Process;
use ProcessMaker\Models\ProcessVersion;
use ProcessMaker\Models\User;
use ProcessMaker\Nayra\Contracts\Storage\BpmnDocumentInterface;
use ProcessMaker\Repositories\BpmnDocument;
trait ProcessTrait
{
/**
* Parsed process BPMN definitions.
*
* @var BpmnDocumentInterface
*/
private $bpmnDefinitions;
/**
* Get the process definitions from BPMN field.
*
* @param bool $forceParse
*
* @return BpmnDocument
*/
public function getDefinitions($forceParse = false, $engine = null)
{
if ($forceParse || empty($this->bpmnDefinitions)) {
$version = $this instanceof ProcessVersion ? $this : null;
$options = [
'process' => $this instanceof ProcessVersion ? $this->process : $this,
'process_version' => $version,
];
!$engine ?: $options['engine'] = $engine;
$this->bpmnDefinitions = app(BpmnDocumentInterface::class, $options);
if ($this->bpmn) {
$this->bpmnDefinitions->loadXML($this->bpmn);
}
}
return $this->bpmnDefinitions;
}
/**
* Get BPMN DOM Document
*
* @return BpmnDocument
*/
public function getDomDocument()
{
$document = new BpmnDocument($this);
$document->loadXML($this->bpmn);
return $document;
}
/**
* Set a value on the properties json column
*
* @param string $name
* @param mixed $value
* @return void
*/
public function setProperty($name, $value)
{
$properties = $this->properties;
$properties[$name] = $value;
$this->properties = $properties;
}
/**
* Get a value from the properties json column
*
* @param string $name
* @return mixed
*/
public function getProperty($name)
{
return isset($this->properties[$name]) ? $this->properties[$name] : null;
}
/**
* Set the manager id
*
* @param int|array $value
* @return void
*/
public function setManagerIdAttribute($value)
{
$this->setProperty('manager_id', $value);
}
/**
* Get the the manager id
*
* @return array|null
*/
public function getManagerIdAttribute()
{
$property = $this->getProperty('manager_id');
// If property is null or undefined, return null
if (is_null($property) || $property === 'undefined') {
return null;
}
// If it's already an array, return it
if (is_array($property)) {
return $property;
}
// If it's a single value, return it as an array
return [$property];
}
/**
* Get the first process manager relationship
* Note: This returns the first manager from the JSON properties->manager_id array
* For multiple managers, use getManagers() method instead
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function manager()
{
$managerIds = $this->getManagerIdAttribute();
if (empty($managerIds) || !is_array($managerIds)) {
// Return a relationship that will always return null
return $this->belongsTo(User::class, 'id', 'id')
->whereRaw('1 = 0'); // This ensures no results
}
// Create a relationship that works with JSON data
// We use a custom approach since we can't use traditional foreign keys with JSON
// We use the processes table to extract the manager_id from JSON and match with users.id
$tableName = $this instanceof ProcessVersion ? 'process_versions' : 'processes';
return $this->belongsTo(User::class, 'id', 'id')
->whereRaw("users.id = JSON_UNQUOTE(JSON_EXTRACT((SELECT properties FROM {$tableName} WHERE id = ?), '$.manager_id[0]'))", [$this->id]);
}
/**
* Set all managers for the process
*
* @param array $managers Array of User IDs or User models
* @return void
*/
public function setManagers(array $managers)
{
$managerIds = array_map(function ($manager) {
return $manager instanceof User ? $manager->id : $manager;
}, $managers);
$this->setManagerIdAttribute($managerIds);
}
/**
* Get all managers as User models
*
* @return \Illuminate\Database\Eloquent\Collection
*/
public function getManagers()
{
$managerIds = $this->getManagerIdAttribute();
if (is_null($managerIds)) {
return collect();
}
if (!is_array($managerIds)) {
$managerIds = [$managerIds];
}
return User::whereIn('id', $managerIds)->get();
}
/**
* Get the users who can start this process
*/
public function usersCanCancel()
{
$query = $this->morphedByMany(User::class, 'processable')
->wherePivot('method', 'CANCEL');
return $this instanceof Process
? $query->wherePivot('process_version_id', '=', null)
: $query;
}
/**
* Get the groups who can start this process
*/
public function groupsCanCancel()
{
$query = $this->morphedByMany(Group::class, 'processable')
->wherePivot('method', 'CANCEL');
return $this instanceof Process
? $query->wherePivot('process_version_id', '=', null)
: $query;
}
/**
* Get the users who can start this process
*/
public function usersCanEditData()
{
$query = $this->morphedByMany(User::class, 'processable')
->wherePivot('method', 'EDIT_DATA');
return $this instanceof Process
? $query->wherePivot('process_version_id', '=', null)
: $query;
}
/**
* Get the groups who can start this process
*/
public function groupsCanEditData()
{
$query = $this->morphedByMany(Group::class, 'processable')
->wherePivot('method', 'EDIT_DATA');
return $this instanceof Process
? $query->wherePivot('process_version_id', '=', null)
: $query;
}
/**
* Get the tasks of the process
*
* @return array
*/
public function getTasks()
{
$response = [];
if (empty($this->bpmn)) {
return $response;
}
$definitions = new BpmnDocument($this);
$definitions->loadXML($this->bpmn);
$types = [
'task',
'userTask',
'manualTask',
'scriptTask',
'serviceTask',
'callActivity',
];
foreach ($types as $type) {
$tasks = $definitions->getElementsByTagNameNS(BpmnDocument::BPMN_MODEL, $type);
foreach ($tasks as $task) {
$response[] = [
'id' => $task->getAttribute('id'),
'name' => $task->getAttribute('name'),
'type' => $task->localName,
];
}
}
return $response;
}
public function getCounts()
{
$result = $this->requests()
->selectRaw('status, count(*) as count')
->groupBy('status')
->get();
$completed = $result->where('status', 'COMPLETED')->first()?->count ?? 0;
$in_progress = $result->where('status', 'ACTIVE')->first()?->count ?? 0;
return [
'completed' => $completed,
'in_progress' => $in_progress,
'total' => $completed + $in_progress,
];
}
/**
* Get the count of stages per request.
*
* This method retrieves the count of stages based on the last_stage_id for each request.
* If a JSON string of stages is provided, it decodes it; otherwise, it fetches all stages
* from the database. The method returns an array containing each stage's ID, name, and count.
*
* @param string|null $stages A JSON string representing stages. If provided, it will be decoded;
* if null, all stages will be fetched from the database.
* @return array An array of associative arrays, each containing:
* - 'id': The ID of the stage.
* - 'name': The name of the stage.
* - 'count': The count of occurrences of the stage based on last_stage_id.
*/
public function getStagesSummary($stages = null)
{
if (!empty($stages)) {
$allStages = $stages;
} else {
return [];
}
// Assuming 'stages' is a relationship defined in the model
$result = $this->requests()
->selectRaw('last_stage_id, count(*) as count')
->groupBy('last_stage_id')
->get();
// Prepare an array to hold the counts for each stage
$stageCounts = [];
// Initialize stage counts with zero for all stages
foreach ($allStages as $stage) {
$stageCounts[] = [
'id' => $stage['id'] ?? 0,
'name' => $stage['name'] ?? 'Unknow Stage',
'count' => 0, // Initialize count to 0 for each stage
'percentage' => 0, // Initialize percentaje to 0 for each stage
];
}
foreach ($result as $stage) {
foreach ($stageCounts as $key => &$countData) {
if ($countData['id'] == $stage->last_stage_id) {
$countData['count'] = $stage->count; // Update the count
}
}
}
// Calculate the total count of all stages
$totalCount = array_sum(array_column($stageCounts, 'count'));
// Calculate the percentage for each stage
foreach ($stageCounts as &$countData) {
if ($totalCount > 0) {
$countData['percentage'] = ($countData['count'] / $totalCount) * 100;
}
}
return $stageCounts;
}
}