forked from ProcessMaker/processmaker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScreenTemplate.php
More file actions
768 lines (655 loc) · 26.5 KB
/
ScreenTemplate.php
File metadata and controls
768 lines (655 loc) · 26.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
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
<?php
namespace ProcessMaker\Templates;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use ProcessMaker\Events\TemplateCreated;
use ProcessMaker\Helpers\ScreenTemplateHelper;
use ProcessMaker\ImportExport\Importer;
use ProcessMaker\ImportExport\Options;
use ProcessMaker\Models\Screen;
use ProcessMaker\Models\ScreenCategory;
use ProcessMaker\Models\ScreenTemplates;
use ProcessMaker\Models\ScreenType;
use ProcessMaker\Traits\HasControllerAddons;
use ProcessMaker\Traits\HideSystemResources;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
/**
* Summary of ScreenTemplate
*/
class ScreenTemplate implements TemplateInterface
{
use HasControllerAddons;
use HideSystemResources;
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 screen templates.
*/
public function index(Request $request)
{
$orderBy = $this->getRequestSortBy($request, 'name');
$include = $this->getRequestInclude($request);
$screenType = (string) $request->input('screen_type');
$isPublic = (int) $request->input('is_public', false);
$templates = ScreenTemplates::nonSystem()->with($include)
->where('is_public', $isPublic);
$pmql = $request->input('pmql', '');
$filter = $request->input('filter');
if (!empty($screenType)) {
$templates->where('screen_type', $screenType);
}
if (!empty($pmql)) {
try {
$templates->pmql($pmql);
} catch (\ProcessMaker\Query\SyntaxError $e) {
return response(['error' => 'PMQL error'], 400);
}
}
if (!$isPublic) {
$templates->where('user_id', Auth::user()->id);
}
return $templates
->select(
'screen_templates.id',
'screen_templates.uuid',
'screen_templates.unique_template_id',
'screen_templates.name',
'screen_templates.description',
'screen_templates.version',
'screen_templates.user_id',
'screen_templates.editing_screen_uuid',
'screen_templates.screen_category_id',
'screen_templates.screen_type',
'screen_templates.is_public',
'screen_templates.is_default_template',
'screen_templates.is_system',
'screen_templates.asset_type',
'screen_templates.media_collection',
'screen_templates.screen_custom_css',
'screen_templates.updated_at',
)
->leftJoin('screen_categories as category', 'screen_templates.screen_category_id', '=', 'category.id')
->leftJoin('users as user', 'screen_templates.user_id', '=', 'user.id')
->orderBy(...$orderBy)
->where(function ($query) use ($filter) {
$query->where('screen_templates.name', 'like', '%' . $filter . '%')
->orWhere('screen_templates.description', 'like', '%' . $filter . '%')
->orWhere('user.firstname', 'like', '%' . $filter . '%')
->orWhere('user.lastname', 'like', '%' . $filter . '%')
->orWhereIn('screen_templates.id', function ($qry) use ($filter) {
$qry->select('assignable_id')
->from('category_assignments')
->leftJoin('screen_categories', function ($join) {
$join->on('screen_categories.id', '=', 'category_assignments.category_id');
$join->where('category_assignments.category_type', '=', ScreenCategory::class);
$join->where('category_assignments.assignable_type', '=', ScreenTemplates::class);
})
->where('screen_categories.name', 'like', '%' . $filter . '%');
});
})
->paginate($request->input('per_page', 10))
->through(function ($template) {
$template->append(['is_owner']);
return $template;
});
}
/**
* Show screen template in screen builder
*
* @param mixed $request Request object
* @return array Returns an array with the screen ID
*/
public function show($request) : array
{
$template = ScreenTemplates::find($request->id);
$screen = Screen::where('uuid', $template->editing_screen_uuid)->where('is_template', 1)->first();
// If a screen exists with the editing screen uuid delete that screen and create a new screen.
// This ensures any updates to the template manifest will be reflected
// in the editing screen being shown in screen builder.
if ($screen) {
$screen->forceDelete();
}
// Import the template to create a new screen
$payload = json_decode($template->manifest, true);
$postOptions = [];
foreach ($payload['export'] as $key => $asset) {
$postOptions[$key] = [
'mode' => 'copy',
];
}
$options = new Options($postOptions);
$importer = new Importer($payload, $options);
$manifest = $importer->doImport();
$rootLog = $manifest[$payload['root']]->log;
$screenId = $rootLog['newId'];
$newScreen = Screen::find($screenId);
$newScreen->update([
'is_template' => 1,
'title' => $template->name,
'description' => $template->description,
'asset_type' => 'SCREEN_TEMPLATE',
]);
// Update the screen template editing screen uuid to match the new screen uuid
ScreenTemplates::where('id', $template->id)->update(['editing_screen_uuid' => $newScreen->uuid]);
return ['id' => $newScreen->id];
}
/**
* Save new screen 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();
$screen = Screen::select('custom_css')->where('id', $data['asset_id'])->first();
$screenCustomCss = $screen['custom_css'];
// Get the screen manifest
$manifest = $this->getManifest('screen', $data['asset_id']);
if (array_key_exists('error', $manifest)) {
return response()->json($manifest, 400);
}
// Create a new screen template
$screenTemplate = $this->createScreenTemplate($data, $manifest, $screenCustomCss);
// Save thumbnails
$this->saveThumbnails($screenTemplate, $data['thumbnails']);
return response()->json(['model' => $screenTemplate]);
}
/**
* Create a screen from the selected screen template
*
* @param mixed $request The HTTP request data
* @return JsonResponse The JSON response containing the new screen ID
*
* @throws ModelNotFoundException if the screen template is not found
*/
public function create(Request $request): JsonResponse
{
$request->validate([
'templateId' => 'required|integer',
]);
// Check for existing assets
$existingAssets = $request->existingAssets;
$requestData = $existingAssets ? $request->toArray()['request'] : $request;
// The created screen should be based on the selected screen template,
// regardless of the default template configuration.
$defaultTemplateId = $requestData['defaultTemplateId'] ?? null;
if ($defaultTemplateId) {
$this->updateDefaultTemplate(
$defaultTemplateId,
$requestData['type'],
$requestData['is_public']
);
}
$newScreenId = $this->importScreen($requestData, $existingAssets);
try {
$screen = Screen::findOrFail($newScreenId);
$screen->title = $requestData['title'];
$screen->description = $requestData['description'];
$screen->save();
$this->syncProjectAssets($requestData, $screen->id);
return response()->json(['id' => $newScreenId, 'title' => $screen->title]);
} catch (Exception $e) {
return response([
'message' => $e->getMessage(),
], 422);
}
}
/**
* Get the default template for the given screen type
*
* @param string $screenType The type of the screen (DISPLAY, FORM, CONVERSATIONAL, EMAIL)
* @return ScreenTemplates|null The default screen template or null if not found
*/
public function getDefaultTemplate(string $screenType, int $isPublic): ?ScreenTemplates
{
return ScreenTemplates::query()
->where([
'screen_type' => $screenType,
'is_public' => $isPublic,
'is_default_template' => 1,
])
->first();
}
/**
* Update the default template for the given screen type
*
* @param int $defaultTemplateId The ID of the new default template
* @param string $screenType The type of screen (FORM, DISPLAY, EMAIL, CONVERSATIONAL)
* @param int $isPublic The visibility of the template (0 = private, 1 = public)
*/
public function updateDefaultTemplate(int $defaultTemplateId, string $screenType, int $isPublic): void
{
ScreenTemplates::query()
->where([
'screen_type' => $screenType,
'is_public' => $isPublic,
])
->update([
'is_default_template' => 0,
]);
ScreenTemplates::where('id', $defaultTemplateId)
->update([
'is_default_template' => 1,
]);
}
/**
* Publish a Screen Template to display in the Shared Templates tab
* @param mixed $request
* @return JsonResponse
*/
public function publishTemplate($request) : JsonResponse
{
$id = (int) $request->id;
$template = ScreenTemplates::where('id', $id)->firstOrFail();
$template->is_default_template = false;
$template->is_public = true;
$template->saveOrFail();
return response()->json();
}
/**
* Update the template.
*/
public function updateTemplate(Request $request): JsonResponse
{
try {
if ($request->has('asset_id')) {
$this->updateTemplateManifest($request->asset_id, $request);
} else {
$templateId = $request->has('existingAssetId') ? $request->existingAssetId : $request->id;
$this->updateScreenTemplateData($request->all(), $templateId);
}
$response = response()->json();
} catch (ModelNotFoundException $e) {
$response = response()->json(['message' => 'Template not found.'], 404);
} catch (Exception $e) {
$response = response()->json(['message' => $e->getMessage()], 500);
}
return $response;
}
/**
* Update process template configurations
*
* @param Request $request
*/
public function updateTemplateConfigs($request): JsonResponse
{
try {
$template = ScreenTemplates::findOrFail((int) $request->id);
$this->syncTemplateMedia($template, $request->input('template_media', []));
if ($request->is_public !== $template->is_public) {
$template->is_default_template = false;
}
$template->fill($request->except(['id', 'user_id']))->saveOrFail();
return response()->json();
} catch (Exception $e) {
return response()->json([
'message' => $e->getMessage(),
], 422);
}
}
/**
* Update the manifest of a screen template.
*
* @param int $screenId The ID of the screen
* @param Illuminate\Http\Request $request The HTTP request containing the updated template data
* @return JsonResponse The JSON response indicating the success of the update
*/
public function updateTemplateManifest(int $screenId, $request) : JsonResponse
{
// Get the screen manifest
$manifest = $this->getManifest('screen', $screenId);
if (array_key_exists('error', $manifest)) {
return response()->json($manifest, 400);
}
// Update the screen template manifest
$data = $request->all();
$templateId = $request->has('existingAssetId') ? $request->existingAssetId : $request->id;
$this->updateScreenTemplateData($data, $templateId, $manifest);
// Save screen template thumbnails
$this->saveThumbnails($data['name'], $data['thumbnails']);
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 = ScreenTemplates::select([
'id',
'uuid',
'media_collection',
'name',
'description',
'user_id',
'screen_category_id',
'version',
'screen_type',
'is_public',
])->where('id', $id)->firstOrFail();
$categories = ScreenCategory::orderBy('name')
->where('status', 'ACTIVE')
->pluck('name', 'id')
->toArray();
$addons = $this->getPluginAddons('edit', compact(['template']));
$route = ['label' => 'Screens', 'action' => 'screens'];
$screenTypes = ScreenType::all()->pluck('name')->toArray();
return ['screen', $template, $addons, $categories, $route, $screenTypes];
}
/**
* Delete screen template
* @param mixed $request
* @return bool
*/
public function destroy(int $id) : bool
{
return ScreenTemplates::find($id)->delete();
}
/**
* Import screen 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($payload);
$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);
}
}
/**
* Delete screen template media
* @param mixed $request
* @return bool
*/
public function deleteMediaImages(Request $request)
{
}
/**
* 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
{
$name = $request->name;
$isPublic = filter_var($request->is_public, FILTER_VALIDATE_BOOLEAN) === true ? 1 : 0;
if ($request->has('existingAssetId')) {
return null;
}
$user = Auth::user();
$query = ScreenTemplates::where(['name' => $name]);
if (!$isPublic) {
$query->where('is_public', $isPublic)->where('user_id', $user->id);
} else {
$query->where('is_public', $isPublic);
}
$template = $query->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;
}
/**
* Create a new screen template.
*
* @param array $data The data for creating the screen template
* @param array $payload The payload for the screen template
* @return \App\Models\ScreenTemplates The created screen template
*/
protected function createScreenTemplate(array $data, array $payload, $customCss) : ScreenTemplates
{
$screenTemplate = ScreenTemplates::make($data)->fill([
'manifest' => json_encode($payload),
'user_id' => auth()->id(),
'screen_type' => $data['screen_type'],
'screen_custom_css' => $customCss,
'media_collection' => '',
'is_public' => filter_var($data['is_public'], FILTER_VALIDATE_BOOLEAN) === true ? 1 : 0,
]);
$screenTemplate->saveOrFail();
$screenTemplate->media_collection = 'st-' . $screenTemplate->uuid . '-media';
$screenTemplate->saveOrFail();
return $screenTemplate;
}
private function updateScreenTemplateData(array $data, int $templateId, array $payload = null)
{
$template = ScreenTemplates::where('id', $templateId)->firstOrFail();
$data['is_public'] = filter_var($data['is_public'], FILTER_VALIDATE_BOOLEAN) === true ? 1 : 0;
$data['media_collection'] = $template->media_collection;
if (!is_null($payload)) {
$template->manifest = json_encode($payload);
}
$template->user_id = auth()->id();
$template->update($data);
}
protected function saveThumbnails($screenTemplate, string $thumbnails)
{
$screenTemplate = $this->resolveScreenTemplate($screenTemplate);
$thumbnails = json_decode($thumbnails, true);
foreach ($thumbnails as $thumbnail) {
$screenTemplate
->addMediaFromBase64($thumbnail['url'])
->toMediaCollection($screenTemplate->media_collection);
}
$screenTemplate->saveOrFail();
}
/**
* Resolve the screen template from the given input.
*
* @param mixed $screenTemplate The screen template name or model
* @return \App\Models\ScreenTemplates The resolved screen template model
*/
protected function resolveScreenTemplate($screenTemplate): ScreenTemplates
{
if ($screenTemplate instanceof ScreenTemplates) {
return $screenTemplate;
}
return ScreenTemplates::where('name', $screenTemplate)->firstOrFail();
}
/**
* Imports a screen using the provided data and existing assets.
*
* @param array $data The data for the screen import.
* @param array $existingAssets The existing assets to be considered during the import.
*/
protected function importScreen($data, $existingAssets)
{
$templateId = (int) $data['templateId'];
$template = ScreenTemplates::where('id', $templateId)->firstOrFail();
$template->fill($data->except('id'));
$template->name = $data['title'];
$payload = json_decode($template->manifest, true);
$payload['title'] = $data['title'];
$payload['description'] = $data['description'];
$postOptions = [];
foreach ($payload['export'] as $key => $asset) {
// Exclude the import of screen categories if the category already exists in the database
if ($asset['model'] === 'ProcessMaker\Models\ScreenCategory') {
$screenCategory = ScreenCategory::where('uuid', $key)->first();
if ($screenCategory !== 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 title and description for the new screen
$payload['export'][$key]['attributes']['name'] = $data['title'];
$payload['export'][$key]['attributes']['description'] = $data['description'];
$payload['export'][$key]['attributes']['screen_category_id'] = $data['screen_category_id'];
$payload['export'][$key]['name'] = $data['title'];
$payload['export'][$key]['description'] = $data['description'];
$payload['export'][$key]['screen_category_id'] = $data['screen_category_id'];
}
}
$options = new Options($postOptions);
$importer = new Importer($payload, $options);
$existingAssetsInDatabase = null;
$importingFromTemplate = true;
$manifest = $importer->doImport($existingAssetsInDatabase, $importingFromTemplate);
$rootLog = $manifest[$payload['root']]->log;
$newScreenId = $rootLog['newId'];
$this->handleTemplateOptions($data, $newScreenId);
return $rootLog['newId'];
}
public function handleTemplateOptions($data, $screenId)
{
// Define available options and their corresponding components
$availableOptions = ScreenComponents::getComponents();
$templateOptions = json_decode($data['templateOptions'], true);
$newScreen = Screen::findOrFail($screenId);
if (is_array($templateOptions)) {
// Iterate through available options to handle each one
foreach ($availableOptions as $option => $components) {
// Check if the current options is in the template options
if (!in_array($option, $templateOptions)) {
// Remove the option configs/components from the new screen config
switch($option) {
case 'CSS':
$newScreen->custom_css = null;
break;
case 'Fields':
case 'Layout':
$newConfig = ScreenTemplateHelper::removeScreenComponents($newScreen->config, $components);
$newScreen->config = $newConfig;
break;
default:
break;
}
}
}
}
$newScreen->save();
}
/**
* Synchronizes project assets with the given data and new screen ID.
*/
public function syncProjectAssets($data, int $newScreenId): void
{
if (class_exists(self::PROJECT_ASSET_MODEL_CLASS) && !empty($data['projects'])) {
$manifest = $this->getManifest('screen', $newScreenId);
foreach (explode(',', $data['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),
]);
}
}
}
}
private function syncTemplateMedia($template, $media)
{
// Get the UUIDs of updated media
$updatedTemplateMediaUuids = $this->getMediaUuids($media);
// Delete media that is missing from the request media
$this->deleteMissingMedia($template, $updatedTemplateMediaUuids);
// Get the UUIDs of existing media associated with the template
$existingMediaUuids = $this->getMediaUuids($template->template_media);
// Add new media that is not already associated with the template
$this->addNewMedia($template, $media, $existingMediaUuids);
}
private function getMediaUuids($media)
{
return array_map(function ($obj) {
return $obj['uuid'];
}, $media);
}
private function deleteMissingMedia($template, $updatedTemplateMediaUuids)
{
$result = array_filter($template->template_media, function ($obj) use ($updatedTemplateMediaUuids) {
return !in_array($obj['uuid'], $updatedTemplateMediaUuids);
});
foreach ($result as $media) {
Media::where('uuid', $media['uuid'])->delete();
}
}
private function addNewMedia($template, $media, $existingMediaUuids)
{
$result = array_filter($media, function ($obj) use ($existingMediaUuids) {
return !in_array($obj['uuid'], $existingMediaUuids);
});
foreach ($result as $media) {
$template->addMediaFromBase64($media['url'])->toMediaCollection($template->media_collection);
}
}
/**
* 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_screen_uuid'] = null;
}
}
/**
* Configure import options.
*
* @param array $payload
* @return \Importer\Options
*/
private function configureImportOptions(array $payload): Options
{
$postOptions = [];
foreach ($payload['export'] as $key => $asset) {
// Set import mode for each asset
$postOptions[$key] = ['mode' => 'copy'];
}
return new Options($postOptions);
}
/**
* 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();
}
}