Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
216 changes: 208 additions & 8 deletions ProcessMaker/Mcp/Processes/ProcessCatalog.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use ProcessMaker\Events\ProcessCreated;
use ProcessMaker\Exception\TaskDoesNotHaveUsersException;
use ProcessMaker\Models\Process;
use ProcessMaker\Models\ProcessVersion;
use ProcessMaker\Models\User;
use ProcessMaker\Nayra\Storage\BpmnDocument;
use ProcessMaker\Validation\CategoryRule;
Expand Down Expand Up @@ -93,11 +95,30 @@ public function list(User $user, array $input): array
/**
* @return array<string, mixed>
*/
public function find(User $user, int $id): array
public function find(User $user, int $id, string $alternative = 'A'): array
{
$this->assertCan($user, self::VIEW);
$alternative = $this->normalizeAlternative($alternative);

return $this->detail(Process::query()->findOrFail($id));
return $this->detail(
Process::query()->findOrFail($id),
$alternative,
$user->can(self::EDIT),
);
}

/**
* Enable Alternative B for a process (clone draft A → B).
*
* @return array<string, mixed>
*/
public function enableAlternativeB(User $user, int $id): array
{
$this->assertCan($user, self::EDIT);
$process = Process::query()->findOrFail($id);
$this->ensureAlternativeBExists($process);

return $this->alternativesPayload($process);
}

