-
Notifications
You must be signed in to change notification settings - Fork 248
Expand file tree
/
Copy pathProcessTemplate.php
More file actions
606 lines (522 loc) · 22.5 KB
/
ProcessTemplate.php
File metadata and controls
606 lines (522 loc) · 22.5 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
<?php
namespace ProcessMaker\Templates;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use ProcessMaker\Events\TemplateCreated;
use ProcessMaker\Http\Controllers\Api\ExportController;
use ProcessMaker\ImportExport\Exporter;
use ProcessMaker\ImportExport\Exporters\ProcessExporter;
use ProcessMaker\ImportExport\Importer;
use ProcessMaker\ImportExport\Options;
use ProcessMaker\Models\Process;
use ProcessMaker\Models\ProcessCategory;
use ProcessMaker\Models\ProcessTemplates;
use ProcessMaker\Models\WizardTemplate;
use ProcessMaker\Traits\HasControllerAddons;
use SebastianBergmann\CodeUnit\Exception;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
/**
* Summary of ProcessTemplate
*/
class ProcessTemplate implements TemplateInterface
{
use HasControllerAddons;
use TemplateRequestHelperTrait;
const PROJECT_ASSET_MODEL_CLASS = 'ProcessMaker\Package\Projects\Models\ProjectAsset';
/**
* List process templates
*
* @param Request $request The request object.
*
* @return array An array containing the list of process templates.
*/
public function index(Request $request)
{
return ProcessTemplates::nonSystem()
->with($this->getRequestInclude($request))
->withFilters($request->input('filter'))
->orderBy(...$this->getRequestSortBy($request, 'name'))
->leftJoin('process_categories as category', 'process_templates.process_category_id', '=', 'category.id')
->leftJoin('users as user', 'process_templates.user_id', '=', 'user.id')
->select([
'process_templates.id',
'process_templates.uuid',
'process_templates.key',
'process_templates.name',
'process_templates.description',
'process_templates.version',
'process_templates.process_id',
'process_templates.editing_process_uuid',
'process_templates.user_id',
'process_templates.process_category_id',
'process_templates.svg',
'process_templates.is_system',
'process_templates.asset_type',
'process_templates.created_at',
'process_templates.updated_at',
])
->get();
}
/**
* Show process template in modeler
*
* @param mixed $request Request object
* @return array Returns an array with the process ID
*/
public function show($request) : array
{
$template = ProcessTemplates::find($request->id);
$process = Process::where('uuid', $template->editing_process_uuid)->where('is_template', 1)->first();
// If a process exists with the template editing process uuid delete that process and create a new process
// this ensures any updates to the template manifest will be reflected
// in the editing process being shown in modeler.
if ($process) {
// We need to remove the relations with other tables first
$process->notification_settings()->delete();
$process->forceDelete();
}
// Otherwise we need to import the template and create a new process
$payload = json_decode($template->manifest, true);
$export = array_filter($payload['export'], function ($asset) {
return $asset['type'] !== 'CommentConfiguration';
});
// Loop through each asset in the "export" array and set postOptions "mode" accordingly
$postOptions = [];
foreach ($export as $key => $asset) {
$mode = 'copy';
$saveMode = 'saveAllAssets';
if (array_key_exists('saveAssetsMode', $asset) && $asset['saveAssetsMode'] === 'saveModelOnly') {
$saveMode = 'saveModelOnly';
}
if ($payload['root'] != $key && $saveMode === 'saveModelOnly' && substr($asset['type'], -8) === 'Category') {
$mode = 'discard'; // set mode to 'discard' for category assets that are not the root
}
$postOptions[$key] = [
'mode' => $mode,
'isTemplate' => true,
'saveAssetsMode' => $saveMode,
];
if ($payload['root'] === $key) {
// Set name, description, and user_id attributes for root asset
$payload['export'][$key]['attributes'] = [
'name' => $template->name,
'description' => $template->description,
'is_template' => true,
'bpmn' => $asset['attributes']['bpmn'],
'user_id' => $template->user_id ?? \Auth::user()->getKey(),
];
// Also set the name, description, and is_template directly on the asset
$payload['export'][$key]['name'] = $template->name;
$payload['export'][$key]['description'] = $template->description;
}
if (in_array($asset['type'], ['Process', 'Screen', 'Scripts', 'Collections', 'DataConnector'])) {
$payload['export'][$key]['attributes']['is_template'] = true; // set attributes for all assets
$payload['export'][$key]['is_template'] = true; // set attributes for all assets
}
}
$options = new Options($postOptions);
$importer = new Importer($payload, $options);
$manifest = $importer->doImport();
$rootLog = $manifest[$payload['root']]->log;
$processId = $rootLog['newId'];
$processUuid = Process::select('uuid')->where('id', $processId)->first()->uuid;
ProcessTemplates::where('id', $template->id)->update(['editing_process_uuid' => $processUuid]);
// Return an array with the process ID
return ['id' => $processId];
}
/**
* Save new process template
* @param mixed $request The HTTP request containing the template data
* @return JsonResponse The JSON response with the saved template model
*/
public function save($request) : JsonResponse
{
$data = $request->all();
// Find the required model
$model = (new ExportController)->getModel('process')->findOrFail($data['asset_id']);
// Get the process manifest
$response = $this->getManifest('process', $data['asset_id']);
if (array_key_exists('error', $response)) {
return response()->json($response, 400);
}
// Array of post options
$uuid = $model->uuid;
// Loop through each asset in the "export" array and set postOptions "mode" accordingly
$postOptions = [];
foreach ($response['export'] as $key => $asset) {
$mode = $data['saveAssetsMode'] === 'saveAllAssets' ? 'copy' : 'discard';
if ($key === $uuid) {
$mode = 'copy';
}
$postOptions[$key] = [
'mode' => $mode,
'isTemplate' => true,
'saveAssetsMode' => $data['saveAssetsMode'],
];
}
$options = new Options($postOptions);
// Create an exporter instance
$exporter = new Exporter();
$exporter->export($model, ProcessExporter::class, $options);
$payload = $exporter->payload();
// Create a new process template
$processTemplate = ProcessTemplates::make($data)->fill([
'manifest' => json_encode($payload),
'svg' => Arr::get($payload, "export.{$payload['root']}.attributes.svg"),
'process_id' => $data['asset_id'],
'user_id' => \Auth::user()->id,
]);
$processTemplate->saveOrFail();
return response()->json(['model' => $processTemplate]);
}
/**
* Create a process from the selected process template
*
* @param mixed $request The HTTP request data
* @return JsonResponse The JSON response containing the new process ID
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException if the process template is not found
*/
public function create($request) : JsonResponse
{
$templateId = (int) $request->id;
$template = ProcessTemplates::where('id', $templateId)->firstOrFail();
$template->fill($request->except('id'));
$payload = json_decode($template->manifest, true);
// Check for existing assets
$existingAssets = $request->existingAssets;
$requestData = $existingAssets ? $request->toArray()['request'] : $request;
$payload['name'] = $requestData['name'];
$payload['description'] = $requestData['description'];
$postOptions = [];
foreach ($payload['export'] as $key => $asset) {
// Exclude the import of comment configurations to account for the unavailability
// of the comment configuration table in the database.
if ($asset['model'] === 'ProcessMaker\Package\PackageComments\Models\CommentConfiguration') {
unset($payload['export'][$key]);
continue;
}
// Exclude the import of process categories if the category already exists in the database
if ($asset['model'] === 'ProcessMaker\Models\ProcessCategory') {
$processCategory = ProcessCategory::where('uuid', $key)->first();
if ($processCategory !== null) {
unset($payload['export'][$key]);
continue;
}
}
$postOptions[$key] = [
'mode' => 'copy',
'isTemplate' => false,
'saveAssetsMode' => 'saveAllAssets',
];
if ($existingAssets) {
foreach ($existingAssets as $item) {
$uuid = $item['uuid'];
if (isset($postOptions[$uuid])) {
$postOptions[$uuid]['mode'] = $item['mode'];
}
}
}
if ($payload['root'] === $key) {
// Set name and description for the new process
$payload['export'][$key]['attributes']['name'] = $requestData['name'];
$payload['export'][$key]['attributes']['description'] = $requestData['description'];
$payload['export'][$key]['attributes']['process_category_id'] = $requestData['process_category_id'];
// Store the wizard template uuid on the process to rerun the helper process
if (isset($requestData['wizardTemplateUuid'])) {
$properties = json_decode($payload['export'][$key]['attributes']['properties'], true);
$properties['wizardTemplateUuid'] = $requestData['wizardTemplateUuid'];
$payload['export'][$key]['attributes']['properties'] = json_encode($properties);
}
// Store the helper process request id that initiated the process creation
if (isset($requestData['helperProcessRequestId'])) {
$properties = json_decode($payload['export'][$key]['attributes']['properties'], true);
$properties['helperProcessRequestId'] = $requestData['helperProcessRequestId'];
$payload['export'][$key]['attributes']['properties'] = json_encode($properties);
}
$payload['export'][$key]['name'] = $requestData['name'];
$payload['export'][$key]['description'] = $requestData['description'];
$payload['export'][$key]['process_category_id'] = $requestData['process_category_id'];
if (!isset($existingAssets)) {
$payload['export'][$key]['process_manager_id'] = $requestData['manager_id'];
}
}
if (in_array($asset['type'], ['Process', 'Screen', 'Scripts', 'Collections', 'DataConnector'])) {
$payload['export'][$key]['attributes']['is_template'] = false;
$payload['export'][$key]['is_template'] = false;
}
}
$options = new Options($postOptions);
$importer = new Importer($payload, $options);
$existingAssetsInDatabase = null;
$importingFromTemplate = true;
$manifest = $importer->doImport($existingAssetsInDatabase, $importingFromTemplate);
$rootLog = $manifest[$payload['root']]->log;
$processId = $rootLog['newId'];
$process = Process::findOrFail($processId);
$process->user_id = Auth::id();
$process->save();
$this->syncLaunchpadAssets($request, $process);
if (class_exists(self::PROJECT_ASSET_MODEL_CLASS) && !empty($requestData['projects'])) {
$manifest = $this->getManifest('process', $processId);
foreach (explode(',', $requestData['projects']) as $project) {
foreach ($manifest['export'] as $asset) {
$model = $asset['model']::find($asset['attributes']['id']);
$projectAsset = new (self::PROJECT_ASSET_MODEL_CLASS);
$projectAsset->create([
'project_id' => $project,
'asset_id' => $model->id,
'asset_type' => get_class($model),
]);
}
}
}
return response()->json(['processId' => $processId, 'processName' => $process->name]);
}
/**
* Update process template bpmn.
* @param mixed $request
* @return JsonResponse
*/
public function updateTemplate($request) : JsonResponse
{
$id = (int) $request->id;
$template = ProcessTemplates::where('id', $id)->firstOrFail();
$manifest = $this->getManifest('process', $request->asset_id);
$rootUuid = Arr::get($manifest, 'root');
$export = Arr::get($manifest, 'export');
$svg = Arr::get($export, $rootUuid . '.attributes.svg', null);
$template->fill($request->all());
$template->svg = $svg;
$template->manifest = json_encode($manifest);
try {
$template->saveOrFail();
return response()->json();
} catch (Exception $e) {
return response(
['message' => $e->getMessage(),
'errors' => ['bpmn' => $e->getMessage()], ],
422
);
}
}
/**
* Update process template configurations
* @param Request
* @return JsonResponse
*/
public function updateTemplateConfigs($request) : JsonResponse
{
$id = (int) $request->id;
$template = ProcessTemplates::where('id', $id)->firstOrFail();
$oldTemplateName = $template->name;
$template->fill($request->except('id'));
$template->user_id = Auth::user()->id;
$process = Process::where('name', $oldTemplateName)->where('is_template', 1)->first();
if ($process) {
$process->fill($request->except('id'));
}
try {
$template->saveOrFail();
return response()->json();
} catch (\Exception $e) {
return response([
'message' => $e->getMessage(),
'errors' => [
'bpmn' => $e->getMessage(),
],
], 422);
}
}
public function updateTemplateManifest(int $processId, $request) : JsonResponse
{
$data = $request->all();
$model = (new ExportController)->getModel('process')->findOrFail($processId);
$model->fill($data);
$model->saveOrFail();
$manifest = $this->getManifest('process', $processId);
$postOptions = [];
foreach ($manifest['export'] as $key => $asset) {
$postOptions[$key] = [
'mode' => 'update',
'isTemplate' => true,
'saveAssetsMode' => 'saveAllAssets',
];
}
$options = new Options($postOptions);
// Create an exporter instance
$exporter = new Exporter();
$exporter->export($model, ProcessExporter::class, $options);
$payload = $exporter->payload();
// Extract svg from payload
$svg = Arr::get($payload, 'export.' . $payload['root'] . '.attributes.svg');
// Update the process template manifest, svg, and user_id
$processTemplate = ProcessTemplates::where('name', $data['name'])->update([
'manifest' => json_encode($payload),
'svg' => $svg,
'user_id' => \Auth::user()->id,
]);
return response()->json();
}
/**
* Displays Template Configurations
*
* @param int $id ID of the process template
* @return array An array containing the template object, addons, and categories
* @throws Illuminate\Database\Eloquent\ModelNotFoundException If no template is found with the given ID
*/
public function configure(int $id) : array
{
$template = (object) [];
$query = ProcessTemplates::select(['name', 'description', 'process_category_id', 'version'])->where('id', $id)->firstOrFail();
$template->id = $id;
$template->name = $query->name;
$template->description = $query->description;
$template->process_category_id = $query['process_category_id'];
$template->version = $query->version;
$template->is_public = $query->is_public;
$categories = ProcessCategory::orderBy('name')
->where('status', 'ACTIVE')
->get()
->pluck('name', 'id')
->toArray();
$addons = $this->getPluginAddons('edit', compact(['template']));
$route = ['label' => 'Processes', 'action' => 'processes'];
return ['process', $template, $addons, $categories, $route, null];
}
/**
* Delete process template
* @param mixed $request
* @return bool
*/
public function destroy(int $id) : bool
{
return ProcessTemplates::where('id', $id)->delete();
}
/**
* Import process template
* @param Request
* @return JsonResponse
*/
public function importTemplate($request) : JsonResponse
{
try {
$jsonData = $request->file('file')->get();
$payload = json_decode($jsonData, true);
$this->preparePayloadForImport($payload);
$importOptions = $this->configureImportOptions($request);
$this->performImport($payload, $importOptions);
// Dispatch event for template creation
TemplateCreated::dispatch($payload);
return response()->json([], 200);
} catch (\Exception $e) {
return response()->json(['message' => $e->getMessage()], 422);
}
}
/**
* Check if an existing process template with the same name exists.
* If exists, return an array with the existing template ID and name.
* Otherwise, return null.
* @param Request $request
*
* @return array|null Array containing the existing template ID and name or null if no existing template found
*/
public function existingTemplate($request) : ?array
{
$templateId = $request->id;
$name = $request->name;
$template = ProcessTemplates::where(['name' => $name])->where('id', '!=', $templateId)->first();
if ($template !== null) {
// If same asset has been Saved as Template previously, offer to choose between “Update Template” and “Save as New Template”
return ['id' => $template->id, 'name' => $name, 'owner_id' => $template->user_id];
}
return null;
}
/**
* Syncs launchpad assets from a guided template to the imported process.
*
* @param Illuminate\Http\Request $request
* @param App\Models\Process $process
* @return void
*/
protected function syncLaunchpadAssets($request, $process)
{
if (empty($request->wizardTemplateUuid)) {
return;
}
// Add media collection for the imported process
$processMediaCollectionName = $process->uuid . '_images_carousel';
$process->addMediaCollection($processMediaCollectionName);
// Retrieve the guided template by UUID
$guidedTemplateUuid = $request->input('wizardTemplateUuid');
$template = WizardTemplate::where('uuid', $guidedTemplateUuid)->first();
// Get launchpad slides media from the guided template
$templateLaunchpadSlides = $template->getMedia($template->media_collection, function (Media $media) {
return $media->custom_properties['media_type'] === 'launchpadSlides';
});
// Iterate over each launchpad slide and add to the imported process media collection
foreach ($templateLaunchpadSlides as $slide) {
// Extract order index from file name
$orderIndex = $this->extractOrderIndexFromFileName($slide->getPath());
// Add media to the imported process collection
$media = $process->addMedia($slide->getPath())->preservingOriginal()->toMediaCollection($processMediaCollectionName);
// Set order column if available
if (!is_null($orderIndex)) {
$media->order_column = $orderIndex;
$media->save();
}
}
}
/**
* Extracts order index from the file name.
*
* @param string $fileName
* @return int|null
*/
protected function extractOrderIndexFromFileName($fileName)
{
preg_match('/\d+/', basename($fileName), $matches);
if (!empty($matches)) {
return intval($matches[0]) - 1;
}
return null;
}
/**
* Prepare payload for import.
*
* @param array $payload
* @return void
*/
private function preparePayloadForImport(array &$payload): void
{
foreach ($payload['export'] as &$asset) {
// Modify asset attributes as needed
$asset['attributes']['editing_process_uuid'] = null;
$asset['attributes']['process_id'] = null;
}
}
/**
* Configure import options.
*
* @param array $payload
* @return \Importer\Options
*/
private function configureImportOptions(Request $request): Options
{
return new Options(json_decode(file_get_contents(utf8_decode($request->file('options'))), true));
}
/**
* Perform the import operation.
*
* @param array $payload
* @param \Importer\Options $options
* @return void
*/
private function performImport(array $payload, Options $options): void
{
$importer = new Importer($payload, $options);
$importer->doImport();
}
}