diff --git a/ProcessMaker/Exception/PluginInstallException.php b/ProcessMaker/Exception/PluginInstallException.php index 03bc81ac4b..6e52a221de 100644 --- a/ProcessMaker/Exception/PluginInstallException.php +++ b/ProcessMaker/Exception/PluginInstallException.php @@ -2,6 +2,7 @@ namespace ProcessMaker\Exception; +use ProcessMaker\Managers\PluginManager; use RuntimeException; class PluginInstallException extends RuntimeException @@ -45,4 +46,9 @@ public static function failedToCopyFile(string $srcPath, string $destPath): self { return new self("Failed to copy file: {$srcPath} to {$destPath}"); } -} \ No newline at end of file + + public static function emptyRepository(): self + { + return new self(PluginManager::EMPTY_REPOSITORY_MESSAGE); + } +} diff --git a/ProcessMaker/Http/Controllers/Api/DeployProcess.php b/ProcessMaker/Http/Controllers/Api/DeployProcess.php index e9eed4beab..b9abdb2695 100644 --- a/ProcessMaker/Http/Controllers/Api/DeployProcess.php +++ b/ProcessMaker/Http/Controllers/Api/DeployProcess.php @@ -9,11 +9,13 @@ use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Validator; +use Illuminate\Validation\ValidationException; use ProcessMaker\Exception\MissingBpmnReferenceException; use ProcessMaker\Http\Controllers\Api\Concerns\AppliesDeployVersionName; use ProcessMaker\Http\Controllers\Controller; use ProcessMaker\Models\Process; use ProcessMaker\Services\DeployCategoryResolver; +use ProcessMaker\Services\DeployProcessAlternativeB; use ProcessMaker\Services\ProcessBpmnReferenceService; use Throwable; @@ -34,6 +36,7 @@ class DeployProcess extends Controller public function __construct( private readonly ProcessBpmnReferenceService $references, private readonly DeployCategoryResolver $categories, + private readonly DeployProcessAlternativeB $alternativeB, ) { } @@ -41,8 +44,10 @@ public function deployProcess(Request $request): JsonResponse { $name = (string) $request->input('name'); $isUpdate = Process::where('name', $name)->exists(); + // Alternative B writes drafts or B versions, not asset version history. + $needsVersionName = $isUpdate && !$this->targetsAlternativeB($request); - if ($unavailable = $this->ensureDeployVersionHistoryAvailable($isUpdate)) { + if ($unavailable = $this->ensureDeployVersionHistoryAvailable($needsVersionName)) { return $unavailable; } @@ -53,7 +58,9 @@ public function deployProcess(Request $request): JsonResponse 'name' => 'required|string|max:255', 'description' => 'nullable|string|max:65535', 'process_category_name' => 'nullable|string|max:255', - ], $isUpdate), + 'alternative' => 'nullable|in:A,B', + 'publish' => 'nullable|boolean', + ], $needsVersionName), ); if ($validator->fails()) { @@ -69,29 +76,59 @@ public function deployProcess(Request $request): JsonResponse private function saveDeployedProcess(Request $request): JsonResponse { try { - $bpmn = $this->references->resolveNamedReferences($request->input('bpmn')); - $xmlErrors = $this->validateXml($bpmn); - if ($xmlErrors !== []) { - return response()->json([ - 'success' => false, - 'message' => 'Invalid BPMN XML.', - 'errors' => ['bpmn' => $xmlErrors], - ], 422); - } - - [$process, $created] = $this->upsertProcessByName($request, $bpmn); - - return response()->json([ - 'success' => true, - 'action' => $created ? 'created' : 'updated', - 'process_id' => $process->id, - 'name' => $process->name, - ]); + return $this->deployFromRequest($request); } catch (Throwable $exception) { return $this->deployProcessFailureResponse($exception); } } + private function deployFromRequest(Request $request): JsonResponse + { + $bpmn = $this->references->resolveNamedReferences($request->input('bpmn')); + $xmlErrors = $this->validateXml($bpmn); + if ($xmlErrors !== []) { + return response()->json([ + 'success' => false, + 'message' => 'Invalid BPMN XML.', + 'errors' => ['bpmn' => $xmlErrors], + ], 422); + } + + if ($this->targetsAlternativeB($request)) { + return $this->saveDeployedAlternativeB($request, $bpmn); + } + + [$process, $created] = $this->upsertProcessByName($request, $bpmn); + + return response()->json([ + 'success' => true, + 'action' => $created ? 'created' : 'updated', + 'process_id' => $process->id, + 'name' => $process->name, + ]); + } + + private function targetsAlternativeB(Request $request): bool + { + return $request->input('alternative') === 'B'; + } + + private function saveDeployedAlternativeB(Request $request, string $bpmn): JsonResponse + { + $process = Process::where('name', $request->input('name'))->first(); + $publish = $request->boolean('publish'); + $result = $this->alternativeB->deploy($process, $bpmn, $publish); + + return response()->json([ + 'success' => true, + 'action' => $publish ? 'published' : 'draft', + 'alternative' => 'B', + 'process_id' => $process->id, + 'name' => $process->name, + 'process_version_id' => $result['version_id'], + ]); + } + /** * @return array{0: Process, 1: bool} */ @@ -144,6 +181,14 @@ private function upsertProcessByName(Request $request, string $bpmn): array private function deployProcessFailureResponse(Throwable $exception): JsonResponse { + if ($exception instanceof ValidationException) { + return response()->json([ + 'success' => false, + 'message' => collect($exception->errors())->flatten()->first(), + 'errors' => $exception->errors(), + ], 422); + } + if ($exception instanceof MissingBpmnReferenceException) { return response()->json([ 'success' => false, diff --git a/ProcessMaker/Http/Controllers/Api/DeployScreen.php b/ProcessMaker/Http/Controllers/Api/DeployScreen.php index 70af34a570..dd3ea90ce0 100644 --- a/ProcessMaker/Http/Controllers/Api/DeployScreen.php +++ b/ProcessMaker/Http/Controllers/Api/DeployScreen.php @@ -132,7 +132,7 @@ public function getScreenYaml(Request $request) } [$screen, $screenVersion] = $resolved; - $config = $this->removeInspectorMetadata($screenVersion->config ?? []); + $config = $this->withEmptyInspector($this->removeInspectorMetadata($screenVersion->config ?? [])); $data = [ 'config' => $config, 'computed' => $screenVersion->computed, @@ -148,6 +148,47 @@ public function getScreenYaml(Request $request) ->header('X-Screen-Name', $screen->title); } + /** + * The export drops the (large) inspector metadata, but the YAML contract expects every + * item to carry `inspector: []`, so a pulled screen can be pushed back unchanged. + * + * @param array $config + * @return array + */ + private function withEmptyInspector(array $config): array + { + foreach ($config as $index => $page) { + if (is_array($page) && isset($page['items']) && is_array($page['items'])) { + $config[$index]['items'] = $this->addEmptyInspector($page['items']); + } + } + + return $config; + } + + /** + * @param array $items + * @return array + */ + private function addEmptyInspector(array $items): array + { + foreach ($items as $index => $item) { + if (!is_array($item)) { + continue; + } + if (isset($item['component']) && !array_key_exists('inspector', $item)) { + $item['inspector'] = []; + } + if (isset($item['items']) && is_array($item['items'])) { + $item['items'] = $this->addEmptyInspector($item['items']); + } + // A FormMultiColumn holds a list of columns, and each column is a list of items. + $items[$index] = array_is_list($item) && $item !== [] ? $this->addEmptyInspector($item) : $item; + } + + return $items; + } + /** * @return array{0: Screen, 1: object}|JsonResponse */ diff --git a/ProcessMaker/Http/Controllers/Api/DeployScript.php b/ProcessMaker/Http/Controllers/Api/DeployScript.php index ae64122157..655940d9a7 100644 --- a/ProcessMaker/Http/Controllers/Api/DeployScript.php +++ b/ProcessMaker/Http/Controllers/Api/DeployScript.php @@ -10,6 +10,8 @@ use ProcessMaker\Http\Controllers\Api\Concerns\AppliesDeployVersionName; use ProcessMaker\Http\Controllers\Controller; use ProcessMaker\Models\Script; +use ProcessMaker\Models\ScriptExecutor; +use ProcessMaker\Models\User; use ProcessMaker\Services\DeployCategoryResolver; use ProcessMaker\Services\ScriptExecutorResolver; @@ -47,6 +49,17 @@ public function deployScript(Request $request): JsonResponse $name = (string) $request->input('name'); $isUpdate = Script::where('title', $name)->exists(); + $rejection = $this->rejectDeployRequest($request, $name, $isUpdate); + + return $rejection ?? $this->persistDeployedScript($request, $name); + } + + /** + * Return the response that stops a deploy (version history unavailable, + * validation failure, or forbidden executor binding), or null to proceed. + */ + private function rejectDeployRequest(Request $request, string $name, bool $isUpdate): ?JsonResponse + { if ($unavailable = $this->ensureDeployVersionHistoryAvailable($isUpdate)) { return $unavailable; } @@ -58,8 +71,11 @@ public function deployScript(Request $request): JsonResponse 'name' => 'required|string', 'description' => 'nullable|string|max:65535', 'script_category_name' => 'nullable|string|max:255', + 'script_executor_id' => 'nullable|integer', + 'script_executor_title' => 'nullable|string|max:255', ], $isUpdate), ); + $validator->after(fn ($validator) => $this->validateRequestedExecutor($request, $validator)); if ($validator->fails()) { return response()->json([ @@ -68,7 +84,89 @@ public function deployScript(Request $request): JsonResponse ], 422); } - return $this->persistDeployedScript($request, $name); + return $this->denyUnauthorizedExecutorBinding($request, $name); + } + + /** + * Binding a script to an executor needs the same rights as the regular script + * routes: edit-scripts, and an administrator for any executor other than the + * default one (or any custom executor). Requests that name no executor, and + * requests that keep the executor a script already has, are not restricted. + */ + private function denyUnauthorizedExecutorBinding(Request $request, string $name): ?JsonResponse + { + $requested = $this->requestedExecutor($request); + $message = $requested === null + ? null + : $this->executorBindingDenialMessage($request->user(), $requested, $name); + + if ($message === null) { + return null; + } + + return response()->json([ + 'success' => false, + 'message' => $message, + ], 403); + } + + /** + * Return why the user may not bind the script to the requested executor, + * or null when the binding is allowed. + */ + private function executorBindingDenialMessage(User $user, ScriptExecutor $requested, string $name): ?string + { + if ($user->is_administrator || $this->keepsCurrentExecutor($name, $requested)) { + return null; + } + + if (!$user->can('edit-scripts')) { + return 'You are not allowed to choose a script executor.'; + } + + return $this->executors->isDefaultForNonAdmins($requested) + ? null + : 'Only administrators can use this script executor.'; + } + + private function keepsCurrentExecutor(string $name, ScriptExecutor $requested): bool + { + $current = Script::where('title', $name)->value('script_executor_id'); + + return $current !== null && (int) $current === $requested->id; + } + + private function requestedExecutor(Request $request): ?ScriptExecutor + { + $id = $request->input('script_executor_id'); + + return $this->executors->findRequested( + $id === null || $id === '' ? null : (int) $id, + $request->input('script_executor_title'), + ); + } + + private function validateRequestedExecutor(Request $request, \Illuminate\Validation\Validator $validator): void + { + $field = $request->filled('script_executor_id') ? 'script_executor_id' : 'script_executor_title'; + if (!$request->filled($field)) { + return; + } + + $executor = $this->requestedExecutor($request); + if ($executor === null) { + $validator->errors()->add($field, 'The selected script executor does not exist.'); + + return; + } + if ($executor->language !== ScriptExecutorResolver::DEPLOY_LANGUAGE) { + $validator->errors()->add($field, sprintf( + 'Script executor "%s" runs %s; deploy-script needs a %s executor.', + $executor->title, + $executor->language, + ScriptExecutorResolver::DEPLOY_LANGUAGE, + )); + } } private function persistDeployedScript(Request $request, string $name): JsonResponse @@ -76,9 +174,10 @@ private function persistDeployedScript(Request $request, string $name): JsonResp $code = $request->input('code'); $script = Script::where('title', $name)->first(); $created = $script === null; + $requestedExecutor = $this->requestedExecutor($request); if ($created) { - $executor = $this->executors->resolveForNewScript(); + $executor = $requestedExecutor ?? $this->executors->resolveForNewScript(); if ($executor === null) { return response()->json([ 'success' => false, @@ -97,6 +196,11 @@ private function persistDeployedScript(Request $request, string $name): JsonResp $script->retry_wait_time = self::DEFAULT_RETRY_WAIT_TIME; } + if (!$created && $requestedExecutor !== null) { + $script->script_executor_id = $requestedExecutor->id; + $script->language = $requestedExecutor->language; + } + if (!$created && $request->has('description')) { $script->description = $this->deployScriptDescription($request, $name); } diff --git a/ProcessMaker/Managers/PluginManager.php b/ProcessMaker/Managers/PluginManager.php index ebc99f99a4..cc860239e7 100644 --- a/ProcessMaker/Managers/PluginManager.php +++ b/ProcessMaker/Managers/PluginManager.php @@ -209,6 +209,12 @@ private function cloneRepositoryForInstall( $this->markNewInstallForRollback($pluginPath); $this->cloneRepository($authenticatedRepoUrl, $pluginPath, $repoName, $userId, $repoUrl); + // An empty remote has no branch or tag to check out: report that instead of a git checkout error. + if (($branch || $tag) && $this->isEmptyGitRepository($pluginPath)) { + $this->logError(self::EMPTY_REPOSITORY_MESSAGE, $repoName, $userId); + throw PluginInstallException::emptyRepository(); + } + if ($branch) { $this->logRunning("Checking out branch: {$branch}", $repoName, $userId); $this->checkoutBranch($pluginPath, $branch, $repoName, $userId); @@ -1032,7 +1038,7 @@ protected function validatePlugin(string $pluginPath, string $repoName, ?int $us if (!file_exists($composerJsonPath)) { if ($this->isEmptyGitRepository($pluginPath) || $this->hasOnlyPlaceholderFiles($pluginPath)) { $this->logError(self::EMPTY_REPOSITORY_MESSAGE, $repoName, $userId); - throw new RuntimeException(self::EMPTY_REPOSITORY_MESSAGE); + throw PluginInstallException::emptyRepository(); } $this->logError('composer.json not found in plugin: ' . $pluginPath, $repoName, $userId); diff --git a/ProcessMaker/Managers/ScreenBuilderManager.php b/ProcessMaker/Managers/ScreenBuilderManager.php index 1821c08cb8..7ce590adb3 100644 --- a/ProcessMaker/Managers/ScreenBuilderManager.php +++ b/ProcessMaker/Managers/ScreenBuilderManager.php @@ -110,36 +110,6 @@ private function addStoragePluginScripts(string $type): void } } - /** - * Prefer tenant-published plugin assets when available, else global public/vendor. - */ - private function publishedPluginScriptWebPath(string $packageName, string $extensionsFile): ?string - { - $relativeJs = '/js/' . $extensionsFile; - - if (PluginVendorAssets::isEnabled()) { - $tenantId = PluginVendorAssets::currentTenantId(); - $tenantFile = PluginVendorAssets::tenantPublicRoot($tenantId, $packageName) . $relativeJs; - if (is_file($tenantFile)) { - return PluginVendorAssets::webPath($tenantId, $packageName, $relativeJs); - } - } - - $globalWeb = '/vendor/processmaker/packages/' . $packageName . $relativeJs; - if (is_file(public_path(ltrim($globalWeb, '/')))) { - return $globalWeb; - } - - return null; - } - - private function filesystemPathForWebScript(string $webScript): string - { - $pathOnly = explode('?', $webScript, 2)[0]; - - return public_path(ltrim($pathOnly, '/')); - } - private function screenBuilderExtensionsFile(string $type): string { return 'screen-builder-' . strtolower($type) . '-components.js'; diff --git a/ProcessMaker/Mcp/Processes/GroupCatalog.php b/ProcessMaker/Mcp/Processes/GroupCatalog.php index 36f0f59ba9..1de284314f 100644 --- a/ProcessMaker/Mcp/Processes/GroupCatalog.php +++ b/ProcessMaker/Mcp/Processes/GroupCatalog.php @@ -5,6 +5,7 @@ namespace ProcessMaker\Mcp\Processes; use Illuminate\Auth\Access\AuthorizationException; +use ProcessMaker\Events\GroupCreated; use ProcessMaker\Models\Group; use ProcessMaker\Models\User; @@ -29,6 +30,7 @@ public function list(User $actor, array $input): array $filters = validator($input, [ 'filter' => 'nullable|string|max:255', + 'name' => 'nullable|string|max:255', 'status' => 'nullable|in:ACTIVE,INACTIVE', 'page' => 'nullable|integer|min:1', 'per_page' => 'nullable|integer|min:1|max:50', @@ -36,7 +38,7 @@ public function list(User $actor, array $input): array 'order_direction' => 'nullable|in:asc,desc', ])->validate(); - $query = Group::query(); + $query = Group::query()->withCount('groupMembers'); $filter = trim((string) ($filters['filter'] ?? '')); if ($filter !== '') { $like = '%' . $filter . '%'; @@ -46,6 +48,12 @@ public function list(User $actor, array $input): array }); } + // Exact (case-insensitive) name match, for resolving one group when names repeat. + $exactName = trim((string) ($filters['name'] ?? '')); + if ($exactName !== '') { + $query->whereRaw('LOWER(name) = ?', [mb_strtolower($exactName)]); + } + if (!empty($filters['status'])) { $query->where('status', $filters['status']); } else { @@ -61,15 +69,11 @@ public function list(User $actor, array $input): array $filters['page'] ?? 1, ); + $items = collect($page->items()); + $sameName = $this->sameNameCounts($items->pluck('name')->all()); + return [ - 'data' => collect($page->items())->map(static fn (Group $group): array => [ - 'id' => $group->id, - 'name' => $group->name, - 'description' => $group->description, - 'status' => $group->status, - 'manager_id' => $group->manager_id, - 'updated_at' => optional($group->updated_at)?->format('c'), - ])->all(), + 'data' => $items->map(fn (Group $group): array => $this->summary($group, $sameName))->all(), 'meta' => [ 'current_page' => $page->currentPage(), 'last_page' => $page->lastPage(), @@ -79,6 +83,74 @@ public function list(User $actor, array $input): array ]; } + /** + * Create a group. Same rules as Api\GroupController::store (unique name, ACTIVE or INACTIVE). + * + * @param array $input + * @return array + */ + public function create(User $actor, array $input): array + { + if (!$actor->can('create-groups')) { + throw new AuthorizationException('You do not have the create-groups permission.'); + } + + $data = validator($input, array_merge(Group::rules(), [ + 'description' => 'nullable|string|max:255', + 'manager_id' => 'nullable|integer|exists:users,id', + ]))->validate(); + + $group = new Group(); + $group->fill($data + ['status' => 'ACTIVE']); + // Same as Api\GroupController::store: never taken from tool arguments. + if (config('password-policies.2fa_enabled', false)) { + $group->enabled_2fa = true; + } + $group->saveOrFail(); + GroupCreated::dispatch($group); + + return $this->summary($group->loadCount('groupMembers'), []); + } + + /** + * Groups with the same name are ambiguous in assignments. Count them for the names on the page. + * + * @param list $names + * @return array + */ + private function sameNameCounts(array $names): array + { + if ($names === []) { + return []; + } + + return Group::query() + ->whereIn('name', array_values(array_unique($names))) + ->selectRaw('name, COUNT(*) as aggregate') + ->groupBy('name') + ->pluck('aggregate', 'name') + ->map(static fn ($count): int => (int) $count) + ->all(); + } + + /** + * @param array $sameName + * @return array + */ + private function summary(Group $group, array $sameName): array + { + return [ + 'id' => $group->id, + 'name' => $group->name, + 'description' => $group->description, + 'status' => $group->status, + 'manager_id' => $group->manager_id, + 'members_count' => (int) $group->group_members_count, + 'same_name_count' => $sameName[$group->name] ?? 1, + 'updated_at' => optional($group->updated_at)?->format('c'), + ]; + } + private function assertCanList(User $user): void { if ($user->can('view-groups') diff --git a/ProcessMaker/Mcp/Processes/ProcessCatalog.php b/ProcessMaker/Mcp/Processes/ProcessCatalog.php index 1b86d0c421..f459e2e431 100644 --- a/ProcessMaker/Mcp/Processes/ProcessCatalog.php +++ b/ProcessMaker/Mcp/Processes/ProcessCatalog.php @@ -18,6 +18,7 @@ use ProcessMaker\Models\ProcessVersion; use ProcessMaker\Models\User; use ProcessMaker\Nayra\Storage\BpmnDocument; +use ProcessMaker\SanitizeHelper; use ProcessMaker\Validation\CategoryRule; class ProcessCatalog @@ -35,8 +36,10 @@ class ProcessCatalog */ private const ORDER_COLUMNS = ['name', 'status', 'updated_at', 'created_at', 'id']; - public function __construct(private readonly ProcessBpmnValidator $validator) - { + public function __construct( + private readonly ProcessBpmnValidator $validator, + private readonly ProcessNotificationSettings $notificationSettings, + ) { } public function actor(?Authenticatable $user): User @@ -107,6 +110,20 @@ public function find(User $user, int $id, string $alternative = 'A'): array ); } + /** + * Map of a process: activities with assets (ids and titles), screens and their fields, + * scripts, gateways with the variables they read. Same visibility rules as find(). + * + * @return array + */ + public function inventory(User $user, int $id, string $alternative = 'A'): array + { + $detail = $this->find($user, $id, $alternative); + $process = Process::query()->findOrFail($id); + + return (new ProcessInventory())->build($process, $detail['alternative'] ?? 'A', $detail['bpmn'] ?? null, $user); + } + /** * Enable Alternative B for a process (clone draft A → B). * @@ -136,6 +153,8 @@ public function create(User $user, array $input): array $validated['bpmn'] = BpmnDocument::replaceHtmlEntities($validated['bpmn']); } + $validated = $this->sanitizeCaseTitle($validated); + $process = new Process(); $process->fill($validated); $process->user_id = $user->id; @@ -182,11 +201,16 @@ public function update(User $user, array $input): array } $attributes = $this->writable($validated); - if ($attributes === []) { + $notifications = $validated['notifications'] ?? null; + if ($attributes === [] && $notifications === null) { throw ValidationException::withMessages([ - 'process' => 'Provide at least one field to update: name, description, status, process_category_id, or bpmn.', + 'process' => 'Provide at least one field to update: name, description, status, process_category_id, ' + . 'case_title, manager_id, notifications, or bpmn.', ]); } + if (is_array($notifications)) { + $this->notificationSettings->assertKnown($notifications); + } if (isset($attributes['bpmn'])) { $this->assertBpmnAcceptable($attributes['bpmn']); @@ -210,6 +234,11 @@ public function update(User $user, array $input): array $this->persistLiveMetadata($process, $attributes, $user); } + if (is_array($notifications)) { + $this->notificationSettings->apply($process, $notifications); + $this->forgetProjectAssetCache($user); + } + return $this->detail($process->refresh(), $alternative); } @@ -304,6 +333,31 @@ private function updateRules(array $input): array $rules['bpmn'] = 'nullable|string'; } + return array_merge($rules, $this->settingsRules($input)); + } + + /** + * Process-level settings. They apply to the live process, so Alternative A + * and B share them, and saving them does not publish a version. + * + * @param array $input + * @return array + */ + private function settingsRules(array $input): array + { + $rules = []; + if (array_key_exists('case_title', $input)) { + $rules['case_title'] = 'nullable|string|max:200'; + } + if (array_key_exists('manager_id', $input)) { + $rules['manager_id'] = 'array|max:10'; + $rules['manager_id.*'] = 'integer|min:1|exists:users,id'; + } + if (array_key_exists('notifications', $input)) { + $rules['notifications'] = 'array'; + $rules['notifications.*'] = 'array'; + } + return $rules; } @@ -326,13 +380,32 @@ private function normalize(array $input): array */ private function writable(array $input): array { - return array_intersect_key($input, array_flip([ + return $this->sanitizeCaseTitle(array_intersect_key($input, array_flip([ 'name', 'description', 'status', 'process_category_id', + 'case_title', + 'manager_id', 'bpmn', - ])); + ]))); + } + + /** + * Same as the HTTP process routes (SanitizeInput with case_title as a + * mustache field): strip HTML/PHP tags, keep mustache expressions. The title + * is later rendered with v-html in task and request lists. + * + * @param array $attributes + * @return array + */ + private function sanitizeCaseTitle(array $attributes): array + { + if (isset($attributes['case_title']) && is_string($attributes['case_title'])) { + $attributes['case_title'] = SanitizeHelper::sanitize($attributes['case_title'], true, false); + } + + return $attributes; } private function assertBpmnAcceptable(string $bpmn): void @@ -420,6 +493,9 @@ private function detail(Process $process, string $alternative = 'A', bool $inclu return [ ...$this->summary($process), + 'case_title' => $process->case_title, + 'manager_id' => $process->manager_id, + 'notifications' => (array) $process->notifications, 'alternative' => $alternative, 'alternatives' => $this->alternativesMeta($process), 'bpmn' => $bpmn, diff --git a/ProcessMaker/Mcp/Processes/ProcessInventory.php b/ProcessMaker/Mcp/Processes/ProcessInventory.php new file mode 100644 index 0000000000..17e85b9dd3 --- /dev/null +++ b/ProcessMaker/Mcp/Processes/ProcessInventory.php @@ -0,0 +1,404 @@ + + */ + public function build(Process $process, string $alternative, ?string $bpmn, ?User $viewer = null): array + { + $dom = new DOMDocument(); + if ($bpmn === null || $bpmn === '' || !@$dom->loadXML($bpmn)) { + return $this->empty($process, $alternative); + } + + $xpath = new DOMXPath($dom); + $xpath->registerNamespace('b', self::BPMN_NS); + + $activities = $this->activities($xpath); + $screens = $this->screens($activities); + $scripts = $this->scripts($activities, $viewer); + $gateways = $this->gateways($xpath); + + return [ + 'process' => [ + 'id' => $process->id, + 'name' => $process->name, + 'status' => $process->status, + 'alternative' => $alternative, + ], + 'counts' => [ + 'activities' => count($activities), + 'gateways' => count($gateways), + 'sequence_flows' => $xpath->query('//b:sequenceFlow')->length, + 'screens' => count($screens), + 'scripts' => count($scripts), + ], + 'activities' => $this->withTitles($activities, $screens, $scripts), + 'screens' => array_values($screens), + 'scripts' => array_values($scripts), + 'gateways' => $gateways, + 'variables' => $this->variables($gateways, $screens), + 'warnings' => $this->warnings($gateways, $screens), + ]; + } + + /** + * @return array + */ + private function empty(Process $process, string $alternative): array + { + return [ + 'process' => ['id' => $process->id, 'name' => $process->name, 'status' => $process->status, 'alternative' => $alternative], + 'counts' => ['activities' => 0, 'gateways' => 0, 'sequence_flows' => 0, 'screens' => 0, 'scripts' => 0], + 'activities' => [], + 'screens' => [], + 'scripts' => [], + 'gateways' => [], + 'variables' => [], + 'warnings' => ['The process has no readable BPMN.'], + ]; + } + + /** + * @return array> + */ + private function activities(DOMXPath $xpath): array + { + $activities = []; + foreach (self::ACTIVITIES as $type) { + foreach ($xpath->query('//b:' . $type) as $node) { + /** @var DOMElement $node */ + $screenId = $this->integerAttribute($node, 'screenRef'); + $scriptId = $this->integerAttribute($node, 'scriptRef'); + $activities[$node->getAttribute('id')] = [ + 'id' => $node->getAttribute('id'), + 'type' => $type, + 'name' => $node->getAttribute('name'), + 'screen_id' => $screenId, + 'script_id' => $scriptId, + 'assignment' => $node->getAttributeNS(self::PM_NS, 'assignment') ?: null, + 'incoming' => $this->childCount($node, 'incoming'), + 'outgoing' => $this->childCount($node, 'outgoing'), + ]; + } + } + + return $activities; + } + + /** + * @param array> $activities + * @return array> + */ + private function screens(array $activities): array + { + $referencedBy = []; + foreach ($activities as $activity) { + if ($activity['screen_id'] !== null) { + $referencedBy[$activity['screen_id']][] = $activity['id']; + } + } + if ($referencedBy === []) { + return []; + } + + $screens = []; + foreach (Screen::query()->whereIn('id', array_keys($referencedBy))->get(['id', 'title', 'type', 'config']) as $screen) { + $controls = $this->controls((array) $screen->config); + $screens[$screen->id] = [ + 'id' => $screen->id, + 'title' => $screen->title, + 'type' => $screen->type, + 'controls' => count($controls), + 'fields' => array_values(array_unique(array_filter(array_map( + static fn (array $control): ?string => $control['field'], + $controls, + )))), + 'referenced_by' => $referencedBy[$screen->id], + ]; + } + foreach (array_diff(array_keys($referencedBy), array_keys($screens)) as $missingId) { + $screens[$missingId] = [ + 'id' => $missingId, 'title' => null, 'type' => null, 'controls' => 0, 'fields' => [], + 'referenced_by' => $referencedBy[$missingId], + ]; + } + ksort($screens); + + return $screens; + } + + /** + * @param array> $activities + * @return array> + */ + private function scripts(array $activities, ?User $viewer): array + { + // Script metadata is gated by view-scripts on the scripts API. Without it + // (or without a known viewer), do not resolve or confirm any script id. + if ($viewer === null || !$viewer->can('view-scripts')) { + return []; + } + + $referencedBy = []; + foreach ($activities as $activity) { + if ($activity['script_id'] !== null) { + $referencedBy[$activity['script_id']][] = $activity['id']; + } + } + if ($referencedBy === []) { + return []; + } + + $scripts = []; + foreach (Script::query()->whereIn('id', array_keys($referencedBy))->get(['id', 'title', 'language', 'script_executor_id']) as $script) { + $scripts[$script->id] = [ + 'id' => $script->id, + 'title' => $script->title, + 'language' => $script->language, + 'script_executor_id' => $script->script_executor_id, + 'referenced_by' => $referencedBy[$script->id], + ]; + } + foreach (array_diff(array_keys($referencedBy), array_keys($scripts)) as $missingId) { + $scripts[$missingId] = [ + 'id' => $missingId, 'title' => null, 'language' => null, 'script_executor_id' => null, + 'referenced_by' => $referencedBy[$missingId], + ]; + } + ksort($scripts); + + return $scripts; + } + + /** + * @return array> + */ + private function gateways(DOMXPath $xpath): array + { + $flows = $this->flowsBySource($xpath); + $gateways = []; + foreach (self::GATEWAYS as $type) { + foreach ($xpath->query('//b:' . $type) as $node) { + /** @var DOMElement $node */ + $id = $node->getAttribute('id'); + $outgoing = $flows[$id] ?? []; + $gateways[] = [ + 'id' => $id, + 'type' => $type, + 'name' => $node->getAttribute('name'), + 'default_flow' => $node->getAttribute('default') ?: null, + 'incoming' => $this->childCount($node, 'incoming'), + 'flows' => $outgoing, + 'variables' => $this->conditionVariables($outgoing), + ]; + } + } + + return $gateways; + } + + /** + * @return array>> + */ + private function flowsBySource(DOMXPath $xpath): array + { + $flows = []; + foreach ($xpath->query('//b:sequenceFlow') as $flow) { + /** @var DOMElement $flow */ + $condition = $xpath->query('b:conditionExpression', $flow)->item(0); + $flows[$flow->getAttribute('sourceRef')][] = [ + 'id' => $flow->getAttribute('id'), + 'target' => $flow->getAttribute('targetRef'), + 'condition' => $condition === null ? null : trim($condition->textContent), + ]; + } + + return $flows; + } + + /** + * @param array> $flows + * @return array + */ + private function conditionVariables(array $flows): array + { + $variables = []; + foreach ($flows as $flow) { + $condition = (string) ($flow['condition'] ?? ''); + preg_match_all('/\b(?:data\.)?([A-Za-z_]\w*)\b(?:\[[^\]]*\])?\s*(?:==|!=|<=|>=|<|>)/', $condition, $matches); + foreach ($matches[1] as $name) { + if (!in_array($name, self::IGNORED_WORDS, true)) { + $variables[$name] = true; + } + } + } + + return array_keys($variables); + } + + /** + * @param array $config + * @return array + */ + private function controls(array $config): array + { + $controls = []; + $walk = function (mixed $node) use (&$walk, &$controls): void { + if (!is_array($node)) { + return; + } + if (isset($node['component']) && is_string($node['component']) && isset($node['config'])) { + $name = $node['config']['name'] ?? null; + $isField = !in_array($node['component'], self::NON_FIELD_COMPONENTS, true) && is_string($name) && $name !== ''; + $controls[] = ['component' => $node['component'], 'field' => $isField ? $name : null]; + } + foreach ($node as $child) { + $walk($child); + } + }; + $walk($config); + + return $controls; + } + + /** + * Only the variables a gateway reads: they decide the route, so their writers matter. + * Every screen's own fields are listed under `screens`. + * + * @param array> $gateways + * @param array> $screens + * @return array, read_by_gateways: array}> + */ + private function variables(array $gateways, array $screens): array + { + $variables = []; + foreach ($gateways as $gateway) { + foreach ($gateway['variables'] as $name) { + $variables[$name]['read_by_gateways'][] = $gateway['id']; + } + } + ksort($variables); + + foreach ($variables as $name => $entry) { + $variables[$name] = [ + 'written_by_screens' => array_values(array_map( + static fn (array $screen): int => $screen['id'], + array_filter($screens, static fn (array $screen): bool => in_array($name, $screen['fields'], true)), + )), + 'read_by_gateways' => $entry['read_by_gateways'], + ]; + } + + return $variables; + } + + /** + * @param array> $gateways + * @param array> $screens + * @return array + */ + private function warnings(array $gateways, array $screens): array + { + $written = []; + foreach ($screens as $screen) { + foreach ($screen['fields'] as $field) { + $written[$field] = true; + } + } + + $warnings = []; + foreach ($gateways as $gateway) { + $unwritten = array_values(array_filter($gateway['variables'], static fn (string $name): bool => !isset($written[$name]))); + if ($unwritten !== []) { + $warnings[] = sprintf( + 'Gateway %s reads %s, but no screen of this process has a field with that name. ' + . 'Scripts, data connectors and call activities may still set it; an undefined variable in a ' + . 'gateway condition puts the request in ERROR.', + $gateway['id'], + implode(', ', $unwritten), + ); + } + } + + return $warnings; + } + + private function integerAttribute(DOMElement $node, string $name): ?int + { + $value = $node->getAttributeNS(self::PM_NS, $name); + + return ctype_digit($value) && $value !== '' ? (int) $value : null; + } + + private function childCount(DOMElement $node, string $name): int + { + $count = 0; + foreach ($node->childNodes as $child) { + if ($child instanceof DOMElement && $child->localName === $name && $child->namespaceURI === self::BPMN_NS) { + $count++; + } + } + + return $count; + } + + /** + * @param array> $activities + * @param array> $screens + * @param array> $scripts + * @return array> + */ + private function withTitles(array $activities, array $screens, array $scripts): array + { + return array_values(array_map(static function (array $activity) use ($screens, $scripts): array { + $activity['screen_title'] = $screens[$activity['screen_id']]['title'] ?? null; + $activity['script_title'] = $scripts[$activity['script_id']]['title'] ?? null; + + return $activity; + }, $activities)); + } +} diff --git a/ProcessMaker/Mcp/Processes/ProcessNotificationSettings.php b/ProcessMaker/Mcp/Processes/ProcessNotificationSettings.php new file mode 100644 index 0000000000..224ca764c0 --- /dev/null +++ b/ProcessMaker/Mcp/Processes/ProcessNotificationSettings.php @@ -0,0 +1,93 @@ + $notifications + * @throws ValidationException + */ + public function assertKnown(array $notifications): void + { + $process = new Process(); + $errors = []; + + foreach ($notifications as $notifiable => $types) { + if (!in_array($notifiable, $process->requestNotifiableTypes, true) || !is_array($types)) { + $errors['notifications'][] = sprintf( + 'Unknown notifiable type "%s". Use: %s.', + (string) $notifiable, + implode(', ', $process->requestNotifiableTypes), + ); + + continue; + } + + foreach (array_keys($types) as $type) { + if (!in_array($type, $process->requestNotificationTypes, true)) { + $errors['notifications'][] = sprintf( + 'Unknown notification type "%s" for %s. Use: %s.', + (string) $type, + $notifiable, + implode(', ', $process->requestNotificationTypes), + ); + } + } + } + + if ($errors !== []) { + throw ValidationException::withMessages($errors); + } + } + + /** + * Turn the sent notifications on or off. Call {@see assertKnown()} first. + * + * @param array> $notifications + */ + public function apply(Process $process, array $notifications): void + { + foreach ($notifications as $notifiable => $types) { + foreach ($types as $type => $wanted) { + if ($wanted === null) { + continue; + } + $this->set($process, (string) $notifiable, (string) $type, filter_var($wanted, FILTER_VALIDATE_BOOLEAN)); + } + } + } + + private function set(Process $process, string $notifiable, string $type, bool $wanted): void + { + $keys = ['element_id' => null, 'notifiable_type' => $notifiable, 'notification_type' => $type]; + + if ($wanted) { + $process->notification_settings()->firstOrCreate($keys); + + return; + } + + $process->notification_settings() + ->whereNull('element_id') + ->where('notifiable_type', $notifiable) + ->where('notification_type', $type) + ->delete(); + } +} diff --git a/ProcessMaker/Mcp/Screens/ScreenCatalog.php b/ProcessMaker/Mcp/Screens/ScreenCatalog.php index be1320f912..14c4a60ad6 100644 --- a/ProcessMaker/Mcp/Screens/ScreenCatalog.php +++ b/ProcessMaker/Mcp/Screens/ScreenCatalog.php @@ -186,13 +186,21 @@ public function validate(User $user, array $input): array $config = $validated['config'] ?? null; $type = $validated['type'] ?? null; - if (($config === null || $config === []) && isset($validated['id'])) { + $editsNativeScreen = false; + if (isset($validated['id'])) { $screen = Screen::query()->findOrFail((int) $validated['id']); - $config = is_array($screen->config) ? $screen->config : []; + $editsNativeScreen = !$this->usesVueEditor(is_array($screen->config) ? $screen->config : []); + if ($config === null || $config === []) { + $config = is_array($screen->config) ? $screen->config : []; + } $type = $type ?? $screen->type; } - return $this->validator->validate(is_array($config) ? $config : null, is_string($type) ? $type : null); + return $this->validator->validate( + is_array($config) ? $config : null, + is_string($type) ? $type : null, + $editsNativeScreen, + ); } /** @@ -508,6 +516,14 @@ private function consoleAdministrator(): ?User return $admin instanceof User ? $admin : null; } + /** + * @param array $config + */ + private function usesVueEditor(array $config): bool + { + return str_contains((string) json_encode($config), '"VueComponentRenderTemplate"'); + } + private function forgetProjectAssetCache(User $user): void { if (!hasPackage('package-projects')) { diff --git a/ProcessMaker/Mcp/Screens/ScreenConfigValidator.php b/ProcessMaker/Mcp/Screens/ScreenConfigValidator.php index 867f835206..5347b3b0d1 100644 --- a/ProcessMaker/Mcp/Screens/ScreenConfigValidator.php +++ b/ProcessMaker/Mcp/Screens/ScreenConfigValidator.php @@ -21,21 +21,26 @@ final class ScreenConfigValidator 'FormHtmlViewer', ]; + /** A native FORM with at most this many controls is not worth a Vue rewrite. */ + private const SMALL_NATIVE_SCREEN_MAX_CONTROLS = 5; + /** * @param array|null $config - * @return array{ok: bool, errors: list, warnings: list} + * @param bool $editsNativeScreen True when the config updates a stored screen that has no Vue component. + * @return array{ok: bool, errors: list, warnings: list, info: list} */ - public function validate(?array $config, ?string $type = null): array + public function validate(?array $config, ?string $type = null, bool $editsNativeScreen = false): array { $errors = []; $warnings = []; + $info = []; if ($config === null) { - return $this->result($errors, $warnings); + return $this->result($errors, $warnings, $info); } $hasVueEditor = false; - $hasNativeFields = false; + $nativeControls = 0; foreach ($config as $pageIndex => $page) { if (!is_array($page)) { @@ -55,19 +60,15 @@ public function validate(?array $config, ?string $type = null): array $errors, $warnings, $hasVueEditor, - $hasNativeFields, + $nativeControls, ); } - if ($type === 'FORM' && $hasNativeFields && !$hasVueEditor) { - $warnings[] = $this->issue( - null, - 'prefer_vue_component_editor', - 'FORM screens should use VueComponentRenderTemplate as the main UI (see the pm4-screen skill). Native FormSelectList/FormInput layouts are fragile and often miss required options.', - ); + if ($type === 'FORM' && $nativeControls > 0 && !$hasVueEditor) { + $this->addNativeFormNotice($nativeControls, $editsNativeScreen, $warnings, $info); } - return $this->result($errors, $warnings); + return $this->result($errors, $warnings, $info); } /** @@ -81,7 +82,7 @@ private function walkItems( array &$errors, array &$warnings, bool &$hasVueEditor, - bool &$hasNativeFields, + int &$nativeControls, ): void { foreach ($items as $index => $item) { if (!is_array($item)) { @@ -95,7 +96,7 @@ private function walkItems( $hasVueEditor = true; $this->validateVueEditor($item, $itemPath, $errors, $warnings); } elseif (in_array($component, self::NATIVE_FIELD_COMPONENTS, true)) { - $hasNativeFields = true; + $nativeControls++; } if ($component === 'FormSelectList') { @@ -113,7 +114,7 @@ private function walkItems( $errors, $warnings, $hasVueEditor, - $hasNativeFields, + $nativeControls, ); } } @@ -237,17 +238,55 @@ private function issue(?string $path, string $code, string $message): array ]; } + /** + * New or large native FORM screens get a warning (the pm4-screen skill expects Vue). Editing a stored + * native screen, or a small native FORM, is legitimate, so those only get an informational note. + * + * @param list $warnings + * @param list $info + */ + private function addNativeFormNotice(int $nativeControls, bool $editsNativeScreen, array &$warnings, array &$info): void + { + if ($editsNativeScreen) { + $info[] = $this->issue( + null, + 'native_screen_edit', + 'This edits a stored screen that is already native, so keeping it native is fine. A Vue rewrite is a separate refactor of the whole screen (see the pm4-screen skill).', + ); + + return; + } + + if ($nativeControls <= self::SMALL_NATIVE_SCREEN_MAX_CONTROLS) { + $info[] = $this->issue( + null, + 'native_small_screen', + sprintf('Small native FORM (%d controls). Vue is optional at this size; check that every select has options.', $nativeControls), + ); + + return; + } + + $warnings[] = $this->issue( + null, + 'prefer_vue_component_editor', + 'FORM screens should use VueComponentRenderTemplate as the main UI (see the pm4-screen skill). Native FormSelectList/FormInput layouts are fragile and often miss required options.', + ); + } + /** * @param list $errors * @param list $warnings - * @return array{ok: bool, errors: list, warnings: list} + * @param list $info + * @return array{ok: bool, errors: list, warnings: list, info: list} */ - private function result(array $errors, array $warnings): array + private function result(array $errors, array $warnings, array $info = []): array { return [ 'ok' => $errors === [], 'errors' => $errors, 'warnings' => $warnings, + 'info' => $info, ]; } } diff --git a/ProcessMaker/Mcp/Servers/ProcessServer.php b/ProcessMaker/Mcp/Servers/ProcessServer.php index b811e24c4d..c6760e9fec 100644 --- a/ProcessMaker/Mcp/Servers/ProcessServer.php +++ b/ProcessMaker/Mcp/Servers/ProcessServer.php @@ -12,8 +12,10 @@ use ProcessMaker\Mcp\McpGuidance; use ProcessMaker\Mcp\Tools\GetMcpGuidanceTool; use ProcessMaker\Mcp\Tools\GetMcpSkillTool; +use ProcessMaker\Mcp\Tools\Processes\CreateGroupTool; use ProcessMaker\Mcp\Tools\Processes\CreateProcessTool; use ProcessMaker\Mcp\Tools\Processes\EnableProcessAlternativeBTool; +use ProcessMaker\Mcp\Tools\Processes\GetProcessInventoryTool; use ProcessMaker\Mcp\Tools\Processes\GetProcessTool; use ProcessMaker\Mcp\Tools\Processes\ListGroupsTool; use ProcessMaker\Mcp\Tools\Processes\ListProcessesTool; @@ -43,6 +45,8 @@ Alternative B (A/B testing): call `enable-process-alternative-b` (or `update-process` with `create_alternative_b: true`) before editing with `alternative: "B"`. BPMN updates write the draft for the chosen alternative (same as PUT /processes/{id}/draft). For BPMN structure, node settings, and package connectors (email, PDF, Slack, FlowGenie, Decision Task, UiPath, DocuSign, IDP, Actions By Email, Data Connector), follow the matching `pm4-*` skill from the ProcessMaker Skills repository (`npx skills add processmaker/skills`, start with `pm4-process`). Do not invent `implementation` strings. For FlowGenie Service Tasks: create/configure the asset via FlowGenies MCP (`create-flow-genie`) first, then set numeric `flow_genie_id` in pm:config. +Call get-process-inventory to review an existing process: it returns activities, screens (id, title, fields), scripts and gateway variables without the BPMN or one read per asset. +list-groups rows carry same_name_count; when above 1 pick by id, or create the group once with create-group. Call validate-process before create/update when unsure. update-process changes only the fields you send. MARKDOWN)] @@ -57,8 +61,10 @@ class ProcessServer extends Server PlanProcessTool::class, ListUsersTool::class, ListGroupsTool::class, + CreateGroupTool::class, ListProcessesTool::class, GetProcessTool::class, + GetProcessInventoryTool::class, CreateProcessTool::class, UpdateProcessTool::class, EnableProcessAlternativeBTool::class, diff --git a/ProcessMaker/Mcp/Tools/Processes/CreateGroupTool.php b/ProcessMaker/Mcp/Tools/Processes/CreateGroupTool.php new file mode 100644 index 0000000000..bd0e8c47c4 --- /dev/null +++ b/ProcessMaker/Mcp/Tools/Processes/CreateGroupTool.php @@ -0,0 +1,45 @@ +respond(fn (): array => $groups->create( + $processes->actor($request->user()), + $request->all(), + )); + } + + /** + * @return array + */ + public function schema(JsonSchema $schema): array + { + return [ + 'name' => $schema->string()->description('Unique group name.')->required(), + 'description' => $schema->string()->description('Short description (max 255).'), + 'status' => $schema->string()->description('ACTIVE (default) or INACTIVE.'), + 'manager_id' => $schema->integer()->description('User id of the group manager.'), + ]; + } +} diff --git a/ProcessMaker/Mcp/Tools/Processes/GetProcessInventoryTool.php b/ProcessMaker/Mcp/Tools/Processes/GetProcessInventoryTool.php new file mode 100644 index 0000000000..ab2b4260e4 --- /dev/null +++ b/ProcessMaker/Mcp/Tools/Processes/GetProcessInventoryTool.php @@ -0,0 +1,51 @@ +respond(function () use ($request, $processes): array { + $validated = $request->validate([ + 'id' => 'required|integer|min:1', + 'alternative' => 'nullable|in:A,B', + ]); + + return $processes->inventory( + $processes->actor($request->user()), + (int) $validated['id'], + $validated['alternative'] ?? 'A', + ); + }); + } + + /** + * @return array + */ + public function schema(JsonSchema $schema): array + { + return [ + 'id' => ProcessFields::id($schema), + 'alternative' => ProcessFields::alternative($schema), + ]; + } +} diff --git a/ProcessMaker/Mcp/Tools/Processes/ListGroupsTool.php b/ProcessMaker/Mcp/Tools/Processes/ListGroupsTool.php index b3ddcc60a6..79716c9dd2 100644 --- a/ProcessMaker/Mcp/Tools/Processes/ListGroupsTool.php +++ b/ProcessMaker/Mcp/Tools/Processes/ListGroupsTool.php @@ -18,7 +18,7 @@ #[Name('list-groups')] #[Title('List Groups')] -#[Description('Lists ProcessMaker groups for Form Task user_group assignment (pm:assignedGroups). Filter by name or description. Defaults to ACTIVE groups. Use while planning process assignees.')] +#[Description('Lists ProcessMaker groups for Form Task user_group assignment (pm:assignedGroups). Filter by name or description, or pass `name` for an exact match. Each row has members_count and same_name_count (above 1 means the name is ambiguous: pick by id). Defaults to ACTIVE groups. Use while planning process assignees.')] #[IsReadOnly] #[IsIdempotent] class ListGroupsTool extends ProcessTool @@ -41,6 +41,7 @@ public function schema(JsonSchema $schema): array { return [ 'filter' => $schema->string()->description('Search name or description.'), + 'name' => $schema->string()->description('Exact group name (case-insensitive).'), 'status' => $schema->string()->description('ACTIVE or INACTIVE (default ACTIVE).'), 'page' => $schema->integer()->description('Page number (default 1).'), 'per_page' => $schema->integer()->description('Results per page (max 50).'), diff --git a/ProcessMaker/Mcp/Tools/Processes/ProcessFields.php b/ProcessMaker/Mcp/Tools/Processes/ProcessFields.php index 3bf0bc66dc..d35fddbdce 100644 --- a/ProcessMaker/Mcp/Tools/Processes/ProcessFields.php +++ b/ProcessMaker/Mcp/Tools/Processes/ProcessFields.php @@ -5,8 +5,10 @@ namespace ProcessMaker\Mcp\Tools\Processes; use Illuminate\Contracts\JsonSchema\JsonSchema; +use Illuminate\JsonSchema\Types\ArrayType; use Illuminate\JsonSchema\Types\BooleanType; use Illuminate\JsonSchema\Types\IntegerType; +use Illuminate\JsonSchema\Types\ObjectType; use Illuminate\JsonSchema\Types\StringType; final class ProcessFields @@ -19,6 +21,12 @@ final class ProcessFields public const CATEGORY = 'Process category id, or comma-separated ids.'; + public const CASE_TITLE = 'Case title template shown in request lists, for example "{{DC_DEAL_PROJECT_NAME}}". Max 200 characters. Process-level: applies to the live process (Alternative A and B share it) and does not publish a version.'; + + public const MANAGER_ID = 'Process manager user ids (array of integers, max 10; an empty array clears them). Process-level: applies to the live process and does not publish a version.'; + + public const NOTIFICATIONS = 'Request notification settings: { requester|assignee|participants|manager: { started|canceled|completed|error|comment: true|false } }. Only the pairs you send change. Process-level: applies to the live process and does not publish a version.'; + public const BPMN = 'Full BPMN 2.0 XML for the process. For MCP create/update use numeric pm:screenRef/pm:scriptRef ids. Portable ${screen:title}/${script:title}/${process:name} resolve when publishing via core deploy-process (POST /api/1.0/deploy-process).'; public const ALTERNATIVE = 'Alternative version line: A (default) or B. Use with get-process / update-process / validate-process.'; @@ -58,6 +66,23 @@ public static function category(JsonSchema $schema, bool $required): StringType return $required ? $field->required() : $field; } + public static function caseTitle(JsonSchema $schema): StringType + { + return $schema->string()->description(self::CASE_TITLE); + } + + public static function managerIds(JsonSchema $schema): ArrayType + { + return $schema->array() + ->items($schema->integer()) + ->description(self::MANAGER_ID); + } + + public static function notifications(JsonSchema $schema): ObjectType + { + return $schema->object()->description(self::NOTIFICATIONS); + } + public static function bpmn(JsonSchema $schema, bool $required): StringType { $field = $schema->string()->description(self::BPMN); diff --git a/ProcessMaker/Mcp/Tools/Processes/UpdateProcessTool.php b/ProcessMaker/Mcp/Tools/Processes/UpdateProcessTool.php index c1ed0be54d..c22b9f20b6 100644 --- a/ProcessMaker/Mcp/Tools/Processes/UpdateProcessTool.php +++ b/ProcessMaker/Mcp/Tools/Processes/UpdateProcessTool.php @@ -15,7 +15,7 @@ #[Name('update-process')] #[Title('Update Process')] -#[Description('Updates a ProcessMaker process. Send only the fields that should change (name, description, status, process_category_id, bpmn). BPMN edits save a draft on alternative A or B (see alternative, create_alternative_b).')] +#[Description('Updates a ProcessMaker process. Send only the fields that should change (name, description, status, process_category_id, case_title, manager_id, notifications, bpmn). BPMN edits save a draft on alternative A or B (see alternative, create_alternative_b). Everything except bpmn is process-level: it changes the live process (A and B share it) and never publishes a version.')] class UpdateProcessTool extends ProcessTool { public function handle(Request $request, ProcessCatalog $processes): Response|ResponseFactory @@ -37,6 +37,9 @@ public function schema(JsonSchema $schema): array 'description' => ProcessFields::description($schema, false), 'status' => ProcessFields::status($schema), 'process_category_id' => ProcessFields::category($schema, false), + 'case_title' => ProcessFields::caseTitle($schema), + 'manager_id' => ProcessFields::managerIds($schema), + 'notifications' => ProcessFields::notifications($schema), 'bpmn' => ProcessFields::bpmn($schema, false), 'alternative' => ProcessFields::alternative($schema), 'create_alternative_b' => ProcessFields::createAlternativeB($schema), diff --git a/ProcessMaker/Mcp/Tools/Screens/ValidateScreenTool.php b/ProcessMaker/Mcp/Tools/Screens/ValidateScreenTool.php index f0d993d900..4a2783744f 100644 --- a/ProcessMaker/Mcp/Tools/Screens/ValidateScreenTool.php +++ b/ProcessMaker/Mcp/Tools/Screens/ValidateScreenTool.php @@ -17,7 +17,7 @@ #[Name('validate-screen')] #[Title('Validate Screen')] -#[Description('Validates a Screen Builder config without saving. Pass config and optional type, and/or an existing screen id. Returns ok, errors, and warnings (select options, Vue component wiring). See the pm4-screen skill for the checklist.')] +#[Description('Validates a Screen Builder config without saving. Pass config and optional type, and/or an existing screen id. Returns ok, errors, warnings and info (select options, Vue component wiring). A small native FORM, or an edit to a stored native screen, gets an info note instead of the Vue warning. See the pm4-screen skill for the checklist.')] #[IsReadOnly] #[IsIdempotent] class ValidateScreenTool extends ScreenTool diff --git a/ProcessMaker/Services/DeployProcessAlternativeB.php b/ProcessMaker/Services/DeployProcessAlternativeB.php new file mode 100644 index 0000000000..3f2776556d --- /dev/null +++ b/ProcessMaker/Services/DeployProcessAlternativeB.php @@ -0,0 +1,88 @@ +assertDeployable($process); + + return DB::transaction(function () use ($process, $bpmn, $publish): array { + // Inside the transaction: if the version write fails below, Alternative B is not left enabled. + $this->ensureAlternativeBEnabled($process); + $this->hydrateFromLatestB($process); + $process->bpmn = $bpmn; + $process->alternative = 'B'; + + try { + $version = $publish ? $process->saveVersion() : $process->saveDraft('B'); + } catch (TaskDoesNotHaveUsersException $exception) { + throw ValidationException::withMessages(['bpmn' => $exception->getMessage()]); + } + + if ($publish) { + // The A/B package listens to this event to set process_version_b_id. + ProcessPublished::dispatch($process->refresh(), [], []); + } + + return ['version_id' => (int) $version->getKey(), 'published' => $publish]; + }); + } + + private function assertDeployable(?Process $process): Process + { + if (!class_exists(self::ALTERNATIVE_MODEL)) { + throw ValidationException::withMessages([ + 'alternative' => 'Alternative B requires package-ab-testing.', + ]); + } + if ($process === null) { + throw ValidationException::withMessages([ + 'alternative' => 'Alternative B needs an existing process. Deploy it as Alternative A first.', + ]); + } + + return $process; + } + + private function ensureAlternativeBEnabled(Process $process): void + { + $model = self::ALTERNATIVE_MODEL; + $alternative = $model::findOrCreateForProcess($process); + if (!$alternative->version_b_enabled) { + $alternative->enableAlternativeB(); + $alternative->save(); + } + } + + private function hydrateFromLatestB(Process $process): void + { + $version = $process->getDraftVersion('B') ?: $process->getDraftOrPublishedLatestVersion('B'); + if ($version instanceof ProcessVersion) { + $process->stages = $version->stages; + } + } +} diff --git a/ProcessMaker/Services/ScriptExecutorResolver.php b/ProcessMaker/Services/ScriptExecutorResolver.php index 3ab4b1e2af..465e00d597 100644 --- a/ProcessMaker/Services/ScriptExecutorResolver.php +++ b/ProcessMaker/Services/ScriptExecutorResolver.php @@ -4,10 +4,43 @@ namespace ProcessMaker\Services; +use ProcessMaker\Enums\ScriptExecutorType; use ProcessMaker\Models\ScriptExecutor; class ScriptExecutorResolver { + public const DEPLOY_LANGUAGE = 'php'; + + /** + * Find the executor a deploy request asked for, by id or by exact title. + * The id wins when both are sent. Returns null when none was requested + * or when it does not exist. + */ + public function findRequested(?int $id, ?string $title): ?ScriptExecutor + { + if ($id !== null) { + return ScriptExecutor::query()->find($id); + } + if ($title !== null && $title !== '') { + return ScriptExecutor::query()->where('title', $title)->first(); + } + + return null; + } + + /** + * Whether a user without administrator rights may bind a script to this executor: + * only the default one a new script would get, and never a custom executor. + */ + public function isDefaultForNonAdmins(ScriptExecutor $executor): bool + { + if ($executor->type === ScriptExecutorType::Custom) { + return false; + } + + return $this->resolveForNewScript()?->id === $executor->id; + } + public function resolveForNewScript(): ?ScriptExecutor { $php = ScriptExecutor::query() diff --git a/resources/js/admin/plugins/Plugins.vue b/resources/js/admin/plugins/Plugins.vue index 0b74ef2374..495f46327a 100644 --- a/resources/js/admin/plugins/Plugins.vue +++ b/resources/js/admin/plugins/Plugins.vue @@ -151,47 +151,13 @@ :class="getError('url') ? 'tw-border-red-500' : ''" :placeholder="$t('https://github.com/org/plugin.git')" /> - {{ getError("url") }} - +
@@ -744,7 +710,6 @@ const plugin = reactive({ gitToken: "", }); -const showGitCredentials = ref(false); const showMcpPrompt = ref(false); const MCP_PROFILES = [ { value: "pm4", label: "PM4 only" }, @@ -1633,7 +1598,6 @@ const resetValues = () => { gitUsername: "", gitToken: "", }); - showGitCredentials.value = false; delete plugin.description; errors.value = { url: null, diff --git a/tests/Feature/Api/DeployProcessControllerTest.php b/tests/Feature/Api/DeployProcessControllerTest.php index c8cc8e1838..e5074a0dcb 100644 --- a/tests/Feature/Api/DeployProcessControllerTest.php +++ b/tests/Feature/Api/DeployProcessControllerTest.php @@ -139,6 +139,95 @@ public function testGetProcessBpmnRestoresNamedReferences(): void $this->assertStringContainsString('${script:restore-script}', $response->json('bpmn')); } + public function testDeployAlternativeBWritesDraftAndKeepsLiveProcess(): void + { + $this->requireAbTesting(); + $name = 'alt-b-draft-process'; + $screen = Screen::factory()->create(['title' => 'alt-b-screen']); + + $this->apiCall('POST', self::DEPLOY_ENDPOINT, [ + 'name' => $name, + 'bpmn' => $this->sampleBpmn('', ''), + ])->assertOk(); + $process = Process::where('name', $name)->firstOrFail(); + $liveBpmn = $process->bpmn; + + $this->apiCall('POST', self::DEPLOY_ENDPOINT, [ + 'name' => $name, + 'alternative' => 'B', + 'bpmn' => $this->sampleBpmn('${screen:alt-b-screen}', ''), + ]) + ->assertOk() + ->assertJson(['success' => true, 'action' => 'draft', 'alternative' => 'B']); + + $this->assertSame($liveBpmn, $process->refresh()->bpmn, 'Alternative A must not change.'); + $draft = $process->versions()->where('draft', true)->where('alternative', 'B')->firstOrFail(); + $this->assertStringContainsString('pm:screenRef="' . $screen->id . '"', $draft->bpmn); + } + + public function testDeployAlternativeBPublishLinksVersionToAbRecord(): void + { + $this->requireAbTesting(); + $name = 'alt-b-publish-process'; + + $this->apiCall('POST', self::DEPLOY_ENDPOINT, [ + 'name' => $name, + 'bpmn' => $this->sampleBpmn('', ''), + ])->assertOk(); + $process = Process::where('name', $name)->firstOrFail(); + $liveBpmn = $process->bpmn; + + $response = $this->apiCall('POST', self::DEPLOY_ENDPOINT, [ + 'name' => $name, + 'alternative' => 'B', + 'publish' => true, + 'bpmn' => str_replace('Task_1', 'Task_B', $this->sampleBpmn('', '')), + ])->assertOk()->assertJson(['action' => 'published', 'alternative' => 'B']); + + $this->assertSame($liveBpmn, $process->refresh()->bpmn, 'Alternative A must not change.'); + $version = ProcessVersion::findOrFail($response->json('process_version_id')); + $this->assertSame('B', $version->alternative); + $this->assertFalse((bool) $version->draft); + $this->assertStringContainsString('Task_B', $version->bpmn); + + $alternativeModel = 'ProcessMaker\Package\PackageABTesting\Models\Alternative'; + $record = $alternativeModel::where('process_id', $process->id)->firstOrFail(); + $this->assertSame($version->id, (int) $record->process_version_b_id); + } + + public function testDeployAlternativeBRequiresExistingProcess(): void + { + $this->requireAbTesting(); + + $this->apiCall('POST', self::DEPLOY_ENDPOINT, [ + 'name' => 'alt-b-missing-process', + 'alternative' => 'B', + 'bpmn' => $this->sampleBpmn('', ''), + ]) + ->assertStatus(422) + ->assertJsonPath('success', false); + + $this->assertNull(Process::where('name', 'alt-b-missing-process')->first()); + } + + public function testDeployRejectsUnknownAlternative(): void + { + $this->apiCall('POST', self::DEPLOY_ENDPOINT, [ + 'name' => 'alt-unknown-process', + 'alternative' => 'C', + 'bpmn' => $this->sampleBpmn('', ''), + ]) + ->assertStatus(422) + ->assertJsonValidationErrors(['alternative']); + } + + private function requireAbTesting(): void + { + if (!class_exists('ProcessMaker\Package\PackageABTesting\Models\Alternative')) { + $this->markTestSkipped('package-ab-testing is not installed.'); + } + } + private function sampleBpmn(string $screenReference, string $scriptReference): string { return <<assertStringContainsString('yaml', (string) $response->headers->get('Content-Type')); } + public function testGetScreenYamlAddsEmptyInspectorToEveryItem(): void + { + $yaml = <<<'YAML' +config: + - name: Page 1 + items: + - component: FormInput + inspector: [] + config: + name: first + - component: FormMultiColumn + inspector: [] + container: true + items: + - - component: FormInput + inspector: [] + config: + name: nested + - [] +YAML; + $this->apiCall('POST', self::API_ENDPOINT, [ + 'yml_content' => $yaml, + 'name' => 'inspector-pull-screen', + ])->assertOk(); + + $pull = $this->actingAs($this->user, 'api') + ->get('/api/1.0' . self::GET_ENDPOINT . '?name=inspector-pull-screen'); + + $pull->assertOk(); + $parsed = \Symfony\Component\Yaml\Yaml::parse($pull->getContent()); + $items = $parsed['config'][0]['items']; + $this->assertSame([], $items[0]['inspector']); + $this->assertSame([], $items[1]['inspector']); + $this->assertSame([], $items[1]['items'][0][0]['inspector']); + $this->assertSame([], $items[1]['items'][1]); + } + public function testDeployScreenPersistsPreviewPresets(): void { $yaml = <<<'YAML' diff --git a/tests/Feature/Api/DeployScriptControllerTest.php b/tests/Feature/Api/DeployScriptControllerTest.php index 337c87c2fd..285e706cb9 100644 --- a/tests/Feature/Api/DeployScriptControllerTest.php +++ b/tests/Feature/Api/DeployScriptControllerTest.php @@ -2,6 +2,7 @@ namespace Tests\Feature\Api; +use ProcessMaker\Models\Permission; use ProcessMaker\Models\Script; use ProcessMaker\Models\ScriptExecutor; use ProcessMaker\Models\ScriptVersion; @@ -241,6 +242,194 @@ public function testDeployScriptPrefersPhpExecutorOnCreate(): void $this->assertSame('Merged migration script.', $script->description); } + public function testDeployScriptCreatesWithRequestedExecutorId(): void + { + $first = $this->phpExecutor('First PHP Executor'); + $second = $this->phpExecutor('Second PHP Executor'); + $this->assertNotSame($first->id, $second->id); + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => ' 'executor-by-id-script', + 'script_executor_id' => $second->id, + ])->assertOk()->assertJson(['action' => 'created']); + + $this->assertSame($second->id, Script::where('title', 'executor-by-id-script')->value('script_executor_id')); + } + + public function testDeployScriptCreatesWithRequestedExecutorTitle(): void + { + $this->phpExecutor('First PHP Executor'); + $target = $this->phpExecutor('Target PHP Executor'); + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => ' 'executor-by-title-script', + 'script_executor_title' => 'Target PHP Executor', + ])->assertOk(); + + $this->assertSame($target->id, Script::where('title', 'executor-by-title-script')->value('script_executor_id')); + } + + public function testDeployScriptUpdateCanMoveScriptToRequestedExecutor(): void + { + $this->phpExecutor('First PHP Executor'); + $target = $this->phpExecutor('Target PHP Executor'); + $script = Script::factory()->create(['title' => 'executor-update-script', 'language' => 'php']); + $this->assertNotSame($target->id, $script->script_executor_id); + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => ' 'executor-update-script', + 'script_executor_id' => $target->id, + 'version_name' => 'Move to the plugin executor', + ])->assertOk()->assertJson(['action' => 'updated']); + + $this->assertSame($target->id, $script->refresh()->script_executor_id); + } + + public function testDeployScriptUpdateKeepsExecutorWhenNoneIsRequested(): void + { + $this->phpExecutor('First PHP Executor'); + $target = $this->phpExecutor('Target PHP Executor'); + $script = Script::factory()->create([ + 'title' => 'executor-kept-script', + 'language' => 'php', + 'script_executor_id' => $target->id, + ]); + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => ' 'executor-kept-script', + 'version_name' => 'Change the code only', + ])->assertOk(); + + $this->assertSame($target->id, $script->refresh()->script_executor_id); + } + + public function testDeployScriptRejectsUnknownExecutor(): void + { + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => ' 'executor-unknown-script', + 'script_executor_id' => 999999, + ]) + ->assertStatus(422) + ->assertJson(['success' => false]) + ->assertJsonValidationErrors(['script_executor_id']); + + $this->assertNull(Script::where('title', 'executor-unknown-script')->first()); + } + + public function testDeployScriptRejectsExecutorOfAnotherLanguage(): void + { + $lua = ScriptExecutor::factory()->create(['language' => 'lua', 'title' => 'Lua Executor']); + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => ' 'executor-wrong-language-script', + 'script_executor_title' => $lua->title, + ]) + ->assertStatus(422) + ->assertJsonValidationErrors(['script_executor_title']); + + $this->assertNull(Script::where('title', 'executor-wrong-language-script')->first()); + } + + public function testNonAdminWithoutEditScriptsCannotChooseExecutor(): void + { + $default = $this->phpExecutor('Default PHP Executor'); + $this->actAsNonAdmin([]); + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => ' 'executor-forbidden-create', + 'script_executor_id' => $default->id, + ])->assertStatus(403)->assertJson(['success' => false]); + + $this->assertNull(Script::where('title', 'executor-forbidden-create')->first()); + } + + public function testNonAdminCannotMoveScriptToNonDefaultExecutor(): void + { + $this->phpExecutor('Default PHP Executor'); + $admin = $this->phpExecutor('Admin PHP Executor'); + $script = Script::factory()->create(['title' => 'executor-forbidden-update', 'language' => 'php']); + $before = $script->script_executor_id; + $this->actAsNonAdmin(['edit-scripts']); + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => ' 'executor-forbidden-update', + 'script_executor_id' => $admin->id, + 'version_name' => 'Move to the admin executor', + ])->assertStatus(403)->assertJson(['success' => false]); + + $this->assertSame($before, $script->refresh()->script_executor_id); + } + + public function testNonAdminCannotUseCustomExecutor(): void + { + $default = $this->phpExecutor('Default PHP Executor'); + $default->update(['type' => 'custom']); + $this->actAsNonAdmin(['edit-scripts']); + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => ' 'executor-forbidden-custom', + 'script_executor_id' => $default->id, + ])->assertStatus(403); + + $this->assertNull(Script::where('title', 'executor-forbidden-custom')->first()); + } + + public function testNonAdminWithEditScriptsCanUseDefaultExecutor(): void + { + $default = ScriptExecutor::query()->where('language', 'php')->orderBy('id')->first() + ?? $this->phpExecutor('Default PHP Executor'); + $this->actAsNonAdmin(['edit-scripts']); + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => ' 'executor-allowed-default', + 'script_executor_id' => $default->id, + ])->assertOk()->assertJson(['action' => 'created']); + + $this->assertSame($default->id, Script::where('title', 'executor-allowed-default')->value('script_executor_id')); + } + + public function testNonAdminWithoutExecutorKeepsCurrentBehavior(): void + { + $this->ensureExecutor(); + $this->actAsNonAdmin([]); + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => ' 'executor-none-requested', + ])->assertOk()->assertJson(['action' => 'created']); + } + + /** + * Make the authenticated user a regular user holding only the given permissions. + */ + private function actAsNonAdmin(array $permissions): void + { + $this->user->is_administrator = false; + $this->user->save(); + $this->initializePermissions(); + + foreach ($permissions as $permission) { + $this->user->permissions()->attach(Permission::byName($permission)->id); + } + $this->user->refresh(); + $this->flushSession(); + } + + private function phpExecutor(string $title): ScriptExecutor + { + return ScriptExecutor::factory()->create(['language' => 'php', 'title' => $title]); + } + private function ensureExecutor(): ScriptExecutor { return ScriptExecutor::query()->first() ?? ScriptExecutor::factory()->create(); diff --git a/tests/Feature/Api/PluginsTest.php b/tests/Feature/Api/PluginsTest.php index c6a08bad11..e800d384c4 100644 --- a/tests/Feature/Api/PluginsTest.php +++ b/tests/Feature/Api/PluginsTest.php @@ -73,6 +73,8 @@ public function testToggleQueuesJob(): void public function testInstallRejectsNonHttpsUrl(): void { + // The https-only rule is enforced in production only. + config(['app.env' => 'production']); Bus::fake([InstallPlugin::class]); $response = $this->apiCall('POST', '/plugins/install', [ diff --git a/tests/Feature/Mcp/ProcessServerTest.php b/tests/Feature/Mcp/ProcessServerTest.php index 5fdf9a8d02..0bf88155e0 100644 --- a/tests/Feature/Mcp/ProcessServerTest.php +++ b/tests/Feature/Mcp/ProcessServerTest.php @@ -11,8 +11,10 @@ use ProcessMaker\Mcp\Servers\ProcessServer; use ProcessMaker\Mcp\Tools\GetMcpGuidanceTool; use ProcessMaker\Mcp\Tools\GetMcpSkillTool; +use ProcessMaker\Mcp\Tools\Processes\CreateGroupTool; use ProcessMaker\Mcp\Tools\Processes\CreateProcessTool; use ProcessMaker\Mcp\Tools\Processes\EnableProcessAlternativeBTool; +use ProcessMaker\Mcp\Tools\Processes\GetProcessInventoryTool; use ProcessMaker\Mcp\Tools\Processes\GetProcessTool; use ProcessMaker\Mcp\Tools\Processes\ListGroupsTool; use ProcessMaker\Mcp\Tools\Processes\ListProcessesTool; @@ -24,6 +26,9 @@ use ProcessMaker\Models\Permission; use ProcessMaker\Models\Process; use ProcessMaker\Models\ProcessCategory; +use ProcessMaker\Models\ProcessVersion; +use ProcessMaker\Models\Screen; +use ProcessMaker\Models\Script; use ProcessMaker\Models\Setting; use ProcessMaker\Models\User; use Tests\Feature\Shared\RequestHelper; @@ -148,6 +153,191 @@ public function testListUsersAndGroupsForAssignment(): void ->etc()); } + public function testListGroupsFindsExactNameAndReportsMembersAndDuplicates(): void + { + $group = Group::factory()->create(['name' => 'Requesters Exact', 'status' => 'ACTIVE']); + Group::factory()->create(['name' => 'Requesters Exact Plus', 'status' => 'ACTIVE']); + $group->groupMembers()->create([ + 'member_id' => $this->user->id, + 'member_type' => User::class, + ]); + + ProcessServer::actingAs($this->user)->tool(ListGroupsTool::class, [ + 'filter' => 'Requesters Exact', + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->has('data', 2) + ->etc()); + + ProcessServer::actingAs($this->user)->tool(ListGroupsTool::class, [ + 'name' => 'requesters exact', + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->has('data', 1) + ->where('data.0.id', $group->id) + ->where('data.0.members_count', 1) + ->where('data.0.same_name_count', 1) + ->etc()); + } + + public function testCreateGroupCreatesAnActiveGroupAndRejectsDuplicates(): void + { + ProcessServer::actingAs($this->user)->tool(CreateGroupTool::class, [ + 'name' => 'Deal Closing Legal', + 'description' => 'Legal sign-off', + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('name', 'Deal Closing Legal') + ->where('status', 'ACTIVE') + ->where('members_count', 0) + ->etc()); + + $this->assertSame(1, Group::where('name', 'Deal Closing Legal')->count()); + + ProcessServer::actingAs($this->user)->tool(CreateGroupTool::class, [ + 'name' => 'Deal Closing Legal', + ])->assertHasErrors(['has already been taken']); + + ProcessServer::actingAs($this->user)->tool(CreateGroupTool::class, [ + 'name' => 'Bad_Name!', + ])->assertHasErrors(['may only contain alphanumeric characters']); + } + + public function testCreateGroupEnforcesTheTwoFactorPolicy(): void + { + config(['password-policies.2fa_enabled' => true]); + ProcessServer::actingAs($this->user)->tool(CreateGroupTool::class, [ + 'name' => 'TwoFactorOnGroup', + 'enabled_2fa' => false, + ])->assertOk(); + $this->assertTrue((bool) Group::where('name', 'TwoFactorOnGroup')->value('enabled_2fa')); + + config(['password-policies.2fa_enabled' => false]); + ProcessServer::actingAs($this->user)->tool(CreateGroupTool::class, [ + 'name' => 'TwoFactorOffGroup', + 'enabled_2fa' => true, + ])->assertOk(); + $this->assertFalse((bool) Group::where('name', 'TwoFactorOffGroup')->value('enabled_2fa')); + } + + public function testCreateGroupRequiresThePermission(): void + { + $this->initializePermissions(); + $member = User::factory()->create(['is_administrator' => false]); + $member->permissions()->attach(Permission::byName('create-processes')); + + ProcessServer::actingAs($member)->tool(CreateGroupTool::class, [ + 'name' => 'Not Allowed Group', + ])->assertHasErrors(['create-groups']); + + $this->assertSame(0, Group::where('name', 'Not Allowed Group')->count()); + } + + public function testProcessInventoryMapsAssetsFieldsAndGatewayVariables(): void + { + $screen = Screen::factory()->create([ + 'title' => 'Inventory Form', + 'type' => 'FORM', + 'config' => [[ + 'name' => 'Page', + 'items' => [ + ['component' => 'FormInput', 'config' => ['name' => 'DC_FLAG']], + ['component' => 'FormButton', 'config' => ['name' => 'submit']], + ['component' => 'FormMultiColumn', 'config' => [], 'items' => [ + [['component' => 'FormTextArea', 'config' => ['name' => 'DC_NOTES']]], + [], + ]], + ], + ]], + ]); + $script = Script::factory()->create(['title' => 'Inventory Script', 'language' => 'php']); + + $bpmn = $this->inventoryBpmn($screen->id, $script->id); + $process = Process::factory()->create(['name' => 'Inventory Process', 'bpmn' => $bpmn]); + + ProcessServer::actingAs($this->user)->tool(GetProcessInventoryTool::class, [ + 'id' => $process->id, + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('process.id', $process->id) + ->where('counts.activities', 2) + ->where('counts.gateways', 1) + ->where('counts.sequence_flows', 3) + ->where('screens.0.title', 'Inventory Form') + ->where('screens.0.controls', 4) + ->where('screens.0.fields', ['DC_FLAG', 'DC_NOTES']) + ->where('scripts.0.title', 'Inventory Script') + ->where('activities.0.screen_title', 'Inventory Form') + ->where('activities.1.script_title', 'Inventory Script') + ->where('gateways.0.variables', ['DC_FLAG', 'DC_MISSING']) + ->where('variables.DC_FLAG.written_by_screens', [$screen->id]) + ->where('variables.DC_MISSING.written_by_screens', []) + ->where('variables.DC_MISSING.read_by_gateways', ['gate_1']) + ->has('warnings', 1) + ->etc()); + } + + public function testUpdateProcessStripsMarkupFromCaseTitleAndKeepsMustache(): void + { + $process = Process::factory()->create(['name' => 'Case Title Process']); + + ProcessServer::actingAs($this->user)->tool(UpdateProcessTool::class, [ + 'id' => $process->id, + 'case_title' => 'Case #{{_request.case_number}}', + ])->assertOk(); + + $this->assertSame('Case #{{_request.case_number}}', $process->refresh()->case_title); + } + + public function testInventoryHidesScriptsWithoutViewScriptsPermission(): void + { + $this->initializePermissions(); + $screen = Screen::factory()->create(['title' => 'Inventory Form', 'type' => 'FORM', 'config' => []]); + $script = Script::factory()->create(['title' => 'Hidden Script', 'language' => 'php']); + $process = Process::factory()->create([ + 'name' => 'Inventory Process', + 'bpmn' => $this->inventoryBpmn($screen->id, $script->id), + ]); + $member = User::factory()->create(['is_administrator' => false]); + $member->permissions()->attach(Permission::byName('view-processes')); + + ProcessServer::actingAs($member)->tool(GetProcessInventoryTool::class, [ + 'id' => $process->id, + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('scripts', []) + ->etc()) + ->assertDontSee('Hidden Script'); + } + + private function inventoryBpmn(int $screenId, int $scriptId): string + { + return << + + + flow_1 + + flow_1flow_2 + + + flow_2flow_3 + + + flow_3 + + + + + DC_FLAG == 'YES' && DC_MISSING != '' + + + +XML; + } + public function testValidateProcessReportsMissingScreenRef(): void { $bpmn = <<<'XML' @@ -298,6 +488,101 @@ public function testMetadataUpdateDoesNotPublishDraftBpmn(): void $this->assertStringContainsString('UnpublishedDraft', (string) $draft->bpmn); } + public function testUpdateProcessSavesCaseTitleManagersAndNotificationsWithoutPublishing(): void + { + $publishedBpmn = Process::getProcessTemplate('OnlyStartElement.bpmn'); + $process = Process::factory()->create(['name' => 'Settings Process', 'bpmn' => $publishedBpmn]); + $manager = User::factory()->create(); + $versionsBefore = ProcessVersion::where('process_id', $process->id)->count(); + + ProcessServer::actingAs($this->user)->tool(UpdateProcessTool::class, [ + 'id' => $process->id, + 'case_title' => '{{customer}} request', + 'manager_id' => [$manager->id], + 'notifications' => ['requester' => ['started' => true, 'error' => true]], + ])->assertOk() + ->assertHasNoErrors() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('case_title', '{{customer}} request') + ->where('manager_id', [$manager->id]) + ->where('notifications.requester.started', true) + ->where('notifications.requester.completed', false) + ->etc()); + + $process->refresh(); + $this->assertSame('{{customer}} request', $process->case_title); + $this->assertSame([$manager->id], array_map('intval', $process->manager_id)); + $this->assertTrue($process->notifications->requester['started']); + $this->assertTrue($process->notifications->requester['error']); + $this->assertFalse($process->notifications->assignee['started']); + $this->assertSame($publishedBpmn, $process->bpmn); + $this->assertSame($versionsBefore, ProcessVersion::where('process_id', $process->id)->count()); + $this->assertSame($this->user->id, (int) $process->updated_by); + } + + public function testNotificationUpdateOnlyChangesTheSentPairs(): void + { + $process = Process::factory()->create([ + 'name' => 'Notification Pairs', + 'bpmn' => Process::getProcessTemplate('OnlyStartElement.bpmn'), + ]); + $tool = fn (array $notifications) => ProcessServer::actingAs($this->user)->tool(UpdateProcessTool::class, [ + 'id' => $process->id, + 'notifications' => $notifications, + ]); + + $tool(['requester' => ['started' => true], 'assignee' => ['completed' => true]])->assertOk(); + $tool(['requester' => ['started' => false], 'manager' => ['error' => true]])->assertOk(); + + $notifications = $process->refresh()->notifications; + $this->assertFalse($notifications->requester['started']); + $this->assertTrue($notifications->assignee['completed']); + $this->assertTrue($notifications->manager['error']); + } + + public function testUpdateProcessRejectsUnknownNotificationKeysAndManagers(): void + { + $process = Process::factory()->create([ + 'name' => 'Rejected Settings', + 'bpmn' => Process::getProcessTemplate('OnlyStartElement.bpmn'), + ]); + + ProcessServer::actingAs($this->user)->tool(UpdateProcessTool::class, [ + 'id' => $process->id, + 'notifications' => ['requestr' => ['started' => true]], + ])->assertHasErrors(['Unknown notifiable type "requestr"']); + + ProcessServer::actingAs($this->user)->tool(UpdateProcessTool::class, [ + 'id' => $process->id, + 'notifications' => ['requester' => ['finished' => true]], + ])->assertHasErrors(['Unknown notification type "finished"']); + + ProcessServer::actingAs($this->user)->tool(UpdateProcessTool::class, [ + 'id' => $process->id, + 'manager_id' => [99999999], + ])->assertHasErrors(['The selected Manager_id.0 is invalid.']); + + $this->assertSame(0, $process->refresh()->notification_settings()->count()); + } + + public function testUpdateProcessClearsManagersWithAnEmptyArray(): void + { + $manager = User::factory()->create(); + $process = Process::factory()->create([ + 'name' => 'Clear Managers', + 'bpmn' => Process::getProcessTemplate('OnlyStartElement.bpmn'), + ]); + $process->manager_id = [$manager->id]; + $process->saveOrFail(); + + ProcessServer::actingAs($this->user)->tool(UpdateProcessTool::class, [ + 'id' => $process->id, + 'manager_id' => [], + ])->assertOk()->assertHasNoErrors(); + + $this->assertSame([], $process->refresh()->manager_id); + } + public function testCombinedBpmnAndMetadataUpdatePersistsLiveMetadata(): void { $publishedBpmn = Process::getProcessTemplate('OnlyStartElement.bpmn'); diff --git a/tests/Feature/Mcp/ScreenServerTest.php b/tests/Feature/Mcp/ScreenServerTest.php index 2e1daabf4f..7e0c5d591d 100644 --- a/tests/Feature/Mcp/ScreenServerTest.php +++ b/tests/Feature/Mcp/ScreenServerTest.php @@ -178,6 +178,51 @@ public function testCreateScreenRejectsSelectListWithoutOptionsList(): void ])->assertHasErrors(['optionsList']); } + public function testNativeFormNoticeDependsOnSizeAndOnEditingANativeScreen(): void + { + ScreenServer::actingAs($this->user)->tool(ValidateScreenTool::class, [ + 'type' => 'FORM', + 'config' => $this->nativeConfig(2), + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('ok', true) + ->where('warnings', []) + ->where('info.0.code', 'native_small_screen') + ->etc()); + + ScreenServer::actingAs($this->user)->tool(ValidateScreenTool::class, [ + 'type' => 'FORM', + 'config' => $this->nativeConfig(6), + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('warnings.0.code', 'prefer_vue_component_editor') + ->where('info', []) + ->etc()); + + $stored = Screen::factory()->create(['type' => 'FORM', 'config' => $this->nativeConfig(8)]); + ScreenServer::actingAs($this->user)->tool(ValidateScreenTool::class, [ + 'id' => $stored->id, + 'config' => $this->nativeConfig(9), + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('warnings', []) + ->where('info.0.code', 'native_screen_edit') + ->etc()); + } + + /** + * @return list> + */ + private function nativeConfig(int $inputs): array + { + $items = []; + for ($index = 0; $index < $inputs; $index++) { + $items[] = ['component' => 'FormInput', 'inspector' => [], 'config' => ['name' => 'field_' . $index]]; + } + + return [['name' => 'Page 1', 'items' => $items]]; + } + public function testValidateScreenReportsSelectAndVueIssues(): void { ScreenServer::actingAs($this->user)->tool(ValidateScreenTool::class, [ diff --git a/tests/Managers/PluginManagerTest.php b/tests/Managers/PluginManagerTest.php index e68e5d8815..4706c9d457 100644 --- a/tests/Managers/PluginManagerTest.php +++ b/tests/Managers/PluginManagerTest.php @@ -77,6 +77,7 @@ private function temporaryPluginDirs(): array $this->pluginsDir . '/plugin-two', $this->pluginsDir . '/valid-plugin', $this->pluginsDir . '/_hidden-plugin', + $this->pluginsDir . '/clone-origin-test', ]; } diff --git a/tests/Managers/ScreenBuilderManagerTest.php b/tests/Managers/ScreenBuilderManagerTest.php index ad1ba3fc05..042cfd9092 100644 --- a/tests/Managers/ScreenBuilderManagerTest.php +++ b/tests/Managers/ScreenBuilderManagerTest.php @@ -143,7 +143,6 @@ public function testStoragePluginScreenBuilderScripts(): void $managerTenant->addPackageScripts('FORM'); $tenantScripts = $managerTenant->getScripts(); $tenantWebPath = PluginVendorAssets::webPath( - 7, $tenantPackage, '/js/screen-builder-form-components.js' ); @@ -158,13 +157,13 @@ public function testStoragePluginScreenBuilderScripts(): void private function touchTenantPublicAsset(int $tenantId, string $packageName, string $fileName): string { - $dir = PluginVendorAssets::tenantPublicRoot($tenantId, $packageName) . '/js'; + $dir = PluginVendorAssets::tenantPackageRoot($tenantId, $packageName) . '/js'; if (!is_dir($dir)) { mkdir($dir, 0755, true); } $path = $dir . '/' . $fileName; file_put_contents($path, '// tenant test asset'); - $this->tenantPublicAssetPaths[] = PluginVendorAssets::tenantPublicRoot($tenantId, $packageName); + $this->tenantPublicAssetPaths[] = PluginVendorAssets::tenantPackageRoot($tenantId, $packageName); return $path; } diff --git a/tests/unit/Managers/PluginManagerTenantAssetsTest.php b/tests/unit/Managers/PluginManagerTenantAssetsTest.php index 5914b170c3..6b8295e3f6 100644 --- a/tests/unit/Managers/PluginManagerTenantAssetsTest.php +++ b/tests/unit/Managers/PluginManagerTenantAssetsTest.php @@ -27,7 +27,7 @@ public function testTenantAssetHooksPublishAndRemoveWhenMultitenancyEnabled(): v $publish = new ReflectionMethod($manager, 'publishTenantPluginAssetsIfApplicable'); $publish->invoke($manager, $pluginDir, 'tenant-assets-plugin', null); - $published = PluginVendorAssets::tenantPublicRoot(6, 'tenant-assets-plugin') . '/js/app.js'; + $published = PluginVendorAssets::tenantPackageRoot(6, 'tenant-assets-plugin') . '/js/app.js'; $this->assertFileExists($published); $remove = new ReflectionMethod($manager, 'removeTenantPluginAssetsIfApplicable'); @@ -43,7 +43,7 @@ public function testTenantAssetHooksPublishAndRemoveWhenMultitenancyEnabled(): v file_put_contents($offDir . '/public/js/app.js', '// noop'); $publish->invoke($manager, $offDir, 'off-tenant-plugin', null); $this->assertFileDoesNotExist( - PluginVendorAssets::tenantPublicRoot(6, 'off-tenant-plugin') . '/js/app.js' + PluginVendorAssets::tenantPackageRoot(6, 'off-tenant-plugin') . '/js/app.js' ); $this->deleteDirectory($pluginDir); diff --git a/tests/unit/Traits/PluginServiceProviderTraitModelerTest.php b/tests/unit/Traits/PluginServiceProviderTraitModelerTest.php index cae9432be8..40ddc802a9 100644 --- a/tests/unit/Traits/PluginServiceProviderTraitModelerTest.php +++ b/tests/unit/Traits/PluginServiceProviderTraitModelerTest.php @@ -18,7 +18,7 @@ public function testModelerStartingRegistersScriptWhenOnlyTenantAssetsExist(): v $this->app->instance('currentTenant', (object) ['id' => 8]); $package = 'modeler-trait-pkg-' . uniqid(); - $tenantRoot = PluginVendorAssets::tenantPublicRoot(8, $package); + $tenantRoot = PluginVendorAssets::tenantPackageRoot(8, $package); mkdir($tenantRoot . '/js', 0755, true); file_put_contents($tenantRoot . '/mix-manifest.json', json_encode([ '/js/modeler-schema-profile.js' => '/js/modeler-schema-profile.js?id=trait-test', @@ -44,7 +44,7 @@ public function runModelerStarting(ModelerManager $manager, string $package): vo $scripts = $manager->getScriptWithParams(); $found = false; foreach ($scripts as $script) { - if (str_contains($script['src'], '/storage/tenant_8/vendor/processmaker/packages/' . $package)) { + if (str_contains($script['src'], '/storage/vendor/processmaker/packages/' . $package)) { $found = true; break; }