A platform for community discussion. Free, open, simple.
FEATURE: Add per-workflow variables (#43337)
Osama Sayegh2ce7bacfbeaa
diff --git a/db/structure.sql b/db/structure.sqlindex c3367d63c77..b0b4842a410 100644--- a/db/structure.sql+++ b/db/structure.sql@@ -5539,11 +5539,14 @@ ALTER SEQUENCE public.discourse_workflows_tags_id_seq OWNED BY public.discourse_CREATE TABLE public.discourse_workflows_variables (id bigint NOT NULL,key character varying(100) NOT NULL,- value character varying(1000) DEFAULT ''::character varying NOT NULL,+ value text,description text,created_by_id integer NOT NULL,created_at timestamp(6) without time zone NOT NULL,- updated_at timestamp(6) without time zone NOT NULL+ updated_at timestamp(6) without time zone NOT NULL,+ workflow_id bigint,+ variable_type character varying(30) DEFAULT 'string'::character varying NOT NULL,+ type_options jsonb DEFAULT '{}'::jsonb NOT NULL);@@ -5761,7 +5764,8 @@ CREATE TABLE public.discourse_workflows_workflow_versions (created_by_id integer NOT NULL,updated_by_id integer,created_at timestamp(6) without time zone NOT NULL,- updated_at timestamp(6) without time zone NOT NULL+ updated_at timestamp(6) without time zone NOT NULL,+ variables_schema jsonb DEFAULT '[]'::jsonb NOT NULL);@@ -19924,10 +19928,17 @@ CREATE INDEX idx_dwf_variables_on_created_by_id ON public.discourse_workflows_va----- Name: idx_dwf_variables_on_key; Type: INDEX; Schema: public; Owner: -+-- Name: idx_dwf_variables_on_key_global; Type: INDEX; Schema: public; Owner: -+--++CREATE UNIQUE INDEX idx_dwf_variables_on_key_global ON public.discourse_workflows_variables USING btree (key) WHERE (workflow_id IS NULL);+++--+-- Name: idx_dwf_variables_on_workflow_key; Type: INDEX; Schema: public; Owner: ----CREATE UNIQUE INDEX idx_dwf_variables_on_key ON public.discourse_workflows_variables USING btree (key);+CREATE UNIQUE INDEX idx_dwf_variables_on_workflow_key ON public.discourse_workflows_variables USING btree (workflow_id, key) WHERE (workflow_id IS NOT NULL);--@@ -25883,6 +25894,7 @@ INSERT INTO "schema_migrations" (version) VALUES('20260914172757'),('20260914140746'),('20260914032737'),+('20260913105655'),('20260910110851'),('20260910033302'),('20260910030427'),@@ -25893,6 +25905,7 @@ INSERT INTO "schema_migrations" (version) VALUES('20260908160656'),('20260908153158'),('20260908112615'),+('20260904171256'),('20260904065041'),('20260904063128'),('20260904000537'),diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-file-io.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-file-io.jsindex 3eb6fa77371..381a97a19d8 100644--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-file-io.js+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-file-io.js@@ -40,6 +40,38 @@ function importedStaticData(data) {return structuredClone(staticData);}+function importedVariables(data) {+ if (!Object.hasOwn(data, "variables")) {+ return undefined;+ }++ const variables = data.variables;+ if (!Array.isArray(variables)) {+ return { error: "invalid" };+ }++ return variables+ .filter(+ (variable) =>+ variable &&+ typeof variable === "object" &&+ typeof variable.key === "string"+ )+ .map((variable) => ({+ key: variable.key,+ description:+ typeof variable.description === "string" ? variable.description : null,+ variable_type:+ typeof variable.variable_type === "string"+ ? variable.variable_type+ : "string",+ type_options:+ variable.type_options && typeof variable.type_options === "object"+ ? variable.type_options+ : {},+ }));+}+function directSettingsFromImportedNode(node) {const settings = {};@@ -90,6 +122,12 @@ export function buildWorkflowExportPayload(...(stickyNotes || []),]),settings: cloneObject(workflowMetadata.settings),+ variables: (workflowMetadata.variables || []).map((variable) => ({+ key: variable.key,+ description: variable.description,+ variable_type: variable.variable_type,+ type_options: variable.type_options,+ })),staticData: cloneObject(workflowMetadata.staticData),};}@@ -145,6 +183,11 @@ export function parseWorkflowImport(text) {return staticData;}+ const variables = importedVariables(data);+ if (variables?.error) {+ return variables;+ }+const allImportedNodes = data.nodes.map((n) =>WorkflowNode.create({clientId: crypto.randomUUID(),@@ -192,5 +235,9 @@ export function parseWorkflowImport(text) {result.staticData = staticData;}+ if (variables !== undefined) {+ result.variables = variables;+ }+return result;}diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/index.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/index.gjsindex ae70533c329..86ea0552e01 100644--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/index.gjs+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/index.gjs@@ -18,6 +18,7 @@ import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";import dIcon from "discourse/ui-kit/helpers/d-icon";import { i18n } from "discourse-i18n";import BuildWithAiModal from "../build-with-ai-modal";+import PublishBanner from "../publish-banner";import {buildCanvasClipboardPayload,isSerializedCanvasClipboardPayload,@@ -47,7 +48,6 @@ import WorkflowNode from "./workflow-node";export default class WorkflowCanvas extends Component {@service keyboardShortcuts;- @service dialog;@service menu;@service router;@service workflowsNodeTypes;@@ -58,7 +58,6 @@ export default class WorkflowCanvas extends Component {@tracked rete = null;@tracked areaTransform = { x: 0, y: 0, k: 1 };@tracked workflowPublishedOverride = null;- @tracked hasUnpublishedChangesOverride = null;@tracked selectionVersion = 0;@tracked aiPanelOpen = false;clipboardPayload = null;@@ -92,37 +91,10 @@ export default class WorkflowCanvas extends Component {);}- get hasUnpublishedChanges() {- return (- this.hasUnpublishedChangesOverride ??- Boolean(this.args.hasUnpublishedChanges)- );- }-- get publishDisabled() {- return this.workflowPublished && !this.hasUnpublishedChanges;- }-get hasNodes() {return (this.args.nodes || []).length > 0;}- get showPublishButton() {- return this.hasNodes && !this.publishDisabled;- }-- get showToolbarPublishButton() {- return this.showPublishButton && !this.showUnpublishedChangesMessage;- }-- get showUnpublishedChangesMessage() {- return this.showPublishButton;- }-- get showDiscardChangesButton() {- return this.workflowPublished && this.hasUnpublishedChanges;- }-get aiAuthoringAvailable() {return (this.siteSettings.discourse_workflows_ai_authoring_enabled &&@@ -174,68 +146,6 @@ export default class WorkflowCanvas extends Component {return this.rete.isStickyNoteSelected(clientId);}- @action- async publishWorkflow() {- if (!this.hasNodes) {- return;- }-- this.workflowPublishedOverride = true;- this.hasUnpublishedChangesOverride = false;- try {- await ajax(- `/admin/plugins/discourse-workflows/workflows/${this.args.workflowId}.json`,- {- type: "PUT",- data: {- workflow: {- published: true,- },- },- }- );- if (this.args.workflow) {- this.args.workflow.activeVersionId = this.args.workflow.versionId;- this.args.workflow.hasUnpublishedChanges = false;- }- this.workflowPublishedOverride = null;- this.hasUnpublishedChangesOverride = null;- } catch {- this.workflowPublishedOverride = this.args.workflowPublished;- this.hasUnpublishedChangesOverride = this.args.hasUnpublishedChanges;- }- }-- @action- async discardWorkflow() {- const confirmed = await this.dialog.confirm({- message: i18n("discourse_workflows.discard_changes_confirmation"),- confirmButtonLabel: "discourse_workflows.discard_changes",- cancelButtonLabel: "discourse_workflows.keep_editing",- });-- if (!confirmed) {- return;- }-- this.hasUnpublishedChangesOverride = false;-- try {- const response = await ajax(- `/admin/plugins/discourse-workflows/workflows/${this.args.workflowId}/discard-draft.json`,- {- type: "POST",- }- );-- this.args.onDiscardWorkflow?.(response.workflow);- this.hasUnpublishedChangesOverride = null;- } catch (e) {- this.hasUnpublishedChangesOverride = this.args.hasUnpublishedChanges;- popupAjaxError(e);- }- }-@actionasync unpublishWorkflow(closeMenu) {if (typeof closeMenu === "function") {@@ -571,7 +481,8 @@ export default class WorkflowCanvas extends Component {result.nodes,result.connections,result.stickyNotes,- result.staticData+ result.staticData,+ result.variables);} catch {this.#showImportError();@@ -1142,56 +1053,16 @@ export default class WorkflowCanvas extends Component {{{#if @onOpenNodePanel}}<div class="workflows-canvas__top-bar">- {{#if this.showUnpublishedChangesMessage}}+ {{#if this.hasNodes}}<div class="workflows-canvas__publish-status">- <span- class="workflows-canvas__publish-status-body"- role="status"- >- <span class="workflows-canvas__publish-status-icon">- {{dIcon "triangle-exclamation"}}- </span>- <span class="workflows-canvas__publish-status-text">- <span class="workflows-canvas__publish-status-title">- {{i18n "discourse_workflows.unpublished_changes_message"}}- </span>- <span class="workflows-canvas__publish-status-detail">- {{i18n- "discourse_workflows.unpublished_changes_message_detail"- }}- </span>- </span>- </span>-- <span class="workflows-canvas__publish-status-actions">- <DButton- class="btn-primary btn-small workflows-canvas__publish-status-btn"- @action={{this.publishWorkflow}}- @translatedLabel={{i18n "discourse_workflows.publish"}}- />-- {{#if this.showDiscardChangesButton}}- <DButton- class="btn-default btn-small workflows-canvas__publish-status-btn"- @action={{this.discardWorkflow}}- @translatedLabel={{i18n- "discourse_workflows.discard_changes"- }}- />- {{/if}}- </span>+ <PublishBanner+ @onDiscard={{@onDiscardWorkflow}}+ @workflow={{@workflow}}+ /></div>{{/if}}<div class="workflows-canvas__toolbar-top-right">- {{#if this.showToolbarPublishButton}}- <DButton- class="btn-primary workflows-canvas__publish-btn"- @action={{this.publishWorkflow}}- @translatedLabel={{i18n "discourse_workflows.publish"}}- />- {{/if}}-{{#if this.aiAuthoringAvailable}}<DButtonclass="btn-default workflows-canvas__ai-btn"diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/expression-input.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/expression-input.gjsindex 9affa6de06e..b4305b38121 100644--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/expression-input.gjs+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/expression-input.gjs@@ -133,7 +133,8 @@ export default class ExpressionInput extends Component {inputFields,ancestorNodes,siteSettings: this.siteSettings,- workflowVars: this.workflowsNodeTypes.workflowVars,+ globalVars: this.workflowsNodeTypes.workflowVars,+ workflowVariables: session?.variables,nodes: graph.nodes,itemPrefix,workflowId: session?.workflowId,diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/context/input.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/context/input.gjsindex e27a18996b3..7f1ffe2ee66 100644--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/context/input.gjs+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/context/input.gjs@@ -56,7 +56,26 @@ function fieldVisible(fieldDef, nodes) {);}-function schemaFieldToEntry(key, def, nodes) {+const WORKFLOW_VARIABLE_TYPE_SCHEMAS = {+ integer: "integer",+ category: "integer",+ group: "integer",+ boolean: "boolean",+ category_list: "array",+ group_list: "array",+ tag_list: "array",+ simple_list: "array",+};++function workflowVariableEntries(workflowVariables) {+ return (workflowVariables || []).map((field) => ({+ key: field.key,+ type: WORKFLOW_VARIABLE_TYPE_SCHEMAS[field.variable_type] || "string",+ id: field.key,+ }));+}++function schemaFieldToEntry(key, def, nodes, workflowVariables) {const displayKey = key.replace(/^\$/, "");const entry = {key: displayKey,@@ -64,7 +83,9 @@ function schemaFieldToEntry(key, def, nodes) {id: key,};- if (def.fields) {+ if (key === "$workflow_vars") {+ entry.children = workflowVariableEntries(workflowVariables);+ } else if (def.fields) {entry.children = Object.entries(def.fields).filter(([, childDef]) => fieldVisible(childDef, nodes)).map(([childKey, childDef]) => ({@@ -86,7 +107,12 @@ function triggerProvidesCurrentUser(nodes, nodeTypesService) {return nodeType?.capabilities?.provides_current_user ?? false;}-function environmentFields(expressionContext, nodes, nodeTypesService) {+function environmentFields(+ expressionContext,+ nodes,+ nodeTypesService,+ workflowVariables+) {const env = expressionContext.environment;if (!env) {return [];@@ -101,7 +127,9 @@ function environmentFields(expressionContext, nodes, nodeTypesService) {}return true;})- .map(([symbol, def]) => schemaFieldToEntry(symbol, def, nodes));+ .map(([symbol, def]) =>+ schemaFieldToEntry(symbol, def, nodes, workflowVariables)+ );}export default class InputContext extends Component {@@ -191,7 +219,8 @@ export default class InputContext extends Component {return environmentFields(this.workflowsNodeTypes.expressionContext,this.args.nodes || [],- this.workflowsNodeTypes+ this.workflowsNodeTypes,+ this.args.session?.variables);}diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/index.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/index.gjsindex 428dba0c7bc..1b8bdd24760 100644--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/index.gjs+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/index.gjs@@ -3,6 +3,7 @@ import { tracked } from "@glimmer/tracking";import { action } from "@ember/object";import { service } from "@ember/service";import Form from "discourse/components/form";+import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";import { bind } from "discourse/lib/decorators";import DiscourseURL from "discourse/lib/url";@@ -164,6 +165,7 @@ export default class WorkflowsEditor extends Component {workflowId: this.args.workflow?.id,lastExecutionRunData: this.args.workflow?.lastExecutionRunData || null,pinData: this.args.workflow?.pinData || {},+ variables: this.args.workflow?.variables || [],});formData = {@@ -812,7 +814,7 @@ export default class WorkflowsEditor extends Component {}@action- importNodes(newNodes, newConnections, newStickyNotes, staticData) {+ importNodes(newNodes, newConnections, newStickyNotes, staticData, variables) {const existingNodes = this.formApi.get("nodes");if (!this.#canAddNodes(newNodes.length, existingNodes)) {return;@@ -850,7 +852,7 @@ export default class WorkflowsEditor extends Component {);}- this.handleSubmit(saveOptions);+ this.#saveThenImportVariables(saveOptions, variables);}@action@@ -1090,6 +1092,7 @@ export default class WorkflowsEditor extends Component {versionCounter: workflow.version_counter,hasUnpublishedChanges: workflow.has_unpublished_changes,settings: workflow.settings || {},+ variables: workflow.variables || [],timezone: workflow.timezone,staticData: workflow.static_data || {},pinData: workflow.pin_data || {},@@ -1443,6 +1446,45 @@ export default class WorkflowsEditor extends Component {);}+ async #saveThenImportVariables(saveOptions, variables) {+ try {+ await this.handleSubmit({ ...saveOptions, throwOnError: true });+ } catch {+ return;+ }++ if (variables?.length) {+ await this.#importVariables(variables);+ }+ }++ async #importVariables(variables) {+ try {+ const response = await ajax(+ `/admin/plugins/discourse-workflows/workflows/${this.args.workflow.id}/variables/import.json`,+ { type: "POST", data: { variables } }+ );+ this.replaceWorkflow(response.workflow);++ if (response.skipped_keys?.length) {+ this.toasts.warning({+ duration: "long",+ data: {+ message: i18n(+ "discourse_workflows.canvas.import_variables_skipped",+ {+ count: response.skipped_keys.length,+ keys: response.skipped_keys.join(", "),+ }+ ),+ },+ });+ }+ } catch (e) {+ popupAjaxError(e);+ }+ }+async #saveWorkflow(options = {}) {this.saving = true;try {diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/publish-banner.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/publish-banner.gjsnew file mode 100644index 00000000000..fe9f532f795--- /dev/null+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/publish-banner.gjs@@ -0,0 +1,71 @@+import Component from "@glimmer/component";+import { action } from "@ember/object";+import { service } from "@ember/service";+import DButton from "discourse/ui-kit/d-button";+import dIcon from "discourse/ui-kit/helpers/d-icon";+import { i18n } from "discourse-i18n";+import WorkflowPublishState from "../../lib/workflows/publish-state";++export default class PublishBanner extends Component {+ @service dialog;++ #publishState = new WorkflowPublishState({+ workflow: this.args.workflow,+ dialog: this.dialog,+ onDiscard: this.args.onDiscard,+ });++ get showBanner() {+ return this.#publishState.visible;+ }++ get showDiscardButton() {+ return this.#publishState.showDiscardButton;+ }++ @action+ async publish() {+ await this.#publishState.publish();+ }++ @action+ async discard() {+ await this.#publishState.discard();+ }++ <template>+ {{#if this.showBanner}}+ <div class="workflows-publish-banner">+ <span class="workflows-publish-banner__body" role="status">+ <span class="workflows-publish-banner__icon">+ {{dIcon "triangle-exclamation"}}+ </span>+ <span class="workflows-publish-banner__text">+ <span class="workflows-publish-banner__title">+ {{i18n "discourse_workflows.unpublished_changes_message"}}+ </span>+ <span class="workflows-publish-banner__detail">+ {{i18n "discourse_workflows.unpublished_changes_message_detail"}}+ </span>+ </span>+ </span>++ <span class="workflows-publish-banner__actions">+ <DButton+ class="btn-primary btn-small workflows-publish-banner__btn"+ @action={{this.publish}}+ @translatedLabel={{i18n "discourse_workflows.publish"}}+ />++ {{#if this.showDiscardButton}}+ <DButton+ class="btn-default btn-small workflows-publish-banner__btn"+ @action={{this.discard}}+ @translatedLabel={{i18n "discourse_workflows.discard_changes"}}+ />+ {{/if}}+ </span>+ </div>+ {{/if}}+ </template>+}diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variable-definitions.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variable-definitions.gjsnew file mode 100644index 00000000000..870331fe545--- /dev/null+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variable-definitions.gjs@@ -0,0 +1,122 @@+import Component from "@glimmer/component";+import { fn } from "@ember/helper";+import { action } from "@ember/object";+import { LinkTo } from "@ember/routing";+import { service } from "@ember/service";+import AdminConfigAreaEmptyList from "discourse/admin/components/admin-config-area-empty-list";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import DButton from "discourse/ui-kit/d-button";+import { i18n } from "discourse-i18n";+import { workflowVariableTypeLabel } from "../../lib/workflows/variable-types";++export default class WorkflowVariableDefinitions extends Component {+ @service dialog;++ get variables() {+ return this.args.workflow.variables;+ }++ @action+ async delete(variable) {+ const confirmed = await this.dialog.confirm({+ message: i18n("discourse_workflows.workflow_variables.delete_confirm", {+ label: variable.label,+ }),+ confirmButtonLabel: "discourse_workflows.delete",+ cancelButtonLabel: "discourse_workflows.cancel",+ });++ if (!confirmed) {+ return;+ }++ try {+ const response = await ajax(+ `/admin/plugins/discourse-workflows/workflows/${this.args.workflow.id}/variables/${variable.id}.json`,+ { type: "DELETE" }+ );++ this.args.workflow.variables = this.variables.filter(+ (v) => v.id !== variable.id+ );+ this.args.workflow.setProperties({+ versionId: response.workflow.version_id,+ activeVersionId: response.workflow.active_version_id,+ hasUnpublishedChanges: response.workflow.has_unpublished_changes,+ });+ } catch (e) {+ popupAjaxError(e);+ }+ }++ <template>+ {{#if this.variables.length}}+ <table class="d-table workflows-variables-table">+ <thead class="d-table__header">+ <tr class="d-table__row">+ <th class="d-table__header-cell">{{i18n+ "discourse_workflows.workflow_variables.key"+ }}</th>+ <th class="d-table__header-cell">{{i18n+ "discourse_workflows.workflow_variables.type"+ }}</th>+ </tr>+ </thead>+ <tbody class="d-table__body">+ {{#each this.variables as |variable|}}+ <tr class="d-table__row workflows-variables-table__row">+ <td class="d-table__cell --overview">+ <LinkTo+ class="d-table__overview-link"+ @model={{variable.id}}+ @route="adminPlugins.show.discourse-workflows.show.variables.edit"+ >+ <span class="d-table__overview-name">{{variable.label}}</span>+ </LinkTo>+ <code class="workflows-variable-key">{{variable.key}}</code>+ </td>+ <td class="d-table__cell --detail">+ <div class="d-table__mobile-label">+ {{i18n "discourse_workflows.workflow_variables.type"}}+ </div>+ <span class="workflows-variables-table__type">+ {{workflowVariableTypeLabel variable.variable_type}}+ </span>+ </td>+ <td class="d-table__cell --controls">+ <div class="d-table__cell-actions">+ <DButton+ class="btn-default btn-small workflows-variables-table__edit"+ @icon="pencil"+ @route="adminPlugins.show.discourse-workflows.show.variables.edit"+ @routeModels={{variable.id}}+ @title="discourse_workflows.edit"+ />+ <DButton+ class="btn-default btn-small btn-danger workflows-variables-table__delete"+ @action={{fn this.delete variable}}+ @icon="trash-can"+ @title="discourse_workflows.delete"+ />+ </div>+ </td>+ </tr>+ {{/each}}+ </tbody>+ </table>+ <DButton+ class="btn-default workflows-variables__add"+ @icon="plus"+ @label="discourse_workflows.workflow_variables.add_variable"+ @route="adminPlugins.show.discourse-workflows.show.variables.new"+ />+ {{else}}+ <AdminConfigAreaEmptyList+ @ctaLabel="discourse_workflows.workflow_variables.add_variable"+ @ctaRoute="adminPlugins.show.discourse-workflows.show.variables.new"+ @emptyLabel="discourse_workflows.workflow_variables.no_variables"+ />+ {{/if}}+ </template>+}diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variable-edit-form.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variable-edit-form.gjsnew file mode 100644index 00000000000..8886acc27fc--- /dev/null+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variable-edit-form.gjs@@ -0,0 +1,203 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { action } from "@ember/object";+import { service } from "@ember/service";+import { trustHTML } from "@ember/template";+import { isBlank } from "@ember/utils";+import SimpleList from "discourse/admin/components/simple-list";+import Form from "discourse/components/form";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import { eq } from "discourse/truth-helpers";+import { i18n } from "discourse-i18n";+import {+ WORKFLOW_VARIABLE_TYPE_VALUES,+ workflowVariableTypeLabel,+} from "../../lib/workflows/variable-types";++const KEY_FORMAT_RE = /^[a-zA-Z_][a-zA-Z0-9_]*$/;++export default class WorkflowVariableForm extends Component {+ @service router;++ @tracked choices = this.existingVariable?.type_options?.choices ?? [];++ get existingVariable() {+ if (!this.args.variableId) {+ return null;+ }++ return this.args.workflow.variables.find(+ (variable) => `${variable.id}` === `${this.args.variableId}`+ );+ }++ get formData() {+ const variable = this.existingVariable;++ return {+ key: variable?.key ?? "",+ description: variable?.description ?? "",+ variable_type: variable?.variable_type ?? "string",+ };+ }++ get choicesJoined() {+ return this.choices.join("\n");+ }++ @action+ setChoices(values) {+ this.choices = values;+ }++ @action+ validateKey(name, value, { addError }) {+ if (isBlank(value)) {+ return;+ }++ if (!KEY_FORMAT_RE.test(value)) {+ addError(name, {+ title: i18n("discourse_workflows.workflow_variables.key"),+ message: i18n(+ "discourse_workflows.workflow_variables.key_format_error"+ ),+ });+ return;+ }++ const isDuplicate = this.args.workflow.variables.some(+ (variable) =>+ variable.key === value && variable.id !== this.existingVariable?.id+ );++ if (isDuplicate) {+ addError(name, {+ title: i18n("discourse_workflows.workflow_variables.key"),+ message: i18n(+ "discourse_workflows.workflow_variables.key_duplicate_error"+ ),+ });+ }+ }++ @action+ async handleSubmit(data) {+ const payload = {+ ...data,+ type_options:+ data.variable_type === "enum" ? { choices: this.choices } : {},+ };++ try {+ const result = this.existingVariable+ ? await ajax(+ `/admin/plugins/discourse-workflows/workflows/${this.args.workflow.id}/variables/${this.existingVariable.id}.json`,+ { type: "PUT", data: payload }+ )+ : await ajax(+ `/admin/plugins/discourse-workflows/workflows/${this.args.workflow.id}/variables.json`,+ { type: "POST", data: payload }+ );++ this.args.workflow.variables = this.existingVariable+ ? this.args.workflow.variables.map((variable) =>+ variable.id === this.existingVariable.id+ ? result.variable+ : variable+ )+ : [...this.args.workflow.variables, result.variable];++ this.args.workflow.setProperties({+ versionId: result.workflow.version_id,+ activeVersionId: result.workflow.active_version_id,+ hasUnpublishedChanges: result.workflow.has_unpublished_changes,+ });++ this.router.transitionTo(+ "adminPlugins.show.discourse-workflows.show.variables.manage",+ this.args.workflow.id+ );+ } catch (e) {+ popupAjaxError(e);+ }+ }++ <template>+ <Form+ class="workflows-variable-form"+ @data={{this.formData}}+ @onSubmit={{this.handleSubmit}}+ as |form transientData|+ >+ <form.Field+ @description={{trustHTML+ (i18n "discourse_workflows.workflow_variables.key_description")+ }}+ @format="large"+ @name="key"+ @title={{i18n "discourse_workflows.workflow_variables.key"}}+ @type="input"+ @validate={{this.validateKey}}+ @validation="required|length:1,100"+ as |field|+ >+ <field.Control />+ </form.Field>++ <form.Field+ @description={{i18n+ "discourse_workflows.workflow_variables.description_description"+ }}+ @format="large"+ @name="description"+ @title={{i18n "discourse_workflows.workflow_variables.description"}}+ @type="textarea"+ @validation="length:,500"+ as |field|+ >+ <field.Control @height={{80}} />+ </form.Field>++ <form.Field+ @description={{i18n+ "discourse_workflows.workflow_variables.type_description"+ }}+ @format="large"+ @name="variable_type"+ @title={{i18n "discourse_workflows.workflow_variables.type"}}+ @type="select"+ @validation="required"+ as |field|+ >+ <field.Control as |select|>+ {{#each WORKFLOW_VARIABLE_TYPE_VALUES as |type|}}+ <select.Option @value={{type}}>+ {{workflowVariableTypeLabel type}}+ </select.Option>+ {{/each}}+ </field.Control>+ </form.Field>++ {{#if (eq transientData.variable_type "enum")}}+ <form.Container+ @description={{i18n+ "discourse_workflows.workflow_variables.choices_description"+ }}+ @format="large"+ @title={{i18n "discourse_workflows.workflow_variables.choices"}}+ >+ <SimpleList+ @onChange={{this.setChoices}}+ @values={{this.choicesJoined}}+ />+ </form.Container>+ {{/if}}++ <form.Actions>+ <form.Submit />+ </form.Actions>+ </Form>+ </template>+}diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variable-list.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variable-list.gjsnew file mode 100644index 00000000000..6f8379732df--- /dev/null+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variable-list.gjs@@ -0,0 +1,26 @@+import Component from "@glimmer/component";+import AdminConfigAreaEmptyList from "discourse/admin/components/admin-config-area-empty-list";+import DButton from "discourse/ui-kit/d-button";++export default class WorkflowVariableList extends Component {+ get variables() {+ return this.args.workflow.variables;+ }++ <template>+ {{#if this.variables.length}}+ <DButton+ class="btn-default workflows-variables__manage"+ @icon="list"+ @label="discourse_workflows.workflow_variables.manage_variables"+ @route="adminPlugins.show.discourse-workflows.show.variables.manage"+ />+ {{else}}+ <AdminConfigAreaEmptyList+ @ctaLabel="discourse_workflows.workflow_variables.add_variable"+ @ctaRoute="adminPlugins.show.discourse-workflows.show.variables.new"+ @emptyLabel="discourse_workflows.workflow_variables.no_variables"+ />+ {{/if}}+ </template>+}diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variables-publish-notice.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variables-publish-notice.gjsnew file mode 100644index 00000000000..fbce41c3778--- /dev/null+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variables-publish-notice.gjs@@ -0,0 +1,70 @@+import Component from "@glimmer/component";+import { action } from "@ember/object";+import { service } from "@ember/service";+import DButton from "discourse/ui-kit/d-button";+import dIcon from "discourse/ui-kit/helpers/d-icon";+import { i18n } from "discourse-i18n";+import WorkflowPublishState from "../../lib/workflows/publish-state";++export default class VariablesPublishNotice extends Component {+ @service dialog;++ #publishState = new WorkflowPublishState({+ workflow: this.args.workflow,+ dialog: this.dialog,+ });++ get showNotice() {+ return this.#publishState.visible;+ }++ get showDiscardButton() {+ return this.#publishState.showDiscardButton;+ }++ @action+ async publish() {+ await this.#publishState.publish();+ }++ @action+ async discard() {+ await this.#publishState.discard();+ }++ <template>+ {{#if this.showNotice}}+ <div class="workflows-variables-publish-notice">+ <span class="workflows-variables-publish-notice__text" role="status">+ <span class="workflows-variables-publish-notice__icon">+ {{dIcon "triangle-exclamation"}}+ </span>+ <span class="workflows-variables-publish-notice__copy">+ <span class="workflows-variables-publish-notice__title">+ {{i18n "discourse_workflows.unpublished_changes_message"}}+ </span>+ <span class="workflows-variables-publish-notice__detail">+ {{i18n "discourse_workflows.unpublished_changes_message_detail"}}+ </span>+ </span>+ </span>++ <span class="workflows-variables-publish-notice__actions">+ <DButton+ class="btn-primary btn-small workflows-variables-publish-notice__btn"+ @action={{this.publish}}+ @translatedLabel={{i18n "discourse_workflows.publish"}}+ />++ {{#if this.showDiscardButton}}+ <DButton+ class="btn-default btn-small workflows-variables-publish-notice__btn"+ @action={{this.discard}}+ @translatedLabel={{i18n "discourse_workflows.discard_changes"}}+ />+ {{/if}}+ </span>+ </div>+ {{/if}}+ </template>+}diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variables.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variables.gjsnew file mode 100644index 00000000000..1d9d43ff7b9--- /dev/null+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variables.gjs@@ -0,0 +1,147 @@+import Component from "@glimmer/component";+import { cached } from "@glimmer/tracking";+import { service } from "@ember/service";+import SiteSettingComponent from "discourse/admin/components/site-setting";+import SiteSetting from "discourse/admin/models/site-setting";+import { ajax } from "discourse/lib/ajax";+import { escapeExpression } from "discourse/lib/utilities";+import DPageSubheader from "discourse/ui-kit/d-page-subheader";+import { i18n } from "discourse-i18n";+import WorkflowVariableList from "./variable-list";+import VariablesPublishNotice from "./variables-publish-notice";++const VARIABLE_TYPE_TO_SITE_SETTING_TYPE = {+ string: { type: "string" },+ integer: { type: "integer" },+ boolean: { type: "bool" },+ enum: { type: "enum" },+ category: { type: "category" },+ category_list: { type: "list", list_type: "category" },+ group: { type: "group" },+ group_list: { type: "list", list_type: "group" },+ tag_list: { type: "list", list_type: "tag" },+ simple_list: { type: "simple_list" },+};++// trackChanges = false keeps these rows out of the global unsaved-changes+// banner used by the real site settings page, since they aren't site settings.+class WorkflowVariableRow extends SiteSettingComponent {+ @service toasts;++ trackChanges = false;++ // These rows have no "default" concept to compare against (buildVariableSetting+ // always sets default: ""), so the inherited overridden/reset UI is meaningless.+ get groupedOverridden() {+ return false;+ }++ get overridden() {+ return false;+ }++ get staffLogFilter() {+ return null;+ }++ async _save(settings) {+ const setting = settings[0];+ const wasPublished = Boolean(setting.workflow.activeVersionId);++ const response = await ajax(+ `/admin/plugins/discourse-workflows/workflows/${setting.workflow.id}/variables/${setting.workflowVariableId}/value.json`,+ { type: "PUT", data: { value: setting.buffered.get("value") } }+ );++ // Mutated in place (not reassigned) so other rows' @cached SiteSetting+ // wrappers aren't rebuilt, discarding their own in-progress edits.+ const savedVariable = setting.workflow.variables.find(+ (variable) => variable.id === setting.workflowVariableId+ );+ if (savedVariable) {+ Object.assign(savedVariable, response.variable);+ }++ setting.workflow.setProperties({+ versionId: response.workflow.version_id,+ activeVersionId: response.workflow.active_version_id,+ hasUnpublishedChanges: response.workflow.has_unpublished_changes,+ });++ if (+ wasPublished &&+ response.workflow.active_version_id &&+ !response.workflow.has_unpublished_changes+ ) {+ this.toasts.success({+ duration: "short",+ data: {+ message: i18n(+ "discourse_workflows.workflow_variables.value_published"+ ),+ },+ });+ }++ return response;+ }+}++function buildVariableSetting(variable, workflow) {+ const { type, list_type } =+ VARIABLE_TYPE_TO_SITE_SETTING_TYPE[variable.variable_type] ??+ VARIABLE_TYPE_TO_SITE_SETTING_TYPE.string;++ return SiteSetting.create({+ setting: variable.key,+ humanized_name: variable.label,+ description: escapeExpression(variable.description),+ type,+ list_type,+ valid_values: variable.type_options?.choices,+ value: variable.value ?? "",+ default: "",+ workflow,+ workflowVariableId: variable.id,+ });+}++export default class WorkflowVariables extends Component {+ get description() {+ const workflow = this.args.workflow;+ const willAutoPublish =+ Boolean(workflow.activeVersionId) && !workflow.hasUnpublishedChanges;++ return i18n(+ willAutoPublish+ ? "discourse_workflows.workflow_variables.description_will_publish"+ : "discourse_workflows.workflow_variables.description_will_draft"+ );+ }++ @cached+ get variableSettings() {+ return this.args.workflow.variables.map((variable) =>+ buildVariableSetting(variable, this.args.workflow)+ );+ }++ <template>+ {{#if @workflow.variables.length}}+ <VariablesPublishNotice @workflow={{@workflow}} />+ {{/if}}++ <DPageSubheader+ @descriptionLabel={{this.description}}+ @titleLabel={{i18n "discourse_workflows.workflow_variables.title"}}+ />++ <section class="form-horizontal settings workflows-variables__field-values">+ {{#each this.variableSettings as |setting|}}+ <WorkflowVariableRow @setting={{setting}} />+ {{/each}}+ </section>++ <WorkflowVariableList @workflow={{@workflow}} />+ </template>+}diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/discourse-workflows-route-map.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/discourse-workflows-route-map.jsindex de8138997b0..27db45dd40a 100644--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/discourse-workflows-route-map.js+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/discourse-workflows-route-map.js@@ -11,7 +11,12 @@ export default {this.route("executions", function () {this.route("show", { path: "/:execution_id" });});- this.route("settings");+ this.route("settings", function () {});+ this.route("variables", function () {+ this.route("manage");+ this.route("new");+ this.route("edit", { path: "/:variable_id/edit" });+ });this.route("versions");});});diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/editor-session.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/editor-session.jsindex 5e375053785..73aa59638f6 100644--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/editor-session.js+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/editor-session.js@@ -34,15 +34,18 @@ export default class WorkflowEditorSession {@tracked lastExecutionRunData = null;@tracked pinData = {};@tracked webhookTestListeners = {};+ @tracked variables = [];constructor({workflowId = null,lastExecutionRunData = null,pinData = {},+ variables = [],} = {}) {this.workflowId = workflowId;this.lastExecutionRunData = lastExecutionRunData;this.pinData = pinData || {};+ this.variables = variables || [];}setEditingContext(node, nodes, connections) {diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-context.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-context.jsindex 848c52155ff..a7d15a76d77 100644--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-context.js+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-context.js@@ -306,16 +306,49 @@ function buildSiteSettingsScope(siteSettings) {return scope;}-function buildVarsScope(workflowVars) {+function buildVarsScope(globalVars) {const scope = Object.create(null);- if (workflowVars?.length) {- for (const v of workflowVars) {+ if (globalVars?.length) {+ for (const v of globalVars) {scope[v.key] = v.value ?? "";}}return scope;}+function typedWorkflowVarValue(field) {+ const raw = field.value;++ switch (field.variable_type) {+ case "integer":+ case "category":+ case "group":+ return raw ? parseInt(raw, 10) : TYPE_EXEMPLARS.integer;+ case "boolean":+ return raw ? raw === "true" : TYPE_EXEMPLARS.boolean;+ case "category_list":+ case "group_list":+ return raw+ ? raw.split("|").filter(Boolean).map(Number)+ : TYPE_EXEMPLARS.array;+ case "tag_list":+ case "simple_list":+ return raw ? raw.split("|").filter(Boolean) : TYPE_EXEMPLARS.array;+ default:+ return raw ?? TYPE_EXEMPLARS.string;+ }+}++function buildWorkflowVarsScope(workflowVariables) {+ const scope = Object.create(null);+ if (workflowVariables?.length) {+ for (const field of workflowVariables) {+ scope[field.key] = typedWorkflowVarValue(field);+ }+ }+ return scope;+}+function buildExecutionScope(nodes) {const scope = cleanObject({id: 0,@@ -372,7 +405,8 @@ export function buildScope({inputFields = [],ancestorNodes = [],siteSettings,- workflowVars,+ globalVars,+ workflowVariables,nodes,}) {const $json = buildScopeFromFields(inputFields);@@ -396,7 +430,8 @@ export function buildScope({$trigger: triggerJson || Object.create(null),$site_settings: buildSiteSettingsScope(siteSettings),$current_user: cleanObject({ id: 0, username: "" }),- $vars: buildVarsScope(workflowVars),+ $vars: buildVarsScope(globalVars),+ $workflow_vars: buildWorkflowVarsScope(workflowVariables),$execution: buildExecutionScope(nodes),$helpers: buildHelpersScope(),$: (name) => nodeOutputs[name] || EMPTY_NODE_OUTPUT,diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/dollar-vars.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/dollar-vars.jsindex aa226c96461..dd094e64d8a 100644--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/dollar-vars.js+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/dollar-vars.js@@ -26,6 +26,10 @@ const DOLLAR_VAR_DOCS = {infoKey: "discourse_workflows.expression_docs.vars.current_user",},$vars: {+ detail: "object",+ infoKey: "discourse_workflows.expression_docs.vars.global_vars",+ },+ $workflow_vars: {detail: "object",infoKey: "discourse_workflows.expression_docs.vars.workflow_vars",},@@ -59,6 +63,7 @@ export function buildDollarVars(scope, sections) {"$site_settings","$current_user","$vars",+ "$workflow_vars","$execution","$helpers",],diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/reference-label.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/reference-label.jsindex 9dc1b2861fa..30af55ed6f4 100644--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/reference-label.js+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/reference-label.js@@ -20,6 +20,7 @@ const ROOT_SOURCES = {$trigger: "trigger",$itemIndex: "item_index",$vars: "variable",+ $workflow_vars: "workflow_variable",$current_user: "current_user",$site_settings: "site_setting",$execution: "execution",@@ -31,6 +32,7 @@ const SOURCE_ICONS = {trigger: "play",item_index: "hashtag",variable: "dollar-sign",+ workflow_variable: "dollar-sign",current_user: "user",site_setting: "gear",execution: "bolt",diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/publish-state.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/publish-state.jsnew file mode 100644index 00000000000..8d1cfdd4b8e--- /dev/null+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/publish-state.js@@ -0,0 +1,104 @@+import { tracked } from "@glimmer/tracking";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import { i18n } from "discourse-i18n";++export default class WorkflowPublishState {+ #workflow;+ #dialog;++ #onDiscard;+ @tracked _publishedOverride = null;+ @tracked _hasUnpublishedChangesOverride = null;++ constructor({ workflow, dialog, onDiscard }) {+ this.#workflow = workflow;+ this.#dialog = dialog;+ this.#onDiscard = onDiscard;+ }++ get published() {+ return this._publishedOverride ?? Boolean(this.#workflow.activeVersionId);+ }++ get hasUnpublishedChanges() {+ return (+ this._hasUnpublishedChangesOverride ??+ Boolean(this.#workflow.hasUnpublishedChanges)+ );+ }++ get publishDisabled() {+ return this.published && !this.hasUnpublishedChanges;+ }++ get visible() {+ return !this.publishDisabled;+ }++ get showDiscardButton() {+ return this.published && this.hasUnpublishedChanges;+ }++ async publish() {+ this._publishedOverride = true;+ this._hasUnpublishedChangesOverride = false;+ try {+ await ajax(+ `/admin/plugins/discourse-workflows/workflows/${this.#workflow.id}.json`,+ {+ type: "PUT",+ data: { workflow: { published: true } },+ }+ );+ this.#workflow.activeVersionId = this.#workflow.versionId;+ this.#workflow.hasUnpublishedChanges = false;+ this._publishedOverride = null;+ this._hasUnpublishedChangesOverride = null;+ } catch (e) {+ this._publishedOverride = null;+ this._hasUnpublishedChangesOverride = null;+ popupAjaxError(e);+ }+ }++ async discard() {+ const confirmed = await this.#dialog.confirm({+ message: i18n("discourse_workflows.discard_changes_confirmation"),+ confirmButtonLabel: "discourse_workflows.discard_changes",+ cancelButtonLabel: "discourse_workflows.keep_editing",+ });++ if (!confirmed) {+ return;+ }++ this._hasUnpublishedChangesOverride = false;++ try {+ const response = await ajax(+ `/admin/plugins/discourse-workflows/workflows/${this.#workflow.id}/discard-draft.json`,+ { type: "POST" }+ );+ this.#workflow.setProperties({+ name: response.workflow.name,+ nodes: response.workflow.nodes || [],+ connections: response.workflow.connections || {},+ versionId: response.workflow.version_id,+ activeVersionId: response.workflow.active_version_id,+ versionCounter: response.workflow.version_counter,+ hasUnpublishedChanges: response.workflow.has_unpublished_changes,+ settings: response.workflow.settings || {},+ variables: response.workflow.variables || [],+ timezone: response.workflow.timezone,+ staticData: response.workflow.static_data || {},+ pinData: response.workflow.pin_data || {},+ });+ this._hasUnpublishedChangesOverride = null;+ this.#onDiscard?.(response.workflow);+ } catch (e) {+ this._hasUnpublishedChangesOverride = null;+ popupAjaxError(e);+ }+ }+}diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/variable-types.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/variable-types.jsnew file mode 100644index 00000000000..683a012a4a9--- /dev/null+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/variable-types.js@@ -0,0 +1,18 @@+import { i18n } from "discourse-i18n";++export const WORKFLOW_VARIABLE_TYPE_VALUES = [+ "string",+ "integer",+ "boolean",+ "enum",+ "category",+ "category_list",+ "group",+ "group_list",+ "tag_list",+ "simple_list",+];++export function workflowVariableTypeLabel(variableType) {+ return i18n(`discourse_workflows.workflow_variables.types.${variableType}`);+}diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/models/discourse-workflows-workflow.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/models/discourse-workflows-workflow.jsindex d495a603918..ee6cd91668f 100644--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/models/discourse-workflows-workflow.js+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/models/discourse-workflows-workflow.js@@ -53,6 +53,9 @@ export default class DiscourseWorkflowsWorkflow extends RestModel {if (Object.hasOwn(json, "pin_data")) {result.pinData = json.pin_data;}+ if (Object.hasOwn(json, "variables")) {+ result.variables = json.variables;+ }return result;}@@ -70,6 +73,7 @@ export default class DiscourseWorkflowsWorkflow extends RestModel {@tracked settings;@tracked staticData;@tracked pinData;+ @tracked variables = [];@tracked nodes = [];@tracked connections = [];@tracked stickyNotes = [];diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/connectors/site-setting-after-label/workflow-variable-key.gjs b/plugins/discourse-workflows/admin/assets/javascripts/discourse/connectors/site-setting-after-label/workflow-variable-key.gjsnew file mode 100644index 00000000000..cec4fdc8504--- /dev/null+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/connectors/site-setting-after-label/workflow-variable-key.gjs@@ -0,0 +1,11 @@+import Component from "@glimmer/component";++export default class WorkflowVariableKey extends Component {+ static shouldRender(args) {+ return Boolean(args.setting?.workflowVariableId);+ }++ <template>+ <code class="workflows-variable-key">{{@outletArgs.setting.setting}}</code>+ </template>+}diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/settings.js b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/settings.jsnew file mode 100644index 00000000000..87c47d41691--- /dev/null+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/settings.js@@ -0,0 +1,7 @@+import DiscourseRoute from "discourse/routes/discourse";++export default class DiscourseWorkflowsShowSettingsRoute extends DiscourseRoute {+ model() {+ return this.modelFor("adminPlugins.show.discourse-workflows.show");+ }+}diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/variables.js b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/variables.jsnew file mode 100644index 00000000000..629d299eba6--- /dev/null+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/variables.js@@ -0,0 +1,3 @@+import DiscourseRoute from "discourse/routes/discourse";++export default class DiscourseWorkflowsShowVariablesRoute extends DiscourseRoute {}diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/variables/edit.js b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/variables/edit.jsnew file mode 100644index 00000000000..3b41e7cce65--- /dev/null+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/variables/edit.js@@ -0,0 +1,12 @@+import DiscourseRoute from "discourse/routes/discourse";++const WORKFLOW_ROUTE = "adminPlugins.show.discourse-workflows.show";++export default class DiscourseWorkflowsShowVariablesEditRoute extends DiscourseRoute {+ model(params) {+ return {+ ...this.modelFor(WORKFLOW_ROUTE),+ variableId: params.variable_id,+ };+ }+}diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/variables/index.js b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/variables/index.jsnew file mode 100644index 00000000000..643eb44039d--- /dev/null+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/variables/index.js@@ -0,0 +1,7 @@+import DiscourseRoute from "discourse/routes/discourse";++export default class DiscourseWorkflowsShowVariablesIndexRoute extends DiscourseRoute {+ model() {+ return this.modelFor("adminPlugins.show.discourse-workflows.show");+ }+}diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/variables/manage.js b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/variables/manage.jsnew file mode 100644index 00000000000..c1d7220273c--- /dev/null+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/variables/manage.js@@ -0,0 +1,7 @@+import DiscourseRoute from "discourse/routes/discourse";++export default class DiscourseWorkflowsShowVariablesManageRoute extends DiscourseRoute {+ model() {+ return this.modelFor("adminPlugins.show.discourse-workflows.show");+ }+}diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/variables/new.js b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/variables/new.jsnew file mode 100644index 00000000000..f5695e64a91--- /dev/null+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/variables/new.js@@ -0,0 +1,7 @@+import DiscourseRoute from "discourse/routes/discourse";++export default class DiscourseWorkflowsShowVariablesNewRoute extends DiscourseRoute {+ model() {+ return this.modelFor("adminPlugins.show.discourse-workflows.show");+ }+}diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show.gjs b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show.gjsindex 310ded4980d..41b7819e1e2 100644--- a/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show.gjs+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show.gjs@@ -69,6 +69,10 @@ class WorkflowShowPage extends Component {@label="discourse_workflows.tabs.executions"@route="adminPlugins.show.discourse-workflows.show.executions"/>+ <DNavItem+ @label="discourse_workflows.tabs.workflow_variables"+ @route="adminPlugins.show.discourse-workflows.show.variables"+ /><DNavItem@label="discourse_workflows.tabs.settings"@route="adminPlugins.show.discourse-workflows.show.settings"diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/variables.gjs b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/variables.gjsnew file mode 100644index 00000000000..a087a33dfcb--- /dev/null+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/variables.gjs@@ -0,0 +1 @@+export default <template>{{outlet}}</template>diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/variables/edit.gjs b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/variables/edit.gjsnew file mode 100644index 00000000000..67f309354fd--- /dev/null+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/variables/edit.gjs@@ -0,0 +1,21 @@+import AdminConfigAreaCard from "discourse/admin/components/admin-config-area-card";+import BackButton from "discourse/components/back-button";+import WorkflowVariableForm from "discourse/plugins/discourse-workflows/admin/components/workflows/variable-edit-form";++export default <template>+ <BackButton+ @label="discourse_workflows.workflow_variables.back_to_manage"+ @route="adminPlugins.show.discourse-workflows.show.variables.manage"+ />++ <AdminConfigAreaCard+ @heading="discourse_workflows.workflow_variables.edit_variable"+ >+ <:content>+ <WorkflowVariableForm+ @variableId={{@controller.model.variableId}}+ @workflow={{@controller.model.workflow}}+ />+ </:content>+ </AdminConfigAreaCard>+</template>diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/variables/index.gjs b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/variables/index.gjsnew file mode 100644index 00000000000..d3c02a1a38f--- /dev/null+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/variables/index.gjs@@ -0,0 +1,10 @@+import DBreadcrumbsItem from "discourse/ui-kit/d-breadcrumbs-item";+import { i18n } from "discourse-i18n";+import WorkflowVariables from "discourse/plugins/discourse-workflows/admin/components/workflows/variables";++export default <template>+ <DBreadcrumbsItem+ @label={{i18n "discourse_workflows.tabs.workflow_variables"}}+ />+ <WorkflowVariables @workflow={{@controller.model.workflow}} />+</template>diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/variables/manage.gjs b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/variables/manage.gjsnew file mode 100644index 00000000000..ec60e195d77--- /dev/null+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/variables/manage.gjs@@ -0,0 +1,31 @@+import BackButton from "discourse/components/back-button";+import DBreadcrumbsItem from "discourse/ui-kit/d-breadcrumbs-item";+import DPageSubheader from "discourse/ui-kit/d-page-subheader";+import { i18n } from "discourse-i18n";+import WorkflowVariableDefinitions from "discourse/plugins/discourse-workflows/admin/components/workflows/variable-definitions";++export default <template>+ <DBreadcrumbsItem+ @label={{i18n "discourse_workflows.tabs.workflow_variables"}}+ @path="/admin/plugins/discourse-workflows/workflows/{{@controller.model.workflow.id}}/variables"+ />+ <DBreadcrumbsItem+ @label={{i18n "discourse_workflows.workflow_variables.manage_variables"}}+ />++ <BackButton+ @label="discourse_workflows.workflow_variables.back"+ @route="adminPlugins.show.discourse-workflows.show.variables"+ />++ <DPageSubheader+ @descriptionLabel={{i18n+ "discourse_workflows.workflow_variables.definitions_description"+ }}+ @titleLabel={{i18n+ "discourse_workflows.workflow_variables.manage_variables"+ }}+ />++ <WorkflowVariableDefinitions @workflow={{@controller.model.workflow}} />+</template>diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/variables/new.gjs b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/variables/new.gjsnew file mode 100644index 00000000000..e399568b2e3--- /dev/null+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/variables/new.gjs@@ -0,0 +1,18 @@+import AdminConfigAreaCard from "discourse/admin/components/admin-config-area-card";+import BackButton from "discourse/components/back-button";+import WorkflowVariableForm from "discourse/plugins/discourse-workflows/admin/components/workflows/variable-edit-form";++export default <template>+ <BackButton+ @label="discourse_workflows.workflow_variables.back_to_manage"+ @route="adminPlugins.show.discourse-workflows.show.variables.manage"+ />++ <AdminConfigAreaCard+ @heading="discourse_workflows.workflow_variables.add_variable"+ >+ <:content>+ <WorkflowVariableForm @workflow={{@controller.model.workflow}} />+ </:content>+ </AdminConfigAreaCard>+</template>diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/workflow_variables_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/workflow_variables_controller.rbnew file mode 100644index 00000000000..14b7d604040--- /dev/null+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/workflow_variables_controller.rb@@ -0,0 +1,158 @@+# frozen_string_literal: true++module DiscourseWorkflows+ class WorkflowVariablesController < ::Admin::AdminController+ requires_plugin DiscourseWorkflows::PLUGIN_NAME++ def create+ DiscourseWorkflows::WorkflowVariable::Create.call(service_params) do |result|+ on_success do |variable:, workflow:|+ render json: {+ variable:+ DiscourseWorkflows::WorkflowVariableSerializer.new(+ variable,+ root: false,+ ).as_json,+ workflow:+ DiscourseWorkflows::WorkflowSerializer.new(workflow, root: false).as_json,+ },+ status: :created+ end+ on_failure { render(json: failed_json, status: :unprocessable_entity) }+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }+ on_failed_contract do |contract|+ render(+ json: failed_json.merge(errors: contract.errors.full_messages),+ status: :bad_request,+ )+ end+ on_model_not_found(:workflow) { raise Discourse::NotFound }+ on_model_errors(:variable) do |model|+ render(+ json: failed_json.merge(errors: model.errors.full_messages),+ status: :unprocessable_entity,+ )+ end+ end+ end++ def update+ DiscourseWorkflows::WorkflowVariable::Update.call(service_params) do |result|+ on_success do |variable:, workflow:|+ render json: {+ variable:+ DiscourseWorkflows::WorkflowVariableSerializer.new(+ variable,+ root: false,+ ).as_json,+ workflow:+ DiscourseWorkflows::WorkflowSerializer.new(workflow, root: false).as_json,+ }+ end+ on_failure { render(json: failed_json, status: :unprocessable_entity) }+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }+ on_failed_policy(:existing_value_compatible_with_new_type) do |policy|+ render(json: failed_json.merge(errors: [policy.reason]), status: :unprocessable_entity)+ end+ on_failed_contract do |contract|+ render(+ json: failed_json.merge(errors: contract.errors.full_messages),+ status: :bad_request,+ )+ end+ on_model_not_found(:workflow) { raise Discourse::NotFound }+ on_model_not_found(:variable) { raise Discourse::NotFound }+ on_model_errors(:variable) do |model|+ render(+ json: failed_json.merge(errors: model.errors.full_messages),+ status: :unprocessable_entity,+ )+ end+ end+ end++ def destroy+ DiscourseWorkflows::WorkflowVariable::Destroy.call(service_params) do |result|+ on_success do |workflow:|+ render json: {+ workflow:+ DiscourseWorkflows::WorkflowSerializer.new(workflow, root: false).as_json,+ }+ end+ on_failure { render(json: failed_json, status: :unprocessable_entity) }+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }+ on_failed_contract do |contract|+ render(+ json: failed_json.merge(errors: contract.errors.full_messages),+ status: :bad_request,+ )+ end+ on_model_not_found(:workflow) { raise Discourse::NotFound }+ on_model_not_found(:variable) { raise Discourse::NotFound }+ end+ end++ def update_value+ DiscourseWorkflows::WorkflowVariable::UpdateValue.call(service_params) do |result|+ on_success do |variable:, workflow:|+ render json: {+ variable:+ DiscourseWorkflows::WorkflowVariableSerializer.new(+ variable,+ root: false,+ ).as_json,+ workflow:+ DiscourseWorkflows::WorkflowSerializer.new(workflow, root: false).as_json,+ }+ end+ on_failed_step(:activate_triggers) do |step_result|+ render(+ json: failed_json.merge(errors: Array(step_result.error)),+ status: :unprocessable_entity,+ )+ end+ on_failure { render(json: failed_json, status: :unprocessable_entity) }+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }+ on_failed_policy(:value_is_valid) do |policy|+ render(json: failed_json.merge(errors: [policy.reason]), status: :unprocessable_entity)+ end+ on_failed_contract do |contract|+ render(+ json: failed_json.merge(errors: contract.errors.full_messages),+ status: :bad_request,+ )+ end+ on_model_not_found(:workflow) { raise Discourse::NotFound }+ on_model_not_found(:variable) { raise Discourse::NotFound }+ on_model_errors(:variable) do |model|+ render(+ json: failed_json.merge(errors: model.errors.full_messages),+ status: :unprocessable_entity,+ )+ end+ end+ end++ def import+ DiscourseWorkflows::WorkflowVariable::ImportDefinitions.call(service_params) do |result|+ on_success do |workflow:, imported_variables:|+ render json: {+ workflow:+ DiscourseWorkflows::WorkflowSerializer.new(workflow, root: false).as_json,+ imported_count: imported_variables[:created].size,+ skipped_keys: imported_variables[:skipped],+ }+ end+ on_failure { render(json: failed_json, status: :unprocessable_entity) }+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }+ on_failed_contract do |contract|+ render(+ json: failed_json.merge(errors: contract.errors.full_messages),+ status: :bad_request,+ )+ end+ on_model_not_found(:workflow) { raise Discourse::NotFound }+ end+ end+ end+enddiff --git a/plugins/discourse-workflows/app/models/discourse_workflows/variable.rb b/plugins/discourse-workflows/app/models/discourse_workflows/variable.rbindex b419b149948..0fa509df285 100644--- a/plugins/discourse-workflows/app/models/discourse_workflows/variable.rb+++ b/plugins/discourse-workflows/app/models/discourse_workflows/variable.rb@@ -4,19 +4,108 @@ module DiscourseWorkflowsclass Variable < ActiveRecord::Baseself.table_name = "discourse_workflows_variables"+ VARIABLE_TYPES = %w[+ string+ integer+ boolean+ enum+ category+ category_list+ group+ group_list+ tag_list+ simple_list+ ]+belongs_to :created_by, class_name: "User", foreign_key: "created_by_id"+ belongs_to :workflow, class_name: "DiscourseWorkflows::Workflow", optional: true++ attribute :type_options, default: -> { {} }validates :key,presence: true,- uniqueness: true,+ uniqueness: {+ scope: :workflow_id,+ },length: {maximum: 100,},format: {with: /\A[a-zA-Z_][a-zA-Z0-9_]*\z/,}- validates :value, length: { maximum: 1000 }+ validates :value, length: { maximum: 10_000 }validates :description, length: { maximum: 500 }, allow_nil: true+ validates :variable_type, presence: true, inclusion: { in: VARIABLE_TYPES }+ validate :enum_must_have_choices++ def label+ key.to_s.tr("_", " ").sub(/\A./, &:upcase)+ end++ def definition+ {+ "key" => key,+ "description" => description,+ "type" => variable_type,+ "type_options" => type_options || {},+ }+ end++ def to_version_entry+ definition.merge("value" => value)+ end++ def self.value_valid_for_type?(value:, variable_type:, type_options:)+ value = value.to_s+ return true if value.blank?++ case variable_type+ when "integer"+ value.match?(/\A-?\d+\z/)+ when "boolean"+ %w[true false].include?(value)+ when "enum"+ Array(type_options["choices"]).include?(value)+ when "category"+ ids_exist?(::Category, [value])+ when "category_list"+ ids_exist?(::Category, value.split("|"))+ when "group"+ ids_exist?(::Group, [value])+ when "group_list"+ ids_exist?(::Group, value.split("|"))+ when "tag_list"+ names_exist?(value.split("|"))+ else+ true+ end+ end++ def self.ids_exist?(klass, raw_ids)+ return false if raw_ids.empty?++ parsed_ids = raw_ids.map { |id| Integer(id, exception: false) }+ return false if parsed_ids.include?(nil)++ klass.where(id: parsed_ids).count == parsed_ids.size+ end+ private_class_method :ids_exist?++ def self.names_exist?(names)+ return false if names.empty?++ ::Tag.where(name: names).count == names.size+ end+ private_class_method :names_exist?++ private++ def enum_must_have_choices+ return unless variable_type == "enum"+ return if type_options.is_a?(Hash) && Array(type_options["choices"]).present?++ errors.add(:type_options, :enum_choices_required)+ endendend@@ -27,13 +116,17 @@ end# id :bigint not null, primary key# description :text# key :string(100) not null-# value :string(1000) default(""), not null+# type_options :jsonb not null+# value :text+# variable_type :string(30) default("string"), not null# created_at :datetime not null# updated_at :datetime not null# created_by_id :integer not null+# workflow_id :bigint## Indexes## idx_dwf_variables_on_created_by_id (created_by_id)-# idx_dwf_variables_on_key (key) UNIQUE+# idx_dwf_variables_on_key_global (key) UNIQUE WHERE (workflow_id IS NULL)+# idx_dwf_variables_on_workflow_key (workflow_id,key) UNIQUE WHERE (workflow_id IS NOT NULL)#diff --git a/plugins/discourse-workflows/app/models/discourse_workflows/workflow.rb b/plugins/discourse-workflows/app/models/discourse_workflows/workflow.rbindex 43b11cf447d..c8617bd3dbe 100644--- a/plugins/discourse-workflows/app/models/discourse_workflows/workflow.rb+++ b/plugins/discourse-workflows/app/models/discourse_workflows/workflow.rb@@ -41,6 +41,10 @@ module DiscourseWorkflowsclass_name: "DiscourseWorkflows::WorkflowTagMapping",foreign_key: "workflow_id",dependent: :delete_all+ has_many :variables,+ class_name: "DiscourseWorkflows::Variable",+ foreign_key: "workflow_id",+ dependent: :delete_allhas_many :tags,-> { order(:name) },class_name: "DiscourseWorkflows::WorkflowTag",@@ -150,6 +154,7 @@ module DiscourseWorkflowsnodes: nodes,connections: connections,settings: settings || {},+ variables_schema: variables_schema,autosaved: autosaved,authors: authors,created_by: user,@@ -165,6 +170,7 @@ module DiscourseWorkflowsnodes: nodes,connections: connections,settings: settings || {},+ variables_schema: variables_schema,autosaved: false,authors: authors,created_by: user,@@ -202,14 +208,17 @@ module DiscourseWorkflowsenddef restore_from_version!(version, user:)- update!(- name: version.name,- nodes: version.nodes || [],- connections: version.connections || {},- settings: version.settings || {},- version_id: version.version_id,- updated_by: user,- )+ transaction do+ update!(+ name: version.name,+ nodes: version.nodes || [],+ connections: version.connections || {},+ settings: version.settings || {},+ version_id: version.version_id,+ updated_by: user,+ )+ restore_variables_from!(version.variables_schema, user:)+ endenddef published?@@ -231,10 +240,15 @@ module DiscourseWorkflowsnodes: nodes || [],connections: connections || {},settings: settings || {},+ variables_schema: variables_schema,}.to_json,)end+ def variables_schema+ variables.order(:id).map(&:to_version_entry)+ end+def find_node_in(node_collection, node_id)node_id_str = node_id.to_snode_collection.find { |n| n["id"] == node_id_str }@@ -384,6 +398,25 @@ module DiscourseWorkflowsupdated_at: Time.current,)end++ def restore_variables_from!(schema, user:)+ desired_by_key = Array(schema).index_by { |field| field["key"] }+ existing_by_key = variables.index_by(&:key)++ keys_to_remove = existing_by_key.keys - desired_by_key.keys+ variables.where(key: keys_to_remove).delete_all if keys_to_remove.any?++ desired_by_key.each do |key, field|+ record = existing_by_key[key]+ record ||= variables.new(key: key, created_by: user)+ record.update!(+ description: field["description"],+ variable_type: field["type"],+ type_options: field["type_options"] || {},+ value: field["value"],+ )+ end+ endendenddiff --git a/plugins/discourse-workflows/app/models/discourse_workflows/workflow_version.rb b/plugins/discourse-workflows/app/models/discourse_workflows/workflow_version.rbindex c1ae15ccbcb..329a75f953a 100644--- a/plugins/discourse-workflows/app/models/discourse_workflows/workflow_version.rb+++ b/plugins/discourse-workflows/app/models/discourse_workflows/workflow_version.rb@@ -14,6 +14,7 @@ module DiscourseWorkflowsattribute :nodes, default: -> { [] }attribute :connections, default: -> { {} }attribute :settings, default: -> { {} }+ attribute :variables_schema, default: -> { [] }validates :version_id, presence: true, length: { maximum: 36 }validates :workflow_id, :version_number, :name, :created_by_id, presence: true@@ -44,19 +45,20 @@ end## Table name: discourse_workflows_workflow_versions#-# authors :text-# autosaved :boolean default(FALSE), not null-# connections :jsonb not null-# name :string(100) not null-# nodes :jsonb not null-# settings :jsonb not null-# version_number :integer not null-# created_at :datetime not null-# updated_at :datetime not null-# created_by_id :integer not null-# updated_by_id :integer-# version_id :string(36) not null, primary key-# workflow_id :bigint not null+# authors :text+# autosaved :boolean default(FALSE), not null+# connections :jsonb not null+# name :string(100) not null+# nodes :jsonb not null+# settings :jsonb not null+# variables_schema :jsonb not null+# version_number :integer not null+# created_at :datetime not null+# updated_at :datetime not null+# created_by_id :integer not null+# updated_by_id :integer+# version_id :string(36) not null, primary key+# workflow_id :bigint not null## Indexes#diff --git a/plugins/discourse-workflows/app/serializers/discourse_workflows/workflow_serializer.rb b/plugins/discourse-workflows/app/serializers/discourse_workflows/workflow_serializer.rbindex 4992b2f9b36..7032436707f 100644--- a/plugins/discourse-workflows/app/serializers/discourse_workflows/workflow_serializer.rb+++ b/plugins/discourse-workflows/app/serializers/discourse_workflows/workflow_serializer.rb@@ -21,6 +21,7 @@ module DiscourseWorkflows:last_execution_at,:last_execution_run_data,:pin_data,+ :variables,:tagsattribute :created_by@@ -123,5 +124,16 @@ module DiscourseWorkflowsdef include_pin_data?!object.attributes.key?("last_execution_status_value")end++ def variables+ object+ .variables+ .order(:id)+ .map { |variable| WorkflowVariableSerializer.new(variable, root: false).as_json }+ end++ def include_variables?+ !object.attributes.key?("last_execution_status_value")+ endendenddiff --git a/plugins/discourse-workflows/app/serializers/discourse_workflows/workflow_variable_serializer.rb b/plugins/discourse-workflows/app/serializers/discourse_workflows/workflow_variable_serializer.rbnew file mode 100644index 00000000000..b68b4a197d8--- /dev/null+++ b/plugins/discourse-workflows/app/serializers/discourse_workflows/workflow_variable_serializer.rb@@ -0,0 +1,7 @@+# frozen_string_literal: true++module DiscourseWorkflows+ class WorkflowVariableSerializer < ApplicationSerializer+ attributes :id, :key, :label, :description, :variable_type, :type_options, :value+ end+enddiff --git a/plugins/discourse-workflows/app/services/discourse_workflows/expression/evaluate.rb b/plugins/discourse-workflows/app/services/discourse_workflows/expression/evaluate.rbindex 038c5f06fbc..9c656dff498 100644--- a/plugins/discourse-workflows/app/services/discourse_workflows/expression/evaluate.rb+++ b/plugins/discourse-workflows/app/services/discourse_workflows/expression/evaluate.rb@@ -15,6 +15,7 @@ module DiscourseWorkflowspolicy :can_manage_workflows, class_name: Policy::CanManageWorkflowsmodel :workflow, optional: truemodel :preview_context, :build_preview_context+ model :workflow_variable_values, :resolve_workflow_variable_values, optional: truemodel :segments, :resolve_segments, optional: trueprivate@@ -27,10 +28,17 @@ module DiscourseWorkflowsWorkflow::Action::BuildExpressionPreviewContext.call(workflow:, node_id: params.node_id)end- def resolve_segments(params:, preview_context:, guardian:)+ def resolve_workflow_variable_values(workflow:)+ return {} unless workflow++ WorkflowVariableValueResolver.new(workflow.variables_schema).resolve+ end++ def resolve_segments(params:, preview_context:, workflow_variable_values:, guardian:)ExpressionResolver.resolve_segments(params.template,context: preview_context,+ workflow_vars: workflow_variable_values,user: guardian.user,)enddiff --git a/plugins/discourse-workflows/app/services/discourse_workflows/variable/destroy.rb b/plugins/discourse-workflows/app/services/discourse_workflows/variable/destroy.rbindex 1f6eb3fa0b9..4f565b80ff3 100644--- a/plugins/discourse-workflows/app/services/discourse_workflows/variable/destroy.rb+++ b/plugins/discourse-workflows/app/services/discourse_workflows/variable/destroy.rb@@ -19,7 +19,7 @@ module DiscourseWorkflowsprivatedef fetch_variable(params:)- DiscourseWorkflows::Variable.find_by(id: params.variable_id)+ DiscourseWorkflows::Variable.where(workflow_id: nil).find_by(id: params.variable_id)enddef log_variable_deletion(variable:, guardian:)diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/variable/list.rb b/plugins/discourse-workflows/app/services/discourse_workflows/variable/list.rbindex 255d9f829f3..e28cce01441 100644--- a/plugins/discourse-workflows/app/services/discourse_workflows/variable/list.rb+++ b/plugins/discourse-workflows/app/services/discourse_workflows/variable/list.rb@@ -20,7 +20,8 @@ module DiscourseWorkflowsprivatedef fetch_variables(params:)- scope = DiscourseWorkflows::Variable.includes(:created_by).order(id: :desc)+ scope =+ DiscourseWorkflows::Variable.where(workflow_id: nil).includes(:created_by).order(id: :desc)context[:page] = DiscourseWorkflows::Pagination.cursor_page(scope: scope,cursor: params.cursor,diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/variable/update.rb b/plugins/discourse-workflows/app/services/discourse_workflows/variable/update.rbindex d33f8a19531..e1c105a054f 100644--- a/plugins/discourse-workflows/app/services/discourse_workflows/variable/update.rb+++ b/plugins/discourse-workflows/app/services/discourse_workflows/variable/update.rb@@ -32,7 +32,7 @@ module DiscourseWorkflowsprivatedef fetch_variable(params:)- DiscourseWorkflows::Variable.find_by(id: params.variable_id)+ DiscourseWorkflows::Variable.where(workflow_id: nil).find_by(id: params.variable_id)enddef save_variable(variable:, params:)diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow_variable/create.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow_variable/create.rbnew file mode 100644index 00000000000..8d7a9194d11--- /dev/null+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow_variable/create.rb@@ -0,0 +1,81 @@+# frozen_string_literal: true++module DiscourseWorkflows+ class WorkflowVariable::Create+ include Service::Base++ params do+ attribute :workflow_id, :integer+ attribute :key, :string+ attribute :description, :string+ attribute :variable_type, :string+ attribute :type_options, default: -> { {} }++ validates :workflow_id, presence: true+ validates :key,+ presence: true,+ length: {+ maximum: 100,+ },+ format: {+ with: /\A[a-zA-Z_][a-zA-Z0-9_]*\z/,+ }+ validates :description, length: { maximum: 500 }, allow_nil: true+ validates :variable_type,+ presence: true,+ inclusion: {+ in: DiscourseWorkflows::Variable::VARIABLE_TYPES,+ }+ validate :type_options_is_a_hash++ def type_options_is_a_hash+ errors.add(:type_options, :invalid) unless type_options.is_a?(Hash)+ end+ end++ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows++ lock(:workflow_id) do+ model :workflow++ transaction do+ model :variable, :create_variable+ model :workflow_version, :snapshot_workflow+ step :index_dependencies+ end+ end++ step :log_variable_creation++ private++ def fetch_workflow(params:)+ DiscourseWorkflows::Workflow.find_by(id: params.workflow_id)+ end++ def create_variable(workflow:, params:, guardian:)+ workflow.variables.create(+ key: params.key,+ description: params.description,+ variable_type: params.variable_type,+ type_options: params.type_options,+ created_by: guardian.user,+ )+ end++ def snapshot_workflow(workflow:, guardian:)+ workflow.snapshot!(user: guardian.user)+ end++ def index_dependencies(workflow:, workflow_version:)+ DiscourseWorkflows::WorkflowDependencyIndexer.call(workflow, version: workflow_version)+ end++ def log_variable_creation(variable:, guardian:)+ StaffActionLogger.new(guardian.user).log_custom(+ "discourse_workflows_workflow_variable_created",+ subject: variable.key,+ )+ end+ end+enddiff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow_variable/destroy.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow_variable/destroy.rbnew file mode 100644index 00000000000..cc3f54389c0--- /dev/null+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow_variable/destroy.rb@@ -0,0 +1,58 @@+# frozen_string_literal: true++module DiscourseWorkflows+ class WorkflowVariable::Destroy+ include Service::Base++ params do+ attribute :workflow_id, :integer+ attribute :variable_id, :integer++ validates :workflow_id, :variable_id, presence: true+ end++ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows++ lock(:workflow_id) do+ model :workflow+ model :variable++ transaction do+ step :destroy_variable+ model :workflow_version, :snapshot_workflow+ step :index_dependencies+ end+ end++ step :log_variable_deletion++ private++ def fetch_workflow(params:)+ DiscourseWorkflows::Workflow.find_by(id: params.workflow_id)+ end++ def fetch_variable(workflow:, params:)+ workflow.variables.find_by(id: params.variable_id)+ end++ def destroy_variable(variable:)+ variable.destroy!+ end++ def snapshot_workflow(workflow:, guardian:)+ workflow.snapshot!(user: guardian.user)+ end++ def index_dependencies(workflow:, workflow_version:)+ DiscourseWorkflows::WorkflowDependencyIndexer.call(workflow, version: workflow_version)+ end++ def log_variable_deletion(variable:, guardian:)+ StaffActionLogger.new(guardian.user).log_custom(+ "discourse_workflows_workflow_variable_destroyed",+ subject: variable.key,+ )+ end+ end+enddiff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow_variable/import_definitions.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow_variable/import_definitions.rbnew file mode 100644index 00000000000..456b21ae0f0--- /dev/null+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow_variable/import_definitions.rb@@ -0,0 +1,104 @@+# frozen_string_literal: true++module DiscourseWorkflows+ class WorkflowVariable::ImportDefinitions+ include Service::Base++ params do+ attribute :workflow_id, :integer+ attribute :variables, default: -> { [] }++ validates :workflow_id, presence: true+ validate :variables_is_an_array_of_hashes++ def variables_is_an_array_of_hashes+ return if variables.is_a?(Array) && variables.all? { |field| field.is_a?(Hash) }++ errors.add(:variables, :invalid)+ end+ end++ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows++ lock(:workflow_id) do+ model :workflow++ transaction do+ model :imported_variables, :import_variables+ only_if(:imported_any_variables) do+ model :workflow_version, :snapshot_workflow+ step :index_dependencies+ end+ end+ end++ step :log_variables_import++ private++ def fetch_workflow(params:)+ DiscourseWorkflows::Workflow.find_by(id: params.workflow_id)+ end++ # Skips (rather than overwrites) any imported variable whose key already+ # exists on this workflow, so an import can never silently clobber an+ # existing variable's type/options.+ def import_variables(workflow:, params:, guardian:)+ existing_keys = workflow.variables.pluck(:key).to_set+ created = []+ skipped = []++ Array(params.variables).each do |raw_field|+ field = raw_field.with_indifferent_access+ key = field["key"].presence+ next if key.blank?++ if existing_keys.include?(key)+ skipped << key+ next+ end++ new_variable =+ workflow.variables.create(+ key: key,+ description: field["description"],+ variable_type: field["variable_type"].presence || "string",+ type_options: field["type_options"].is_a?(Hash) ? field["type_options"] : {},+ created_by: guardian.user,+ )++ if new_variable.persisted?+ created << new_variable+ existing_keys << key+ else+ skipped << key+ end+ end++ { created:, skipped: }+ end++ def imported_any_variables(imported_variables:)+ imported_variables[:created].any?+ end++ def snapshot_workflow(workflow:, guardian:)+ workflow.snapshot!(user: guardian.user)+ end++ def index_dependencies(workflow:, workflow_version:)+ DiscourseWorkflows::WorkflowDependencyIndexer.call(workflow, version: workflow_version)+ end++ def log_variables_import(workflow:, imported_variables:, guardian:)+ return if imported_variables[:created].empty?++ StaffActionLogger.new(guardian.user).log_custom(+ "discourse_workflows_workflow_variables_imported",+ subject: workflow.name,+ created_count: imported_variables[:created].size,+ skipped_count: imported_variables[:skipped].size,+ )+ end+ end+enddiff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow_variable/policy/existing_value_compatible_with_new_type.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow_variable/policy/existing_value_compatible_with_new_type.rbnew file mode 100644index 00000000000..596fadd71a5--- /dev/null+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow_variable/policy/existing_value_compatible_with_new_type.rb@@ -0,0 +1,19 @@+# frozen_string_literal: true++module DiscourseWorkflows+ class WorkflowVariable::Policy::ExistingValueCompatibleWithNewType < Service::PolicyBase+ delegate :variable, :params, to: :context, private: true++ def call+ DiscourseWorkflows::Variable.value_valid_for_type?(+ value: variable.value,+ variable_type: params.variable_type,+ type_options: params.type_options,+ )+ end++ def reason+ I18n.t("discourse_workflows.errors.workflow_variable.incompatible_value_for_new_type")+ end+ end+enddiff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow_variable/policy/value_is_valid.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow_variable/policy/value_is_valid.rbnew file mode 100644index 00000000000..356952bb0b8--- /dev/null+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow_variable/policy/value_is_valid.rb@@ -0,0 +1,19 @@+# frozen_string_literal: true++module DiscourseWorkflows+ class WorkflowVariable::Policy::ValueIsValid < Service::PolicyBase+ delegate :variable, :params, to: :context, private: true++ def call+ DiscourseWorkflows::Variable.value_valid_for_type?(+ value: params.value,+ variable_type: variable.variable_type,+ type_options: variable.type_options,+ )+ end++ def reason+ I18n.t("discourse_workflows.errors.workflow_variable.invalid_value")+ end+ end+enddiff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow_variable/update.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow_variable/update.rbnew file mode 100644index 00000000000..076cd1b247f--- /dev/null+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow_variable/update.rb@@ -0,0 +1,108 @@+# frozen_string_literal: true++module DiscourseWorkflows+ class WorkflowVariable::Update+ include Service::Base++ params do+ attribute :workflow_id, :integer+ attribute :variable_id, :integer+ attribute :key, :string+ attribute :description, :string+ attribute :variable_type, :string+ attribute :type_options, default: -> { {} }++ validates :workflow_id, :variable_id, presence: true+ validates :key,+ presence: true,+ length: {+ maximum: 100,+ },+ format: {+ with: /\A[a-zA-Z_][a-zA-Z0-9_]*\z/,+ }+ validates :description, length: { maximum: 500 }, allow_nil: true+ validates :variable_type,+ presence: true,+ inclusion: {+ in: DiscourseWorkflows::Variable::VARIABLE_TYPES,+ }+ validate :type_options_is_a_hash++ def type_options_is_a_hash+ errors.add(:type_options, :invalid) unless type_options.is_a?(Hash)+ end+ end++ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows++ lock(:workflow_id) do+ model :workflow+ model :variable+ model :previous_definition, :capture_previous_definition+ only_if(:variable_type_or_options_changing) do+ policy :existing_value_compatible_with_new_type,+ class_name: WorkflowVariable::Policy::ExistingValueCompatibleWithNewType+ end++ transaction do+ model :variable, :save_variable+ only_if(:definition_changed) do+ model :workflow_version, :snapshot_workflow+ step :index_dependencies+ end+ end+ end++ step :log_variable_update++ private++ def fetch_workflow(params:)+ DiscourseWorkflows::Workflow.find_by(id: params.workflow_id)+ end++ def fetch_variable(workflow:, params:)+ workflow.variables.find_by(id: params.variable_id)+ end++ def capture_previous_definition(variable:)+ variable.definition+ end++ def variable_type_or_options_changing(variable:, params:)+ variable.variable_type != params.variable_type || variable.type_options != params.type_options+ end++ def save_variable(variable:, params:)+ variable.tap do |v|+ v.assign_attributes(+ key: params.key,+ description: params.description,+ variable_type: params.variable_type,+ type_options: params.type_options,+ )+ v.save+ end+ end++ def definition_changed(variable:, previous_definition:)+ variable.definition != previous_definition+ end++ def snapshot_workflow(workflow:, guardian:)+ workflow.snapshot!(user: guardian.user)+ end++ def index_dependencies(workflow:, workflow_version:)+ DiscourseWorkflows::WorkflowDependencyIndexer.call(workflow, version: workflow_version)+ end++ def log_variable_update(variable:, guardian:)+ StaffActionLogger.new(guardian.user).log_custom(+ "discourse_workflows_workflow_variable_updated",+ subject: variable.key,+ )+ end+ end+enddiff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow_variable/update_value.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow_variable/update_value.rbnew file mode 100644index 00000000000..698dd831e6d--- /dev/null+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow_variable/update_value.rb@@ -0,0 +1,99 @@+# frozen_string_literal: true++module DiscourseWorkflows+ class WorkflowVariable::UpdateValue+ include Service::Base++ MAX_VALUE_LENGTH = 10_000++ params do+ attribute :workflow_id, :integer+ attribute :variable_id, :integer+ attribute :value, :string++ validates :workflow_id, :variable_id, presence: true+ validates :value, length: { maximum: MAX_VALUE_LENGTH }, allow_nil: true+ end++ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows++ lock(:workflow_id) do+ model :workflow+ model :variable+ policy :value_is_valid, class_name: WorkflowVariable::Policy::ValueIsValid+ model :draft_was_clean, :capture_draft_was_clean, optional: true++ transaction do+ model :variable, :save_value+ model :workflow_version, :snapshot_workflow+ step :index_dependencies+ end++ # A separate transaction: if publishing fails (e.g. a webhook route+ # collision), the value save above must still stand, matching how a+ # manual Publish click can fail without undoing the draft edit it+ # follows.+ only_if(:should_auto_publish) do+ transaction do+ step :publish_workflow+ step :activate_triggers+ end+ end+ end++ step :expire_workflow_caches++ private++ def fetch_workflow(params:)+ DiscourseWorkflows::Workflow.find_by(id: params.workflow_id)+ end++ def fetch_variable(workflow:, params:)+ workflow.variables.find_by(id: params.variable_id)+ end++ # Must run before the transaction below: snapshot_workflow mutates+ # workflow.version_id, so this is the only point this is knowable.+ def capture_draft_was_clean(workflow:)+ workflow.published? && workflow.version_id == workflow.active_version_id+ end++ def save_value(variable:, params:)+ variable.tap { |v| v.update(value: params.value) }+ end++ def snapshot_workflow(workflow:, guardian:)+ workflow.snapshot!(user: guardian.user)+ end++ def index_dependencies(workflow:, workflow_version:)+ DiscourseWorkflows::WorkflowDependencyIndexer.call(workflow, version: workflow_version)+ end++ # Passthrough of the pre-transaction value, not a recompute.+ def should_auto_publish(draft_was_clean:)+ draft_was_clean+ end++ def publish_workflow(workflow:, guardian:)+ workflow.publish!(user: guardian.user)+ end++ def activate_triggers(workflow:, workflow_version:)+ TriggerRuntime.activate_workflow!(workflow, workflow_version: workflow_version)+ rescue Webhook::Action::ActivateWebhooks::CollisionError => e+ fail!(+ I18n.t(+ "discourse_workflows.errors.webhook_route_collision",+ method: e.method,+ path: "/#{e.path}",+ ),+ )+ end++ def expire_workflow_caches+ Workflow::Action::ExpireCaches.call+ end+ end+enddiff --git a/plugins/discourse-workflows/assets/stylesheets/common/canvas/canvas.scss b/plugins/discourse-workflows/assets/stylesheets/common/canvas/canvas.scssindex d9122eb8fa8..eb2ae8cc30b 100644--- a/plugins/discourse-workflows/assets/stylesheets/common/canvas/canvas.scss+++ b/plugins/discourse-workflows/assets/stylesheets/common/canvas/canvas.scss@@ -142,10 +142,6 @@text-align: center;}- &__publish-btn {- min-width: 6.5em;- }-&__top-bar {position: absolute;top: var(--space-2);@@ -166,65 +162,6 @@&__publish-status {grid-column: 1;justify-self: center;- display: flex;- align-items: center;- gap: var(--space-4);- min-width: 0;- max-width: min(100%, 36rem);- padding: var(--space-1) var(--space-2);- border: 1px solid var(--primary-low-mid);- border-radius: var(--d-border-radius);- background: var(--secondary);- box-shadow: 0 2px 8px rgb(0, 0, 0, 0.1);- }-- &__publish-status-body {- display: flex;- align-items: flex-start;- gap: var(--space-2);- min-width: 0;- line-height: 1.2;- }-- &__publish-status-icon {- flex: 0 0 auto;- margin-top: 0.1rem;- color: var(--workflow-status-running);- font-size: var(--font-down-1);- }-- &__publish-status-text {- display: flex;- flex-direction: column;- min-width: 0;- }-- &__publish-status-title {- overflow: hidden;- color: var(--primary-high);- font-size: var(--font-down-1);- font-weight: 600;- text-overflow: ellipsis;- white-space: nowrap;- }-- &__publish-status-detail {- overflow: hidden;- color: var(--primary-medium);- font-size: var(--font-down-2);- text-overflow: ellipsis;- white-space: nowrap;- }-- &__publish-status-btn {- flex: 0 0 auto;- }-- &__publish-status-actions {- display: flex;- flex: 0 0 auto;- align-items: center;- gap: var(--space-1);}&__toolbar-top-right {diff --git a/plugins/discourse-workflows/assets/stylesheets/common/index.scss b/plugins/discourse-workflows/assets/stylesheets/common/index.scssindex a085e68cc28..1e3457d1fa6 100644--- a/plugins/discourse-workflows/assets/stylesheets/common/index.scss+++ b/plugins/discourse-workflows/assets/stylesheets/common/index.scss@@ -2,6 +2,8 @@@import "workflows-index";@import "tags";@import "editor/editor";+@import "publish-banner";+@import "variables-publish-notice";@import "canvas/canvas";@import "canvas/ai-build-tool";@import "canvas/hover-toolbar";@@ -21,6 +23,7 @@@import "executions/execution-detail";@import "data-table/data-tables";@import "settings";+@import "variables";@import "form/workflows-form";@import "empty-state";@import "templates";diff --git a/plugins/discourse-workflows/assets/stylesheets/common/publish-banner.scss b/plugins/discourse-workflows/assets/stylesheets/common/publish-banner.scssnew file mode 100644index 00000000000..99ac63b2f4d--- /dev/null+++ b/plugins/discourse-workflows/assets/stylesheets/common/publish-banner.scss@@ -0,0 +1,61 @@+.workflows-publish-banner {+ display: flex;+ align-items: center;+ gap: var(--space-4);+ min-width: 0;+ max-width: min(100%, 36rem);+ padding: var(--space-1) var(--space-2);+ border: 1px solid var(--primary-low-mid);+ border-radius: var(--d-border-radius);+ background: var(--secondary);+ box-shadow: 0 2px 8px rgb(0, 0, 0, 0.1);++ &__body {+ display: flex;+ align-items: flex-start;+ gap: var(--space-2);+ min-width: 0;+ line-height: 1.2;+ }++ &__icon {+ flex: 0 0 auto;+ margin-top: 0.1rem;+ color: var(--workflow-status-running);+ font-size: var(--font-down-1);+ }++ &__text {+ display: flex;+ flex-direction: column;+ min-width: 0;+ }++ &__title {+ overflow: hidden;+ color: var(--primary-high);+ font-size: var(--font-down-1);+ font-weight: 600;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ &__detail {+ overflow: hidden;+ color: var(--primary-medium);+ font-size: var(--font-down-2);+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ &__btn {+ flex: 0 0 auto;+ }++ &__actions {+ display: flex;+ flex: 0 0 auto;+ align-items: center;+ gap: var(--space-1);+ }+}diff --git a/plugins/discourse-workflows/assets/stylesheets/common/settings.scss b/plugins/discourse-workflows/assets/stylesheets/common/settings.scssindex f722b517e83..9428238d3eb 100644--- a/plugins/discourse-workflows/assets/stylesheets/common/settings.scss+++ b/plugins/discourse-workflows/assets/stylesheets/common/settings.scss@@ -2,6 +2,7 @@display: flex;flex-direction: column;gap: var(--space-6);+ margin-top: var(--space-6);padding: var(--space-4) 0;&__section {diff --git a/plugins/discourse-workflows/assets/stylesheets/common/variables-publish-notice.scss b/plugins/discourse-workflows/assets/stylesheets/common/variables-publish-notice.scssnew file mode 100644index 00000000000..5babe5435be--- /dev/null+++ b/plugins/discourse-workflows/assets/stylesheets/common/variables-publish-notice.scss@@ -0,0 +1,46 @@+.workflows-variables-publish-notice {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-4);+ margin-bottom: var(--space-4);+ padding: var(--space-3) var(--space-4);+ border: 1px solid var(--primary-low);+ border-radius: var(--d-border-radius);++ &__text {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ min-width: 0;+ line-height: 1.2;+ }++ &__icon {+ flex: 0 0 auto;+ color: var(--highlight-high);+ font-size: var(--font-up-1);+ }++ &__copy {+ display: flex;+ flex-direction: column;+ min-width: 0;+ }++ &__title {+ font-size: var(--font-down-1);+ font-weight: 600;+ }++ &__detail {+ font-size: var(--font-down-2);+ }++ &__actions {+ display: flex;+ flex: 0 0 auto;+ align-items: center;+ gap: var(--space-1);+ }+}diff --git a/plugins/discourse-workflows/assets/stylesheets/common/variables.scss b/plugins/discourse-workflows/assets/stylesheets/common/variables.scssnew file mode 100644index 00000000000..0063111e3d5--- /dev/null+++ b/plugins/discourse-workflows/assets/stylesheets/common/variables.scss@@ -0,0 +1,28 @@+.workflows-variables {+ &__field-values {+ margin-top: var(--space-6);++ > .setting:last-child {+ padding-bottom: 0;+ }+ }++ &__manage {+ margin-top: var(--space-6);+ }+}++.workflows-variable-form {+ --form-kit-large-input: 32em;+ margin-top: var(--space-4);+}++.workflows-variable-key {+ display: inline-block;+ color: var(--primary-medium);+ font-size: var(--font-down-2);+}++.workflows-variables-table {+ margin-bottom: var(--space-4);+}diff --git a/plugins/discourse-workflows/config/locales/client.en.yml b/plugins/discourse-workflows/config/locales/client.en.ymlindex e320d8ed93e..b992746c3e3 100644--- a/plugins/discourse-workflows/config/locales/client.en.yml+++ b/plugins/discourse-workflows/config/locales/client.en.yml@@ -152,6 +152,7 @@ en:workflow: "Workflow"executions: "Executions"settings: "Settings"+ workflow_variables: "Variables"versions: "Versions"data_tables: "Data tables"templates: "Templates"@@ -168,6 +169,40 @@ en:timezone_description: "Schedule triggers, time conditions, and date values without a timezone offset use this timezone. If unset, they use the site timezone."danger_zone: "Danger zone"delete_description: "Permanently delete this workflow and all its executions. This action cannot be undone."+ workflow_variables:+ title: "Variables"+ description_will_publish: "Values used by this workflow's nodes. A change publishes immediately."+ description_will_draft: "Values used by this workflow's nodes. Changes are saved as a draft until you publish."+ back: "Back to variables"+ back_to_manage: "Back to manage variables"+ add_variable: "Add variable"+ edit_variable: "Edit variable"+ manage_variables: "Manage variables"+ definitions_description: "Add, edit, or remove the variables this workflow's nodes read values from."+ delete_confirm: "Are you sure you want to delete the variable \"%{label}\"?"+ value_published: "Value published"+ no_variables: "This workflow has no variables yet."+ key: "Key"+ key_description: "How nodes reference this variable's value, e.g. <code>$workflow_vars.my_key</code>."+ key_format_error: "Must start with a letter or underscore, and contain only letters, numbers, and underscores."+ key_duplicate_error: "A variable with this key already exists."+ description: "Description"+ description_description: "Optional help text shown to admins next to this variable's value."+ type: "Type"+ type_description: "The kind of value this variable accepts."+ types:+ string: "String"+ integer: "Integer"+ boolean: "Boolean"+ enum: "Enum"+ category: "Category"+ category_list: "Category list"+ group: "Group"+ group_list: "Group list"+ tag_list: "Tag list"+ simple_list: "Simple list"+ choices: "Choices"+ choices_description: "The options an admin can choose from when setting this variable's value."versions:title: "Versions"version: "Version"@@ -779,6 +814,7 @@ en:trigger: "Trigger"item_index: "Item index"variable: "Variable"+ workflow_variable: "Workflow variable"current_user: "Current user"site_setting: "Site setting"execution: "Execution"@@ -797,7 +833,8 @@ en:trigger: "The trigger node's output data. Example: $trigger.topic.id"site_settings: "Access Discourse site settings. Example: $site_settings.title"current_user: "The user who triggered the workflow. Properties: id, username"- workflow_vars: "Workflow variables defined in the admin panel."+ global_vars: "Global variables shared across all workflows, defined in the admin panel."+ workflow_vars: "This workflow's local variables."execution: "Execution metadata: id, workflow_id, workflow_name"node_ref: "Reference a previous node's output. Example: $('Node Name').item.json"helpers: "Utility functions. Currently: $helpers.absoluteUrl(path)."@@ -1567,6 +1604,7 @@ en:import_nodes: "Import"import_error: "Failed to import: invalid file format"import_version_error: "Failed to import: unsupported format version"+ import_variables_skipped: "Skipped %{count} variable(s) already on this workflow: %{keys}"max_nodes_reached: "Workflows are limited to %{max} nodes"sync_error: "Failed to sync canvas changes. Please reload the page."sticky_note:diff --git a/plugins/discourse-workflows/config/locales/server.en.yml b/plugins/discourse-workflows/config/locales/server.en.ymlindex 4b45e8e0da7..85e8fafea29 100644--- a/plugins/discourse-workflows/config/locales/server.en.yml+++ b/plugins/discourse-workflows/config/locales/server.en.yml@@ -6,6 +6,10 @@ en:attributes:error_workflow_id:cannot_be_self: "cannot be set to the workflow itself"+ discourse_workflows/variable:+ attributes:+ type_options:+ enum_choices_required: "must include at least one choice for an enum field"discourse_workflows:ai:default_code_node_name: "Code"@@ -48,6 +52,9 @@ en:too_many_tags: "A workflow can have at most %{max} tags."tag_too_long: "Tags can have at most %{max} characters."tag_contains_comma: "Tags cannot contain commas."+ workflow_variable:+ invalid_value: "is not valid for this field's type"+ incompatible_value_for_new_type: "has a current value that is not valid for the new type. Update or clear the value first."approval_timed_out: "Approval timed out"rate_limited:global:diff --git a/plugins/discourse-workflows/config/routes.rb b/plugins/discourse-workflows/config/routes.rbindex d41021ead30..034c54ff1f6 100644--- a/plugins/discourse-workflows/config/routes.rb+++ b/plugins/discourse-workflows/config/routes.rb@@ -26,6 +26,14 @@ DiscourseWorkflows::Engine.routes.draw doexecution_id: /\d+/,}get "/workflows/:id/settings" => "admin#index", :constraints => { id: /\d+/ }+ get "/workflows/:id/variables" => "admin#index", :constraints => { id: /\d+/ }+ get "/workflows/:id/variables/manage" => "admin#index", :constraints => { id: /\d+/ }+ get "/workflows/:id/variables/new" => "admin#index", :constraints => { id: /\d+/ }+ get "/workflows/:id/variables/:variable_id/edit" => "admin#index",+ :constraints => {+ id: /\d+/,+ variable_id: /\d+/,+ }get "/workflows/:id/versions" => "admin#index", :constraints => { id: /\d+/ }end@@ -59,6 +67,12 @@ DiscourseWorkflows::Engine.routes.draw do:constraints => {version_id: /[0-9a-f-]{36}/,}+ post "/workflows/:workflow_id/variables" => "workflow_variables#create"+ post "/workflows/:workflow_id/variables/import" => "workflow_variables#import"+ put "/workflows/:workflow_id/variables/:variable_id" => "workflow_variables#update"+ delete "/workflows/:workflow_id/variables/:variable_id" => "workflow_variables#destroy"+ put "/workflows/:workflow_id/variables/:variable_id/value" =>+ "workflow_variables#update_value"delete "/executions" => "executions#destroy"get "/executions/:id" => "executions#show"get "/stats" => "stats#index"diff --git a/plugins/discourse-workflows/db/migrate/20260904171256_add_variables_schema_to_workflow_versions.rb b/plugins/discourse-workflows/db/migrate/20260904171256_add_variables_schema_to_workflow_versions.rbnew file mode 100644index 00000000000..5ec210367af--- /dev/null+++ b/plugins/discourse-workflows/db/migrate/20260904171256_add_variables_schema_to_workflow_versions.rb@@ -0,0 +1,10 @@+# frozen_string_literal: true+class AddVariablesSchemaToWorkflowVersions < ActiveRecord::Migration[8.0]+ def change+ add_column :discourse_workflows_workflow_versions,+ :variables_schema,+ :jsonb,+ null: false,+ default: []+ end+enddiff --git a/plugins/discourse-workflows/db/migrate/20260913105655_add_workflow_scope_to_variables.rb b/plugins/discourse-workflows/db/migrate/20260913105655_add_workflow_scope_to_variables.rbnew file mode 100644index 00000000000..4f24ecdb6b9--- /dev/null+++ b/plugins/discourse-workflows/db/migrate/20260913105655_add_workflow_scope_to_variables.rb@@ -0,0 +1,27 @@+# frozen_string_literal: true+class AddWorkflowScopeToVariables < ActiveRecord::Migration[8.0]+ def change+ add_column :discourse_workflows_variables, :workflow_id, :bigint+ add_column :discourse_workflows_variables,+ :variable_type,+ :string,+ limit: 30,+ null: false,+ default: "string"+ add_column :discourse_workflows_variables, :type_options, :jsonb, null: false, default: {}+ change_column :discourse_workflows_variables, :value, :text, default: nil+ change_column_null :discourse_workflows_variables, :value, true++ remove_index :discourse_workflows_variables, :key, name: "idx_dwf_variables_on_key"+ add_index :discourse_workflows_variables,+ %i[workflow_id key],+ unique: true,+ where: "workflow_id IS NOT NULL",+ name: "idx_dwf_variables_on_workflow_key"+ add_index :discourse_workflows_variables,+ :key,+ unique: true,+ where: "workflow_id IS NULL",+ name: "idx_dwf_variables_on_key_global"+ end+enddiff --git a/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_node_catalog.rb b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_node_catalog.rbindex 4ac8ace55a1..cb3e140a7ce 100644--- a/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_node_catalog.rb+++ b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_node_catalog.rb@@ -268,7 +268,7 @@ module DiscourseWorkflowsNOTES = {"action:code" => [- "The default value of the code property documents the runtime variables: $input, $json, $(\"Node name\"), $vars, $site_settings, $execution, $current_user, $helpers and console.",+ "The default value of the code property documents the runtime variables: $input, $json, $(\"Node name\"), $vars, $workflow_vars, $site_settings, $execution, $current_user, $helpers and console.","runOnceForAllItems must return an array of items such as [{ json: { ... } }]; plain objects are normalized under json.","runOnceForEachItem must return one object per input item, not an array, and cannot use $input.first, $input.last, $input.all or $input.itemMatching.","Output items may use the reserved keys json, pairedItem, error and index; do not mix them with plain fields.",diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor.rbindex 9c8e4d0376d..9b75eb965fe 100644--- a/plugins/discourse-workflows/lib/discourse_workflows/executor.rb+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor.rb@@ -569,6 +569,7 @@ module DiscourseWorkflowsuser: @options.user,resolver:,vars: preloaded_vars,+ workflow_vars: preloaded_workflow_vars,workflow: @workflow,workflow_version: @options.workflow_version,execution_id: @store.execution&.id,@@ -1120,12 +1121,35 @@ module DiscourseWorkflows@context.resolver_context,user: @options.user,vars: preloaded_vars,+ workflow_vars: preloaded_workflow_vars,budget_tracker: sandbox_budget_tracker,)enddef preloaded_vars- @preloaded_vars ||= DiscourseWorkflows::Variable.pluck(:key, :value).to_h+ @preloaded_vars ||=+ DiscourseWorkflows::Variable.where(workflow_id: nil).pluck(:key, :value).to_h+ end++ # Mirrors the same nodes/connections source-selection above: whatever+ # variables schema a workflow_snapshot was built with (a resume, a node+ # preview, a step execution, a form test session) travels with it, the+ # same way its nodes/connections do.+ def preloaded_workflow_vars+ @preloaded_workflow_vars ||=+ DiscourseWorkflows::WorkflowVariableValueResolver.new(variables_schema).resolve+ end++ def variables_schema+ if @options.workflow_snapshot+ @options.workflow_snapshot.variables_schema+ elsif @options.workflow_version+ @options.workflow_version.variables_schema+ elsif @options.draft_execution+ @workflow.variables_schema+ else+ @workflow.active_version&.variables_schema || []+ endenddef preloaded_workflow_dependenciesdiff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/code_runner.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/code_runner.rbindex 16c80ebadab..6da26869f77 100644--- a/plugins/discourse-workflows/lib/discourse_workflows/executor/code_runner.rb+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/code_runner.rb@@ -27,6 +27,7 @@ module DiscourseWorkflowsresolver_context:,user:,vars:,+ workflow_vars:,flow_context:,runtime_state:)@@ -36,6 +37,7 @@ module DiscourseWorkflows@resolver_context = resolver_context || {}@user = user@vars = vars+ @workflow_vars = workflow_vars@flow_context = flow_context || {}@runtime_state = runtime_stateend@@ -114,6 +116,7 @@ module DiscourseWorkflowsresolver_context_for_item_index(item_index),user: @user,vars: @vars,+ workflow_vars: @workflow_vars,capture_logs: capture_logs,budget_tracker: sandbox_budget_tracker,)diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/node_execution_context.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/node_execution_context.rbindex 529701b1ce4..48fa0f31fde 100644--- a/plugins/discourse-workflows/lib/discourse_workflows/executor/node_execution_context.rb+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/node_execution_context.rb@@ -132,6 +132,7 @@ module DiscourseWorkflowsuser: nil,resolver: nil,vars: nil,+ workflow_vars: nil,workflow: nil,workflow_version: nil,execution_id: nil,@@ -166,6 +167,7 @@ module DiscourseWorkflows@user = user@resolver = resolver@vars = vars+ @workflow_vars = workflow_vars@workflow = workflow@workflow_version = workflow_version@execution_id = execution_id@@ -770,6 +772,7 @@ module DiscourseWorkflowsresolver_context: @resolver_context,user: @user,vars: @vars,+ workflow_vars: @workflow_vars,flow_context: @flow_context,runtime_state: @runtime_state,)diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/webhook_execution_context.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/webhook_execution_context.rbindex 33c7d6b426e..7bab0275485 100644--- a/plugins/discourse-workflows/lib/discourse_workflows/executor/webhook_execution_context.rb+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/webhook_execution_context.rb@@ -108,7 +108,12 @@ module DiscourseWorkflows)resolver_context.merge!("$json" => current_item.fetch("json") { {} })- @sandbox = DiscourseWorkflows::JsSandbox.new(resolver_context, user: user)+ @sandbox =+ DiscourseWorkflows::JsSandbox.new(+ resolver_context,+ user: user,+ workflow_vars: preloaded_workflow_vars,+ )@resolver =DiscourseWorkflows::ExpressionResolver.new(resolver_context,@@ -127,6 +132,7 @@ module DiscourseWorkflowsnode_context: node_context,user: user,resolver: @resolver,+ workflow_vars: preloaded_workflow_vars,workflow: @execution.workflow,execution_id: @execution.id,resume_token: @execution.resume_token,@@ -139,6 +145,14 @@ module DiscourseWorkflows)end+ # Resolves from the same frozen snapshot the rest of this execution's+ # node graph comes from, so $workflow_vars never mixes an old execution+ # graph with a newer, unrelated variable value.+ def preloaded_workflow_vars+ @preloaded_workflow_vars ||=+ DiscourseWorkflows::WorkflowVariableValueResolver.new(@snapshot.variables_schema).resolve+ end+def execution_snapshotif @execution.execution_data&.workflow_data.present?WorkflowSnapshot.new(@execution.execution_data.workflow_data)diff --git a/plugins/discourse-workflows/lib/discourse_workflows/expression_context_schema.rb b/plugins/discourse-workflows/lib/discourse_workflows/expression_context_schema.rbindex aceefa77f7c..1dd56d75177 100644--- a/plugins/discourse-workflows/lib/discourse_workflows/expression_context_schema.rb+++ b/plugins/discourse-workflows/lib/discourse_workflows/expression_context_schema.rb@@ -12,6 +12,9 @@ module DiscourseWorkflows"$vars" => {type: :object,},+ "$workflow_vars" => {+ type: :object,+ },"$current_user" => {type: :object,provided_by_trigger: true,diff --git a/plugins/discourse-workflows/lib/discourse_workflows/expression_resolver.rb b/plugins/discourse-workflows/lib/discourse_workflows/expression_resolver.rbindex b81deeeccaf..d3a362107c9 100644--- a/plugins/discourse-workflows/lib/discourse_workflows/expression_resolver.rb+++ b/plugins/discourse-workflows/lib/discourse_workflows/expression_resolver.rb@@ -32,15 +32,17 @@ module DiscourseWorkflowswith_owned_sandbox(context, user: user) { |resolver| resolver.resolve_hash(hash) }end- def self.resolve_segments(template, context: {}, user: nil)- with_owned_sandbox(context, user: user) { |resolver| resolver.resolve_segments(template) }+ def self.resolve_segments(template, context: {}, user: nil, workflow_vars: nil)+ with_owned_sandbox(context, user: user, workflow_vars: workflow_vars) do |resolver|+ resolver.resolve_segments(template)+ endrescue MiniRacer::Error, JsSandbox::BudgetExceededError, JsSandbox::SandboxError => eRails.logger.warn("Expression evaluation failed: #{e.message}")[]end- def self.with_owned_sandbox(context, user: nil)- sandbox = JsSandbox.new(context, user: user)+ def self.with_owned_sandbox(context, user: nil, workflow_vars: nil)+ sandbox = JsSandbox.new(context, user: user, workflow_vars: workflow_vars)resolver = new(context, user: user, sandbox: sandbox)yield resolverensurediff --git a/plugins/discourse-workflows/lib/discourse_workflows/js_sandbox.rb b/plugins/discourse-workflows/lib/discourse_workflows/js_sandbox.rbindex d89cbf25cb1..0a526302df6 100644--- a/plugins/discourse-workflows/lib/discourse_workflows/js_sandbox.rb+++ b/plugins/discourse-workflows/lib/discourse_workflows/js_sandbox.rb@@ -18,10 +18,18 @@ module DiscourseWorkflowsclass PayloadTooLargeError < StandardErrorend- def initialize(workflow_context, user: nil, vars: nil, capture_logs: false, budget_tracker: nil)+ def initialize(+ workflow_context,+ user: nil,+ vars: nil,+ workflow_vars: nil,+ capture_logs: false,+ budget_tracker: nil+ )@workflow_context = workflow_context@user = user- @vars = vars || DiscourseWorkflows::Variable.pluck(:key, :value).to_h+ @vars = vars || DiscourseWorkflows::Variable.where(workflow_id: nil).pluck(:key, :value).to_h+ @workflow_vars = workflow_vars || {}@budget_tracker = budget_tracker@site_setting_store = SiteSettingStore.new@js_context = create_js_context@@ -121,6 +129,7 @@ module DiscourseWorkflowsexecution = @workflow_context.fetch("__execution") { {} }declare_json("__vars", @vars)+ declare_json("__workflow_vars", @workflow_vars)declare_json("__executionData", execution)declare_json("__currentUser", build_current_user)@@ -128,6 +137,9 @@ module DiscourseWorkflowsObject.defineProperty(this, '$vars', {value: Object.freeze(__vars)});+ Object.defineProperty(this, '$workflow_vars', {+ value: Object.freeze(__workflow_vars)+ });Object.defineProperty(this, '$execution', {value: Object.freeze(__executionData)});diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/code/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/code/v1.rbindex 8b322f49080..2c564e4a8a4 100644--- a/plugins/discourse-workflows/lib/discourse_workflows/nodes/code/v1.rb+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/code/v1.rb@@ -10,7 +10,8 @@ module DiscourseWorkflows// $input.all() - array of all input items// $json - shortcut for $input.item.json// $("NodeName").item - access the paired item from another node- // $vars.KEY - workflow variables+ // $vars.KEY - global variables+ // $workflow_vars.KEY - this workflow's local variables// $site_settings.NAME - site settings// $execution - execution metadata (id, workflow_name, ...)// $current_user - user running the workflowdiff --git a/plugins/discourse-workflows/lib/discourse_workflows/workflow_snapshot.rb b/plugins/discourse-workflows/lib/discourse_workflows/workflow_snapshot.rbindex dd8c2afcd08..44380c138cc 100644--- a/plugins/discourse-workflows/lib/discourse_workflows/workflow_snapshot.rb+++ b/plugins/discourse-workflows/lib/discourse_workflows/workflow_snapshot.rb@@ -47,12 +47,13 @@ module DiscourseWorkflowskeyword_init: true,)- attr_reader :nodes, :connections, :pin_data, :workflow_name+ attr_reader :nodes, :connections, :pin_data, :workflow_name, :variables_schemadef initialize(workflow_data)data = workflow_data.deep_stringify_keys@workflow_name = data["name"]@pin_data = data["pinData"] || {}+ @variables_schema = data["variablesSchema"] || []@nodes =data.fetch("nodes") { [] }@@ -198,6 +199,7 @@ module DiscourseWorkflowsconnections,),"pinData" => pin_data,+ "variablesSchema" => variables_schema,}.compactend@@ -205,11 +207,14 @@ module DiscourseWorkflowsnodes = published ? workflow.published_nodes : workflow.nodesconnections = published ? workflow.published_connections : workflow.connectionsworkflow_name = published ? workflow.active_version&.name : workflow.name+ variables_schema =+ published ? workflow.active_version&.variables_schema || [] : workflow.variables_schemanew("name" => workflow_name || workflow.name,"nodes" => nodes,"connections" => connections,"pinData" => workflow.pin_data || {},+ "variablesSchema" => variables_schema,)end@@ -218,6 +223,7 @@ module DiscourseWorkflows"name" => version.name || workflow.name,"nodes" => version.nodes,"connections" => version.connections,+ "variablesSchema" => version.variables_schema,)enddiff --git a/plugins/discourse-workflows/lib/discourse_workflows/workflow_variable_value_resolver.rb b/plugins/discourse-workflows/lib/discourse_workflows/workflow_variable_value_resolver.rbnew file mode 100644index 00000000000..85c01d86371--- /dev/null+++ b/plugins/discourse-workflows/lib/discourse_workflows/workflow_variable_value_resolver.rb@@ -0,0 +1,39 @@+# frozen_string_literal: true++module DiscourseWorkflows+ class WorkflowVariableValueResolver+ def initialize(schema)+ @schema = Array(schema)+ end++ def resolve+ @schema.each_with_object({}) do |field, result|+ key = field["key"]+ next if key.blank?++ result[key] = typed_value(field["type"], field["value"])+ end+ end++ private++ def typed_value(type, raw_value)+ case type+ when "integer", "category", "group"+ raw_value.presence&.to_i+ when "boolean"+ raw_value == "true"+ when "category_list", "group_list"+ split(raw_value).filter_map { |id| Integer(id, exception: false) }+ when "tag_list", "simple_list"+ split(raw_value)+ else+ raw_value+ end+ end++ def split(raw_value)+ raw_value.to_s.split("|").filter_map(&:presence)+ end+ end+enddiff --git a/plugins/discourse-workflows/spec/fabricators/discourse_workflows_fabricator.rb b/plugins/discourse-workflows/spec/fabricators/discourse_workflows_fabricator.rbindex 7d12f7e810d..539f85f09fa 100644--- a/plugins/discourse-workflows/spec/fabricators/discourse_workflows_fabricator.rb+++ b/plugins/discourse-workflows/spec/fabricators/discourse_workflows_fabricator.rb@@ -103,6 +103,13 @@ Fabricator(:discourse_workflows_variable, class_name: "DiscourseWorkflows::Variacreated_by { Fabricate(:user) }end+Fabricator(:discourse_workflows_workflow_variable, class_name: "DiscourseWorkflows::Variable") do+ workflow { Fabricate(:discourse_workflows_workflow) }+ key { sequence(:key) { |n| "workflow_variable_#{n}" } }+ variable_type "string"+ created_by { Fabricate(:user) }+end+Fabricator(:discourse_workflows_credential, class_name: "DiscourseWorkflows::Credential") doname { sequence(:name) { |n| "Credential #{n}" } }credential_type "basic_auth"diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_validate_script_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_validate_script_spec.rbindex 3daa6dd1777..ce25a802b14 100644--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_validate_script_spec.rb+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_validate_script_spec.rb@@ -234,6 +234,23 @@ RSpec.describe DiscourseWorkflows::Ai::Tools::WorkflowValidateScript do)end+ it "accepts code referencing $workflow_vars" do+ result =+ invoke_tool(+ mode: "runOnceForAllItems",+ code: "return [{ json: { priority: $workflow_vars.priority } }];",+ )++ expect(result).to include(valid: true, errors: [])+ end++ it "accepts code referencing $vars" do+ result =+ invoke_tool(mode: "runOnceForAllItems", code: "return [{ json: { region: $vars.region } }];")++ expect(result).to include(valid: true, errors: [])+ end+it "reports output the Code node rejects" doresult = invoke_tool(mode: "runOnceForAllItems", code: "return 5;")diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/code_runner_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/code_runner_spec.rbindex 8ad05349da0..35c6e8bd402 100644--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/code_runner_spec.rb+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/code_runner_spec.rb@@ -10,6 +10,8 @@ RSpec.describe DiscourseWorkflows::Executor::CodeRunner doresolver_context: resolver_context,user: nil,vars: nil,+ workflow_vars: {+ },flow_context: {},runtime_state: runtime_state,diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_spec.rbindex b86879582cf..76988cf6daa 100644--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_spec.rb+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_spec.rb@@ -1041,5 +1041,121 @@ RSpec.describe DiscourseWorkflows::Executor doendendend++ context "with $workflow_vars" do+ def build_workflow_vars_workflow+ graph =+ build_workflow_graph do |g|+ g.node "trigger-1", "trigger:topic_closed"+ g.node "code-1",+ "action:code",+ configuration: {+ "code" =>+ "return { json: { priority: $workflow_vars.priority, region: $vars.region } };",+ }+ g.chain "trigger-1", "code-1"+ end+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)+ end++ def resolved_priority(execution)+ execution.execution_data.find_step(node_id: "code-1")["output"].first.dig(+ "json",+ "priority",+ )+ end++ def resolved_region(execution)+ execution.execution_data.find_step(node_id: "code-1")["output"].first.dig("json", "region")+ end++ it "resolves $workflow_vars.<key> to the variable's live value" do+ workflow = build_workflow_vars_workflow+ Fabricate(+ :discourse_workflows_workflow_variable,+ workflow: workflow,+ key: "priority",+ variable_type: "string",+ value: "urgent",+ )+ workflow.snapshot!(user: user)+ workflow.publish!(user: user)++ execution = described_class.new(workflow, "trigger-1", { topic_id: topic.id }).run++ expect(resolved_priority(execution)).to eq("urgent")+ end++ it "resolves $workflow_vars.<key> to the published version's embedded value even after the live variable is deleted" do+ workflow = build_workflow_vars_workflow+ variable =+ Fabricate(+ :discourse_workflows_workflow_variable,+ workflow: workflow,+ key: "priority",+ variable_type: "string",+ value: "urgent",+ )+ workflow.snapshot!(user: user)+ workflow.publish!(user: user)+ variable.destroy!++ execution = described_class.new(workflow, "trigger-1", { topic_id: topic.id }).run++ expect(resolved_priority(execution)).to eq("urgent")+ end++ it "resolves $workflow_vars.<key> and $vars.<key> independently in the same expression" do+ workflow = build_workflow_vars_workflow+ Fabricate(+ :discourse_workflows_workflow_variable,+ workflow: workflow,+ key: "priority",+ variable_type: "string",+ value: "urgent",+ )+ Fabricate(:discourse_workflows_variable, key: "region", value: "emea")+ workflow.snapshot!(user: user)+ workflow.publish!(user: user)++ execution = described_class.new(workflow, "trigger-1", { topic_id: topic.id }).run++ expect(resolved_priority(execution)).to eq("urgent")+ expect(resolved_region(execution)).to eq("emea")+ end++ it "resolves $workflow_vars.<key> after a wait/resume cycle" do+ graph =+ build_workflow_graph do |g|+ g.node "trigger-1", "trigger:topic_closed"+ g.node "wait-1", "flow:wait", configuration: { "resume" => "webhook" }+ g.node "code-1",+ "action:code",+ configuration: {+ "code" => "return { json: { priority: $workflow_vars.priority } };",+ }+ g.chain "trigger-1", "wait-1", "code-1"+ end+ workflow =+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)+ Fabricate(+ :discourse_workflows_workflow_variable,+ workflow: workflow,+ key: "priority",+ variable_type: "string",+ value: "urgent",+ )+ workflow.snapshot!(user: user)+ workflow.publish!(user: user)++ execution = described_class.new(workflow, "trigger-1", { topic_id: topic.id }).run+ expect(execution.status).to eq("waiting")++ claimed = DiscourseWorkflows::Execution.claim_for_resume(execution.reload)+ resumed = DiscourseWorkflows::Executor.resume(claimed, [{ "json" => {} }])++ expect(resolved_priority(resumed)).to eq("urgent")+ end+ endendenddiff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/expression_context_schema_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/expression_context_schema_spec.rbindex eb993382ae3..78dea54e8c4 100644--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/expression_context_schema_spec.rb+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/expression_context_schema_spec.rb@@ -9,12 +9,13 @@ RSpec.describe DiscourseWorkflows::ExpressionContextSchema doexpect(schema).to have_key(:item_prefix)end- it "declares $helpers, $site_settings, $vars, $current_user, $execution as environment symbols" do+ it "declares $helpers, $site_settings, $vars, $workflow_vars, $current_user, $execution as environment symbols" dosymbols = described_class.environment_symbols.keysexpect(symbols).to contain_exactly("$helpers","$site_settings","$vars",+ "$workflow_vars","$current_user","$execution",)@@ -87,7 +88,7 @@ RSpec.describe DiscourseWorkflows::ExpressionContextSchema dosandbox = DiscourseWorkflows::JsSandbox.new(context, user: user)# $execution is injected by ExpressionResolver, not JsSandbox directly- sandbox_symbols = %w[$site_settings $vars $current_user $helpers]+ sandbox_symbols = %w[$site_settings $vars $workflow_vars $current_user $helpers]sandbox_symbols.each do |symbol|result = sandbox.eval("typeof #{symbol}")expect(result).not_to eq("undefined"),diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/workflow_snapshot_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/workflow_snapshot_spec.rbindex 8fdad18e03a..cdd75d9a755 100644--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/workflow_snapshot_spec.rb+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/workflow_snapshot_spec.rb@@ -47,4 +47,68 @@ RSpec.describe DiscourseWorkflows::WorkflowSnapshot doendendend++ describe "#variables_schema" do+ it "defaults to an empty array when the source data has none" do+ expect(described_class.new({}).variables_schema).to eq([])+ end++ it "reads variablesSchema from the source data" do+ schema = [{ "key" => "priority", "type" => "string", "value" => "urgent" }]++ expect(described_class.new("variablesSchema" => schema).variables_schema).to eq(schema)+ end++ it "round-trips through #to_h" do+ schema = [{ "key" => "priority", "type" => "string", "value" => "urgent" }]+ snapshot = described_class.new("variablesSchema" => schema)++ expect(described_class.new(snapshot.to_h).variables_schema).to eq(schema)+ end+ end++ describe ".from_workflow" do+ fab!(:workflow, :discourse_workflows_workflow)+ fab!(:variable) do+ Fabricate(:discourse_workflows_workflow_variable, workflow:, value: "urgent")+ end++ context "when published: false" do+ it "uses the workflow's live variables schema" do+ snapshot = described_class.from_workflow(workflow, published: false)++ expect(snapshot.variables_schema).to eq(workflow.reload.variables_schema)+ expect(snapshot.variables_schema.first["value"]).to eq("urgent")+ end+ end++ context "when published: true" do+ before do+ version = workflow.snapshot!(user: workflow.created_by)+ workflow.update_columns(active_version_id: version.version_id)+ end++ it "uses the active version's variables schema" do+ snapshot = described_class.from_workflow(workflow.reload, published: true)++ expect(snapshot.variables_schema).to eq(workflow.active_version.variables_schema)+ end+ end+ end++ describe ".from_version" do+ fab!(:workflow, :discourse_workflows_workflow)+ fab!(:variable) do+ Fabricate(:discourse_workflows_workflow_variable, workflow:, value: "urgent")+ end++ it "uses the given version's variables schema" do+ version = workflow.snapshot!(user: workflow.created_by)++ snapshot = described_class.from_version(workflow, version)++ expect(snapshot.variables_schema).to eq(version.variables_schema)+ expect(snapshot.variables_schema.first["value"]).to eq("urgent")+ end+ endenddiff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/workflow_variable_value_resolver_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/workflow_variable_value_resolver_spec.rbnew file mode 100644index 00000000000..884d03223fb--- /dev/null+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/workflow_variable_value_resolver_spec.rb@@ -0,0 +1,124 @@+# frozen_string_literal: true++RSpec.describe DiscourseWorkflows::WorkflowVariableValueResolver do+ describe "#resolve" do+ subject(:resolved) { described_class.new(schema).resolve }++ context "with a blank schema" do+ let(:schema) { nil }++ it { is_expected.to eq({}) }+ end++ context "with a field missing a key" do+ let(:schema) { [{ "type" => "string", "value" => "hi" }] }++ it "skips the entry" do+ expect(resolved).to eq({})+ end+ end++ context "with a string field" do+ let(:schema) { [{ "key" => "label", "type" => "string", "value" => "hello" }] }++ it { is_expected.to eq("label" => "hello") }+ end++ context "with a string field that has no value" do+ let(:schema) { [{ "key" => "label", "type" => "string", "value" => nil }] }++ it { is_expected.to eq("label" => nil) }+ end++ context "with an integer field" do+ let(:schema) { [{ "key" => "count", "type" => "integer", "value" => "42" }] }++ it { is_expected.to eq("count" => 42) }+ end++ context "with an integer field that has no value" do+ let(:schema) { [{ "key" => "count", "type" => "integer", "value" => nil }] }++ it { is_expected.to eq("count" => nil) }+ end++ context "with a category field" do+ let(:schema) { [{ "key" => "cat", "type" => "category", "value" => "7" }] }++ it { is_expected.to eq("cat" => 7) }+ end++ context "with a group field" do+ let(:schema) { [{ "key" => "grp", "type" => "group", "value" => "3" }] }++ it { is_expected.to eq("grp" => 3) }+ end++ context "with a boolean field set to true" do+ let(:schema) { [{ "key" => "enabled", "type" => "boolean", "value" => "true" }] }++ it { is_expected.to eq("enabled" => true) }+ end++ context "with a boolean field set to anything else" do+ let(:schema) { [{ "key" => "enabled", "type" => "boolean", "value" => "false" }] }++ it { is_expected.to eq("enabled" => false) }+ end++ context "with a boolean field that has no value" do+ let(:schema) { [{ "key" => "enabled", "type" => "boolean", "value" => nil }] }++ it { is_expected.to eq("enabled" => false) }+ end++ context "with a category_list field" do+ let(:schema) { [{ "key" => "cats", "type" => "category_list", "value" => "1|2|3" }] }++ it { is_expected.to eq("cats" => [1, 2, 3]) }+ end++ context "with a category_list field that has no value" do+ let(:schema) { [{ "key" => "cats", "type" => "category_list", "value" => nil }] }++ it { is_expected.to eq("cats" => []) }+ end++ context "with a group_list field" do+ let(:schema) { [{ "key" => "grps", "type" => "group_list", "value" => "4|5" }] }++ it { is_expected.to eq("grps" => [4, 5]) }+ end++ context "with a tag_list field" do+ let(:schema) { [{ "key" => "tags", "type" => "tag_list", "value" => "bug|feature" }] }++ it { is_expected.to eq("tags" => %w[bug feature]) }+ end++ context "with a simple_list field" do+ let(:schema) { [{ "key" => "list", "type" => "simple_list", "value" => "a|b|c" }] }++ it { is_expected.to eq("list" => %w[a b c]) }+ end++ context "with an enum field" do+ let(:schema) { [{ "key" => "priority", "type" => "enum", "value" => "high" }] }++ it { is_expected.to eq("priority" => "high") }+ end++ context "with multiple fields" do+ let(:schema) do+ [+ { "key" => "priority", "type" => "enum", "value" => "high" },+ { "key" => "notify_categories", "type" => "category_list", "value" => "2|24" },+ ]+ end++ it "resolves every field" do+ expect(resolved).to eq("priority" => "high", "notify_categories" => [2, 24])+ end+ end+ end+enddiff --git a/plugins/discourse-workflows/spec/models/discourse_workflows/variable_spec.rb b/plugins/discourse-workflows/spec/models/discourse_workflows/variable_spec.rbnew file mode 100644index 00000000000..1c031b8613c--- /dev/null+++ b/plugins/discourse-workflows/spec/models/discourse_workflows/variable_spec.rb@@ -0,0 +1,187 @@+# frozen_string_literal: true++RSpec.describe DiscourseWorkflows::Variable do+ fab!(:workflow, :discourse_workflows_workflow)++ it { is_expected.to belong_to(:created_by) }+ it { is_expected.to belong_to(:workflow).optional }+ it { is_expected.to validate_length_of(:description).is_at_most(500) }+ it { is_expected.to validate_presence_of(:variable_type) }++ it do+ is_expected.to validate_inclusion_of(:variable_type).in_array(described_class::VARIABLE_TYPES)+ end++ it "validates key presence, length and format" do+ variable = described_class.new(variable_type: "string")++ expect(variable).to validate_presence_of(:key)+ expect(variable).to validate_length_of(:key).is_at_most(100)+ expect(variable).to allow_values("valid_key", "Key_123", "_underscore").for(:key)+ expect(variable).not_to allow_values("invalid key", "123start", "key!@#").for(:key)+ end++ describe "key uniqueness" do+ it "is scoped to the workflow for workflow-scoped variables" do+ Fabricate(:discourse_workflows_workflow_variable, workflow:, key: "priority")+ duplicate = described_class.new(workflow:, key: "priority", variable_type: "string")++ expect(duplicate).not_to be_valid+ expect(duplicate.errors[:key]).to be_present+ end++ it "allows the same key on a different workflow" do+ other_workflow = Fabricate(:discourse_workflows_workflow)+ Fabricate(:discourse_workflows_workflow_variable, workflow:, key: "priority")+ variable =+ described_class.new(workflow: other_workflow, key: "priority", variable_type: "string")++ expect(variable).to be_valid+ end++ it "is enforced across global variables" do+ Fabricate(:discourse_workflows_variable, key: "priority")+ duplicate = described_class.new(key: "priority", variable_type: "string")++ expect(duplicate).not_to be_valid+ expect(duplicate.errors[:key]).to be_present+ end++ it "allows a local variable to share a key with a global variable" do+ Fabricate(:discourse_workflows_variable, key: "priority")+ variable = described_class.new(workflow:, key: "priority", variable_type: "string")++ expect(variable).to be_valid+ end++ it "allows a global variable to share a key with a local variable" do+ Fabricate(:discourse_workflows_workflow_variable, workflow:, key: "priority")+ variable = described_class.new(key: "priority", variable_type: "string")++ expect(variable).to be_valid+ end+ end++ describe "database-level uniqueness (partial indexes)" do+ it "allows two variables sharing a key when one is global and one is workflow-scoped" do+ Fabricate(:discourse_workflows_variable, key: "priority")++ expect {+ described_class.insert!(+ {+ key: "priority",+ workflow_id: workflow.id,+ variable_type: "string",+ created_by_id: workflow.created_by_id,+ },+ )+ }.not_to raise_error+ end++ it "allows two workflow-scoped variables sharing a key on different workflows" do+ other_workflow = Fabricate(:discourse_workflows_workflow)+ Fabricate(:discourse_workflows_workflow_variable, workflow:, key: "priority")++ expect {+ described_class.insert!(+ {+ key: "priority",+ workflow_id: other_workflow.id,+ variable_type: "string",+ created_by_id: other_workflow.created_by_id,+ },+ )+ }.not_to raise_error+ end++ it "rejects two workflow-scoped variables sharing a key on the same workflow" do+ Fabricate(:discourse_workflows_workflow_variable, workflow:, key: "priority")++ expect {+ described_class.insert!(+ {+ key: "priority",+ workflow_id: workflow.id,+ variable_type: "string",+ created_by_id: workflow.created_by_id,+ },+ )+ }.to raise_error(ActiveRecord::RecordNotUnique)+ end++ it "rejects two global variables sharing a key" do+ global_variable = Fabricate(:discourse_workflows_variable, key: "priority")++ expect {+ described_class.insert!(+ {+ key: "priority",+ variable_type: "string",+ created_by_id: global_variable.created_by_id,+ },+ )+ }.to raise_error(ActiveRecord::RecordNotUnique)+ end+ end++ describe "#label" do+ it "is derived from the key" do+ variable = described_class.new(key: "notify_categories")+ expect(variable.label).to eq("Notify categories")+ end++ it "handles a single-word key" do+ variable = described_class.new(key: "priority")+ expect(variable.label).to eq("Priority")+ end+ end++ describe "enum choices validation" do+ it "requires type_options.choices when variable_type is enum" do+ variable = described_class.new(workflow:, key: "priority", variable_type: "enum")++ expect(variable).not_to be_valid+ expect(variable.errors[:type_options]).to be_present+ end++ it "is valid when choices are present" do+ variable =+ described_class.new(+ workflow:,+ key: "priority",+ variable_type: "enum",+ type_options: {+ "choices" => %w[low high],+ },+ )++ expect(variable).to be_valid+ end+ end++ describe "#definition" do+ it "returns the variable's portable definition without the value" do+ variable =+ Fabricate(+ :discourse_workflows_workflow_variable,+ workflow:,+ key: "priority",+ description: "How urgent",+ variable_type: "enum",+ type_options: {+ "choices" => %w[low medium high],+ },+ value: "high",+ )++ expect(variable.definition).to eq(+ "key" => "priority",+ "description" => "How urgent",+ "type" => "enum",+ "type_options" => {+ "choices" => %w[low medium high],+ },+ )+ end+ end+enddiff --git a/plugins/discourse-workflows/spec/models/discourse_workflows/workflow_spec.rb b/plugins/discourse-workflows/spec/models/discourse_workflows/workflow_spec.rbindex e14fbc915d6..d37a4723d18 100644--- a/plugins/discourse-workflows/spec/models/discourse_workflows/workflow_spec.rb+++ b/plugins/discourse-workflows/spec/models/discourse_workflows/workflow_spec.rb@@ -79,6 +79,115 @@ RSpec.describe DiscourseWorkflows::Workflow doendend+ describe "#restore_from_version!" do+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: user) }++ it "restores a variable's value from the target version" do+ variable =+ workflow.variables.create!(+ key: "priority",+ variable_type: "string",+ value: "urgent",+ created_by: user,+ )+ old_version = workflow.snapshot!(user: user)++ variable.update!(value: "low")+ workflow.snapshot!(user: user)++ workflow.restore_from_version!(old_version, user: user)++ expect(workflow.variables.find_by(key: "priority").value).to eq("urgent")+ end++ it "recreates a deleted variable with both its definition and value" do+ variable =+ workflow.variables.create!(+ key: "priority",+ variable_type: "string",+ value: "urgent",+ created_by: user,+ )+ old_version = workflow.snapshot!(user: user)++ variable.destroy!+ workflow.snapshot!(user: user)+ workflow.reload++ workflow.restore_from_version!(old_version, user: user)++ restored = workflow.variables.find_by(key: "priority")+ expect(restored).to be_present+ expect(restored.label).to eq("Priority")+ expect(restored.value).to eq("urgent")+ end++ it "sets created_by to the restoring user on a recreated variable" do+ variable =+ workflow.variables.create!(+ key: "priority",+ variable_type: "string",+ value: "urgent",+ created_by: user,+ )+ old_version = workflow.snapshot!(user: user)++ variable.destroy!+ workflow.snapshot!(user: user)+ workflow.reload++ restoring_user = Fabricate(:admin)+ workflow.restore_from_version!(old_version, user: restoring_user)++ expect(workflow.variables.find_by(key: "priority").created_by_id).to eq(restoring_user.id)+ end++ it "does not overwrite created_by on a variable that already exists" do+ variable =+ workflow.variables.create!(+ key: "priority",+ variable_type: "string",+ value: "urgent",+ created_by: user,+ )+ old_version = workflow.snapshot!(user: user)++ variable.update!(value: "low")+ workflow.snapshot!(user: user)++ restoring_user = Fabricate(:admin)+ workflow.restore_from_version!(old_version, user: restoring_user)++ expect(workflow.variables.find_by(key: "priority").created_by_id).to eq(user.id)+ end++ it "deletes a variable that no longer exists in the target version" do+ variable =+ workflow.variables.create!(+ key: "priority",+ variable_type: "string",+ value: "urgent",+ created_by: user,+ )+ old_version = workflow.snapshot!(user: user)++ other_variable =+ workflow.variables.create!(+ key: "extra",+ variable_type: "string",+ value: "keep-me",+ created_by: user,+ )+ workflow.snapshot!(user: user)++ workflow.restore_from_version!(old_version, user: user)++ expect(workflow.variables.find_by(key: "priority")).to be_present+ expect(workflow.variables.find_by(id: other_variable.id)).to be_nil+ expect(variable.reload).to be_present+ end+ end+describe "#node_static_data" dofab!(:workflow) doFabricate(diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/workflow_variables_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/workflow_variables_controller_spec.rbnew file mode 100644index 00000000000..86f9889379f--- /dev/null+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/workflow_variables_controller_spec.rb@@ -0,0 +1,239 @@+# frozen_string_literal: true++RSpec.describe DiscourseWorkflows::WorkflowVariablesController do+ fab!(:admin)+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: admin) }++ before { sign_in(admin) }++ context "when not logged in as admin" do+ fab!(:user)++ before { sign_in(user) }++ it "returns 404 for create" do+ post "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/variables.json",+ params: {+ key: "priority",+ variable_type: "string",+ }+ expect(response).to have_http_status(:not_found)+ end+ end++ describe "POST /admin/plugins/discourse-workflows/workflows/:workflow_id/variables" do+ it "creates a variable and returns the workflow's updated publish state" do+ workflow.update_columns(active_version_id: workflow.version_id)++ post "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/variables.json",+ params: {+ key: "priority",+ variable_type: "string",+ }++ expect(response).to have_http_status(:created)+ json = response.parsed_body+ expect(json["variable"]).to include("key" => "priority", "label" => "Priority")+ expect(json["workflow"]["has_unpublished_changes"]).to be(true)+ end++ it "returns 400 when key is missing" do+ post "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/variables.json",+ params: {+ variable_type: "string",+ }+ expect(response).to have_http_status(:bad_request)+ end++ it "returns 404 when the workflow does not exist" do+ post "/admin/plugins/discourse-workflows/workflows/-1/variables.json",+ params: {+ key: "priority",+ variable_type: "string",+ }+ expect(response).to have_http_status(:not_found)+ end+ end++ describe "PUT /admin/plugins/discourse-workflows/workflows/:workflow_id/variables/:variable_id" do+ fab!(:variable) do+ Fabricate(+ :discourse_workflows_workflow_variable,+ workflow:,+ key: "priority",+ variable_type: "string",+ )+ end++ it "updates a variable and returns the workflow's updated publish state" do+ workflow.update_columns(active_version_id: workflow.version_id)++ put "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/variables/#{variable.id}.json",+ params: {+ key: "priority_level",+ variable_type: "string",+ }++ expect(response).to have_http_status(:ok)+ expect(response.parsed_body["variable"]["key"]).to eq("priority_level")+ expect(response.parsed_body["workflow"]["has_unpublished_changes"]).to be(true)+ end++ it "returns 404 when the variable does not exist" do+ put "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/variables/-1.json",+ params: {+ key: "priority",+ variable_type: "string",+ }+ expect(response).to have_http_status(:not_found)+ end++ it "returns 404 when the variable is actually a global variable" do+ global_variable = Fabricate(:discourse_workflows_variable, key: "global_one")++ put "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/variables/#{global_variable.id}.json",+ params: {+ key: "priority",+ variable_type: "string",+ }+ expect(response).to have_http_status(:not_found)+ end+ end++ describe "DELETE /admin/plugins/discourse-workflows/workflows/:workflow_id/variables/:variable_id" do+ fab!(:variable) do+ Fabricate(+ :discourse_workflows_workflow_variable,+ workflow:,+ key: "priority",+ variable_type: "string",+ )+ end++ it "deletes a variable and returns the workflow's updated publish state" do+ workflow.update_columns(active_version_id: workflow.version_id)++ delete "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/variables/#{variable.id}.json"++ expect(response).to have_http_status(:ok)+ expect(DiscourseWorkflows::Variable.exists?(variable.id)).to be(false)+ expect(response.parsed_body["workflow"]["has_unpublished_changes"]).to be(true)+ end++ it "returns 404 when the variable does not exist" do+ delete "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/variables/-1.json"+ expect(response).to have_http_status(:not_found)+ end+ end++ describe "PUT /admin/plugins/discourse-workflows/workflows/:workflow_id/variables/:variable_id/value" do+ fab!(:variable) do+ Fabricate(+ :discourse_workflows_workflow_variable,+ workflow:,+ key: "priority",+ variable_type: "enum",+ type_options: {+ "choices" => %w[low medium high],+ },+ )+ end++ it "updates the variable's value" do+ put "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/variables/#{variable.id}/value.json",+ params: {+ value: "high",+ }++ expect(response).to have_http_status(:ok)+ json = response.parsed_body+ expect(json["variable"]["value"]).to eq("high")+ expect(json["workflow"]).to include(+ "has_unpublished_changes" => false,+ "active_version_id" => nil,+ )+ end++ it "auto-publishes the value when the workflow is published with a clean draft" do+ workflow.update!(active_version_id: workflow.version_id)++ put "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/variables/#{variable.id}/value.json",+ params: {+ value: "high",+ }++ expect(response).to have_http_status(:ok)+ json = response.parsed_body+ expect(json["workflow"]["has_unpublished_changes"]).to eq(false)+ expect(json["workflow"]["active_version_id"]).to eq(json["workflow"]["version_id"])+ end++ it "returns 422 when the value is invalid for the variable's type" do+ put "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/variables/#{variable.id}/value.json",+ params: {+ value: "extreme",+ }++ expect(response).to have_http_status(:unprocessable_entity)+ end++ it "returns 404 when the variable does not exist" do+ put "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/variables/-1/value.json",+ params: {+ value: "high",+ }+ expect(response).to have_http_status(:not_found)+ end+ end++ describe "POST /admin/plugins/discourse-workflows/workflows/:workflow_id/variables/import" do+ it "creates every imported variable in a single new version" do+ expect {+ post "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/variables/import.json",+ params: {+ variables: [+ { key: "priority", variable_type: "string" },+ { key: "notify_categories", variable_type: "category_list" },+ ],+ }+ }.to change { workflow.reload.version_counter }.by(1)++ expect(response).to have_http_status(:ok)+ json = response.parsed_body+ expect(json["imported_count"]).to eq(2)+ expect(json["skipped_keys"]).to eq([])+ expect(workflow.variables.pluck(:key)).to contain_exactly("priority", "notify_categories")+ end++ it "skips variables whose key already exists on the workflow" do+ Fabricate(+ :discourse_workflows_workflow_variable,+ workflow:,+ key: "priority",+ variable_type: "enum",+ type_options: {+ "choices" => %w[low high],+ },+ )++ post "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/variables/import.json",+ params: {+ variables: [{ key: "priority", variable_type: "string" }],+ }++ expect(response).to have_http_status(:ok)+ json = response.parsed_body+ expect(json["imported_count"]).to eq(0)+ expect(json["skipped_keys"]).to eq(["priority"])+ expect(workflow.variables.find_by(key: "priority").variable_type).to eq("enum")+ end++ it "returns 404 when the workflow does not exist" do+ post "/admin/plugins/discourse-workflows/workflows/-1/variables/import.json",+ params: {+ variables: [{ key: "priority", variable_type: "string" }],+ }+ expect(response).to have_http_status(:not_found)+ end+ end+enddiff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/workflows_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/workflows_controller_spec.rbindex fcd5877679a..390c85d6ebb 100644--- a/plugins/discourse-workflows/spec/requests/discourse_workflows/workflows_controller_spec.rb+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/workflows_controller_spec.rb@@ -96,6 +96,23 @@ RSpec.describe DiscourseWorkflows::WorkflowsController doexpect(json["workflows"].length).to eq(1)expect(json["workflows"][0]["id"]).to eq(workflow_1.id.to_s)end++ it "omits variables and does not query them per workflow" do+ 3.times do+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin)+ Fabricate(:discourse_workflows_workflow_variable, workflow:, value: "urgent")+ end++ queries = track_sql_queries { get "/admin/plugins/discourse-workflows/workflows.json" }++ expect(response).to have_http_status(:ok)+ json = response.parsed_body+ expect(json["workflows"].length).to eq(3)+ json["workflows"].each { |workflow| expect(workflow).not_to have_key("variables") }++ variable_queries = queries.select { |query| query.include?("discourse_workflows_variables") }+ expect(variable_queries).to be_empty+ endenddescribe "POST /admin/plugins/discourse-workflows/workflows" dodiff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/expression/evaluate_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/expression/evaluate_spec.rbindex e316dafcb10..2c2b9347ab5 100644--- a/plugins/discourse-workflows/spec/services/discourse_workflows/expression/evaluate_spec.rb+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/expression/evaluate_spec.rb@@ -103,5 +103,27 @@ RSpec.describe DiscourseWorkflows::Expression::Evaluate doexpect(result[:segments].first[:state]).to eq("valid")endend++ context "with a workflow local variable" do+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: admin) }+ fab!(:variable) do+ Fabricate(+ :discourse_workflows_workflow_variable,+ workflow:,+ key: "notify_categories",+ variable_type: "category_list",+ value: "4|9",+ )+ end++ let(:params) do+ { template: "{{ $workflow_vars.notify_categories }}", workflow_id: workflow.id }+ end++ it "resolves the variable's current value" do+ expect(result).to run_successfully+ expect(result[:segments].first).to include(state: "valid", text: "4, 9")+ end+ endendenddiff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/variable/create_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/variable/create_spec.rbindex 3c299e01607..dc12e78172b 100644--- a/plugins/discourse-workflows/spec/services/discourse_workflows/variable/create_spec.rb+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/variable/create_spec.rb@@ -39,6 +39,16 @@ RSpec.describe DiscourseWorkflows::Variable::Create doit { is_expected.to fail_with_an_invalid_model(:variable) }end+ context "when the key already exists on a workflow-scoped local variable" do+ before { Fabricate(:discourse_workflows_workflow_variable, key: "API_BASE_URL") }++ it { is_expected.to run_successfully }+ end++ it "has no workflow_id attribute on its contract, so a client can never scope a global create" do+ expect(described_class::Contract.attribute_names).not_to include("workflow_id")+ end+context "when everything's ok" doit { is_expected.to run_successfully }diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/variable/destroy_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/variable/destroy_spec.rbindex cc69852584d..93f84c150f3 100644--- a/plugins/discourse-workflows/spec/services/discourse_workflows/variable/destroy_spec.rb+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/variable/destroy_spec.rb@@ -34,6 +34,18 @@ RSpec.describe DiscourseWorkflows::Variable::Destroy doit { is_expected.to fail_a_policy(:can_manage_workflows) }end+ context "when the target id is actually a workflow-scoped local variable" do+ fab!(:local_variable) { Fabricate(:discourse_workflows_workflow_variable, key: "local") }++ let(:params) { { variable_id: local_variable.id } }++ it { is_expected.to fail_to_find_a_model(:variable) }++ it "does not destroy the local variable" do+ expect { result }.not_to change { DiscourseWorkflows::Variable.count }+ end+ end+context "when everything's ok" doit { is_expected.to run_successfully }diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/variable/list_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/variable/list_spec.rbindex 239d15388e4..9258a10b50f 100644--- a/plugins/discourse-workflows/spec/services/discourse_workflows/variable/list_spec.rb+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/variable/list_spec.rb@@ -48,6 +48,16 @@ RSpec.describe DiscourseWorkflows::Variable::List doendend+ context "when there are workflow-scoped local variables alongside global ones" do+ fab!(:global_variable) { Fabricate(:discourse_workflows_variable, key: "GLOBAL") }+ fab!(:local_variable) { Fabricate(:discourse_workflows_workflow_variable, key: "local") }++ it "returns only global variables" do+ expect(result[:variables]).to contain_exactly(global_variable)+ expect(result[:total_rows]).to eq(1)+ end+ end+context "with pagination" dolet(:params) { { limit: 2 } }diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/variable/update_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/variable/update_spec.rbindex 9f39396d46b..ec9c1a176af 100644--- a/plugins/discourse-workflows/spec/services/discourse_workflows/variable/update_spec.rb+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/variable/update_spec.rb@@ -46,6 +46,18 @@ RSpec.describe DiscourseWorkflows::Variable::Update doit { is_expected.to fail_with_an_invalid_model(:variable) }end+ context "when the target id is actually a workflow-scoped local variable" do+ fab!(:local_variable) { Fabricate(:discourse_workflows_workflow_variable, key: "local") }++ let(:params) { { variable_id: local_variable.id, key: "NEW_KEY", value: "new_value" } }++ it { is_expected.to fail_to_find_a_model(:variable) }++ it "does not modify the local variable" do+ expect { result }.not_to change { local_variable.reload.key }+ end+ end+context "when everything's ok" doit { is_expected.to run_successfully }diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/discard_draft_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/discard_draft_spec.rbindex 03bacf267f2..d6a8f103561 100644--- a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/discard_draft_spec.rb+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/discard_draft_spec.rb@@ -75,6 +75,25 @@ RSpec.describe DiscourseWorkflows::Workflow::DiscardDraft doexpect(workflow).not_to have_unpublished_changesend+ it "restores the published version's variable value" do+ variable =+ workflow.variables.create!(+ key: "priority",+ variable_type: "string",+ value: "urgent",+ created_by: user,+ )+ workflow.snapshot!(user: user)+ workflow.publish!(user: user)++ variable.update!(value: "changed")+ workflow.snapshot!(user: user)++ result++ expect(workflow.reload.variables.find_by(key: "priority").value).to eq("urgent")+ end+it_behaves_like "expires workflow caches"endenddiff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/revert_to_version_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/revert_to_version_spec.rbindex 977ee497355..8e069f5f1e0 100644--- a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/revert_to_version_spec.rb+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/revert_to_version_spec.rb@@ -86,6 +86,30 @@ RSpec.describe DiscourseWorkflows::Workflow::RevertToVersion doexpect { result }.not_to change { workflow.workflow_versions.count }end+ it "restores a variable's value along with the chosen version" do+ variable =+ workflow.variables.create!(+ key: "priority",+ variable_type: "string",+ value: "urgent",+ created_by: user,+ )+ target_version = workflow.snapshot!(user: user)++ variable.update!(value: "changed")+ workflow.snapshot!(user: user)++ described_class.call(+ params: {+ workflow_id: workflow.id,+ version_id: target_version.version_id,+ },+ guardian: user.guardian,+ )++ expect(workflow.variables.find_by(key: "priority").value).to eq("urgent")+ end+it_behaves_like "expires workflow caches"endenddiff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow_variable/create_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow_variable/create_spec.rbnew file mode 100644index 00000000000..46d4b6091fb--- /dev/null+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow_variable/create_spec.rb@@ -0,0 +1,121 @@+# frozen_string_literal: true++RSpec.describe DiscourseWorkflows::WorkflowVariable::Create do+ describe described_class::Contract, type: :model do+ it { is_expected.to validate_presence_of(:workflow_id) }+ it { is_expected.to validate_presence_of(:key) }+ it { is_expected.to validate_presence_of(:variable_type) }+ it { is_expected.to validate_length_of(:key).is_at_most(100) }+ it { is_expected.to validate_length_of(:description).is_at_most(500) }++ it do+ is_expected.to validate_inclusion_of(:variable_type).in_array(+ DiscourseWorkflows::Variable::VARIABLE_TYPES,+ )+ end++ it { is_expected.to allow_values("valid_key", "Key_123", "_underscore").for(:key) }+ it { is_expected.not_to allow_values("invalid key", "123start", "key!@#").for(:key) }+ end++ describe ".call" do+ subject(:result) { described_class.call(params:, **dependencies) }++ fab!(:admin)+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: admin) }++ let(:params) { { workflow_id: workflow.id, key: "priority", variable_type: "string" } }+ let(:dependencies) { { guardian: admin.guardian } }++ context "when contract is invalid" do+ let(:params) { { workflow_id: workflow.id, key: "invalid key!", variable_type: nil } }++ it { is_expected.to fail_a_contract }+ end++ context "when user cannot manage workflows" do+ fab!(:user)++ let(:dependencies) { { guardian: user.guardian } }++ it { is_expected.to fail_a_policy(:can_manage_workflows) }+ end++ context "when the workflow does not exist" do+ let(:params) { super().merge(workflow_id: -1) }++ it { is_expected.to fail_to_find_a_model(:workflow) }+ end++ context "when the key is already used on that workflow" do+ before do+ workflow.variables.create!(key: "priority", variable_type: "string", created_by: admin)+ end++ it { is_expected.to fail_with_an_invalid_model(:variable) }+ end++ context "when the key is already used by a global variable" do+ before { Fabricate(:discourse_workflows_variable, key: "priority") }++ it { is_expected.to run_successfully }+ end++ context "when variable_type is enum without choices" do+ let(:params) { super().merge(variable_type: "enum") }++ it { is_expected.to fail_with_an_invalid_model(:variable) }+ end++ context "when everything's ok" do+ it { is_expected.to run_successfully }++ it "creates the variable, scoped to the workflow" do+ expect { result }.to change { workflow.variables.count }.by(1)+ expect(workflow.variables.last).to have_attributes(+ key: "priority",+ variable_type: "string",+ workflow_id: workflow.id,+ )+ end++ it "derives the label from the key" do+ result+ expect(workflow.variables.last.label).to eq("Priority")+ end++ it "does not affect global variables" do+ expect { result }.not_to change {+ DiscourseWorkflows::Variable.where(workflow_id: nil).count+ }+ end++ it "creates a new workflow version" do+ expect { result }.to change { workflow.reload.version_counter }.by(1)+ end++ it "logs a staff action" do+ expect { result }.to change { UserHistory.count }.by(1)+ expect(UserHistory.last).to have_attributes(+ custom_type: "discourse_workflows_workflow_variable_created",+ subject: "priority",+ )+ end++ it "indexes workflow dependencies for the new version" do+ error_workflow = Fabricate(:discourse_workflows_workflow, created_by: admin)+ workflow.update!(error_workflow_id: error_workflow.id)++ expect(result).to run_successfully++ dependency =+ DiscourseWorkflows::WorkflowDependency.find_by(+ workflow_version_id: result.workflow_version.version_id,+ dependency_type: "error_workflow",+ )+ expect(dependency).to be_present+ expect(dependency.dependency_key).to eq(error_workflow.id.to_s)+ end+ end+ end+enddiff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow_variable/destroy_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow_variable/destroy_spec.rbnew file mode 100644index 00000000000..0dca617e3cf--- /dev/null+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow_variable/destroy_spec.rb@@ -0,0 +1,95 @@+# frozen_string_literal: true++RSpec.describe DiscourseWorkflows::WorkflowVariable::Destroy do+ describe described_class::Contract, type: :model do+ it { is_expected.to validate_presence_of(:workflow_id) }+ it { is_expected.to validate_presence_of(:variable_id) }+ end++ describe ".call" do+ subject(:result) { described_class.call(params:, **dependencies) }++ fab!(:admin)+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: admin) }+ fab!(:variable) do+ Fabricate(+ :discourse_workflows_workflow_variable,+ workflow:,+ key: "priority",+ variable_type: "string",+ )+ end++ let(:params) { { workflow_id: workflow.id, variable_id: variable.id } }+ let(:dependencies) { { guardian: admin.guardian } }++ context "when user cannot manage workflows" do+ fab!(:user)++ let(:dependencies) { { guardian: user.guardian } }++ it { is_expected.to fail_a_policy(:can_manage_workflows) }+ end++ context "when the workflow does not exist" do+ let(:params) { super().merge(workflow_id: -1) }++ it { is_expected.to fail_to_find_a_model(:workflow) }+ end++ context "when the variable does not exist" do+ let(:params) { super().merge(variable_id: -1) }++ it { is_expected.to fail_to_find_a_model(:variable) }+ end++ context "when the variable is actually a global variable" do+ fab!(:global_variable) { Fabricate(:discourse_workflows_variable, key: "global_one") }++ let(:params) { super().merge(variable_id: global_variable.id) }++ it { is_expected.to fail_to_find_a_model(:variable) }++ it "does not destroy the global variable" do+ expect { result }.not_to change {+ DiscourseWorkflows::Variable.where(workflow_id: nil).count+ }+ end+ end++ context "when everything's ok" do+ it { is_expected.to run_successfully }++ it "destroys the variable" do+ expect { result }.to change { workflow.variables.count }.by(-1)+ end++ it "creates a new workflow version" do+ expect { result }.to change { workflow.reload.version_counter }.by(1)+ end++ it "logs a staff action" do+ expect { result }.to change { UserHistory.count }.by(1)+ expect(UserHistory.last).to have_attributes(+ custom_type: "discourse_workflows_workflow_variable_destroyed",+ subject: "priority",+ )+ end++ it "indexes workflow dependencies for the new version" do+ error_workflow = Fabricate(:discourse_workflows_workflow, created_by: admin)+ workflow.update!(error_workflow_id: error_workflow.id)++ expect(result).to run_successfully++ dependency =+ DiscourseWorkflows::WorkflowDependency.find_by(+ workflow_version_id: result.workflow_version.version_id,+ dependency_type: "error_workflow",+ )+ expect(dependency).to be_present+ expect(dependency.dependency_key).to eq(error_workflow.id.to_s)+ end+ end+ end+enddiff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow_variable/import_definitions_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow_variable/import_definitions_spec.rbnew file mode 100644index 00000000000..98443b09d0d--- /dev/null+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow_variable/import_definitions_spec.rb@@ -0,0 +1,151 @@+# frozen_string_literal: true++RSpec.describe DiscourseWorkflows::WorkflowVariable::ImportDefinitions do+ describe described_class::Contract, type: :model do+ it { is_expected.to validate_presence_of(:workflow_id) }++ it "rejects a variables value that isn't an array of hashes" do+ contract = described_class.new(workflow_id: 1, variables: "not-an-array")+ expect(contract).to be_invalid+ expect(contract.errors[:variables]).to be_present+ end+ end++ describe ".call" do+ subject(:result) { described_class.call(params:, **dependencies) }++ fab!(:admin)+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: admin) }++ let(:params) do+ {+ workflow_id: workflow.id,+ variables: [+ { "key" => "priority", "variable_type" => "string" },+ { "key" => "notify_categories", "variable_type" => "category_list" },+ ],+ }+ end+ let(:dependencies) { { guardian: admin.guardian } }++ context "when user cannot manage workflows" do+ fab!(:user)++ let(:dependencies) { { guardian: user.guardian } }++ it { is_expected.to fail_a_policy(:can_manage_workflows) }+ end++ context "when the workflow does not exist" do+ let(:params) { super().merge(workflow_id: -1) }++ it { is_expected.to fail_to_find_a_model(:workflow) }+ end++ context "when everything's ok" do+ it { is_expected.to run_successfully }++ it "creates every imported variable" do+ expect { result }.to change { workflow.variables.count }.by(2)+ expect(workflow.variables.pluck(:key)).to contain_exactly("priority", "notify_categories")+ end++ it "sets created_by on every imported variable to the importing admin" do+ result+ expect(workflow.variables.pluck(:created_by_id).uniq).to eq([admin.id])+ end++ it "creates exactly one new workflow version for the whole import" do+ expect { result }.to change { workflow.reload.version_counter }.by(1)+ end++ it "logs a single staff action" do+ expect { result }.to change { UserHistory.count }.by(1)+ expect(UserHistory.last).to have_attributes(+ custom_type: "discourse_workflows_workflow_variables_imported",+ )+ end++ it "indexes workflow dependencies for the new version" do+ error_workflow = Fabricate(:discourse_workflows_workflow, created_by: admin)+ workflow.update!(error_workflow_id: error_workflow.id)++ expect(result).to run_successfully++ dependency =+ DiscourseWorkflows::WorkflowDependency.find_by(+ workflow_version_id: result.workflow_version.version_id,+ dependency_type: "error_workflow",+ )+ expect(dependency).to be_present+ expect(dependency.dependency_key).to eq(error_workflow.id.to_s)+ end+ end++ context "when an imported key already exists on the workflow" do+ fab!(:existing_variable) do+ Fabricate(+ :discourse_workflows_workflow_variable,+ workflow:,+ key: "priority",+ variable_type: "enum",+ type_options: {+ "choices" => %w[low high],+ },+ )+ end++ it "skips the colliding variable without touching it" do+ expect { result }.to change { workflow.variables.count }.by(1)+ expect(existing_variable.reload.variable_type).to eq("enum")+ end++ it "reports the skipped key" do+ expect(result[:imported_variables][:skipped]).to eq(["priority"])+ end+ end++ context "when an imported key already exists as a global variable" do+ fab!(:global_variable) { Fabricate(:discourse_workflows_variable, key: "priority") }++ it "still imports it as a workflow-scoped variable" do+ expect { result }.to change { workflow.variables.count }.by(2)+ expect(workflow.variables.pluck(:key)).to include("priority")+ expect(global_variable.reload.workflow_id).to be_nil+ end+ end++ context "when every imported variable is skipped" do+ fab!(:existing_variable) do+ Fabricate(+ :discourse_workflows_workflow_variable,+ workflow:,+ key: "priority",+ variable_type: "string",+ )+ end+ fab!(:existing_notify_variable) do+ Fabricate(+ :discourse_workflows_workflow_variable,+ workflow:,+ key: "notify_categories",+ variable_type: "category_list",+ )+ end++ it "does not create a new workflow version" do+ expect { result }.not_to change { workflow.reload.version_counter }+ end+ end++ context "when variables is empty" do+ let(:params) { super().merge(variables: []) }++ it { is_expected.to run_successfully }++ it "does not create a new workflow version" do+ expect { result }.not_to change { workflow.reload.version_counter }+ end+ end+ end+enddiff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow_variable/update_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow_variable/update_spec.rbnew file mode 100644index 00000000000..f9564622734--- /dev/null+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow_variable/update_spec.rb@@ -0,0 +1,191 @@+# frozen_string_literal: true++RSpec.describe DiscourseWorkflows::WorkflowVariable::Update do+ describe described_class::Contract, type: :model do+ it { is_expected.to validate_presence_of(:workflow_id) }+ it { is_expected.to validate_presence_of(:variable_id) }+ it { is_expected.to validate_presence_of(:key) }+ it { is_expected.to validate_presence_of(:variable_type) }++ it do+ is_expected.to validate_inclusion_of(:variable_type).in_array(+ DiscourseWorkflows::Variable::VARIABLE_TYPES,+ )+ end+ end++ describe ".call" do+ subject(:result) { described_class.call(params:, **dependencies) }++ fab!(:admin)+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: admin) }+ fab!(:variable) do+ Fabricate(+ :discourse_workflows_workflow_variable,+ workflow:,+ key: "priority",+ variable_type: "string",+ )+ end++ let(:params) do+ {+ workflow_id: workflow.id,+ variable_id: variable.id,+ key: "priority_level",+ variable_type: "string",+ }+ end+ let(:dependencies) { { guardian: admin.guardian } }++ context "when contract is invalid" do+ let(:params) do+ { workflow_id: workflow.id, variable_id: variable.id, key: nil, variable_type: nil }+ end++ it { is_expected.to fail_a_contract }+ end++ context "when user cannot manage workflows" do+ fab!(:user)++ let(:dependencies) { { guardian: user.guardian } }++ it { is_expected.to fail_a_policy(:can_manage_workflows) }+ end++ context "when the workflow does not exist" do+ let(:params) { super().merge(workflow_id: -1) }++ it { is_expected.to fail_to_find_a_model(:workflow) }+ end++ context "when the variable does not exist" do+ let(:params) { super().merge(variable_id: -1) }++ it { is_expected.to fail_to_find_a_model(:variable) }+ end++ context "when the variable belongs to another workflow" do+ fab!(:other_workflow) { Fabricate(:discourse_workflows_workflow, created_by: admin) }+ fab!(:other_variable) do+ Fabricate(:discourse_workflows_workflow_variable, workflow: other_workflow, key: "other")+ end++ let(:params) { super().merge(variable_id: other_variable.id) }++ it { is_expected.to fail_to_find_a_model(:variable) }+ end++ context "when the variable is actually a global variable" do+ fab!(:global_variable) { Fabricate(:discourse_workflows_variable, key: "global_one") }++ let(:params) { super().merge(variable_id: global_variable.id) }++ it { is_expected.to fail_to_find_a_model(:variable) }+ end++ context "when the new key collides with another variable on the workflow" do+ before do+ workflow.variables.create!(key: "other", variable_type: "string", created_by: admin)+ end++ let(:params) { super().merge(key: "other") }++ it { is_expected.to fail_with_an_invalid_model(:variable) }+ end++ context "when the new key collides with a global variable's key" do+ before { Fabricate(:discourse_workflows_variable, key: "priority_level") }++ it { is_expected.to run_successfully }+ end++ context "when nothing actually changed" do+ let(:params) do+ {+ workflow_id: workflow.id,+ variable_id: variable.id,+ key: "priority",+ variable_type: "string",+ }+ end++ it { is_expected.to run_successfully }++ it "does not create a new workflow version" do+ expect { result }.not_to change { workflow.reload.version_counter }+ end+ end++ context "when the variable type changes to something incompatible with the current value" do+ before { variable.update!(value: "hello") }++ let(:params) { super().merge(variable_type: "integer") }++ it { is_expected.to fail_a_policy(:existing_value_compatible_with_new_type) }++ it "does not update the variable" do+ expect { result }.not_to change { variable.reload.variable_type }+ end+ end++ context "when the variable type changes but the current value is still compatible" do+ before { variable.update!(value: "42") }++ let(:params) { super().merge(variable_type: "integer") }++ it { is_expected.to run_successfully }++ it "updates the variable" do+ expect { result }.to change { variable.reload.variable_type }.to("integer")+ end+ end++ context "when the variable type changes and the current value is blank" do+ let(:params) { super().merge(variable_type: "integer") }++ it { is_expected.to run_successfully }+ end++ context "when the definition changed" do+ it { is_expected.to run_successfully }++ it "updates the variable" do+ expect { result }.to change { variable.reload.key }.to("priority_level")+ end++ it "the derived label reflects the new key" do+ result+ expect(variable.reload.label).to eq("Priority level")+ end++ it "creates a new workflow version" do+ expect { result }.to change { workflow.reload.version_counter }.by(1)+ end++ it "logs a staff action" do+ expect { result }.to change { UserHistory.count }.by(1)+ expect(UserHistory.last).to have_attributes(+ custom_type: "discourse_workflows_workflow_variable_updated",+ subject: "priority_level",+ )+ end++ it "indexes workflow dependencies for the new version" do+ error_workflow = Fabricate(:discourse_workflows_workflow, created_by: admin)+ workflow.update!(error_workflow_id: error_workflow.id)++ expect(result).to run_successfully++ dependency =+ DiscourseWorkflows::WorkflowDependency.find_by(+ workflow_version_id: result.workflow_version.version_id,+ dependency_type: "error_workflow",+ )+ expect(dependency).to be_present+ expect(dependency.dependency_key).to eq(error_workflow.id.to_s)+ end+ end+ end+enddiff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow_variable/update_value_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow_variable/update_value_spec.rbnew file mode 100644index 00000000000..db9e0beddd1--- /dev/null+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow_variable/update_value_spec.rb@@ -0,0 +1,351 @@+# frozen_string_literal: true++RSpec.describe DiscourseWorkflows::WorkflowVariable::UpdateValue do+ describe described_class::Contract, type: :model do+ it { is_expected.to validate_presence_of(:workflow_id) }+ it { is_expected.to validate_presence_of(:variable_id) }++ it do+ is_expected.to validate_length_of(:value).is_at_most(+ DiscourseWorkflows::WorkflowVariable::UpdateValue::MAX_VALUE_LENGTH,+ )+ end+ end++ describe ".call" do+ subject(:result) { described_class.call(params:, **dependencies) }++ fab!(:admin)+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: admin) }+ fab!(:variable) do+ Fabricate(+ :discourse_workflows_workflow_variable,+ workflow:,+ key: "priority",+ variable_type: "enum",+ type_options: {+ "choices" => %w[low medium high],+ },+ )+ end++ let(:params) { { workflow_id: workflow.id, variable_id: variable.id, value: "medium" } }+ let(:dependencies) { { guardian: admin.guardian } }++ context "when user cannot manage workflows" do+ fab!(:user)++ let(:dependencies) { { guardian: user.guardian } }++ it { is_expected.to fail_a_policy(:can_manage_workflows) }+ end++ context "when the workflow does not exist" do+ let(:params) { super().merge(workflow_id: -1) }++ it { is_expected.to fail_to_find_a_model(:workflow) }+ end++ context "when the variable does not exist" do+ let(:params) { super().merge(variable_id: -1) }++ it { is_expected.to fail_to_find_a_model(:variable) }+ end++ context "when the variable is actually a global variable" do+ fab!(:global_variable) { Fabricate(:discourse_workflows_variable, key: "global_one") }++ let(:params) { super().merge(variable_id: global_variable.id) }++ it { is_expected.to fail_to_find_a_model(:variable) }+ end++ context "when the value is not one of the enum's choices" do+ let(:params) { super().merge(value: "extreme") }++ it { is_expected.to fail_a_policy(:value_is_valid) }+ end++ context "when the variable is a boolean and the value isn't true/false" do+ fab!(:variable) do+ Fabricate(+ :discourse_workflows_workflow_variable,+ workflow:,+ key: "enabled",+ variable_type: "boolean",+ )+ end++ let(:params) { super().merge(value: "yes") }++ it { is_expected.to fail_a_policy(:value_is_valid) }+ end++ context "when the variable is a category_list and the id doesn't exist" do+ fab!(:variable) do+ Fabricate(+ :discourse_workflows_workflow_variable,+ workflow:,+ key: "cats",+ variable_type: "category_list",+ )+ end++ let(:params) { super().merge(value: "999999") }++ it { is_expected.to fail_a_policy(:value_is_valid) }+ end++ context "when the variable is a category_list and the id exists" do+ fab!(:category)+ fab!(:variable) do+ Fabricate(+ :discourse_workflows_workflow_variable,+ workflow:,+ key: "cats",+ variable_type: "category_list",+ )+ end++ let(:params) { super().merge(value: category.id.to_s) }++ it { is_expected.to run_successfully }+ end++ context "when the variable is a category and the id doesn't exist" do+ fab!(:variable) do+ Fabricate(+ :discourse_workflows_workflow_variable,+ workflow:,+ key: "cat",+ variable_type: "category",+ )+ end++ let(:params) { super().merge(value: "999999") }++ it { is_expected.to fail_a_policy(:value_is_valid) }+ end++ context "when the variable is a category and the id exists" do+ fab!(:category)+ fab!(:variable) do+ Fabricate(+ :discourse_workflows_workflow_variable,+ workflow:,+ key: "cat",+ variable_type: "category",+ )+ end++ let(:params) { super().merge(value: category.id.to_s) }++ it { is_expected.to run_successfully }+ end++ context "when the variable is a group and the id doesn't exist" do+ fab!(:variable) do+ Fabricate(+ :discourse_workflows_workflow_variable,+ workflow:,+ key: "grp",+ variable_type: "group",+ )+ end++ let(:params) { super().merge(value: "999999") }++ it { is_expected.to fail_a_policy(:value_is_valid) }+ end++ context "when the variable is a group and the id exists" do+ fab!(:group)+ fab!(:variable) do+ Fabricate(+ :discourse_workflows_workflow_variable,+ workflow:,+ key: "grp",+ variable_type: "group",+ )+ end++ let(:params) { super().merge(value: group.id.to_s) }++ it { is_expected.to run_successfully }+ end++ context "when clearing the value" do+ let(:params) { super().merge(value: nil) }++ it { is_expected.to run_successfully }+ end++ context "when everything's ok" do+ it { is_expected.to run_successfully }++ it "updates the value" do+ expect { result }.to change { variable.reload.value }.to("medium")+ end++ it "always creates a new workflow version, even when unpublished" do+ expect { result }.to change { workflow.reload.version_counter }.by(1)+ end++ it "embeds the new value in the version snapshot" do+ result+ new_version = workflow.reload.workflow_versions.find_by(version_id: workflow.version_id)+ entry = new_version.variables_schema.find { |f| f["key"] == "priority" }+ expect(entry["value"]).to eq("medium")+ end++ it "indexes workflow dependencies for the new version" do+ error_workflow = Fabricate(:discourse_workflows_workflow, created_by: admin)+ workflow.update!(error_workflow_id: error_workflow.id)++ expect(result).to run_successfully++ dependency =+ DiscourseWorkflows::WorkflowDependency.find_by(+ workflow_version_id: result.workflow_version.version_id,+ dependency_type: "error_workflow",+ )+ expect(dependency).to be_present+ expect(dependency.dependency_key).to eq(error_workflow.id.to_s)+ end++ it_behaves_like "expires workflow caches"+ end++ context "when the workflow has never been published" do+ it "snapshots but does not publish" do+ expect { result }.to change { workflow.reload.version_counter }.by(1)+ expect(workflow.published?).to eq(false)+ expect(workflow.active_version_id).to be_nil+ end+ end++ context "when the workflow is published and the draft was clean" do+ fab!(:workflow) do+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true)+ end+ fab!(:variable) do+ Fabricate(+ :discourse_workflows_workflow_variable,+ workflow:,+ key: "priority",+ variable_type: "enum",+ type_options: {+ "choices" => %w[low medium high],+ },+ )+ end++ it "auto-publishes the value immediately" do+ result+ workflow.reload+ expect(workflow.active_version_id).to eq(workflow.version_id)+ expect(workflow.has_unpublished_changes?).to eq(false)+ end++ it "re-pins the workflow's production webhook to the newly auto-published version" do+ graph =+ build_workflow_graph do |g|+ g.node "webhook-1",+ "trigger:webhook",+ configuration: {+ "path" => "priority-hook",+ "http_method" => "POST",+ }+ end+ workflow.update!(nodes: graph[:nodes], connections: graph[:connections])+ workflow.snapshot!(user: admin)+ workflow.publish!(user: admin)+ published_version_id = workflow.active_version_id++ result++ webhook_row = DiscourseWorkflows::Webhook.production.find_by(workflow_id: workflow.id)+ expect(webhook_row.workflow_version_id).to eq(workflow.reload.active_version_id)+ expect(webhook_row.workflow_version_id).not_to eq(published_version_id)+ end++ it_behaves_like "expires workflow caches"++ context "when another active workflow already owns the same webhook route" do+ before do+ graph =+ build_workflow_graph do |g|+ g.node "webhook-1",+ "trigger:webhook",+ configuration: {+ "path" => "shared-hook",+ "http_method" => "POST",+ }+ end+ owner =+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)+ version = owner.workflow_versions.find_by(version_id: owner.version_id)+ DiscourseWorkflows::Webhook::Action::ActivateWebhooks.call(+ workflow: owner,+ workflow_version: version,+ )++ conflicting_graph =+ build_workflow_graph do |g|+ g.node "webhook-1",+ "trigger:webhook",+ configuration: {+ "path" => "shared-hook",+ "http_method" => "POST",+ }+ end+ workflow.update!(+ nodes: conflicting_graph[:nodes],+ connections: conflicting_graph[:connections],+ )+ workflow.snapshot!(user: admin)+ workflow.publish!(user: admin)+ end++ it { is_expected.to fail_a_step(:activate_triggers) }++ it "still saves the value as a draft, without publishing it" do+ published_version_id = workflow.active_version_id++ result++ expect(variable.reload.value).to eq("medium")+ expect(workflow.reload.active_version_id).to eq(published_version_id)+ expect(workflow.has_unpublished_changes?).to eq(true)+ end+ end+ end++ context "when the workflow is published but has other pending changes" do+ fab!(:workflow) do+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true)+ end+ fab!(:variable) do+ Fabricate(+ :discourse_workflows_workflow_variable,+ workflow:,+ key: "priority",+ variable_type: "enum",+ type_options: {+ "choices" => %w[low medium high],+ },+ )+ end++ it "snapshots the value but does not auto-publish" do+ published_version_id = workflow.active_version_id+ workflow.update!(name: "#{workflow.name} (draft edit)")+ workflow.snapshot!(user: admin)++ expect { result }.to change { workflow.reload.version_counter }+ expect(workflow.reload.active_version_id).to eq(published_version_id)+ expect(workflow.has_unpublished_changes?).to eq(true)+ end+ end+ end+enddiff --git a/plugins/discourse-workflows/spec/system/manage_variables_spec.rb b/plugins/discourse-workflows/spec/system/manage_variables_spec.rbnew file mode 100644index 00000000000..2b3e48314f9--- /dev/null+++ b/plugins/discourse-workflows/spec/system/manage_variables_spec.rb@@ -0,0 +1,91 @@+# frozen_string_literal: true++RSpec.describe "Manage workflow variables" do+ fab!(:admin)+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: admin) }++ let(:variables_page) { PageObjects::Pages::DiscourseWorkflows::WorkflowVariables.new }+ let(:dialog) { PageObjects::Components::Dialog.new }++ before { sign_in(admin) }++ it "lets an admin add a variable from the empty state" do+ variables_page.visit_manage(workflow.id)+ variables_page.click_add_variable_empty_state++ variables_page.fill_in_key("priority")+ variables_page.submit++ expect(page).to have_current_path(+ "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/variables/manage",+ )+ new_variable = workflow.variables.find_by(key: "priority")+ expect(variables_page).to have_variable(new_variable)++ page.refresh+ expect(variables_page).to have_variable(new_variable)+ end++ context "with an existing variable" do+ fab!(:variable) do+ Fabricate(+ :discourse_workflows_workflow_variable,+ workflow:,+ key: "priority",+ variable_type: "string",+ )+ end++ it "lets an admin add another variable via the Add variable button" do+ variables_page.visit_manage(workflow.id)+ variables_page.click_add_variable++ variables_page.fill_in_key("notes")+ variables_page.submit++ expect(page).to have_current_path(+ "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/variables/manage",+ )+ expect(variables_page).to have_variable(variable)+ new_variable = workflow.variables.find_by(key: "notes")+ expect(variables_page).to have_variable(new_variable)+ end++ it "lets an admin edit a variable's key" do+ variables_page.visit_manage(workflow.id)+ variables_page.click_edit(variable)++ expect(variables_page).to have_key_value("priority")++ variables_page.fill_in_key("urgency")+ variables_page.submit++ expect(page).to have_current_path(+ "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/variables/manage",+ )+ expect(variables_page).to have_variable(variable.reload)++ page.refresh+ expect(variables_page).to have_variable(variable.reload)+ end++ it "lets an admin delete a variable after confirming" do+ variables_page.visit_manage(workflow.id)+ variables_page.click_delete(variable)+ dialog.click_yes++ expect(variables_page).to have_no_variable(variable)++ page.refresh+ expect(variables_page).to have_no_variable(variable)+ end++ it "keeps the variable when the admin cancels the delete confirmation" do+ variables_page.visit_manage(workflow.id)+ variables_page.click_delete(variable)+ dialog.click_no++ expect(variables_page).to have_variable(variable)+ end+ end+enddiff --git a/plugins/discourse-workflows/spec/system/page_objects/pages/workflow_editor.rb b/plugins/discourse-workflows/spec/system/page_objects/pages/workflow_editor.rbindex 3b122c5d383..daea77ae71b 100644--- a/plugins/discourse-workflows/spec/system/page_objects/pages/workflow_editor.rb+++ b/plugins/discourse-workflows/spec/system/page_objects/pages/workflow_editor.rb@@ -300,6 +300,24 @@ module PageObjectspage.has_css?(".workflow-rete-node__port-pill", text: "false", wait: 10)end+ def has_publish_banner?+ page.has_css?(".workflows-publish-banner")+ end++ def has_no_publish_banner?+ page.has_no_css?(".workflows-publish-banner")+ end++ def click_publish+ find(".workflows-publish-banner__btn.btn-primary").click+ self+ end++ def click_discard+ find(".workflows-publish-banner__btn.btn-default").click+ self+ end+privatedef workflow_path(workflow)diff --git a/plugins/discourse-workflows/spec/system/page_objects/pages/workflow_variables.rb b/plugins/discourse-workflows/spec/system/page_objects/pages/workflow_variables.rbnew file mode 100644index 00000000000..9313847444a--- /dev/null+++ b/plugins/discourse-workflows/spec/system/page_objects/pages/workflow_variables.rb@@ -0,0 +1,116 @@+# frozen_string_literal: true++module PageObjects+ module Pages+ module DiscourseWorkflows+ class WorkflowVariables < PageObjects::Pages::Base+ BASE_PATH = "/admin/plugins/discourse-workflows/workflows"++ def visit_index(workflow_id)+ page.visit("#{BASE_PATH}/#{workflow_id}/variables")+ self+ end++ def visit_manage(workflow_id)+ page.visit("#{BASE_PATH}/#{workflow_id}/variables/manage")+ self+ end++ def visit_new(workflow_id)+ page.visit("#{BASE_PATH}/#{workflow_id}/variables/new")+ self+ end++ def visit_edit(workflow_id, variable)+ page.visit("#{BASE_PATH}/#{workflow_id}/variables/#{variable.id}/edit")+ self+ end++ def has_variable?(variable)+ has_css?(".d-table__overview-name", text: variable.label) &&+ has_css?(".workflows-variable-key", text: variable.key)+ end++ def has_no_variable?(variable)+ has_no_css?(".d-table__overview-name", text: variable.label)+ end++ def has_variable_value?(variable, value)+ within(value_row_for(variable)) { has_field?(with: value) }+ end++ def fill_in_variable_value(variable, value)+ within(value_row_for(variable)) { fill_in(with: value) }+ self+ end++ def save_variable_value(variable)+ within(value_row_for(variable)) { find(".setting-controls__ok").click }+ self+ end++ def click_add_variable+ find(".workflows-variables__add").click+ self+ end++ def click_add_variable_empty_state+ find(".admin-config-area-empty-list__cta-button").click+ self+ end++ def click_edit(variable)+ within(row_for(variable)) { find(".workflows-variables-table__edit").click }+ self+ end++ def click_delete(variable)+ within(row_for(variable)) { find(".workflows-variables-table__delete").click }+ self+ end++ def has_key_value?(value)+ has_field?("key", with: value)+ end++ def fill_in_key(key)+ fill_in("key", with: key)+ self+ end++ def submit+ find(".form-kit__button").click+ self+ end++ def has_publish_notice?+ has_css?(".workflows-variables-publish-notice")+ end++ def has_no_publish_notice?+ has_no_css?(".workflows-variables-publish-notice")+ end++ def click_publish+ find(".workflows-variables-publish-notice__btn.btn-primary").click+ self+ end++ def click_discard+ find(".workflows-variables-publish-notice__btn.btn-default").click+ self+ end++ private++ def row_for(variable)+ find(".workflows-variables-table__row", text: variable.label)+ end++ def value_row_for(variable)+ "[data-setting='#{variable.key}']"+ end+ end+ end+ end+enddiff --git a/plugins/discourse-workflows/spec/system/publish_and_discard_workflow_spec.rb b/plugins/discourse-workflows/spec/system/publish_and_discard_workflow_spec.rbnew file mode 100644index 00000000000..cd1ccc4be22--- /dev/null+++ b/plugins/discourse-workflows/spec/system/publish_and_discard_workflow_spec.rb@@ -0,0 +1,93 @@+# frozen_string_literal: true++RSpec.describe "Publish and discard a workflow" do+ fab!(:admin)++ let(:variables_page) { PageObjects::Pages::DiscourseWorkflows::WorkflowVariables.new }+ let(:editor_page) { PageObjects::Pages::DiscourseWorkflows::WorkflowEditor.new }+ let(:dialog) { PageObjects::Components::Dialog.new }++ before { sign_in(admin) }++ context "when acting from the Variables page" do+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: admin, published: true) }+ fab!(:variable) do+ Fabricate(:discourse_workflows_workflow_variable, workflow:, key: "priority")+ end++ before { workflow.snapshot!(user: admin) }++ it "lets an admin publish pending changes" do+ variables_page.visit_index(workflow.id)+ expect(variables_page).to have_publish_notice++ variables_page.click_publish+ expect(variables_page).to have_no_publish_notice++ page.refresh+ expect(variables_page).to have_no_publish_notice+ end++ it "lets an admin discard pending changes" do+ variables_page.visit_index(workflow.id)+ expect(variables_page).to have_publish_notice++ variables_page.click_discard+ dialog.click_yes++ expect(variables_page).to have_no_publish_notice++ page.refresh+ expect(variables_page).to have_no_publish_notice+ end+ end++ context "when acting from the canvas" do+ fab!(:workflow) do+ graph = build_workflow_graph { |g| g.node "trigger-1", "trigger:manual" }+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)+ end++ it "lets an admin publish pending canvas changes" do+ graph =+ build_workflow_graph do |g|+ g.node "trigger-1", "trigger:manual"+ g.node "trigger-2", "trigger:schedule"+ end+ workflow.update!(nodes: graph[:nodes], connections: graph[:connections])+ workflow.snapshot!(user: admin)++ editor_page.visit(workflow.id)+ expect(editor_page).to have_publish_banner+ expect(editor_page).to have_node_count(2)++ editor_page.click_publish+ expect(editor_page).to have_no_publish_banner++ page.refresh+ expect(editor_page).to have_node_count(2)+ end++ it "lets an admin discard pending canvas changes and restores the published graph" do+ graph =+ build_workflow_graph do |g|+ g.node "trigger-1", "trigger:manual"+ g.node "trigger-2", "trigger:schedule"+ end+ workflow.update!(nodes: graph[:nodes], connections: graph[:connections])+ workflow.snapshot!(user: admin)++ editor_page.visit(workflow.id)+ expect(editor_page).to have_node_count(2)++ editor_page.click_discard+ dialog.click_yes++ expect(editor_page).to have_no_publish_banner+ expect(editor_page).to have_node_count(1)++ page.refresh+ expect(editor_page).to have_node_count(1)+ end+ end+enddiff --git a/plugins/discourse-workflows/spec/system/variable_values_spec.rb b/plugins/discourse-workflows/spec/system/variable_values_spec.rbnew file mode 100644index 00000000000..83fdb486bab--- /dev/null+++ b/plugins/discourse-workflows/spec/system/variable_values_spec.rb@@ -0,0 +1,39 @@+# frozen_string_literal: true++RSpec.describe "Edit workflow variable values" do+ fab!(:admin)+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: admin) }+ fab!(:priority_variable) do+ Fabricate(+ :discourse_workflows_workflow_variable,+ workflow:,+ key: "priority",+ variable_type: "string",+ )+ end+ fab!(:owner_variable) do+ Fabricate(+ :discourse_workflows_workflow_variable,+ workflow:,+ key: "owner",+ variable_type: "string",+ )+ end++ let(:variables_page) { PageObjects::Pages::DiscourseWorkflows::WorkflowVariables.new }++ before { sign_in(admin) }++ it "saves a variable's value without disturbing a sibling variable's unsaved edit" do+ variables_page.visit_index(workflow.id)++ variables_page.fill_in_variable_value(owner_variable, "alice")+ variables_page.fill_in_variable_value(priority_variable, "urgent")+ variables_page.save_variable_value(priority_variable)++ expect(variables_page).to have_variable_value(owner_variable, "alice")++ page.refresh+ expect(variables_page).to have_variable_value(priority_variable, "urgent")+ end+enddiff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/context-input-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/context-input-test.gjsindex f769b2075f0..51f16af614a 100644--- a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/context-input-test.gjs+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/context-input-test.gjs@@ -9,6 +9,7 @@ const EXPRESSION_CONTEXT = {environment: {$site_settings: { type: "object" },$vars: { type: "object" },+ $workflow_vars: { type: "object" },$current_user: {type: "object",fields: { id: { type: "integer" }, username: { type: "string" } },@@ -236,6 +237,72 @@ module(assert.true(allKeys.includes("resumeFormUrl"));});+ test("workflow_vars expands to show the workflow's declared variables", async function (assert) {+ const node = {+ clientId: "n1",+ type: "action:http_request",+ name: "HTTP",+ };+ const nodes = makeNodes(node);+ this.session = new WorkflowEditorSession({+ lastExecutionRunData: {},+ variables: [+ { key: "notify_categories", variable_type: "category_list" },+ { key: "priority", variable_type: "enum" },+ ],+ });++ await render(+ <template>+ <InputContext+ @connections={{(Array)}}+ @node={{node}}+ @nodes={{nodes}}+ @nodeTypes={{(Array)}}+ @session={{this.session}}+ />+ </template>+ );++ const schemaFields = [+ ...this.element.querySelectorAll(".workflows-schema-field"),+ ];+ const workflowVarsField = schemaFields.find(+ (el) =>+ el+ .querySelector(".workflows-schema-field__key")+ ?.textContent.trim() === "workflow_vars"+ );++ await click(+ workflowVarsField.querySelector(".workflows-schema-field__row")+ );++ const allKeys = [+ ...this.element.querySelectorAll(".workflows-schema-field__key"),+ ].map((el) => el.textContent.trim());++ assert.true(allKeys.includes("notify_categories"));+ assert.true(allKeys.includes("priority"));++ const notifyField = [+ ...this.element.querySelectorAll(".workflows-schema-field__key"),+ ].find((el) => el.textContent.trim() === "notify_categories");+ const dragged = {};+ await triggerEvent(notifyField, "dragstart", {+ dataTransfer: {+ setData(type, value) {+ dragged[type] = value;+ },+ },+ });++ assert.strictEqual(+ JSON.parse(dragged[WORKFLOW_VARIABLE_MIME]).id,+ "$workflow_vars.notify_categories"+ );+ });+test("uses previous node name as the input heading", async function (assert) {const triggerNode = {clientId: "t1",diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/publish-banner-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/publish-banner-test.gjsnew file mode 100644index 00000000000..f2e9b26de33--- /dev/null+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/publish-banner-test.gjs@@ -0,0 +1,47 @@+import { render } from "@ember/test-helpers";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import PublishBanner from "discourse/plugins/discourse-workflows/admin/components/workflows/publish-banner";++module("Integration | Component | Workflows | PublishBanner", function (hooks) {+ setupRenderingTest(hooks);++ test("hides when the published workflow has no pending changes", async function (assert) {+ const workflow = {+ id: 1,+ activeVersionId: "published-uuid",+ hasUnpublishedChanges: false,+ };++ await render(<template><PublishBanner @workflow={{workflow}} /></template>);++ assert.dom(".workflows-publish-banner").doesNotExist();+ });++ test("shows when the published workflow has pending changes", async function (assert) {+ const workflow = {+ id: 1,+ activeVersionId: "published-uuid",+ hasUnpublishedChanges: true,+ };++ await render(<template><PublishBanner @workflow={{workflow}} /></template>);++ assert.dom(".workflows-publish-banner").exists();+ assert+ .dom(".workflows-publish-banner__title")+ .hasText("You have unpublished changes");+ });++ test("shows for a never-published workflow", async function (assert) {+ const workflow = {+ id: 1,+ activeVersionId: null,+ hasUnpublishedChanges: false,+ };++ await render(<template><PublishBanner @workflow={{workflow}} /></template>);++ assert.dom(".workflows-publish-banner").exists();+ });+});diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/variable-definitions-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/variable-definitions-test.gjsnew file mode 100644index 00000000000..91e17d5331c--- /dev/null+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/variable-definitions-test.gjs@@ -0,0 +1,147 @@+import { tracked } from "@glimmer/tracking";+import { click, render } from "@ember/test-helpers";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import WorkflowVariableDefinitions from "discourse/plugins/discourse-workflows/admin/components/workflows/variable-definitions";++class TestWorkflow {+ @tracked variables;+ @tracked hasUnpublishedChanges;+ @tracked versionId;+ @tracked activeVersionId;++ constructor({+ id,+ variables = [],+ hasUnpublishedChanges = false,+ versionId = "draft-uuid",+ activeVersionId = "published-uuid",+ } = {}) {+ this.id = id;+ this.variables = variables;+ this.hasUnpublishedChanges = hasUnpublishedChanges;+ this.versionId = versionId;+ this.activeVersionId = activeVersionId;+ }++ setProperties(props) {+ Object.assign(this, props);+ }+}++module(+ "Integration | Component | WorkflowVariableDefinitions",+ function (hooks) {+ setupRenderingTest(hooks);++ test("renders existing variable definitions", async function (assert) {+ const workflow = new TestWorkflow({+ id: 1,+ variables: [+ {+ id: 10,+ key: "priority",+ label: "Priority",+ variable_type: "string",+ },+ ],+ });++ await render(+ <template>+ <WorkflowVariableDefinitions @workflow={{workflow}} />+ </template>+ );++ assert.dom(".d-table__overview-name").hasText("Priority");+ assert.dom(".workflows-variable-key").hasText("priority");+ assert.dom(".workflows-variables-table__type").hasText("String");+ });++ test("edit navigates to the dedicated edit route", async function (assert) {+ let transitionedTo;+ this.owner.lookup("service:router").transitionTo = (route, ...models) => {+ transitionedTo = { route, models };+ };++ const workflow = new TestWorkflow({+ id: 1,+ variables: [+ {+ id: 10,+ key: "priority",+ label: "Priority",+ variable_type: "string",+ },+ ],+ });++ await render(+ <template>+ <WorkflowVariableDefinitions @workflow={{workflow}} />+ </template>+ );++ await click(".workflows-variables-table__edit");++ assert.deepEqual(transitionedTo, {+ route: "adminPlugins.show.discourse-workflows.show.variables.edit",+ models: [10],+ });+ });++ test("add variable navigates to the dedicated new route", async function (assert) {+ let transitionedTo;+ this.owner.lookup("service:router").transitionTo = (route) => {+ transitionedTo = route;+ };++ const workflow = new TestWorkflow({+ id: 1,+ variables: [+ {+ id: 10,+ key: "priority",+ label: "Priority",+ variable_type: "string",+ },+ ],+ });++ await render(+ <template>+ <WorkflowVariableDefinitions @workflow={{workflow}} />+ </template>+ );++ await click(".workflows-variables__add");++ assert.strictEqual(+ transitionedTo,+ "adminPlugins.show.discourse-workflows.show.variables.new"+ );+ });++ test("empty state CTA navigates to the dedicated new route", async function (assert) {+ let transitionedTo;+ this.owner.lookup("service:router").transitionTo = (route) => {+ transitionedTo = route;+ };++ const workflow = new TestWorkflow({ id: 1, variables: [] });++ await render(+ <template>+ <WorkflowVariableDefinitions @workflow={{workflow}} />+ </template>+ );++ await click(".admin-config-area-empty-list__cta-button");++ assert.strictEqual(+ transitionedTo,+ "adminPlugins.show.discourse-workflows.show.variables.new"+ );+ });+ }+);diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/variable-edit-form-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/variable-edit-form-test.gjsnew file mode 100644index 00000000000..7b17d6d9dc5--- /dev/null+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/variable-edit-form-test.gjs@@ -0,0 +1,122 @@+import { tracked } from "@glimmer/tracking";+import { click, fillIn, render } from "@ember/test-helpers";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import WorkflowVariableForm from "discourse/plugins/discourse-workflows/admin/components/workflows/variable-edit-form";++class TestWorkflow {+ @tracked variables;+ @tracked hasUnpublishedChanges;+ @tracked versionId;+ @tracked activeVersionId;++ constructor({+ id,+ variables = [],+ hasUnpublishedChanges = false,+ versionId = "draft-uuid",+ activeVersionId = "published-uuid",+ } = {}) {+ this.id = id;+ this.variables = variables;+ this.hasUnpublishedChanges = hasUnpublishedChanges;+ this.versionId = versionId;+ this.activeVersionId = activeVersionId;+ }++ setProperties(props) {+ Object.assign(this, props);+ }+}++module("Integration | Component | WorkflowVariableForm", function (hooks) {+ setupRenderingTest(hooks);++ test("has no label field", async function (assert) {+ const workflow = new TestWorkflow({ id: 1, variables: [] });++ await render(+ <template><WorkflowVariableForm @workflow={{workflow}} /></template>+ );++ assert.dom('input[name="label"]').doesNotExist();+ });++ test("create shows the choices editor for enum variables", async function (assert) {+ const workflow = new TestWorkflow({ id: 1, variables: [] });++ await render(+ <template><WorkflowVariableForm @workflow={{workflow}} /></template>+ );++ assert.dom(".simple-list").doesNotExist();++ await fillIn('select[name="variable_type"]', "enum");++ assert.dom(".simple-list").exists("shows the choices editor for enum");+ });++ test("edit pre-fills the form with the existing variable's values", async function (assert) {+ const workflow = new TestWorkflow({+ id: 1,+ variables: [+ {+ id: 10,+ key: "priority",+ label: "Priority",+ description: "How urgent",+ variable_type: "enum",+ type_options: { choices: ["low", "high"] },+ },+ ],+ });++ await render(+ <template>+ <WorkflowVariableForm @variableId="10" @workflow={{workflow}} />+ </template>+ );++ assert.dom('input[name="key"]').hasValue("priority");+ assert.dom('textarea[name="description"]').hasValue("How urgent");+ assert.dom(".simple-list").exists("shows the choices editor for enum");+ });++ test("duplicate key surfaces a validation error", async function (assert) {+ const workflow = new TestWorkflow({+ id: 1,+ variables: [+ { id: 10, key: "priority", label: "Priority", variable_type: "string" },+ { id: 11, key: "notes", label: "Notes", variable_type: "string" },+ ],+ });++ await render(+ <template>+ <WorkflowVariableForm @variableId="11" @workflow={{workflow}} />+ </template>+ );++ await fillIn('input[name="key"]', "priority");+ await click(".form-kit__button");++ assert+ .dom(".form-kit__errors")+ .exists("shows a validation error for the duplicate key");+ });++ test("malformed key surfaces a validation error", async function (assert) {+ const workflow = new TestWorkflow({ id: 1, variables: [] });++ await render(+ <template><WorkflowVariableForm @workflow={{workflow}} /></template>+ );++ await fillIn('input[name="key"]', "1notes");+ await click(".form-kit__button");++ assert+ .dom(".form-kit__errors")+ .exists("shows a validation error for the malformed key");+ });+});diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/variable-list-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/variable-list-test.gjsnew file mode 100644index 00000000000..199bb2d106f--- /dev/null+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/variable-list-test.gjs@@ -0,0 +1,59 @@+import { click, render } from "@ember/test-helpers";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import WorkflowVariableList from "discourse/plugins/discourse-workflows/admin/components/workflows/variable-list";++module("Integration | Component | WorkflowVariableList", function (hooks) {+ setupRenderingTest(hooks);++ test("shows a single Manage variables link when variables exist", async function (assert) {+ const workflow = {+ id: 1,+ variables: [+ { id: 10, key: "priority", label: "Priority", variable_type: "string" },+ ],+ };++ await render(+ <template><WorkflowVariableList @workflow={{workflow}} /></template>+ );++ assert+ .dom(".workflows-variables__manage")+ .exists({ count: 1 }, "renders exactly one entry point");+ assert.dom(".workflows-variables__add").doesNotExist();+ assert.dom(".admin-config-area-empty-list").doesNotExist();+ });++ test("shows the empty-list CTA when there are no variables", async function (assert) {+ const workflow = { id: 1, variables: [] };++ await render(+ <template><WorkflowVariableList @workflow={{workflow}} /></template>+ );++ assert.dom(".admin-config-area-empty-list").exists();+ assert.dom(".workflows-variables__manage").doesNotExist();+ });++ test("empty-list CTA routes directly to the add-variable form", async function (assert) {+ let transitionedTo;+ this.owner.lookup("service:router").transitionTo = (route) => {+ transitionedTo = route;+ };++ const workflow = { id: 1, variables: [] };++ await render(+ <template><WorkflowVariableList @workflow={{workflow}} /></template>+ );++ await click(".admin-config-area-empty-list__cta-button");++ assert.strictEqual(+ transitionedTo,+ "adminPlugins.show.discourse-workflows.show.variables.new",+ "routes straight to the new-variable form, not the (also empty) manage page"+ );+ });+});diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/variables-publish-notice-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/variables-publish-notice-test.gjsnew file mode 100644index 00000000000..ac8f1555cb3--- /dev/null+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/variables-publish-notice-test.gjs@@ -0,0 +1,97 @@+import { click, render } from "@ember/test-helpers";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import VariablesPublishNotice from "discourse/plugins/discourse-workflows/admin/components/workflows/variables-publish-notice";++module(+ "Integration | Component | Workflows | VariablesPublishNotice",+ function (hooks) {+ setupRenderingTest(hooks);++ test("hides when the published workflow has no pending changes", async function (assert) {+ const workflow = {+ id: 1,+ activeVersionId: "published-uuid",+ hasUnpublishedChanges: false,+ };++ await render(+ <template><VariablesPublishNotice @workflow={{workflow}} /></template>+ );++ assert.dom(".workflows-variables-publish-notice").doesNotExist();+ });++ test("shows when the published workflow has pending changes", async function (assert) {+ const workflow = {+ id: 1,+ activeVersionId: "published-uuid",+ hasUnpublishedChanges: true,+ };++ await render(+ <template><VariablesPublishNotice @workflow={{workflow}} /></template>+ );++ assert.dom(".workflows-variables-publish-notice").exists();+ assert+ .dom(".workflows-variables-publish-notice__title")+ .hasText("You have unpublished changes");+ });++ test("shows for a never-published workflow", async function (assert) {+ const workflow = {+ id: 1,+ activeVersionId: null,+ hasUnpublishedChanges: false,+ };++ await render(+ <template><VariablesPublishNotice @workflow={{workflow}} /></template>+ );++ assert.dom(".workflows-variables-publish-notice").exists();+ });++ test("publish failure surfaces an error and leaves the workflow's state untouched", async function (assert) {+ pretender.put("/admin/plugins/discourse-workflows/workflows/1.json", () =>+ response(422, { errors: ["Something went wrong"] })+ );++ const workflow = {+ id: 1,+ versionId: "draft-uuid",+ activeVersionId: "published-uuid",+ hasUnpublishedChanges: true,+ };++ let alertedWith;+ this.owner.lookup("service:dialog").alert = (message) =>+ (alertedWith = message);++ await render(+ <template><VariablesPublishNotice @workflow={{workflow}} /></template>+ );++ await click(".workflows-variables-publish-notice__btn.btn-primary");++ assert.true(+ String(alertedWith).includes("Something went wrong"),+ "the error is surfaced to the admin"+ );+ assert.strictEqual(+ workflow.activeVersionId,+ "published-uuid",+ "the workflow's active version is unchanged"+ );+ assert.true(+ workflow.hasUnpublishedChanges,+ "the workflow still has unpublished changes"+ );+ assert+ .dom(".workflows-variables-publish-notice")+ .exists("the notice is still shown, not stuck hidden");+ });+ }+);diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/variables-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/variables-test.gjsnew file mode 100644index 00000000000..303f18ec707--- /dev/null+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/variables-test.gjs@@ -0,0 +1,91 @@+import { render } from "@ember/test-helpers";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import WorkflowVariables from "discourse/plugins/discourse-workflows/admin/components/workflows/variables";++function buildWorkflow(overrides = {}) {+ return {+ id: 1,+ name: "Test workflow",+ versionId: "draft-uuid",+ activeVersionId: "published-uuid",+ hasUnpublishedChanges: false,+ variables: [],+ setProperties(props) {+ Object.assign(this, props);+ },+ ...overrides,+ };+}++module("Integration | Component | WorkflowVariables", function (hooks) {+ setupRenderingTest(hooks);++ test("escapes HTML in a variable's description before rendering it", async function (assert) {+ const workflow = buildWorkflow({+ variables: [+ {+ id: 10,+ key: "priority",+ label: "Priority",+ description: "<img src=x onerror=alert(1)>",+ variable_type: "string",+ type_options: {},+ value: "",+ },+ ],+ });++ await render(+ <template><WorkflowVariables @workflow={{workflow}} /></template>+ );++ assert+ .dom("[data-setting='priority'] img")+ .doesNotExist(+ "the description does not render as an executable <img> element"+ );+ assert+ .dom("[data-setting='priority'] .setting-value .desc")+ .includesText(+ "<img src=x onerror=alert(1)>",+ "the description renders as inert text"+ );+ });++ test("hides the publish notice when the workflow has no local variables", async function (assert) {+ const workflow = buildWorkflow({+ hasUnpublishedChanges: true,+ variables: [],+ });++ await render(+ <template><WorkflowVariables @workflow={{workflow}} /></template>+ );++ assert.dom(".workflows-variables-publish-notice").doesNotExist();+ });++ test("shows the publish notice when the workflow has local variables and pending changes", async function (assert) {+ const workflow = buildWorkflow({+ hasUnpublishedChanges: true,+ variables: [+ {+ id: 10,+ key: "priority",+ label: "Priority",+ description: "",+ variable_type: "string",+ type_options: {},+ value: "",+ },+ ],+ });++ await render(+ <template><WorkflowVariables @workflow={{workflow}} /></template>+ );++ assert.dom(".workflows-variables-publish-notice").exists();+ });+});diff --git a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas-test.js b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas-test.jsindex 44966f4bc29..4572a95778a 100644--- a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas-test.js+++ b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas-test.js@@ -1,7 +1,6 @@import { setupTest } from "ember-qunit";import { module, test } from "qunit";import pretender, { response } from "discourse/tests/helpers/create-pretender";-import { i18n } from "discourse-i18n";import WorkflowCanvas from "discourse/plugins/discourse-workflows/admin/components/workflows/canvas";module("Unit | Component | workflows canvas", function (hooks) {@@ -45,76 +44,6 @@ module("Unit | Component | workflows canvas", function (hooks) {assert.verifySteps(["browse"]);});- test("publish success clears optimistic unpublished changes override", async function (assert) {- pretender.put("/admin/plugins/discourse-workflows/workflows/1.json", () =>- response({})- );-- const workflow = {- versionId: "draft-uuid",- activeVersionId: "published-uuid",- hasUnpublishedChanges: true,- };-- const canvas = Object.create(WorkflowCanvas.prototype);- Object.defineProperty(canvas, "args", {- value: {- workflow,- workflowId: 1,- nodes: [{ clientId: "node-1", type: "trigger:manual" }],- get workflowPublished() {- return workflow.activeVersionId;- },- get hasUnpublishedChanges() {- return workflow.hasUnpublishedChanges;- },- },- });-- await canvas.publishWorkflow();-- assert.true(canvas.publishDisabled, "publish is disabled after publish");- assert.false(- canvas.showPublishButton,- "publish is hidden after publish with no draft changes"- );- assert.false(- canvas.showToolbarPublishButton,- "toolbar publish is hidden after publish with no draft changes"- );- assert.false(- canvas.showUnpublishedChangesMessage,- "unpublished changes message is hidden after publish with no draft changes"- );- assert.false(- canvas.showDiscardChangesButton,- "discard changes is hidden after publish with no draft changes"- );-- workflow.hasUnpublishedChanges = true;-- assert.false(- canvas.publishDisabled,- "later draft edits can re-enable publish"- );- assert.true(- canvas.showPublishButton,- "later draft edits show publish again"- );- assert.false(- canvas.showToolbarPublishButton,- "later draft edits move publish into the unpublished changes panel"- );- assert.true(- canvas.showUnpublishedChangesMessage,- "later draft edits show the unpublished changes message"- );- assert.true(- canvas.showDiscardChangesButton,- "later draft edits show discard changes"- );- });-test("unpublish closes the menu", async function (assert) {pretender.put("/admin/plugins/discourse-workflows/workflows/1.json", () =>response({})@@ -144,148 +73,19 @@ module("Unit | Component | workflows canvas", function (hooks) {canvas.workflowPublished,"workflow is no longer published after unpublish");- assert.false(- canvas.showToolbarPublishButton,- "toolbar publish remains hidden for fully unpublished workflows"- );- assert.true(- canvas.showUnpublishedChangesMessage,- "publish status remains visible for fully unpublished workflows"- );- assert.false(- canvas.showDiscardChangesButton,- "discard changes is hidden for fully unpublished workflows"- );});- test("discard success clears unpublished changes and syncs workflow", async function (assert) {- const restoredWorkflow = {- id: "1",- name: "Published workflow",- nodes: [{ id: "published-1", type: "trigger:manual" }],- connections: {},- version_id: "published-uuid",- active_version_id: "published-uuid",- has_unpublished_changes: false,- };-- pretender.post(- "/admin/plugins/discourse-workflows/workflows/1/discard-draft.json",- () => response({ workflow: restoredWorkflow })- );-- const state = {- hasUnpublishedChanges: true,- workflowPublished: "published-uuid",- };+ test("hasNodes reflects whether the canvas has any nodes", function (assert) {const canvas = Object.create(WorkflowCanvas.prototype);- Object.defineProperty(canvas, "dialog", {- value: {- confirm({ message, confirmButtonLabel, cancelButtonLabel }) {- assert.strictEqual(- message,- i18n("discourse_workflows.discard_changes_confirmation")- );- assert.strictEqual(- confirmButtonLabel,- "discourse_workflows.discard_changes"- );- assert.strictEqual(- cancelButtonLabel,- "discourse_workflows.keep_editing"- );- return true;- },- },- });Object.defineProperty(canvas, "args", {- value: {- workflowId: 1,- nodes: [{ clientId: "node-1", type: "trigger:manual" }],- get hasUnpublishedChanges() {- return state.hasUnpublishedChanges;- },- get workflowPublished() {- return state.workflowPublished;- },- onDiscardWorkflow(workflow) {- state.hasUnpublishedChanges = workflow.has_unpublished_changes;- state.workflowPublished = workflow.active_version_id;- assert.deepEqual(- workflow,- restoredWorkflow,- "restored workflow is passed to the editor"- );- assert.step("discarded");- },- },- });-- assert.true(- canvas.showUnpublishedChangesMessage,- "unpublished changes message is visible before discard"- );-- await canvas.discardWorkflow();-- assert.verifySteps(["discarded"]);- assert.false(- canvas.showUnpublishedChangesMessage,- "unpublished changes message is hidden after discard"- );- assert.false(- canvas.showDiscardChangesButton,- "discard changes is hidden after discard"- );- });-- test("publish is hidden until the workflow has a node", async function (assert) {- const canvas = Object.create(WorkflowCanvas.prototype);- Object.defineProperty(canvas, "args", {- value: {- workflowId: 1,- nodes: [],- workflowPublished: null,- hasUnpublishedChanges: true,- },+ value: { nodes: [] },});assert.false(canvas.hasNodes, "the workflow has no nodes");- assert.false(- canvas.showPublishButton,- "publish is hidden before a node is added"- );- assert.false(- canvas.showToolbarPublishButton,- "toolbar publish is hidden before a node is added"- );- assert.false(- canvas.showUnpublishedChangesMessage,- "unpublished changes publish message is hidden before a node is added"- );-- await canvas.publishWorkflow();-- assert.strictEqual(- canvas.workflowPublishedOverride,- null,- "publish action does not optimistically mark an empty workflow published"- );canvas.args.nodes.push({ clientId: "node-1", type: "trigger:manual" });- assert.false(- canvas.showToolbarPublishButton,- "toolbar publish stays hidden once a node exists"- );- assert.true(- canvas.showUnpublishedChangesMessage,- "publish status is shown once a node exists"- );- assert.false(- canvas.showDiscardChangesButton,- "discard changes is hidden for an unpublished workflow"- );+ assert.true(canvas.hasNodes, "the workflow has a node");});test("translateSelected moves selected sticky notes and selected nodes", async function (assert) {diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/expression-context-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/expression-context-test.jsindex 011ecd2567a..c33d0d093de 100644--- a/plugins/discourse-workflows/test/javascripts/unit/lib/expression-context-test.js+++ b/plugins/discourse-workflows/test/javascripts/unit/lib/expression-context-test.js@@ -131,9 +131,9 @@ module("Unit | lib | discourse-workflows | buildScope", function () {assert.deepEqual(Object.keys(ref.item.json), []);});- test("builds $vars from workflowVars", function (assert) {+ test("builds $vars from globalVars", function (assert) {const scope = buildScope({- workflowVars: [+ globalVars: [{ key: "API_KEY", value: "secret" },{ key: "URL", value: "https://example.com" },],@@ -143,6 +143,42 @@ module("Unit | lib | discourse-workflows | buildScope", function () {assert.strictEqual(scope.$vars.URL, "https://example.com");});+ test("builds $workflow_vars with typed values from workflowVariables", function (assert) {+ const scope = buildScope({+ workflowVariables: [+ { key: "priority", variable_type: "string", value: "urgent" },+ { key: "max_retries", variable_type: "integer", value: "3" },+ { key: "enabled", variable_type: "boolean", value: "true" },+ { key: "categories", variable_type: "category_list", value: "4|9" },+ { key: "tags", variable_type: "tag_list", value: "bug|urgent" },+ { key: "category", variable_type: "category", value: "7" },+ { key: "group", variable_type: "group", value: "12" },+ ],+ });++ assert.strictEqual(scope.$workflow_vars.priority, "urgent");+ assert.strictEqual(scope.$workflow_vars.max_retries, 3);+ assert.true(scope.$workflow_vars.enabled);+ assert.deepEqual(scope.$workflow_vars.categories, [4, 9]);+ assert.deepEqual(scope.$workflow_vars.tags, ["bug", "urgent"]);+ assert.strictEqual(scope.$workflow_vars.category, 7);+ assert.strictEqual(scope.$workflow_vars.group, 12);+ });++ test("falls back to a type exemplar when a $workflow_vars field has no value", function (assert) {+ const scope = buildScope({+ workflowVariables: [+ { key: "priority", variable_type: "string" },+ { key: "max_retries", variable_type: "integer" },+ { key: "categories", variable_type: "category_list" },+ ],+ });++ assert.strictEqual(scope.$workflow_vars.priority, "");+ assert.strictEqual(scope.$workflow_vars.max_retries, 0);+ assert.deepEqual(scope.$workflow_vars.categories, []);+ });+test("builds $execution with standard fields", function (assert) {const scope = buildScope({});diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/expression-reference-label-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/expression-reference-label-test.jsindex bfba705259f..d2f276a0d57 100644--- a/plugins/discourse-workflows/test/javascripts/unit/lib/expression-reference-label-test.js+++ b/plugins/discourse-workflows/test/javascripts/unit/lib/expression-reference-label-test.js@@ -50,6 +50,10 @@ module("Unit | lib | discourse-workflows | parseReference", function () {test("parses the remaining dollar roots", function (assert) {assert.strictEqual(parseReference("$vars.api_key").source.type, "variable");+ assert.strictEqual(+ parseReference("$workflow_vars.priority").source.type,+ "workflow_variable"+ );assert.strictEqual(parseReference("$current_user.username").source.type,"current_user"@@ -118,6 +122,19 @@ module("Unit | lib | discourse-workflows | referenceLabel", function () {assert.strictEqual(itemIndex.icon, "hashtag");});+ test("labels $workflow_vars distinctly from $vars", function (assert) {+ const globalVar = referenceLabel(parseReference("$vars.api_key"));+ assert.strictEqual(globalVar.sourceType, "variable");+ assert.strictEqual(globalVar.badge, "Variable");++ const workflowVar = referenceLabel(+ parseReference("$workflow_vars.priority")+ );+ assert.strictEqual(workflowVar.sourceType, "workflow_variable");+ assert.strictEqual(workflowVar.badge, "Workflow variable");+ assert.strictEqual(workflowVar.icon, "dollar-sign");+ });+test("returns null for unparseable expressions", function (assert) {assert.strictEqual(referenceLabel(parseReference("$json.a + 1")), null);});diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-canvas-file-io-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-canvas-file-io-test.jsindex 8a4b9b13efc..be2a826dc98 100644--- a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-canvas-file-io-test.js+++ b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-canvas-file-io-test.js@@ -32,6 +32,17 @@ module("Unit | lib | discourse-workflows | canvas-file-io", function () {id: 42,name: "Imported workflow",settings: { executionOrder: "v1" },+ variables: [+ {+ id: 7,+ key: "notify_categories",+ label: "Notify categories",+ description: "Categories to notify",+ variable_type: "category_list",+ type_options: {},+ value: "2|24",+ },+ ],staticData: { "node:Send request": { count: 1 } },pinData: { "node-1": [{ json: { ok: true } }] },versionId: "version-1",@@ -44,6 +55,14 @@ module("Unit | lib | discourse-workflows | canvas-file-io", function () {nodes: payload.nodes,connections: {},settings: { executionOrder: "v1" },+ variables: [+ {+ key: "notify_categories",+ description: "Categories to notify",+ variable_type: "category_list",+ type_options: {},+ },+ ],staticData: { "node:Send request": { count: 1 } },});assert.deepEqual(payload.nodes[0].credentials, {@@ -55,6 +74,14 @@ module("Unit | lib | discourse-workflows | canvas-file-io", function () {assert.true(payload.nodes[0].alwaysOutputData);assert.false("settings" in payload.nodes[0]);assert.false("credentials" in payload.nodes[0].parameters);+ assert.false(+ "id" in payload.variables[0],+ "export never includes a variable's database id"+ );+ assert.false(+ "value" in payload.variables[0],+ "export never includes a variable's site-specific value"+ );});test("buildWorkflowExportPayload serializes multi-output connections without null holes", function (assert) {@@ -311,6 +338,84 @@ module("Unit | lib | discourse-workflows | canvas-file-io", function () {}});+ test("parseWorkflowImport preserves imported variables", function (assert) {+ const result = parseWorkflowImport(+ JSON.stringify({+ nodes: [+ {+ type: "action:log",+ typeVersion: "1.0",+ name: "Log",+ parameters: {},+ },+ ],+ connections: {},+ variables: [+ {+ key: "notify_categories",+ description: "Categories to notify",+ variable_type: "category_list",+ type_options: {},+ },+ ],+ })+ );++ assert.deepEqual(result.variables, [+ {+ key: "notify_categories",+ description: "Categories to notify",+ variable_type: "category_list",+ type_options: {},+ },+ ]);+ });++ test("parseWorkflowImport fills in defaults for a malformed variable", function (assert) {+ const result = parseWorkflowImport(+ JSON.stringify({+ nodes: [+ {+ type: "action:log",+ typeVersion: "1.0",+ name: "Log",+ parameters: {},+ },+ ],+ connections: {},+ variables: [{ key: "priority" }, { description: "No key, dropped" }],+ })+ );++ assert.deepEqual(result.variables, [+ {+ key: "priority",+ description: null,+ variable_type: "string",+ type_options: {},+ },+ ]);+ });++ test("parseWorkflowImport rejects a non-array variables", function (assert) {+ const result = parseWorkflowImport(+ JSON.stringify({+ nodes: [+ {+ type: "action:log",+ typeVersion: "1.0",+ name: "Log",+ parameters: {},+ },+ ],+ connections: {},+ variables: "not-an-array",+ })+ );++ assert.deepEqual(result, { error: "invalid" });+ });+test("parseWorkflowImport rejects non-object workflow JSON", function (assert) {assert.deepEqual(parseWorkflowImport("null"), { error: "invalid" });assert.deepEqual(parseWorkflowImport("[]"), { error: "invalid" });