diff --git a/ProcessMaker/Exception/MissingBpmnReferenceException.php b/ProcessMaker/Exception/MissingBpmnReferenceException.php new file mode 100644 index 0000000000..5aec7b716e --- /dev/null +++ b/ProcessMaker/Exception/MissingBpmnReferenceException.php @@ -0,0 +1,11 @@ +all(), [ + 'bpmn' => 'required|string', + 'name' => 'required|string|max:255', + ]); + + if ($validator->fails()) { + return response()->json([ + 'success' => false, + 'errors' => $validator->errors(), + ], 422); + } + + return $this->saveDeployedProcess($request); + } + + 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, + ]); + } catch (Throwable $exception) { + return $this->deployProcessFailureResponse($exception); + } + } + + /** + * @return array{0: Process, 1: bool} + */ + private function upsertProcessByName(Request $request, string $bpmn): array + { + return DB::transaction(function () use ($request, $bpmn): array { + $process = Process::where('name', $request->input('name'))->first(); + $created = $process === null; + + if ($created) { + $process = new Process(); + $process->name = $request->input('name'); + $process->description = ''; + $process->status = 'ACTIVE'; + $process->user_id = $request->user()->id; + } + + $process->bpmn = $bpmn; + $process->saveOrFail(); + + return [$process->refresh(), $created]; + }); + } + + private function deployProcessFailureResponse(Throwable $exception): JsonResponse + { + if ($exception instanceof MissingBpmnReferenceException) { + return response()->json([ + 'success' => false, + 'message' => $exception->getMessage(), + ], 422); + } + + report($exception); + + return response()->json([ + 'success' => false, + 'message' => 'The process could not be saved.', + 'error' => $exception->getMessage(), + ], 422); + } + + public function getProcessBpmn(Request $request): JsonResponse + { + $validator = Validator::make($request->all(), [ + 'name' => 'required|string|max:255', + ]); + + if ($validator->fails()) { + return response()->json([ + 'success' => false, + 'errors' => $validator->errors(), + ], 422); + } + + $process = Process::where('name', $request->input('name'))->first(); + if ($process === null) { + return response()->json([ + 'success' => false, + 'message' => 'Process not found.', + 'name' => $request->input('name'), + ], 404); + } + + return response()->json([ + 'success' => true, + 'process_id' => $process->id, + 'name' => $process->name, + 'bpmn' => $this->references->restoreNamedReferences((string) $process->bpmn), + ]); + } + + /** + * @return list + */ + private function validateXml(string $bpmn): array + { + $previous = libxml_use_internal_errors(true); + libxml_clear_errors(); + + $document = new DOMDocument(); + $valid = $document->loadXML($bpmn, LIBXML_NONET); + $errors = array_map( + static fn (\LibXMLError $error): string => trim($error->message), + libxml_get_errors() + ); + + libxml_clear_errors(); + libxml_use_internal_errors($previous); + + return $valid ? [] : $errors; + } +} diff --git a/ProcessMaker/Http/Controllers/Api/DeployScreen.php b/ProcessMaker/Http/Controllers/Api/DeployScreen.php new file mode 100644 index 0000000000..d063c6da21 --- /dev/null +++ b/ProcessMaker/Http/Controllers/Api/DeployScreen.php @@ -0,0 +1,184 @@ +all(), [ + 'yml_content' => 'required|string', + 'name' => 'required|string', + ]); + + if ($validator->fails()) { + return response()->json([ + 'success' => false, + 'errors' => $validator->errors(), + ], 422); + } + + $ymlContent = $request->input('yml_content'); + $name = $request->input('name'); + + $parsedData = $this->parseDeployYaml($ymlContent); + if ($parsedData instanceof JsonResponse) { + return $parsedData; + } + + $screen = Screen::where('title', $name)->first(); + $created = $screen === null; + + if ($created) { + $screen = new Screen(); + $screen->title = $name; + $screen->description = $parsedData['description'] ?? ''; + $screen->type = $parsedData['type'] ?? 'FORM'; + } + + $this->applyYamlFields($screen, $parsedData, $created); + $screen->save(); + $screen->refresh(); + + return response()->json([ + 'success' => true, + 'action' => $created ? 'created' : 'updated', + 'screen_id' => $screen->id, + 'name' => $screen->title, + 'message' => $created + ? 'Screen created from YAML.' + : 'Screen updated from YAML.', + ]); + } + + /** + * @return \Illuminate\Http\Response|JsonResponse + */ + public function getScreenYaml(Request $request) + { + $validator = Validator::make($request->all(), [ + 'name' => 'required|string', + ]); + + if ($validator->fails()) { + return response()->json([ + 'success' => false, + 'errors' => $validator->errors(), + ], 422); + } + + $name = $request->input('name'); + $resolved = $this->resolvePublishedScreenByTitle($name); + if ($resolved instanceof JsonResponse) { + return $resolved; + } + + [$screen, $screenVersion] = $resolved; + $config = $this->removeInspectorMetadata($screenVersion->config ?? []); + $data = [ + 'config' => $config, + 'computed' => $screenVersion->computed, + 'watchers' => $screenVersion->watchers, + 'custom_css' => $screenVersion->custom_css, + ]; + $yaml = Yaml::dump($data, 100, 2, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK); + + return response($yaml, 200) + ->header('Content-Type', 'text/yaml') + ->header('X-Screen-Id', (string) $screen->id) + ->header('X-Screen-Name', $screen->title); + } + + /** + * @return array{0: Screen, 1: object}|JsonResponse + */ + private function resolvePublishedScreenByTitle(string $name): array|JsonResponse + { + $screen = Screen::where('title', $name)->first(); + if ($screen === null) { + return response()->json([ + 'success' => false, + 'message' => 'Screen not found', + 'name' => $name, + ], 404); + } + + $screenVersion = $screen->getPublishedVersion([]); + if ($screenVersion === null) { + return response()->json([ + 'success' => false, + 'message' => 'Screen does not have a published version', + 'name' => $name, + 'screen_id' => $screen->id, + ], 404); + } + + return [$screen, $screenVersion]; + } + + /** + * @return array|JsonResponse + */ + private function parseDeployYaml(string $ymlContent): array|JsonResponse + { + try { + $parsedData = Yaml::parse($ymlContent) ?? []; + } catch (\Exception $e) { + return response()->json([ + 'success' => false, + 'message' => 'Invalid YAML content', + 'error' => $e->getMessage(), + ], 400); + } + + if (!is_array($parsedData)) { + return response()->json([ + 'success' => false, + 'message' => 'Invalid YAML content', + 'error' => 'YAML must parse to a mapping of screen fields', + ], 400); + } + + return $parsedData; + } + + private function applyYamlFields(Screen $screen, array $parsedData, bool $created): void + { + $defaults = [ + 'config' => [], + 'computed' => [], + 'watchers' => [], + 'custom_css' => '', + ]; + + foreach ($defaults as $field => $default) { + if (array_key_exists($field, $parsedData)) { + $screen->{$field} = $parsedData[$field]; + } elseif ($created) { + $screen->{$field} = $default; + } + } + } +} diff --git a/ProcessMaker/Http/Controllers/Api/DeployScript.php b/ProcessMaker/Http/Controllers/Api/DeployScript.php new file mode 100644 index 0000000000..8d978ab0c9 --- /dev/null +++ b/ProcessMaker/Http/Controllers/Api/DeployScript.php @@ -0,0 +1,135 @@ +all(), [ + 'code' => 'required|string', + 'name' => 'required|string', + ]); + + if ($validator->fails()) { + return response()->json([ + 'success' => false, + 'errors' => $validator->errors(), + ], 422); + } + + $name = $request->input('name'); + $code = $request->input('code'); + + $script = Script::where('title', $name)->first(); + $created = $script === null; + + if ($created) { + $executor = $this->executors->resolveForNewScript(); + if ($executor === null) { + return response()->json([ + 'success' => false, + 'message' => 'No script executor is available to create a script.', + ], 422); + } + + $script = new Script(); + $script->title = $name; + $script->description = ''; + $script->language = $executor->language; + $script->script_executor_id = $executor->id; + $script->run_as_user_id = $request->user()->id; + $script->timeout = self::DEFAULT_TIMEOUT; + $script->retry_attempts = self::DEFAULT_RETRY_ATTEMPTS; + $script->retry_wait_time = self::DEFAULT_RETRY_WAIT_TIME; + } + + $script->code = $code; + $script->save(); + $script->refresh(); + + return response()->json([ + 'success' => true, + 'action' => $created ? 'created' : 'updated', + 'script_id' => $script->id, + 'name' => $script->title, + 'message' => $created + ? 'Script created from PHP.' + : 'Script updated from PHP.', + ]); + } + + /** + * Return the published script PHP source, looked up by title. + * + * @return \Illuminate\Http\Response|JsonResponse + */ + public function getScriptPhp(Request $request) + { + $validator = Validator::make($request->all(), [ + 'name' => 'required|string', + ]); + + if ($validator->fails()) { + return response()->json([ + 'success' => false, + 'errors' => $validator->errors(), + ], 422); + } + + $name = $request->input('name'); + $script = Script::where('title', $name)->first(); + $scriptVersion = $script?->getPublishedVersion([]); + if ($script === null || $scriptVersion === null) { + $payload = [ + 'success' => false, + 'message' => $script === null + ? 'Script not found' + : 'Script does not have a published version', + 'name' => $name, + ]; + if ($script !== null) { + $payload['script_id'] = $script->id; + } + + return response()->json($payload, 404); + } + + return response((string) ($scriptVersion->code ?? ''), 200) + ->header('Content-Type', 'text/plain; charset=UTF-8') + ->header('X-Script-Id', (string) $script->id) + ->header('X-Script-Name', $script->title); + } +} diff --git a/ProcessMaker/Mcp/Processes/ProcessBpmnValidator.php b/ProcessMaker/Mcp/Processes/ProcessBpmnValidator.php index 4838dc5405..e557b1ca06 100644 --- a/ProcessMaker/Mcp/Processes/ProcessBpmnValidator.php +++ b/ProcessMaker/Mcp/Processes/ProcessBpmnValidator.php @@ -264,7 +264,7 @@ private function requireFlowWiring(DOMXPath $xpath, array &$errors): void /** * MCP create/update-process does not resolve ${screen:title} / ${script:title} / ${process:name}. - * Those portable refs only resolve via package-plg deploy-process. Leave them as hard errors here. + * Those portable refs resolve via core deploy-process. Leave them as hard errors here. * * @param list $errors */ diff --git a/ProcessMaker/Mcp/Servers/ProcessServer.php b/ProcessMaker/Mcp/Servers/ProcessServer.php index e98021343b..65b4745b17 100644 --- a/ProcessMaker/Mcp/Servers/ProcessServer.php +++ b/ProcessMaker/Mcp/Servers/ProcessServer.php @@ -38,7 +38,7 @@ Use list-processes to search before creating one. create-process requires name and description; bpmn is optional (empty template if omitted — add a start event before running). -For MCP create-process/update-process use numeric pm:screenRef / pm:scriptRef (list-screens after create-screen). Portable ${screen:title} only resolves via package-plg deploy-process. +For MCP create-process/update-process use numeric pm:screenRef / pm:scriptRef (list-screens after create-screen). Portable ${screen:title} resolves via core deploy-process (POST /api/1.0/deploy-process). 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 validate-process before create/update when unsure. diff --git a/ProcessMaker/Mcp/Tools/Processes/ProcessFields.php b/ProcessMaker/Mcp/Tools/Processes/ProcessFields.php index cb04cfabd5..fb3f67a97e 100644 --- a/ProcessMaker/Mcp/Tools/Processes/ProcessFields.php +++ b/ProcessMaker/Mcp/Tools/Processes/ProcessFields.php @@ -18,7 +18,7 @@ final class ProcessFields public const CATEGORY = 'Process category id, or comma-separated ids.'; - 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} only when publishing via package-plg deploy-process.'; + 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 static function id(JsonSchema $schema): IntegerType { diff --git a/ProcessMaker/Services/ProcessBpmnReferenceService.php b/ProcessMaker/Services/ProcessBpmnReferenceService.php new file mode 100644 index 0000000000..142c007dfd --- /dev/null +++ b/ProcessMaker/Services/ProcessBpmnReferenceService.php @@ -0,0 +1,314 @@ +replaceNamedReferences( + $bpmn, + 'screen', + fn (array $names) => Screen::query() + ->whereIn('title', $names) + ->pluck('id', 'title') + ->all() + ); + + $bpmn = $this->replaceNamedReferences( + $bpmn, + 'script', + fn (array $names) => Script::query() + ->whereIn('title', $names) + ->pluck('id', 'title') + ->all() + ); + + $bpmn = $this->resolveWebEntryScreenReferences($bpmn); + + return $this->resolveNamedProcessCalls($bpmn); + } + + public function restoreNamedReferences(string $bpmn): string + { + $bpmn = $this->replaceIdReferences( + $bpmn, + 'screen', + fn (array $ids) => Screen::query() + ->whereIn('id', $ids) + ->pluck('title', 'id') + ->all() + ); + + $bpmn = $this->replaceIdReferences( + $bpmn, + 'script', + fn (array $ids) => Script::query() + ->whereIn('id', $ids) + ->pluck('title', 'id') + ->all() + ); + + $bpmn = $this->restoreWebEntryScreenReferences($bpmn); + + return $this->restoreNamedProcessCalls($bpmn); + } + + private function resolveWebEntryScreenReferences(string $bpmn): string + { + $names = []; + + $this->transformWebEntryConfigs($bpmn, function (array $config) use (&$names): array { + foreach (['screen_id', 'completed_screen_id'] as $field) { + $name = $this->screenReferenceName($config['web_entry'][$field] ?? null); + if ($name !== null) { + $names[] = $name; + } + } + + return $config; + }); + + $names = array_values(array_unique($names)); + if ($names === []) { + return $bpmn; + } + + $idsByName = Screen::query() + ->whereIn('title', $names) + ->pluck('id', 'title') + ->all(); + $missing = array_values(array_diff($names, array_keys($idsByName))); + if ($missing !== []) { + throw new MissingBpmnReferenceException( + 'Missing screen reference(s): ' . implode(', ', $missing) + ); + } + + return $this->transformWebEntryConfigs($bpmn, function (array $config) use ($idsByName): array { + foreach (['screen_id', 'completed_screen_id'] as $field) { + $name = $this->screenReferenceName($config['web_entry'][$field] ?? null); + if ($name !== null) { + $config['web_entry'][$field] = $idsByName[$name]; + } + } + + return $config; + }); + } + + private function restoreWebEntryScreenReferences(string $bpmn): string + { + $ids = []; + + $this->transformWebEntryConfigs($bpmn, function (array $config) use (&$ids): array { + foreach (['screen_id', 'completed_screen_id'] as $field) { + $id = $this->screenId($config['web_entry'][$field] ?? null); + if ($id !== null) { + $ids[] = $id; + } + } + + return $config; + }); + + $ids = array_values(array_unique($ids)); + if ($ids === []) { + return $bpmn; + } + + $titlesById = Screen::query() + ->whereIn('id', $ids) + ->pluck('title', 'id') + ->all(); + + return $this->transformWebEntryConfigs($bpmn, function (array $config) use ($titlesById): array { + foreach (['screen_id', 'completed_screen_id'] as $field) { + $id = $this->screenId($config['web_entry'][$field] ?? null); + if ($id !== null && isset($titlesById[$id])) { + $config['web_entry'][$field] = '${screen:' . $titlesById[$id] . '}'; + } + } + + return $config; + }); + } + + private function transformWebEntryConfigs(string $bpmn, callable $transform): string + { + $pattern = '/(pm:config\s*=\s*)(["\'])(.*?)\2/s'; + + return preg_replace_callback($pattern, static function (array $match) use ($transform): string { + $json = html_entity_decode($match[3], ENT_QUOTES | ENT_XML1, 'UTF-8'); + $config = json_decode($json, true); + if (!is_array($config) || !is_array($config['web_entry'] ?? null)) { + return $match[0]; + } + + $transformed = $transform($config); + if ($transformed === $config) { + return $match[0]; + } + + $encoded = htmlspecialchars( + json_encode($transformed, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), + ENT_QUOTES | ENT_XML1, + 'UTF-8' + ); + + return $match[1] . $match[2] . $encoded . $match[2]; + }, $bpmn) ?? $bpmn; + } + + private function screenReferenceName(mixed $value): ?string + { + if (is_string($value) && preg_match('/^\$\{screen:([^}]+)\}$/', $value, $match)) { + return $match[1]; + } + + return null; + } + + private function screenId(mixed $value): ?int + { + if (is_int($value) || (is_string($value) && ctype_digit($value))) { + return (int) $value; + } + + return null; + } + + private function replaceNamedReferences( + string $bpmn, + string $type, + callable $loadIds + ): string { + $pattern = '/(pm:' . $type . 'Ref\s*=\s*)(["\'])\$\{' . $type . ':([^}]+)\}\2/'; + preg_match_all($pattern, $bpmn, $matches); + $names = array_values(array_unique($matches[3] ?? [])); + + if ($names === []) { + return $bpmn; + } + + $idsByName = $loadIds($names); + $missing = array_values(array_diff($names, array_keys($idsByName))); + if ($missing !== []) { + throw new MissingBpmnReferenceException( + 'Missing ' . $type . ' reference(s): ' . implode(', ', $missing) + ); + } + + return preg_replace_callback( + $pattern, + static fn (array $match): string => $match[1] . $match[2] + . $idsByName[$match[3]] . $match[2], + $bpmn + ); + } + + private function replaceIdReferences( + string $bpmn, + string $type, + callable $loadNames + ): string { + $pattern = '/(pm:' . $type . 'Ref\s*=\s*)(["\'])(\d+)\2/'; + preg_match_all($pattern, $bpmn, $matches); + $ids = array_values(array_unique($matches[3] ?? [])); + + if ($ids === []) { + return $bpmn; + } + + $namesById = $loadNames($ids); + + return preg_replace_callback( + $pattern, + static function (array $match) use ($namesById, $type): string { + $name = $namesById[$match[3]] ?? null; + if ($name === null) { + return $match[0]; + } + + return $match[1] . $match[2] . '${' . $type . ':' . $name . '}' . $match[2]; + }, + $bpmn + ); + } + + private function resolveNamedProcessCalls(string $bpmn): string + { + $pattern = '/(calledElement\s*=\s*)(["\'])\$\{process:([^}]+)\}\2/'; + preg_match_all($pattern, $bpmn, $matches); + $names = array_values(array_unique($matches[3] ?? [])); + if ($names === []) { + return $bpmn; + } + + $processes = Process::query()->whereIn('name', $names)->get()->keyBy('name'); + $missing = array_values(array_diff($names, $processes->keys()->all())); + if ($missing !== []) { + throw new MissingBpmnReferenceException( + 'Missing process reference(s): ' . implode(', ', $missing) + ); + } + + $calledElementByName = []; + foreach ($processes as $name => $process) { + $calledElementByName[$name] = $this->bpmnProcessXmlId((string) $process->bpmn) + . '-' . $process->id; + } + + return preg_replace_callback( + $pattern, + static fn (array $match): string => $match[1] . $match[2] + . $calledElementByName[$match[3]] . $match[2], + $bpmn + ); + } + + private function restoreNamedProcessCalls(string $bpmn): string + { + $pattern = '/(calledElement\s*=\s*)(["\'])([^"\']+)-(\d+)\2/'; + preg_match_all($pattern, $bpmn, $matches); + $ids = array_values(array_unique($matches[4] ?? [])); + if ($ids === []) { + return $bpmn; + } + + $namesById = Process::query()->whereIn('id', $ids)->pluck('name', 'id')->all(); + + return preg_replace_callback( + $pattern, + static function (array $match) use ($namesById): string { + $name = $namesById[(int) $match[4]] ?? $namesById[$match[4]] ?? null; + if ($name === null) { + return $match[0]; + } + + return $match[1] . $match[2] . '${process:' . $name . '}' . $match[2]; + }, + $bpmn + ); + } + + private function bpmnProcessXmlId(string $childBpmn): string + { + if ($childBpmn !== '' && preg_match( + '/]*\bid\s*=\s*["\']([^"\']+)["\']/', + $childBpmn, + $match + )) { + return $match[1]; + } + + return 'ProcessId'; + } +} diff --git a/ProcessMaker/Services/ScriptExecutorResolver.php b/ProcessMaker/Services/ScriptExecutorResolver.php new file mode 100644 index 0000000000..c50f3fbcc7 --- /dev/null +++ b/ProcessMaker/Services/ScriptExecutorResolver.php @@ -0,0 +1,31 @@ +where('language', 'php-nayra') + ->orderBy('id') + ->first(); + if ($nayra !== null) { + return $nayra; + } + + $php = ScriptExecutor::query() + ->where('language', 'php') + ->orderBy('id') + ->first(); + if ($php !== null) { + return $php; + } + + return ScriptExecutor::query()->orderBy('id')->first(); + } +} diff --git a/routes/api.php b/routes/api.php index 8a8fc104c3..cfad1cb39c 100644 --- a/routes/api.php +++ b/routes/api.php @@ -10,6 +10,9 @@ use ProcessMaker\Http\Controllers\Api\CommentController; use ProcessMaker\Http\Controllers\Api\CssOverrideController; use ProcessMaker\Http\Controllers\Api\DebugController; +use ProcessMaker\Http\Controllers\Api\DeployProcess; +use ProcessMaker\Http\Controllers\Api\DeployScreen; +use ProcessMaker\Http\Controllers\Api\DeployScript; use ProcessMaker\Http\Controllers\Api\DevLinkController; use ProcessMaker\Http\Controllers\Api\EncryptedDataController; use ProcessMaker\Http\Controllers\Api\EnvironmentVariablesController; @@ -141,6 +144,26 @@ Route::get('scripts/execution/{key}', [ScriptController::class, 'execution'])->name('scripts.execution'); Route::post('scripts/microservice/execution', [ScriptController::class, 'microserviceExecution']); + // Deploy / sync helpers (core). Canonical paths + package-skeleton aliases for BC. + Route::post('deploy-script', [DeployScript::class, 'deployScript'])->name('deploy-script'); + Route::get('script-php', [DeployScript::class, 'getScriptPhp'])->name('script-php'); + Route::post('deploy-screen', [DeployScreen::class, 'deployScreen'])->name('deploy-screen'); + Route::get('screen-yaml', [DeployScreen::class, 'getScreenYaml'])->name('screen-yaml'); + Route::post('deploy-process', [DeployProcess::class, 'deployProcess'])->name('deploy-process'); + Route::get('process-bpmn', [DeployProcess::class, 'getProcessBpmn'])->name('process-bpmn'); + Route::post('package-skeleton/deploy-script', [DeployScript::class, 'deployScript']) + ->name('package-skeleton.deploy-script'); + Route::get('package-skeleton/script-php', [DeployScript::class, 'getScriptPhp']) + ->name('package-skeleton.script-php'); + Route::post('package-skeleton/deploy-screen', [DeployScreen::class, 'deployScreen']) + ->name('package-skeleton.deploy-screen'); + Route::get('package-skeleton/screen-yaml', [DeployScreen::class, 'getScreenYaml']) + ->name('package-skeleton.screen-yaml'); + Route::post('package-skeleton/deploy-process', [DeployProcess::class, 'deployProcess']) + ->name('package-skeleton.deploy-process'); + Route::get('package-skeleton/process-bpmn', [DeployProcess::class, 'getProcessBpmn']) + ->name('package-skeleton.process-bpmn'); + // Script Categories Route::get('script_categories', [ScriptCategoryController::class, 'index'])->name('script_categories.index')->middleware('can:view-script-categories'); Route::get('script_categories/{script_category}', [ScriptCategoryController::class, 'show'])->name('script_categories.show')->middleware('can:view-script-categories'); diff --git a/tests/Feature/Api/DeployProcessControllerTest.php b/tests/Feature/Api/DeployProcessControllerTest.php new file mode 100644 index 0000000000..b5cac34ff6 --- /dev/null +++ b/tests/Feature/Api/DeployProcessControllerTest.php @@ -0,0 +1,78 @@ +create(['title' => 'sample-screen-ref']); + $script = Script::factory()->create(['title' => 'sample-script-ref']); + + $this->apiCall('POST', self::DEPLOY_ENDPOINT, [ + 'name' => 'sample-process', + 'bpmn' => $this->sampleBpmn( + '${screen:sample-screen-ref}', + '${script:sample-script-ref}' + ), + ]) + ->assertOk() + ->assertJson([ + 'success' => true, + 'action' => 'created', + 'name' => 'sample-process', + ]); + + $process = Process::where('name', 'sample-process')->firstOrFail(); + $this->assertStringContainsString('pm:screenRef="' . $screen->id . '"', $process->bpmn); + $this->assertStringContainsString('pm:scriptRef="' . $script->id . '"', $process->bpmn); + } + + public function testGetProcessBpmnRestoresNamedReferences(): void + { + Screen::factory()->create(['title' => 'restore-screen']); + Script::factory()->create(['title' => 'restore-script']); + + $this->apiCall('POST', self::DEPLOY_ENDPOINT, [ + 'name' => 'restore-process', + 'bpmn' => $this->sampleBpmn( + '${screen:restore-screen}', + '${script:restore-script}' + ), + ])->assertOk(); + + $response = $this->apiCall('GET', self::GET_ENDPOINT . '?name=restore-process'); + + $response->assertOk()->assertJsonPath('success', true); + $this->assertStringContainsString('${screen:restore-screen}', $response->json('bpmn')); + $this->assertStringContainsString('${script:restore-script}', $response->json('bpmn')); + } + + private function sampleBpmn(string $screenReference, string $scriptReference): string + { + return << + + + + + + +XML; + } +} diff --git a/tests/Feature/Api/DeployScreenControllerTest.php b/tests/Feature/Api/DeployScreenControllerTest.php new file mode 100644 index 0000000000..c6a5f02a10 --- /dev/null +++ b/tests/Feature/Api/DeployScreenControllerTest.php @@ -0,0 +1,64 @@ +postJson('/api/1.0' . self::API_ENDPOINT, [ + 'yml_content' => "config: []\n", + 'name' => 'sample-screen', + ])->assertStatus(401); + } + + public function testDeployScreenCreatesFromYaml(): void + { + $yaml = <<<'YAML' +config: + - component: FormBlank + items: [] +computed: [] +watchers: [] +custom_css: '' +YAML; + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'yml_content' => $yaml, + 'name' => 'sample-screen', + ]) + ->assertOk() + ->assertJson([ + 'success' => true, + 'action' => 'created', + 'name' => 'sample-screen', + ]); + + $this->assertNotNull(Screen::where('title', 'sample-screen')->first()); + } + + public function testGetScreenYamlReturnsYamlForPublishedScreen(): void + { + $yaml = "config: []\n"; + $this->apiCall('POST', self::API_ENDPOINT, [ + 'yml_content' => $yaml, + 'name' => 'yaml-pull-screen', + ])->assertOk(); + + $response = $this->actingAs($this->user, 'api') + ->get('/api/1.0' . self::GET_ENDPOINT . '?name=yaml-pull-screen'); + + $response->assertOk(); + $this->assertStringContainsString('yaml', (string) $response->headers->get('Content-Type')); + } +} diff --git a/tests/Feature/Api/DeployScriptControllerTest.php b/tests/Feature/Api/DeployScriptControllerTest.php new file mode 100644 index 0000000000..cd1740d451 --- /dev/null +++ b/tests/Feature/Api/DeployScriptControllerTest.php @@ -0,0 +1,141 @@ +postJson('/api/1.0' . self::API_ENDPOINT, [ + 'code' => ' 'sample-sync-script', + ])->assertStatus(401); + } + + public function testDeployScriptValidatesCodeRequired(): void + { + $this->apiCall('POST', self::API_ENDPOINT, [ + 'name' => 'sample-sync-script', + ]) + ->assertStatus(422) + ->assertJson(['success' => false]) + ->assertJsonValidationErrors(['code']); + } + + public function testDeployScriptCreatesWhenTitleDoesNotExist(): void + { + $this->ensureExecutor(); + $code = " true];\n"; + $name = 'sample-sync-script'; + + $response = $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => $code, + 'name' => $name, + ]); + + $response->assertStatus(200) + ->assertJson([ + 'success' => true, + 'action' => 'created', + 'name' => $name, + ]); + + $script = Script::where('title', $name)->first(); + $this->assertNotNull($script); + $this->assertSame(rtrim($code), rtrim((string) $script->code)); + $this->assertSame($this->user->id, $script->run_as_user_id); + } + + public function testCanonicalDeployScriptRouteCreatesScript(): void + { + $this->ensureExecutor(); + + $this->apiCall('POST', self::CANONICAL_ENDPOINT, [ + 'code' => ' true];', + 'name' => 'canonical-sync-script', + ]) + ->assertStatus(200) + ->assertJson([ + 'success' => true, + 'action' => 'created', + 'name' => 'canonical-sync-script', + ]); + } + + public function testDeployScriptUpdatesExistingScriptByTitle(): void + { + $existing = Script::factory()->create([ + 'title' => 'sample-update-script', + 'code' => ' true];', + 'run_as_user_id' => $this->user->id, + ]); + + $newCode = " true];\n"; + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => $newCode, + 'name' => 'sample-update-script', + ]) + ->assertStatus(200) + ->assertJson([ + 'success' => true, + 'action' => 'updated', + 'script_id' => $existing->id, + ]); + + $existing->refresh(); + $this->assertSame(rtrim($newCode), rtrim((string) $existing->code)); + } + + public function testGetScriptPhpByNameReturnsPhpCode(): void + { + $code = " true];\n"; + $script = Script::factory()->create([ + 'title' => 'sample-get-script', + 'code' => $code, + 'run_as_user_id' => $this->user->id, + ]); + + $response = $this->actingAs($this->user, 'api') + ->get('/api/1.0' . self::GET_ENDPOINT . '?name=sample-get-script'); + + $response->assertStatus(200); + $this->assertStringContainsString('text/plain', (string) $response->headers->get('Content-Type')); + $this->assertSame((string) $script->id, $response->headers->get('X-Script-Id')); + $this->assertSame($code, $response->getContent()); + } + + public function testDeployScriptPrefersPhpNayraExecutorOnCreate(): void + { + ScriptExecutor::factory()->create(['language' => 'php']); + $nayra = ScriptExecutor::factory()->create(['language' => 'php-nayra']); + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => ' 'new-nayra-script', + ]) + ->assertStatus(200) + ->assertJson(['action' => 'created']); + + $script = Script::where('title', 'new-nayra-script')->first(); + $this->assertSame($nayra->id, $script->script_executor_id); + } + + private function ensureExecutor(): ScriptExecutor + { + return ScriptExecutor::query()->first() ?? ScriptExecutor::factory()->create(); + } +}