/**
Expand Down Expand Up @@ -145,9 +166,21 @@ public function update(User $user, array $input): array
$input = $this->normalize($input);
$validated = validator($input, array_merge([
'id' => 'required|integer|min:1',
'alternative' => 'nullable|in:A,B',
'create_alternative_b' => 'nullable|boolean',
], $this->updateRules($input)))->validate();

$process = Process::query()->findOrFail((int) $validated['id']);
$alternative = $this->normalizeAlternative($validated['alternative'] ?? 'A');

if (!empty($validated['create_alternative_b'])) {
$this->ensureAlternativeBExists($process);
}

if ($alternative === 'B') {
$this->assertAlternativeBReady($process);
}

$attributes = $this->writable($validated);
if ($attributes === []) {
throw ValidationException::withMessages([
Expand All @@ -160,10 +193,24 @@ public function update(User $user, array $input): array
$attributes['bpmn'] = BpmnDocument::replaceHtmlEntities($attributes['bpmn']);
}

$process->fill($attributes);
$process->saveOrFail();
if (isset($attributes['bpmn'])) {
// Hydrate only for draft BPMN writes. Metadata-only updates must not
// copy draft/B bpmn+stages onto the live process via saveOrFail.
$this->hydrateProcessFromAlternativeVersion($process, $alternative);
$process->fill($attributes);
try {
$process->alternative = $alternative;
$process->saveDraft($alternative);
} catch (TaskDoesNotHaveUsersException $e) {
throw ValidationException::withMessages(['bpmn' => $e->getMessage()]);
}

$this->persistLiveMetadata($process, array_diff_key($attributes, ['bpmn' => true]), $user);
} else {
$this->persistLiveMetadata($process, $attributes, $user);
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

return $this->detail($process->refresh());
return $this->detail($process->refresh(), $alternative);
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}

/**
Expand All @@ -176,11 +223,17 @@ public function validate(User $user, array $input): array
$validated = validator($input, [
'bpmn' => 'nullable|string',
'id' => 'nullable|integer|min:1',
'alternative' => 'nullable|in:A,B',
])->validate();

$bpmn = $validated['bpmn'] ?? null;
if (($bpmn === null || $bpmn === '') && isset($validated['id'])) {
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
$bpmn = Process::query()->findOrFail((int) $validated['id'])->bpmn;
$process = Process::query()->findOrFail((int) $validated['id']);
$alternative = $this->normalizeAlternative($validated['alternative'] ?? 'A');
// Same gate as get-process: view-only must not validate draft / Alt B XML.
$bpmn = $user->can(self::EDIT)
? ($this->bpmnForAlternative($process, $alternative) ?? $process->bpmn)
: $process->bpmn;
}

return $this->validator->validate(is_string($bpmn) ? $bpmn : null);
Expand Down Expand Up @@ -311,18 +364,165 @@ private function summary(Process $process): array
];
}

/**
* Persist name/description/status/category on the live process without
* HasVersioning publish + deleteDraft (which wipe unpublished BPMN).
*
* @param array<string, mixed> $metadata
*/
private function persistLiveMetadata(Process $process, array $metadata, User $user): void
{
if ($metadata === []) {
return;
}

// Drop any hydrated draft/B bpmn+stages before touching the live row.
$process->refresh();

$hasCategory = array_key_exists('process_category_id', $metadata);
$categoryValue = $metadata['process_category_id'] ?? null;

Process::withoutEvents(function () use ($process, $metadata, $hasCategory, $categoryValue, $user): void {
$process->fill($metadata);
// withoutEvents skips Process::updating (updated_by + project-assets cache).
$process->updated_by = $user->id;
$process->saveOrFail();

// Mass/eventless save skips setProcessCategoryIdAttribute's saved sync.
if ($hasCategory) {
$ids = ($categoryValue === null || $categoryValue === '')
? []
: array_values(array_filter(
explode(',', (string) $categoryValue),
static fn (string $id): bool => $id !== '',
));
$process->categories()->sync($ids);
}
});

$this->forgetProjectAssetCache($user);
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

/**
* @return array<string, mixed>
*/
private function detail(Process $process): array
private function detail(Process $process, string $alternative = 'A', bool $includeVersionBpmn = true): array
{
$alternative = $this->normalizeAlternative($alternative);
// view-processes alone must not reveal unpublished draft / Alt B BPMN.
// Live processes.bpmn is alternative A; do not mislabel it as B.
if (!$includeVersionBpmn) {
$alternative = 'A';
$bpmn = $process->bpmn;
} else {
$bpmn = $this->bpmnForAlternative($process, $alternative) ?? $process->bpmn;
}

return [
...$this->summary($process),
'bpmn' => $process->bpmn,
'alternative' => $alternative,
'alternatives' => $this->alternativesMeta($process),
'bpmn' => $bpmn,
'created_at' => $this->timestamp($process->created_at),
];
}

private function normalizeAlternative(string $alternative): string
{
return strtoupper($alternative) === 'B' ? 'B' : 'A';
}

private function hydrateProcessFromAlternativeVersion(Process $process, string $alternative): void
{
$version = $this->versionForAlternative($process, $alternative);
if ($version instanceof ProcessVersion) {
$process->bpmn = $version->bpmn;
$process->stages = $version->stages;
}
$process->alternative = $alternative;
}

private function versionForAlternative(Process $process, string $alternative): ?ProcessVersion
{
$version = $process->getDraftVersion($alternative);
if ($version instanceof ProcessVersion) {
return $version;
}

$version = $process->getDraftOrPublishedLatestVersion($alternative);

return $version instanceof ProcessVersion ? $version : null;
}

private function bpmnForAlternative(Process $process, string $alternative): ?string
{
return $this->versionForAlternative($process, $alternative)?->bpmn;
}

/**
* @return array{b_enabled: bool, package_installed: bool}
*/
private function alternativesMeta(Process $process): array
{
if (!class_exists('ProcessMaker\Package\PackageABTesting\Models\Alternative')) {
return [
'package_installed' => false,
'b_enabled' => false,
];
}

$record = \ProcessMaker\Package\PackageABTesting\Models\Alternative::forProcess($process)->first();

return [
'package_installed' => true,
'b_enabled' => (bool) ($record?->version_b_enabled),
];
}

/**
* @return array<string, mixed>
*/
private function alternativesPayload(Process $process): array
{
return [
'id' => $process->id,
'name' => $process->name,
...$this->alternativesMeta($process),
];
}

private function ensureAlternativeBExists(Process $process): void
{
if (!class_exists('ProcessMaker\Package\PackageABTesting\Models\Alternative')) {
throw ValidationException::withMessages([
'create_alternative_b' => 'package-ab-testing is not installed on this instance.',
]);
}

$alternative = \ProcessMaker\Package\PackageABTesting\Models\Alternative::findOrCreateForProcess($process);
if ($alternative->version_b_enabled) {
return;
}

$alternative->enableAlternativeB();
$alternative->save();
}

private function assertAlternativeBReady(Process $process): void
{
$meta = $this->alternativesMeta($process);
if (!$meta['package_installed']) {
throw ValidationException::withMessages([
'alternative' => 'Alternative B requires package-ab-testing.',
]);
}
if (!$meta['b_enabled']) {
throw ValidationException::withMessages([
'alternative' => 'Alternative B is not enabled for this process. Call enable-process-alternative-b or set create_alternative_b on update-process.',
]);
}
}

private function timestamp(mixed $value): ?string
{
if ($value instanceof DateTimeInterface) {
Expand Down
3 changes: 3 additions & 0 deletions ProcessMaker/Mcp/Servers/ProcessServer.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use ProcessMaker\Mcp\Tools\GetMcpGuidanceTool;
use ProcessMaker\Mcp\Tools\GetMcpSkillTool;
use ProcessMaker\Mcp\Tools\Processes\CreateProcessTool;
use ProcessMaker\Mcp\Tools\Processes\EnableProcessAlternativeBTool;
use ProcessMaker\Mcp\Tools\Processes\GetProcessTool;
use ProcessMaker\Mcp\Tools\Processes\ListGroupsTool;
use ProcessMaker\Mcp\Tools\Processes\ListProcessesTool;
Expand All @@ -39,6 +40,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} resolves via core deploy-process (POST /api/1.0/deploy-process).
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 validate-process before create/update when unsure.
Expand All @@ -59,6 +61,7 @@ class ProcessServer extends Server
GetProcessTool::class,
CreateProcessTool::class,
UpdateProcessTool::class,
EnableProcessAlternativeBTool::class,
ValidateProcessTool::class,
];

Expand Down
44 changes: 44 additions & 0 deletions ProcessMaker/Mcp/Tools/Processes/EnableProcessAlternativeBTool.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

declare(strict_types=1);

namespace ProcessMaker\Mcp\Tools\Processes;

use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\ResponseFactory;
use Laravel\Mcp\Server\Attributes\Description;
use Laravel\Mcp\Server\Attributes\Name;
use Laravel\Mcp\Server\Attributes\Title;
use ProcessMaker\Mcp\Processes\ProcessCatalog;

#[Name('enable-process-alternative-b')]
#[Title('Enable process Alternative B')]
#[Description('Creates Alternative B for a process by cloning the current Alternative A draft/published BPMN (package-ab-testing). Idempotent if B already exists.')]
class EnableProcessAlternativeBTool extends ProcessTool
{
public function handle(Request $request, ProcessCatalog $processes): Response|ResponseFactory
{
return $this->respond(function () use ($request, $processes): array {
$validated = $request->validate([
'id' => 'required|integer|min:1',
]);

return $processes->enableAlternativeB(
$processes->actor($request->user()),
(int) $validated['id'],
);
});
}

/**
* @return array<string, \Illuminate\JsonSchema\Types\Type>
*/
public function schema(JsonSchema $schema): array
{
return [
'id' => ProcessFields::id($schema),
];
}
}
3 changes: 3 additions & 0 deletions ProcessMaker/Mcp/Tools/Processes/GetProcessTool.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,13 @@ public function handle(Request $request, ProcessCatalog $processes): Response|Re
return $this->respond(function () use ($request, $processes): array {
$validated = $request->validate([
'id' => 'required|integer|min:1',
'alternative' => 'nullable|in:A,B',
]);

return $processes->find(
$processes->actor($request->user()),
(int) $validated['id'],
$validated['alternative'] ?? 'A',
);
});
}
Expand All @@ -43,6 +45,7 @@ public function schema(JsonSchema $schema): array
{
return [
'id' => ProcessFields::id($schema),
'alternative' => ProcessFields::alternative($schema),
];
}
}
Loading
Loading