A platform for community discussion. Free, open, simple.
FEATURE: Add workflow tags (#42056)
Joffrey JAFFEUX46ddecdbb865
diff --git a/app/assets/stylesheets/common/components/d-multi-select.scss b/app/assets/stylesheets/common/components/d-multi-select.scssindex bead6b0add9..ceb2edaf6d0 100644--- a/app/assets/stylesheets/common/components/d-multi-select.scss+++ b/app/assets/stylesheets/common/components/d-multi-select.scss@@ -1,14 +1,14 @@.d-multi-select-trigger {@include form-item-sizing;display: inline-flex;- border-radius: var(--d-border-radius);+ border-radius: var(--d-input-border-radius);cursor: pointer;align-items: center;gap: 0.25em;line-height: normal;box-sizing: border-box;width: 200px;- border: 1px solid var(--primary-low-mid);+ border: var(--d-input-border);justify-content: space-between;&.-expanded {diff --git a/db/structure.sql b/db/structure.sqlindex b4f7d7e6f32..9eef9dc4fcb 100644--- a/db/structure.sql+++ b/db/structure.sql@@ -4730,6 +4730,37 @@ CREATE SEQUENCE public.discourse_workflows_executions_id_seqALTER SEQUENCE public.discourse_workflows_executions_id_seq OWNED BY public.discourse_workflows_executions.id;+--+-- Name: discourse_workflows_tags; Type: TABLE; Schema: public; Owner: -+--++CREATE TABLE public.discourse_workflows_tags (+ id bigint NOT NULL,+ name character varying(100) NOT NULL,+ created_at timestamp(6) without time zone NOT NULL,+ updated_at timestamp(6) without time zone NOT NULL+);+++--+-- Name: discourse_workflows_tags_id_seq; Type: SEQUENCE; Schema: public; Owner: -+--++CREATE SEQUENCE public.discourse_workflows_tags_id_seq+ START WITH 1+ INCREMENT BY 1+ NO MINVALUE+ NO MAXVALUE+ CACHE 1;+++--+-- Name: discourse_workflows_tags_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -+--++ALTER SEQUENCE public.discourse_workflows_tags_id_seq OWNED BY public.discourse_workflows_tags.id;++---- Name: discourse_workflows_variables; Type: TABLE; Schema: public; Owner: ---@@ -4911,6 +4942,37 @@ CREATE SEQUENCE public.discourse_workflows_workflow_publish_history_id_seqALTER SEQUENCE public.discourse_workflows_workflow_publish_history_id_seq OWNED BY public.discourse_workflows_workflow_publish_history.id;+--+-- Name: discourse_workflows_workflow_tags; Type: TABLE; Schema: public; Owner: -+--++CREATE TABLE public.discourse_workflows_workflow_tags (+ id bigint NOT NULL,+ workflow_id bigint NOT NULL,+ workflow_tag_id bigint NOT NULL,+ created_at timestamp(6) without time zone DEFAULT CURRENT_TIMESTAMP NOT NULL+);+++--+-- Name: discourse_workflows_workflow_tags_id_seq; Type: SEQUENCE; Schema: public; Owner: -+--++CREATE SEQUENCE public.discourse_workflows_workflow_tags_id_seq+ START WITH 1+ INCREMENT BY 1+ NO MINVALUE+ NO MAXVALUE+ CACHE 1;+++--+-- Name: discourse_workflows_workflow_tags_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -+--++ALTER SEQUENCE public.discourse_workflows_workflow_tags_id_seq OWNED BY public.discourse_workflows_workflow_tags.id;++---- Name: discourse_workflows_workflow_versions; Type: TABLE; Schema: public; Owner: ---@@ -13200,6 +13262,13 @@ ALTER TABLE ONLY public.discourse_workflows_execution_stats ALTER COLUMN id SETALTER TABLE ONLY public.discourse_workflows_executions ALTER COLUMN id SET DEFAULT nextval('public.discourse_workflows_executions_id_seq'::regclass);+--+-- Name: discourse_workflows_tags id; Type: DEFAULT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.discourse_workflows_tags ALTER COLUMN id SET DEFAULT nextval('public.discourse_workflows_tags_id_seq'::regclass);++---- Name: discourse_workflows_variables id; Type: DEFAULT; Schema: public; Owner: ---@@ -13235,6 +13304,13 @@ ALTER TABLE ONLY public.discourse_workflows_workflow_dependencies ALTER COLUMN iALTER TABLE ONLY public.discourse_workflows_workflow_publish_history ALTER COLUMN id SET DEFAULT nextval('public.discourse_workflows_workflow_publish_history_id_seq'::regclass);+--+-- Name: discourse_workflows_workflow_tags id; Type: DEFAULT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.discourse_workflows_workflow_tags ALTER COLUMN id SET DEFAULT nextval('public.discourse_workflows_workflow_tags_id_seq'::regclass);++---- Name: discourse_workflows_workflows id; Type: DEFAULT; Schema: public; Owner: ---@@ -15566,6 +15642,14 @@ ALTER TABLE ONLY public.discourse_workflows_executionsADD CONSTRAINT discourse_workflows_executions_pkey PRIMARY KEY (id);+--+-- Name: discourse_workflows_tags discourse_workflows_tags_pkey; Type: CONSTRAINT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.discourse_workflows_tags+ ADD CONSTRAINT discourse_workflows_tags_pkey PRIMARY KEY (id);++---- Name: discourse_workflows_variables discourse_workflows_variables_pkey; Type: CONSTRAINT; Schema: public; Owner: ---@@ -15606,6 +15690,14 @@ ALTER TABLE ONLY public.discourse_workflows_workflow_publish_historyADD CONSTRAINT discourse_workflows_workflow_publish_history_pkey PRIMARY KEY (id);+--+-- Name: discourse_workflows_workflow_tags discourse_workflows_workflow_tags_pkey; Type: CONSTRAINT; Schema: public; Owner: -+--++ALTER TABLE ONLY public.discourse_workflows_workflow_tags+ ADD CONSTRAINT discourse_workflows_workflow_tags_pkey PRIMARY KEY (id);++---- Name: discourse_workflows_workflow_versions discourse_workflows_workflow_versions_pkey; Type: CONSTRAINT; Schema: public; Owner: ---@@ -17686,6 +17778,13 @@ CREATE INDEX idx_dwf_executions_on_workflow_version_id ON public.discourse_workfCREATE INDEX idx_dwf_publish_history_on_workflow_created_at_id_desc ON public.discourse_workflows_workflow_publish_history USING btree (workflow_id, created_at DESC, id DESC);+--+-- Name: idx_dwf_tags_on_name; Type: INDEX; Schema: public; Owner: -+--++CREATE UNIQUE INDEX idx_dwf_tags_on_name ON public.discourse_workflows_tags USING btree (name);++---- Name: idx_dwf_variables_on_created_by_id; Type: INDEX; Schema: public; Owner: ---@@ -17756,6 +17855,20 @@ CREATE INDEX idx_dwf_webhooks_on_workflow_id ON public.discourse_workflows_webhoCREATE INDEX idx_dwf_webhooks_on_workflow_version_id ON public.discourse_workflows_webhooks USING btree (workflow_version_id);+--+-- Name: idx_dwf_workflow_tags_on_tag_workflow; Type: INDEX; Schema: public; Owner: -+--++CREATE UNIQUE INDEX idx_dwf_workflow_tags_on_tag_workflow ON public.discourse_workflows_workflow_tags USING btree (workflow_tag_id, workflow_id);+++--+-- Name: idx_dwf_workflow_tags_on_workflow_tag; Type: INDEX; Schema: public; Owner: -+--++CREATE UNIQUE INDEX idx_dwf_workflow_tags_on_workflow_tag ON public.discourse_workflows_workflow_tags USING btree (workflow_id, workflow_tag_id);++---- Name: idx_dwf_workflows_on_active_version_id; Type: INDEX; Schema: public; Owner: ---@@ -22882,6 +22995,7 @@ ALTER TABLE ONLY public.ad_plugin_house_ads_groupsSET search_path TO "$user", public;INSERT INTO "schema_migrations" (version) VALUES+('20260723100008'),('20260723013754'),('20260722140539'),('20260722140536'),diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/adapters/discourse-workflows-workflow.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/adapters/discourse-workflows-workflow.jsindex e4595e7cd11..284f0055ee2 100644--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/adapters/discourse-workflows-workflow.js+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/adapters/discourse-workflows-workflow.js@@ -1,3 +1,4 @@+import { underscore } from "@ember/string";import RestAdapter from "discourse/adapters/rest";export default class DiscourseWorkflowsWorkflowAdapter extends RestAdapter {@@ -8,7 +9,10 @@ export default class DiscourseWorkflowsWorkflowAdapter extends RestAdapter {}pathFor(store, type, findArgs) {- return super.pathFor(store, type, findArgs) + ".json";+ const path =+ this.basePath() + underscore(store.pluralize(this.apiNameFor()));+ const result = this.appendQueryParams(path, findArgs, ".json");+ return result === path ? `${path}.json` : result;}apiNameFor() {diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/index.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/index.gjsindex e168f981301..d08ae7d830a 100644--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/index.gjs+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/index.gjs@@ -1,12 +1,23 @@import Component from "@glimmer/component";import { tracked } from "@glimmer/tracking";+import { fn, hash } from "@ember/helper";+import { on } from "@ember/modifier";import { action } from "@ember/object";import { LinkTo } from "@ember/routing";import { service } from "@ember/service";import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";+import discourseDebounce from "discourse/lib/debounce";+import { INPUT_DELAY } from "discourse/lib/environment";+import getURL from "discourse/lib/get-url";+import DiscourseURL, {+ applyQueryParams,+ searchParamsFromPath,+} from "discourse/lib/url";import { eq } from "discourse/truth-helpers";import DButton from "discourse/ui-kit/d-button";+import DFilterInput from "discourse/ui-kit/d-filter-input";+import DMultiSelect from "discourse/ui-kit/d-multi-select";import dAvatar from "discourse/ui-kit/helpers/d-avatar";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";import dFormatDate from "discourse/ui-kit/helpers/d-format-date";@@ -14,23 +25,175 @@ import dIcon from "discourse/ui-kit/helpers/d-icon";import { i18n } from "discourse-i18n";import AdminTable from "./admin-table";import EmptyState from "./empty-state";-import Stats from "./stats";export default class WorkflowsIndex extends Component {@service currentUser;@service router;+ @service store;@tracked loading = false;+ @tracked filtering = false;+ @tracked filteredResultSet = null;+ @tracked nameFilter = null;+ @tracked tagFilter = [];+ @tracked hasWorkflows = this.args.workflows.totalRows > 0;++ #latestRequest = null;++ constructor() {+ super(...arguments);++ const params = searchParamsFromPath(this.router.currentURL);+ this.nameFilter = params.get("filter");+ this.tagFilter = this.normalizeTagFilter(params.get("tags"));++ if (this.hasActiveFilters) {+ // the route model is unfiltered; refetch so deep links apply, and keep+ // the filter bar visible even when the filtered set comes back empty+ this.hasWorkflows = true;+ this.refetch();+ }+ }++ get workflowTags() {+ return this.args.workflowTags ?? [];+ }++ get availableTagNames() {+ return this.workflowTags.map((tag) => tag.name);+ }++ normalizeTagName(tag) {+ return (tag || "").trim().toLowerCase().replace(/\s+/g, " ");+ }++ normalizeTagFilter(tagsParam) {+ return (tagsParam || "")+ .split(",")+ .map((tag) => this.normalizeTagName(tag))+ .filter(Boolean)+ .filter((tag) => this.availableTagNames.includes(tag));+ }++ get resultSet() {+ return this.filteredResultSet ?? this.args.workflows;+ }++ get hasActiveFilters() {+ return Boolean(this.nameFilter) || this.tagFilter.length > 0;+ }++ get tagSelection() {+ return this.workflowTags.filter((tag) => this.tagFilter.includes(tag.name));+ }++ @action+ async loadTags(searchTerm) {+ const term = (searchTerm || "").toLowerCase();+ return this.workflowTags.filter((tag) => tag.name.includes(term));+ }++ async refetch() {+ this.filtering = true;++ const args = {};+ if (this.nameFilter) {+ args.filter = this.nameFilter;+ }+ if (this.tagFilter.length) {+ args.tags = this.tagFilter.join(",");+ }++ const token = (this.#latestRequest = {});+ try {+ const result = await this.store.findAll(+ "discourse-workflows-workflow",+ args+ );+ if (token === this.#latestRequest) {+ this.filteredResultSet = result;+ if (!this.hasActiveFilters) {+ this.hasWorkflows = result.totalRows > 0;+ }+ }+ } catch (e) {+ popupAjaxError(e);+ } finally {+ if (token === this.#latestRequest) {+ this.filtering = false;+ }+ }+ }++ syncQueryParams() {+ if (!this.router.currentURL) {+ return;+ }++ DiscourseURL.replaceState(+ applyQueryParams(this.router.currentURL, {+ filter: this.nameFilter || null,+ tags: this.tagFilter.length ? this.tagFilter.join(",") : null,+ })+ );+ }++ @action+ applyFilters() {+ this.syncQueryParams();+ this.refetch();+ }++ @action+ onNameFilterChange(event) {+ this.nameFilter = event.target.value || null;+ discourseDebounce(this, this.applyFilters, INPUT_DELAY);+ }++ @action+ onTagFilterChange(selection) {+ this.tagFilter = selection.map((tag) => tag.name);+ this.applyFilters();+ }++ @action+ addTagFilter(tagName, event) {+ event?.preventDefault();++ if (this.tagFilter.includes(tagName)) {+ return;+ }++ this.tagFilter = [...this.tagFilter, tagName];+ this.applyFilters();+ }++ @action+ tagFilterHref(tagName) {+ return getURL(+ applyQueryParams(+ this.router.urlFor("adminPlugins.show.discourse-workflows.index"),+ { tags: tagName }+ )+ );+ }++ @action+ resetFilters() {+ this.nameFilter = null;+ this.tagFilter = [];+ this.applyFilters();+ }@actionasync loadMore() {- if (!this.args.workflows.canLoadMore || this.loading) {+ if (!this.resultSet.canLoadMore || this.loading) {return;}this.loading = true;try {- await this.args.workflows.loadMore();+ await this.resultSet.loadMore();} finally {this.loading = false;}@@ -80,133 +243,203 @@ export default class WorkflowsIndex extends Component {}<template>- <Stats @stats={{@stats}} />-- <AdminTable- @items={{@workflows.content}}- @isLoading={{false}}- @canLoadMore={{@workflows.canLoadMore}}- @loadMore={{this.loadMore}}- @loadingMore={{this.loading}}- @rowClass="workflows-index__row"- >- <:empty>- <EmptyState- @emoji="wave"- @title={{i18n- "discourse_workflows.empty_title"- username=this.currentUser.displayName- }}- @description={{i18n "discourse_workflows.empty_description"}}- @buttonLabel="discourse_workflows.create_first_workflow"- @onAction={{this.createWorkflow}}- />- </:empty>- <:toolbar>+ {{#if this.hasWorkflows}}+ <div class="d-filter-controls workflows-index__filters">+ <div class="d-filter-controls__inputs">+ <DFilterInput+ placeholder={{i18n "discourse_workflows.search_placeholder"}}+ @filterAction={{this.onNameFilterChange}}+ @value={{this.nameFilter}}+ class="d-filter-controls__input"+ @icons={{hash left="magnifying-glass"}}+ />++ <DMultiSelect+ @loadFn={{this.loadTags}}+ @selection={{this.tagSelection}}+ @onChange={{this.onTagFilterChange}}+ @label={{i18n "discourse_workflows.tags.filter_label"}}+ @noResultsLabel={{i18n "discourse_workflows.tags.no_results"}}+ class="workflows-index__tag-filter"+ >+ <:selection as |tag|>{{tag.name}}</:selection>+ <:result as |tag|>+ <span class="workflows-index__tag-filter-name">+ {{tag.name}}+ </span>+ <span class="workflows-index__tag-filter-count">+ {{tag.workflow_count}}+ </span>+ </:result>+ </DMultiSelect>++ {{#unless this.filtering}}+ {{#if this.hasActiveFilters}}+ <DButton+ @icon="arrow-rotate-left"+ @label="filter_controls.reset"+ @action={{this.resetFilters}}+ class="btn-default d-filter-controls__reset"+ />+ {{/if}}+ {{/unless}}+ </div>+<DButton@action={{this.createWorkflow}}@label="discourse_workflows.new_workflow"@icon="plus"- class="btn-primary btn-small"+ class="btn-primary workflows-index__new-btn"/>- </:toolbar>- <:head>- <th class="d-table__header-cell">{{i18n- "discourse_workflows.creator"- }}</th>- <th class="d-table__header-cell">{{i18n- "discourse_workflows.workflow_name"- }}</th>- <th class="d-table__header-cell">{{i18n- "discourse_workflows.last_editor"- }}</th>- <th class="d-table__header-cell">{{i18n- "discourse_workflows.last_update"- }}</th>- <th class="d-table__header-cell">{{i18n- "discourse_workflows.last_run"- }}</th>- <th class="d-table__header-cell">{{i18n- "discourse_workflows.status"- }}</th>- </:head>- <:row as |workflow|>- <td class="d-table__cell --detail workflows-index__creator">- <div class="d-table__mobile-label">- {{i18n "discourse_workflows.creator"}}- </div>- {{#if workflow.createdBy}}- <a- href={{workflow.createdBy.path}}- class="workflows-index__creator-link"- >- {{dAvatar workflow.createdBy imageSize="tiny"}}- </a>- {{/if}}- </td>- <td class="d-table__cell --overview workflows-index__name">- <LinkTo- @route="adminPlugins.show.discourse-workflows.show"- @model={{workflow.id}}- class="d-table__overview-link"- >- <strong class="d-table__overview-name">{{workflow.name}}</strong>- {{#if (eq workflow.lastExecutionStatus "error")}}+ </div>++ {{#if this.resultSet.content.length}}+ <AdminTable+ @items={{this.resultSet.content}}+ @isLoading={{this.filtering}}+ @canLoadMore={{this.resultSet.canLoadMore}}+ @loadMore={{this.loadMore}}+ @loadingMore={{this.loading}}+ @rowClass="workflows-index__row"+ >+ <:head>+ <th class="d-table__header-cell">{{i18n+ "discourse_workflows.creator"+ }}</th>+ <th class="d-table__header-cell">{{i18n+ "discourse_workflows.workflow_name"+ }}</th>+ <th class="d-table__header-cell">{{i18n+ "discourse_workflows.last_editor"+ }}</th>+ <th class="d-table__header-cell">{{i18n+ "discourse_workflows.last_update"+ }}</th>+ <th class="d-table__header-cell">{{i18n+ "discourse_workflows.last_run"+ }}</th>+ <th class="d-table__header-cell">{{i18n+ "discourse_workflows.status"+ }}</th>+ </:head>+ <:row as |workflow|>+ <td class="d-table__cell --detail workflows-index__creator">+ <div class="d-table__mobile-label">+ {{i18n "discourse_workflows.creator"}}+ </div>+ {{#if workflow.createdBy}}+ <a+ href={{workflow.createdBy.path}}+ class="workflows-index__creator-link"+ >+ {{dAvatar workflow.createdBy imageSize="tiny"}}+ </a>+ {{/if}}+ </td>+ <td class="d-table__cell --overview workflows-index__name">+ <LinkTo+ @route="adminPlugins.show.discourse-workflows.show"+ @model={{workflow.id}}+ class="d-table__overview-link"+ >+ <strong+ class="d-table__overview-name"+ >{{workflow.name}}</strong>+ {{#if (eq workflow.lastExecutionStatus "error")}}+ <span+ class="workflows-index__warning"+ role="img"+ aria-label={{i18n+ "discourse_workflows.last_execution_failed"+ }}+ title={{i18n "discourse_workflows.last_execution_failed"}}+ >+ {{dIcon "triangle-exclamation"}}+ </span>+ {{/if}}+ </LinkTo>+ {{#if workflow.tags.length}}+ <div class="d-table__badges workflows-index__tags">+ {{#each workflow.tags as |tag|}}+ <a+ href={{this.tagFilterHref tag}}+ class="d-table-badge"+ title={{i18n "discourse_workflows.tags.filter_by"}}+ {{on "click" (fn this.addTagFilter tag)}}+ >+ <span class="d-table-badge__content">{{tag}}</span>+ </a>+ {{/each}}+ </div>+ {{/if}}+ </td>+ <td class="d-table__cell --detail workflows-index__last-editor">+ <div class="d-table__mobile-label">+ {{i18n "discourse_workflows.last_editor"}}+ </div>+ {{#if workflow.updatedBy}}+ <a+ href={{workflow.updatedBy.path}}+ class="workflows-index__last-editor-link"+ >+ {{dAvatar workflow.updatedBy imageSize="tiny"}}+ <span>{{workflow.updatedBy.username}}</span>+ </a>+ {{/if}}+ </td>+ <td class="d-table__cell --detail workflows-index__last-update">+ <div class="d-table__mobile-label">+ {{i18n "discourse_workflows.last_update"}}+ </div>+ {{dFormatDate workflow.updatedAt format="medium"}}+ </td>+ <td class="d-table__cell --detail workflows-index__last-run">+ <div class="d-table__mobile-label">+ {{i18n "discourse_workflows.last_run"}}+ </div>+ {{#if workflow.lastExecutionAt}}+ {{dFormatDate workflow.lastExecutionAt format="medium"}}+ {{else}}+ {{i18n "discourse_workflows.last_execution_never"}}+ {{/if}}+ </td>+ <td class="d-table__cell --detail">+ <div class="d-table__mobile-label">+ {{i18n "discourse_workflows.status"}}+ </div><span- class="workflows-index__warning"- role="img"- aria-label={{i18n "discourse_workflows.last_execution_failed"}}- title={{i18n "discourse_workflows.last_execution_failed"}}+ class={{dConcatClass+ "workflows-index__badge"+ (this.workflowStatusClass workflow)+ }}>- {{dIcon "triangle-exclamation"}}+ {{i18n (this.workflowStatusLabel workflow)}}</span>- {{/if}}- </LinkTo>- </td>- <td class="d-table__cell --detail workflows-index__last-editor">- <div class="d-table__mobile-label">- {{i18n "discourse_workflows.last_editor"}}- </div>- {{#if workflow.updatedBy}}- <a- href={{workflow.updatedBy.path}}- class="workflows-index__last-editor-link"- >- {{dAvatar workflow.updatedBy imageSize="tiny"}}- <span>{{workflow.updatedBy.username}}</span>- </a>- {{/if}}- </td>- <td class="d-table__cell --detail workflows-index__last-update">- <div class="d-table__mobile-label">- {{i18n "discourse_workflows.last_update"}}- </div>- {{dFormatDate workflow.updatedAt format="medium"}}- </td>- <td class="d-table__cell --detail workflows-index__last-run">- <div class="d-table__mobile-label">- {{i18n "discourse_workflows.last_run"}}- </div>- {{#if workflow.lastExecutionAt}}- {{dFormatDate workflow.lastExecutionAt format="medium"}}- {{else}}- {{i18n "discourse_workflows.last_execution_never"}}- {{/if}}- </td>- <td class="d-table__cell --detail">- <div class="d-table__mobile-label">- {{i18n "discourse_workflows.status"}}- </div>- <span- class={{dConcatClass- "workflows-index__badge"- (this.workflowStatusClass workflow)- }}- >- {{i18n (this.workflowStatusLabel workflow)}}- </span>- </td>- </:row>- </AdminTable>+ </td>+ </:row>+ </AdminTable>+ {{else if this.hasActiveFilters}}+ <div class="d-filter-controls__no-results workflows-index__no-results">+ <p>{{i18n "discourse_workflows.no_workflows_found"}}</p>+ <DButton+ @icon="arrow-rotate-left"+ @label="filter_controls.reset"+ @action={{this.resetFilters}}+ class="btn-default"+ />+ </div>+ {{/if}}+ {{else}}+ <EmptyState+ @emoji="wave"+ @title={{i18n+ "discourse_workflows.empty_title"+ username=this.currentUser.displayName+ }}+ @description={{i18n "discourse_workflows.empty_description"}}+ @buttonLabel="discourse_workflows.create_first_workflow"+ @onAction={{this.createWorkflow}}+ />+ {{/if}}</template>}diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/tags-editor.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/tags-editor.gjsnew file mode 100644index 00000000000..064eda239d1--- /dev/null+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/tags-editor.gjs@@ -0,0 +1,130 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { hash } from "@ember/helper";+import { action } from "@ember/object";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import ListSetting from "discourse/select-kit/components/list-setting";+import DButton from "discourse/ui-kit/d-button";++export default class WorkflowTagsEditor extends Component {+ @tracked isEditing = false;+ @tracked availableTags = [];++ #inFlight = false;+ #queued = false;+ #lastSavedTags;++ constructor() {+ super(...arguments);+ this.#lastSavedTags = [...(this.args.workflow.tags ?? [])];+ this.loadAvailableTags();+ }++ get tags() {+ return this.args.workflow.tags ?? [];+ }++ get choices() {+ return [...new Set([...this.tags, ...this.availableTags])];+ }++ async loadAvailableTags() {+ try {+ const result = await ajax(+ "/admin/plugins/discourse-workflows/workflow-tags.json"+ );+ this.availableTags = result.workflow_tags.map((tag) => tag.name);+ } catch {+ this.availableTags = [];+ }+ }++ @action+ startEditing() {+ this.isEditing = true;+ }++ @action+ stopEditing() {+ this.isEditing = false;+ }++ @action+ async onChange(tags) {+ this.args.workflow.set("tags", [...tags]);++ if (this.#inFlight) {+ this.#queued = true;+ return;+ }++ this.#inFlight = true;+ try {+ do {+ this.#queued = false;+ const tagsToSave = [...(this.args.workflow.tags ?? [])];+ const rollbackTo = [...this.#lastSavedTags];++ try {+ // JSON-encoded so an emptied tag list still reaches the server (form+ // encoding drops empty arrays, which would read as "not provided")+ const result = await ajax(+ `/admin/plugins/discourse-workflows/workflows/${this.args.workflow.id}.json`,+ {+ type: "PUT",+ contentType: "application/json",+ data: JSON.stringify({ workflow: { tags: tagsToSave } }),+ }+ );+ this.#lastSavedTags = [...result.workflow.tags];+ if (!this.#queued) {+ this.args.workflow.set("tags", result.workflow.tags);+ }+ } catch (e) {+ popupAjaxError(e);+ if (!this.#queued) {+ this.args.workflow.set("tags", rollbackTo);+ }+ }+ } while (this.#queued);+ } finally {+ this.#inFlight = false;+ }+ }++ <template>+ <div class="workflows-tags-editor">+ {{#if this.isEditing}}+ <ListSetting+ @value={{this.tags}}+ @choices={{this.choices}}+ @onChange={{this.onChange}}+ @options={{hash+ allowAny=true+ maximum=10+ filterPlaceholder="discourse_workflows.tags.placeholder"+ }}+ />+ <DButton+ @action={{this.stopEditing}}+ @icon="check"+ @title="discourse_workflows.save"+ class="btn-flat workflows-tags-editor__done"+ />+ {{else}}+ {{#each this.tags as |tag|}}+ <span class="d-table-badge">+ <span class="d-table-badge__content">{{tag}}</span>+ </span>+ {{/each}}+ <DButton+ @action={{this.startEditing}}+ @icon="plus"+ @label="discourse_workflows.tags.manage"+ class="btn-flat workflows-tags-editor__manage"+ />+ {{/if}}+ </div>+ </template>+}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 c72d1f9b4d9..d495a603918 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@@ -58,6 +58,7 @@ export default class DiscourseWorkflowsWorkflow extends RestModel {}@tracked name;+ @tracked tags = [];@tracked errorWorkflowId;@tracked versionId;@tracked activeVersionId;diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/index.js b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/index.jsindex 4a18b5aca01..5b547d30eba 100644--- a/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/index.js+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/index.js@@ -6,10 +6,10 @@ export default class DiscourseWorkflowsIndexRoute extends DiscourseRoute {@service store;async model() {- const [workflows, stats] = await Promise.all([+ const [workflows, workflowTags] = await Promise.all([this.store.findAll("discourse-workflows-workflow"),- ajax("/admin/plugins/discourse-workflows/stats.json"),+ ajax("/admin/plugins/discourse-workflows/workflow-tags.json"),]);- return { workflows, stats };+ return { workflows, workflowTags: workflowTags.workflow_tags };}}diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/index.gjs b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/index.gjsindex 3ce09f196af..a6d8c54de69 100644--- a/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/index.gjs+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/index.gjs@@ -9,7 +9,7 @@ export default <template>/><WorkflowsIndex@workflows={{@controller.model.workflows}}- @stats={{@controller.model.stats}}+ @workflowTags={{@controller.model.workflowTags}}/></div></template>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 938ecf47898..0d95b2d0370 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@@ -8,6 +8,7 @@ import DHorizontalOverflowNav from "discourse/ui-kit/d-horizontal-overflow-nav";import DNavItem from "discourse/ui-kit/d-nav-item";import WorkflowEditableTitle from "discourse/plugins/discourse-workflows/admin/components/workflows/editable-title";import Stats from "discourse/plugins/discourse-workflows/admin/components/workflows/stats";+import WorkflowTagsEditor from "discourse/plugins/discourse-workflows/admin/components/workflows/tags-editor";class WorkflowShowPage extends Component {get workflow() {@@ -40,10 +41,14 @@ class WorkflowShowPage extends Component {<div class="admin-config-page__main-area"><div class="workflows-header">- <WorkflowEditableTitle- @value={{this.workflow.name}}- @onSave={{this.updateName}}- />+ <div class="workflows-header__title-area">+ <WorkflowEditableTitle+ @value={{this.workflow.name}}+ @onSave={{this.updateName}}+ />++ <WorkflowTagsEditor @workflow={{this.workflow}} />+ </div><Stats @stats={{this.stats}} /></div>diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/workflow_tags_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/workflow_tags_controller.rbnew file mode 100644index 00000000000..d91c2e0bc02--- /dev/null+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/workflow_tags_controller.rb@@ -0,0 +1,20 @@+# frozen_string_literal: true++module DiscourseWorkflows+ class WorkflowTagsController < ::Admin::AdminController+ requires_plugin DiscourseWorkflows::PLUGIN_NAME++ def index+ DiscourseWorkflows::WorkflowTag::List.call(service_params) do |result|+ on_success do |workflow_tags:|+ render json: {+ workflow_tags:+ serialize_data(workflow_tags, DiscourseWorkflows::WorkflowTagSerializer),+ }+ end+ on_failure { render(json: failed_json, status: :unprocessable_entity) }+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }+ end+ end+ end+enddiff --git a/plugins/discourse-workflows/app/models/discourse_workflows/workflow.rb b/plugins/discourse-workflows/app/models/discourse_workflows/workflow.rbindex cb2725c0406..f2266e1b2ad 100644--- a/plugins/discourse-workflows/app/models/discourse_workflows/workflow.rb+++ b/plugins/discourse-workflows/app/models/discourse_workflows/workflow.rb@@ -37,6 +37,15 @@ module DiscourseWorkflowsclass_name: "DiscourseWorkflows::WorkflowCallRun",foreign_key: "target_workflow_id",dependent: :delete_all+ has_many :workflow_tag_mappings,+ class_name: "DiscourseWorkflows::WorkflowTagMapping",+ foreign_key: "workflow_id",+ dependent: :delete_all+ has_many :tags,+ -> { order(:name) },+ class_name: "DiscourseWorkflows::WorkflowTag",+ through: :workflow_tag_mappings,+ source: :workflow_tagbelongs_to :created_by, class_name: "User", foreign_key: "created_by_id"belongs_to :updated_by, class_name: "User", foreign_key: "updated_by_id", optional: true@@ -82,11 +91,24 @@ module DiscourseWorkflows[{ "type" => "trigger:#{type}" }].to_json,)end+ scope :filter_by_tags,+ ->(tag_names) do+ Array.wrap(tag_names).reduce(all) { |scope, tag_name| scope.where(<<~SQL, tag_name) }+ EXISTS (+ SELECT 1+ FROM discourse_workflows_workflow_tags wtm+ JOIN discourse_workflows_tags wt ON wt.id = wtm.workflow_tag_id+ WHERE wtm.workflow_id = discourse_workflows_workflows.id+ AND wt.name = ?+ )+ SQL+ end- def self.filtered(name: nil, trigger_type: nil, exclude_id: nil)+ def self.filtered(name: nil, trigger_type: nil, exclude_id: nil, tags: nil)scope = allscope = scope.filter_by_name(name) if name.present?scope = scope.filter_by_trigger_type(trigger_type) if trigger_type.present?+ scope = scope.filter_by_tags(tags) if tags.present?scope = scope.where.not(id: exclude_id) if exclude_idscopeenddiff --git a/plugins/discourse-workflows/app/models/discourse_workflows/workflow_tag.rb b/plugins/discourse-workflows/app/models/discourse_workflows/workflow_tag.rbnew file mode 100644index 00000000000..34e2bbbc789--- /dev/null+++ b/plugins/discourse-workflows/app/models/discourse_workflows/workflow_tag.rb@@ -0,0 +1,99 @@+# frozen_string_literal: true++module DiscourseWorkflows+ class WorkflowTag < ActiveRecord::Base+ self.table_name = "discourse_workflows_tags"++ MAX_TAGS_PER_WORKFLOW = 10+ MAX_NAME_LENGTH = 100++ has_many :workflow_tag_mappings,+ class_name: "DiscourseWorkflows::WorkflowTagMapping",+ foreign_key: "workflow_tag_id",+ dependent: :delete_all++ validates :name,+ presence: true,+ uniqueness: true,+ length: {+ maximum: MAX_NAME_LENGTH,+ },+ format: {+ without: /,/,+ }++ def self.normalize_name(name)+ name.to_s.strip.downcase.gsub(/[[:space:]]+/, " ")+ end++ def self.normalize_all(names)+ Array.wrap(names).map { |name| normalize_name(name) }.reject(&:blank?).uniq+ end++ def self.validate_names(names, errors)+ if names.size > MAX_TAGS_PER_WORKFLOW+ errors.add(+ :base,+ I18n.t("discourse_workflows.errors.too_many_tags", max: MAX_TAGS_PER_WORKFLOW),+ )+ end++ if names.any? { |name| name.length > MAX_NAME_LENGTH }+ errors.add(:base, I18n.t("discourse_workflows.errors.tag_too_long", max: MAX_NAME_LENGTH))+ end++ if names.any? { |name| name.include?(",") }+ errors.add(:base, I18n.t("discourse_workflows.errors.tag_contains_comma"))+ end+ end++ def self.resolve_or_create!(names)+ return [] if names.blank?++ now = Time.zone.now+ insert_all(+ names.map { |name| { name:, created_at: now, updated_at: now } },+ unique_by: :idx_dwf_tags_on_name,+ )+ where(name: names).to_a+ end++ def self.sync!(workflow:, names:)+ desired = resolve_or_create!(normalize_all(names))+ desired_ids = desired.map(&:id)+ current_ids = WorkflowTagMapping.where(workflow_id: workflow.id).pluck(:workflow_tag_id)++ removed_ids = current_ids - desired_ids+ if removed_ids.present?+ WorkflowTagMapping.where(workflow_id: workflow.id, workflow_tag_id: removed_ids).delete_all+ end+ (desired_ids - current_ids).each do |workflow_tag_id|+ WorkflowTagMapping.create!(workflow_id: workflow.id, workflow_tag_id:)+ end++ prune!(removed_ids)+ workflow.association(:tags).reset+ desired+ end++ def self.prune!(tag_ids)+ return if tag_ids.blank?++ where(id: tag_ids).where.not(id: WorkflowTagMapping.select(:workflow_tag_id)).delete_all+ end+ end+end++# == Schema Information+#+# Table name: discourse_workflows_tags+#+# id :bigint not null, primary key+# name :string(100) not null+# created_at :datetime not null+# updated_at :datetime not null+#+# Indexes+#+# idx_dwf_tags_on_name (name) UNIQUE+#diff --git a/plugins/discourse-workflows/app/models/discourse_workflows/workflow_tag_mapping.rb b/plugins/discourse-workflows/app/models/discourse_workflows/workflow_tag_mapping.rbnew file mode 100644index 00000000000..248b4a551fa--- /dev/null+++ b/plugins/discourse-workflows/app/models/discourse_workflows/workflow_tag_mapping.rb@@ -0,0 +1,25 @@+# frozen_string_literal: true++module DiscourseWorkflows+ class WorkflowTagMapping < ActiveRecord::Base+ self.table_name = "discourse_workflows_workflow_tags"++ belongs_to :workflow, class_name: "DiscourseWorkflows::Workflow"+ belongs_to :workflow_tag, class_name: "DiscourseWorkflows::WorkflowTag"+ end+end++# == Schema Information+#+# Table name: discourse_workflows_workflow_tags+#+# id :bigint not null, primary key+# created_at :datetime not null+# workflow_id :bigint not null+# workflow_tag_id :bigint not null+#+# Indexes+#+# idx_dwf_workflow_tags_on_tag_workflow (workflow_tag_id,workflow_id) UNIQUE+# idx_dwf_workflow_tags_on_workflow_tag (workflow_id,workflow_tag_id) UNIQUE+#diff --git a/plugins/discourse-workflows/app/serializers/discourse_workflows/workflow_serializer.rb b/plugins/discourse-workflows/app/serializers/discourse_workflows/workflow_serializer.rbindex 16e5a6536e9..b841b8599e6 100644--- a/plugins/discourse-workflows/app/serializers/discourse_workflows/workflow_serializer.rb+++ b/plugins/discourse-workflows/app/serializers/discourse_workflows/workflow_serializer.rb@@ -20,7 +20,8 @@ module DiscourseWorkflows:last_execution_status,:last_execution_at,:last_execution_run_data,- :pin_data+ :pin_data,+ :tagsattribute :created_byattribute :updated_by@@ -111,6 +112,10 @@ module DiscourseWorkflowsexecution&.execution_data&.run_dataend+ def tags+ object.tags.map(&:name)+ end+def pin_dataobject.pin_data || {}enddiff --git a/plugins/discourse-workflows/app/serializers/discourse_workflows/workflow_tag_serializer.rb b/plugins/discourse-workflows/app/serializers/discourse_workflows/workflow_tag_serializer.rbnew file mode 100644index 00000000000..5296f4987fa--- /dev/null+++ b/plugins/discourse-workflows/app/serializers/discourse_workflows/workflow_tag_serializer.rb@@ -0,0 +1,11 @@+# frozen_string_literal: true++module DiscourseWorkflows+ class WorkflowTagSerializer < ApplicationSerializer+ attributes :id, :name, :workflow_count++ def workflow_count+ object.attributes["workflow_count_value"].to_i+ end+ end+enddiff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/create.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/create.rbindex 9d03f70037b..8f32d49d414 100644--- a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/create.rb+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/create.rb@@ -9,21 +9,30 @@ module DiscourseWorkflowsattribute :nodes, default: -> { [] }attribute :connections, default: -> { {} }attribute :static_data, default: -> { {} }+ attribute :tags, default: -> { [] }++ before_validation { self.tags = DiscourseWorkflows::WorkflowTag.normalize_all(tags) }validates :name, presence: true, length: { maximum: 100 }validate :static_data_is_valid_map+ validate :tags_are_validdef static_data_is_valid_mapreturn if DiscourseWorkflows::Workflow.valid_static_data_map?(static_data)errors.add(:static_data, :invalid)end++ def tags_are_valid+ DiscourseWorkflows::WorkflowTag.validate_names(tags, errors)+ endendpolicy :can_manage_workflows, class_name: Policy::CanManageWorkflowstransaction domodel :workflow, :create_workflow+ step :sync_tagsstep :populate_graphmodel :workflow_version, :create_initial_snapshotstep :index_dependencies@@ -43,6 +52,12 @@ module DiscourseWorkflows)end+ def sync_tags(workflow:, params:)+ return if params.tags.blank?++ DiscourseWorkflows::WorkflowTag.sync!(workflow:, names: params.tags)+ end+def populate_graph(workflow:, params:)result =Workflow::Action::PopulateGraph.call(diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/destroy.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/destroy.rbindex cba908aa2bd..0338e856572 100644--- a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/destroy.rb+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/destroy.rb@@ -13,8 +13,13 @@ module DiscourseWorkflowsmodel :workflowmodel :referencing_workflows, optional: truepolicy :workflow_not_called_by_other_workflows+ model :orphan_candidate_tag_ids, optional: true++ transaction do+ step :delete_workflow+ step :prune_orphan_tags+ end- step :delete_workflowstep :logstep :expire_workflow_caches@@ -42,10 +47,18 @@ module DiscourseWorkflowsreferencing_workflows.blank?end+ def fetch_orphan_candidate_tag_ids(workflow:)+ workflow.workflow_tag_mappings.pluck(:workflow_tag_id)+ end+def delete_workflow(workflow:)workflow.destroy!end+ def prune_orphan_tags(orphan_candidate_tag_ids:)+ DiscourseWorkflows::WorkflowTag.prune!(orphan_candidate_tag_ids)+ end+def log(workflow:, guardian:)StaffActionLogger.new(guardian.user).log_custom("discourse_workflows_workflow_destroyed",diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/list.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/list.rbindex 7d40e11d0f4..1183b59b1be 100644--- a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/list.rb+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/list.rb@@ -22,6 +22,7 @@ module DiscourseWorkflowsattribute :filter, :stringattribute :trigger_type, :stringattribute :exclude_id, :integer+ attribute :tags, :stringafter_validation doself.limit =@@ -29,6 +30,15 @@ module DiscourseWorkflows1,DiscourseWorkflows::Pagination::MAX_LIMIT,)+ self.tags =+ DiscourseWorkflows::WorkflowTag+ .normalize_all(tags.to_s.split(","))+ .first(DiscourseWorkflows::WorkflowTag::MAX_TAGS_PER_WORKFLOW)+ .join(",")+ end++ def tag_names+ tags.to_s.split(",")endend@@ -46,8 +56,9 @@ module DiscourseWorkflowsname: params.filter,trigger_type: params.trigger_type,exclude_id: params.exclude_id,+ tags: params.tag_names,)- .includes(:created_by, :updated_by, :error_workflow)+ .includes(:created_by, :updated_by, :error_workflow, :tags).joins(LATEST_EXECUTION_JOIN).select("discourse_workflows_workflows.*",@@ -77,6 +88,7 @@ module DiscourseWorkflowsname: params.filter,trigger_type: params.trigger_type,exclude_id: params.exclude_id,+ tags: params.tag_names,).countend@@ -89,6 +101,7 @@ module DiscourseWorkflowsfilter: params.filter.presence,trigger_type: params.trigger_type.presence,exclude_id: params.exclude_id,+ tags: params.tags.presence,}.compact"/admin/plugins/discourse-workflows/workflows.json?#{query.to_query}"diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/show.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/show.rbindex 1b289a4f85f..bd072034e22 100644--- a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/show.rb+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/show.rb@@ -15,9 +15,12 @@ module DiscourseWorkflowsprivatedef fetch_workflow(params:)- DiscourseWorkflows::Workflow.includes(:created_by, :updated_by, :error_workflow).find_by(- id: params.workflow_id,- )+ DiscourseWorkflows::Workflow.includes(+ :created_by,+ :updated_by,+ :error_workflow,+ :tags,+ ).find_by(id: params.workflow_id)endendenddiff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/update.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/update.rbindex 14e016d32c4..615a0986e6f 100644--- a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/update.rb+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/update.rb@@ -12,14 +12,20 @@ module DiscourseWorkflowsattribute :error_workflow_id, default: -> { NOT_PROVIDED }attribute :timezone, default: -> { NOT_PROVIDED }attribute :static_data, default: -> { NOT_PROVIDED }+ attribute :tags, default: -> { NOT_PROVIDED }attribute :nodesattribute :connectionsattribute :autosaved, :boolean, default: false+ before_validation do+ self.tags = DiscourseWorkflows::WorkflowTag.normalize_all(tags) if tags_provided?+ end+validates :workflow_id, presence: truevalidates :name, presence: true, length: { maximum: 100 }, if: :name_provided?validate :timezone_is_validvalidate :static_data_is_valid_map+ validate :tags_are_valid, if: :tags_provided?def updatable_attributesattrs = {}@@ -45,6 +51,10 @@ module DiscourseWorkflowsstatic_data != NOT_PROVIDEDend+ def tags_provided?+ tags != NOT_PROVIDED+ end+def graph_data_provided?!nodes.nil? || !connections.nil?end@@ -62,6 +72,10 @@ module DiscourseWorkflowserrors.add(:static_data, :invalid)end++ def tags_are_valid+ DiscourseWorkflows::WorkflowTag.validate_names(tags, errors)+ endendpolicy :can_manage_workflows, class_name: Policy::CanManageWorkflows@@ -73,6 +87,7 @@ module DiscourseWorkflowstransaction domodel :workflow, :update_workflowmodel :workflow, :save_workflow+ only_if(:tags_provided) { step :sync_tags }only_if(:graph_data_provided) dostep :populate_graphonly_if(:versioned_payload_changed) do@@ -99,6 +114,14 @@ module DiscourseWorkflowsparams.graph_data_provided?end+ def tags_provided(params:)+ params.tags_provided?+ end++ def sync_tags(workflow:, params:)+ DiscourseWorkflows::WorkflowTag.sync!(workflow:, names: params.tags)+ end+def versioned_payload_changed(workflow:, previous_versioned_payload:)workflow.versioned_payload != previous_versioned_payloadenddiff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow_tag/list.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow_tag/list.rbnew file mode 100644index 00000000000..50efcd8fc67--- /dev/null+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow_tag/list.rb@@ -0,0 +1,24 @@+# frozen_string_literal: true++module DiscourseWorkflows+ class WorkflowTag::List+ include Service::Base++ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows++ model :workflow_tags, optional: true++ private++ def fetch_workflow_tags+ DiscourseWorkflows::WorkflowTag+ .joins(+ "LEFT JOIN discourse_workflows_workflow_tags wtm ON wtm.workflow_tag_id = discourse_workflows_tags.id",+ )+ .select("discourse_workflows_tags.*", "COUNT(wtm.id) AS workflow_count_value")+ .group("discourse_workflows_tags.id")+ .order(:name)+ .to_a+ end+ end+enddiff --git a/plugins/discourse-workflows/assets/stylesheets/common/admin-page.scss b/plugins/discourse-workflows/assets/stylesheets/common/admin-page.scssindex 3075e43f948..31252bf8f1b 100644--- a/plugins/discourse-workflows/assets/stylesheets/common/admin-page.scss+++ b/plugins/discourse-workflows/assets/stylesheets/common/admin-page.scss@@ -13,6 +13,14 @@justify-content: space-between;margin-bottom: 0.5em;gap: 1em;++ &__title-area {+ display: flex;+ flex-direction: column;+ align-items: flex-start;+ gap: var(--space-1);+ min-width: 0;+ }}.workflows-editable-title {diff --git a/plugins/discourse-workflows/assets/stylesheets/common/admin-table.scss b/plugins/discourse-workflows/assets/stylesheets/common/admin-table.scssindex ff1f306688d..1661f6b7eed 100644--- a/plugins/discourse-workflows/assets/stylesheets/common/admin-table.scss+++ b/plugins/discourse-workflows/assets/stylesheets/common/admin-table.scss@@ -12,6 +12,7 @@th {border-bottom: 1px solid var(--primary-low);+ white-space: nowrap;}}diff --git a/plugins/discourse-workflows/assets/stylesheets/common/index.scss b/plugins/discourse-workflows/assets/stylesheets/common/index.scssindex 6f9dfc1279f..a085e68cc28 100644--- a/plugins/discourse-workflows/assets/stylesheets/common/index.scss+++ b/plugins/discourse-workflows/assets/stylesheets/common/index.scss@@ -1,5 +1,6 @@@import "colors";@import "workflows-index";+@import "tags";@import "editor/editor";@import "canvas/canvas";@import "canvas/ai-build-tool";diff --git a/plugins/discourse-workflows/assets/stylesheets/common/tags.scss b/plugins/discourse-workflows/assets/stylesheets/common/tags.scssnew file mode 100644index 00000000000..b367bc17b1b--- /dev/null+++ b/plugins/discourse-workflows/assets/stylesheets/common/tags.scss@@ -0,0 +1,21 @@+.workflows-tags-editor {+ display: flex;+ align-items: center;+ flex-wrap: wrap;+ gap: var(--space-1);++ &__manage {+ font-size: var(--font-down-2);+ color: var(--primary-medium);+ padding: var(--space-half) var(--space-2);+ min-height: 0;+ }++ .list-setting {+ min-width: 16em;++ .select-kit-header {+ background: var(--secondary);+ }+ }+}diff --git a/plugins/discourse-workflows/assets/stylesheets/common/workflows-index.scss b/plugins/discourse-workflows/assets/stylesheets/common/workflows-index.scssindex a39f13eb798..060b74803da 100644--- a/plugins/discourse-workflows/assets/stylesheets/common/workflows-index.scss+++ b/plugins/discourse-workflows/assets/stylesheets/common/workflows-index.scss@@ -36,7 +36,8 @@}&__last-editor-link {- display: inline-flex;+ display: flex;+ width: fit-content;align-items: center;gap: var(--space-1);}@@ -64,6 +65,7 @@display: inline-flex;align-items: center;gap: 0.4em;+ white-space: nowrap;font-size: var(--font-down-1);padding: 0.25em 0.6em;border-radius: var(--d-border-radius);@@ -73,6 +75,7 @@&::before {content: "";display: inline-block;+ flex: none;width: 0.55em;height: 0.55em;border-radius: 50%;@@ -97,4 +100,34 @@}}}++ &__filters {+ flex-wrap: wrap;+ }++ &__tag-filter {+ min-width: 11em;++ .d-multi-select-trigger__label {+ white-space: nowrap;+ }+ }++ &__tag-filter-count {+ color: var(--primary-medium);+ font-size: var(--font-down-1);+ }++ &__name.d-table__cell .d-table__overview-name {+ margin-bottom: 0;+ }++ &__tags {+ min-height: 0;+ margin-top: var(--space-1);+ }++ &__no-results {+ color: var(--primary-high);+ }}diff --git a/plugins/discourse-workflows/config/locales/client.en.yml b/plugins/discourse-workflows/config/locales/client.en.ymlindex 0570ed07050..ef4266d42c3 100644--- a/plugins/discourse-workflows/config/locales/client.en.yml+++ b/plugins/discourse-workflows/config/locales/client.en.yml@@ -128,6 +128,14 @@ en:create_first_workflow: "Create your first workflow"empty_title: "%{username}, let's set up a workflow"empty_description: "Workflows automate tasks by connecting triggers, conditions, and actions into a visual flow"+ search_placeholder: "Filter by name"+ no_workflows_found: "No workflows match your filters"+ tags:+ manage: "Manage tags"+ filter_label: "Filter by tags"+ filter_by: "Filter the list by this tag"+ no_results: "No tags found"+ placeholder: "Search or create tags…"delete_confirm: "Are you sure you want to delete the workflow \"%{name}\"?"in_use_title: "Workflow in use"in_use_description: "This workflow cannot be deleted because it is called by the following workflows:"diff --git a/plugins/discourse-workflows/config/locales/server.en.yml b/plugins/discourse-workflows/config/locales/server.en.ymlindex b9b2d958f76..0c4f928a4e8 100644--- a/plugins/discourse-workflows/config/locales/server.en.yml+++ b/plugins/discourse-workflows/config/locales/server.en.yml@@ -40,6 +40,9 @@ en:tool_finished: "Finished %{tool}"summarizing: "Preparing workflow authoring response"errors:+ 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."approval_timed_out: "Approval timed out"step_execution:not_executable: "This node cannot be executed as a single step."diff --git a/plugins/discourse-workflows/config/routes.rb b/plugins/discourse-workflows/config/routes.rbindex 43143a49e26..5b5bbc5de19 100644--- a/plugins/discourse-workflows/config/routes.rb+++ b/plugins/discourse-workflows/config/routes.rb@@ -27,6 +27,7 @@ DiscourseWorkflows::Engine.routes.draw doscope format: :json doget "/workflows" => "workflows#index"post "/workflows" => "workflows#create"+ get "/workflow-tags" => "workflow_tags#index"post "/workflows/ai/author" => "ai_authoring#create"post "/workflows/:workflow_id/ai/author" => "ai_authoring#create"post "/workflows/:workflow_id/ai/apply" => "ai_authoring#apply"diff --git a/plugins/discourse-workflows/db/migrate/20260723100008_create_workflow_tags.rb b/plugins/discourse-workflows/db/migrate/20260723100008_create_workflow_tags.rbnew file mode 100644index 00000000000..5cce2ff9776--- /dev/null+++ b/plugins/discourse-workflows/db/migrate/20260723100008_create_workflow_tags.rb@@ -0,0 +1,25 @@+# frozen_string_literal: true++class CreateWorkflowTags < ActiveRecord::Migration[8.0]+ def change+ create_table :discourse_workflows_tags do |t|+ t.string :name, null: false, limit: 100+ t.timestamps null: false+ end+ add_index :discourse_workflows_tags, :name, unique: true, name: "idx_dwf_tags_on_name"++ create_table :discourse_workflows_workflow_tags do |t|+ t.bigint :workflow_id, null: false+ t.bigint :workflow_tag_id, null: false+ t.datetime :created_at, null: false, default: -> { "CURRENT_TIMESTAMP" }+ end+ add_index :discourse_workflows_workflow_tags,+ %i[workflow_id workflow_tag_id],+ unique: true,+ name: "idx_dwf_workflow_tags_on_workflow_tag"+ add_index :discourse_workflows_workflow_tags,+ %i[workflow_tag_id workflow_id],+ unique: true,+ name: "idx_dwf_workflow_tags_on_tag_workflow"+ end+enddiff --git a/plugins/discourse-workflows/spec/fabricators/discourse_workflows_fabricator.rb b/plugins/discourse-workflows/spec/fabricators/discourse_workflows_fabricator.rbindex 2a01504402e..7d12f7e810d 100644--- a/plugins/discourse-workflows/spec/fabricators/discourse_workflows_fabricator.rb+++ b/plugins/discourse-workflows/spec/fabricators/discourse_workflows_fabricator.rb@@ -2,16 +2,22 @@Fabricator(:discourse_workflows_workflow, class_name: "DiscourseWorkflows::Workflow") dotransient :published+ transient :tagsname { sequence(:name) { |n| "Workflow #{n}" } }created_by { Fabricate(:user) }after_create do |workflow, attrs|version = workflow.initial_snapshot!(user: workflow.created_by)workflow.update_columns(active_version_id: workflow.version_id) if attrs[:published]+ DiscourseWorkflows::WorkflowTag.sync!(workflow:, names: attrs[:tags]) if attrs[:tags]DiscourseWorkflows::WorkflowDependencyIndexer.call(workflow.reload, version:)endend+Fabricator(:discourse_workflows_workflow_tag, class_name: "DiscourseWorkflows::WorkflowTag") do+ name { sequence(:name) { |n| "tag-#{n}" } }+end+Fabricator(:discourse_workflows_execution, class_name: "DiscourseWorkflows::Execution") doworkflow { Fabricate(:discourse_workflows_workflow) }workflow_version_id { |attrs| attrs[:workflow].version_id }diff --git a/plugins/discourse-workflows/spec/models/discourse_workflows/workflow_tag_spec.rb b/plugins/discourse-workflows/spec/models/discourse_workflows/workflow_tag_spec.rbnew file mode 100644index 00000000000..8f7a614831a--- /dev/null+++ b/plugins/discourse-workflows/spec/models/discourse_workflows/workflow_tag_spec.rb@@ -0,0 +1,75 @@+# frozen_string_literal: true++RSpec.describe DiscourseWorkflows::WorkflowTag do+ fab!(:workflow, :discourse_workflows_workflow)++ describe ".normalize_all" do+ it "strips, downcases, collapses whitespace, drops blanks, and dedupes" do+ expect(described_class.normalize_all([" Ops ", "OPS", "a \t b", "", nil, "billing"])).to eq(+ %w[ops a\ b billing],+ )+ end++ it "returns an empty array for nil" do+ expect(described_class.normalize_all(nil)).to eq([])+ end+ end++ describe ".resolve_or_create!" do+ it "creates missing tags and reuses existing ones" do+ existing = Fabricate(:discourse_workflows_workflow_tag, name: "ops")++ tags = described_class.resolve_or_create!(%w[ops billing])++ expect(tags.map(&:name)).to contain_exactly("ops", "billing")+ expect(tags.find { |tag| tag.name == "ops" }.id).to eq(existing.id)+ expect(described_class.count).to eq(2)+ end++ it "does not create duplicates when called twice with the same names" do+ 2.times { described_class.resolve_or_create!(%w[ops]) }++ expect(described_class.where(name: "ops").count).to eq(1)+ end+ end++ describe ".sync!" do+ fab!(:other_workflow, :discourse_workflows_workflow)++ it "assigns the given tags to the workflow" do+ described_class.sync!(workflow:, names: ["Ops", " billing "])++ expect(workflow.tags.map(&:name)).to eq(%w[billing ops])+ end++ it "removes tags no longer present and prunes orphans" do+ described_class.sync!(workflow:, names: %w[ops billing])+ described_class.sync!(workflow:, names: %w[billing])++ expect(workflow.tags.map(&:name)).to eq(%w[billing])+ expect(described_class.exists?(name: "ops")).to eq(false)+ end++ it "keeps a removed tag that is still used by another workflow" do+ described_class.sync!(workflow:, names: %w[ops])+ described_class.sync!(workflow: other_workflow, names: %w[ops])+ described_class.sync!(workflow:, names: [])++ expect(workflow.tags).to be_empty+ expect(other_workflow.tags.map(&:name)).to eq(%w[ops])+ expect(described_class.exists?(name: "ops")).to eq(true)+ end+ end++ describe ".prune!" do+ it "only deletes tags with no remaining mappings" do+ mapped = Fabricate(:discourse_workflows_workflow_tag, name: "mapped")+ orphan = Fabricate(:discourse_workflows_workflow_tag, name: "orphan")+ DiscourseWorkflows::WorkflowTagMapping.create!(workflow:, workflow_tag: mapped)++ described_class.prune!([mapped.id, orphan.id])++ expect(described_class.pluck(:name)).to eq(%w[mapped])+ end+ end+enddiff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/workflow_tags_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/workflow_tags_controller_spec.rbnew file mode 100644index 00000000000..6f7405c116d--- /dev/null+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/workflow_tags_controller_spec.rb@@ -0,0 +1,47 @@+# frozen_string_literal: true++RSpec.describe DiscourseWorkflows::WorkflowTagsController do+ fab!(:admin)++ describe "GET /admin/plugins/discourse-workflows/workflow-tags" do+ context "when not logged in as admin" do+ fab!(:user)++ before { sign_in(user) }++ it "returns 404" do+ get "/admin/plugins/discourse-workflows/workflow-tags.json"++ expect(response).to have_http_status(:not_found)+ end+ end++ context "when logged in as admin" do+ before { sign_in(admin) }++ it "returns the tags ordered by name with their workflow counts" do+ Fabricate(:discourse_workflows_workflow, created_by: admin, tags: %w[ops])+ Fabricate(:discourse_workflows_workflow, created_by: admin, tags: %w[ops billing])++ get "/admin/plugins/discourse-workflows/workflow-tags.json"++ expect(response).to have_http_status(:ok)+ expect(+ response.parsed_body["workflow_tags"].map { |tag| tag.slice("name", "workflow_count") },+ ).to eq(+ [+ { "name" => "billing", "workflow_count" => 1 },+ { "name" => "ops", "workflow_count" => 2 },+ ],+ )+ end++ it "returns an empty list when there are no tags" do+ get "/admin/plugins/discourse-workflows/workflow-tags.json"++ expect(response).to have_http_status(:ok)+ expect(response.parsed_body["workflow_tags"]).to eq([])+ end+ 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 37e9f18a937..fcd5877679a 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@@ -48,6 +48,18 @@ RSpec.describe DiscourseWorkflows::WorkflowsController doexpect(json["workflows"][0]["last_execution_status"]).to eq("success")end+ it "filters by tags and serializes each workflow's tags" do+ ops_workflow = Fabricate(:discourse_workflows_workflow, created_by: admin, tags: %w[ops])+ Fabricate(:discourse_workflows_workflow, created_by: admin, tags: %w[billing])++ get "/admin/plugins/discourse-workflows/workflows.json", params: { tags: "ops" }++ expect(response).to have_http_status(:ok)+ json = response.parsed_body+ expect(json["workflows"].map { |workflow| workflow["id"] }).to eq([ops_workflow.id.to_s])+ expect(json["workflows"][0]["tags"]).to eq(%w[ops])+ end+it "returns meta with total rows" doFabricate(:discourse_workflows_workflow, created_by: admin)@@ -128,6 +140,23 @@ RSpec.describe DiscourseWorkflows::WorkflowsController doexpect(json["workflow"]["static_data"]).to eq("node:Topic Closed" => { "cursor" => "abc" })end+ it "creates a workflow with normalized tags" do+ post "/admin/plugins/discourse-workflows/workflows.json",+ params: {+ workflow: {+ name: "Tagged Workflow",+ tags: ["Ops", " billing ", "Ops"],+ },+ },+ as: :json++ expect(response).to have_http_status(:created)+ expect(response.parsed_body["workflow"]["tags"]).to eq(%w[billing ops])+ expect(+ DiscourseWorkflows::Workflow.find(response.parsed_body["workflow"]["id"]).tags.map(&:name),+ ).to eq(%w[billing ops])+ end+it "returns 400 when name is missing" dopost "/admin/plugins/discourse-workflows/workflows.json", params: { workflow: { nodes: [] } }expect(response).to have_http_status(:bad_request)@@ -178,6 +207,37 @@ RSpec.describe DiscourseWorkflows::WorkflowsController doexpect(response.parsed_body["workflow"]["active_version_id"]).to be_nilend+ it "updates the workflow tags" do+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin)++ put "/admin/plugins/discourse-workflows/workflows/#{workflow.id}.json",+ params: {+ workflow: {+ tags: %w[Ops billing],+ },+ }++ expect(response).to have_http_status(:ok)+ expect(response.parsed_body["workflow"]["tags"]).to eq(%w[billing ops])+ end++ it "rejects updates with too many tags" do+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin, tags: %w[keep])++ put "/admin/plugins/discourse-workflows/workflows/#{workflow.id}.json",+ params: {+ workflow: {+ tags: (1..11).map { |index| "tag-#{index}" },+ },+ }++ expect(response).to have_http_status(:bad_request)+ expect(response.parsed_body["errors"].join).to include(+ I18n.t("discourse_workflows.errors.too_many_tags", max: 10),+ )+ expect(workflow.reload.tags.map(&:name)).to eq(%w[keep])+ end+it "publishes a workflow draft" doworkflow = Fabricate(:discourse_workflows_workflow, created_by: admin)diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/create_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/create_spec.rbindex 3ff709daa61..a62f89bfe08 100644--- a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/create_spec.rb+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/create_spec.rb@@ -11,12 +11,13 @@ RSpec.describe DiscourseWorkflows::Workflow::Create dofab!(:user, :admin)- let(:params) { { name:, nodes:, connections:, static_data: } }+ let(:params) { { name:, nodes:, connections:, static_data:, tags: } }let(:dependencies) { { guardian: user.guardian } }let(:name) { "My Workflow" }let(:nodes) { [] }let(:connections) { {} }let(:static_data) { {} }+ let(:tags) { [] }context "when contract is invalid" dolet(:name) { nil }@@ -54,6 +55,35 @@ RSpec.describe DiscourseWorkflows::Workflow::Create doit { is_expected.to fail_a_contract }end+ context "when there are too many tags" do+ let(:tags) { (1..11).map { |index| "tag-#{index}" } }++ it { is_expected.to fail_a_contract }+ end++ context "when a tag is too long" do+ let(:tags) { ["a" * 101] }++ it { is_expected.to fail_a_contract }+ end++ context "when a tag contains a comma" do+ let(:tags) { ["ops,billing"] }++ it { is_expected.to fail_a_contract }+ end++ context "when tags are provided" do+ let(:tags) { ["Ops", " ops ", "Billing"] }++ it { is_expected.to run_successfully }++ it "assigns the normalized tags to the workflow" do+ expect(result[:workflow].tags.map(&:name)).to eq(%w[billing ops])+ expect(DiscourseWorkflows::WorkflowTag.count).to eq(2)+ end+ end+context "when two nodes share the same name" dolet(:nodes) do[diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/destroy_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/destroy_spec.rbindex d31a7be9f97..71eecc63bce 100644--- a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/destroy_spec.rb+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/destroy_spec.rb@@ -65,5 +65,18 @@ RSpec.describe DiscourseWorkflows::Workflow::Destroy doit_behaves_like "expires workflow caches"end++ context "when the workflow has tags" do+ fab!(:other_workflow) { Fabricate(:discourse_workflows_workflow, tags: %w[shared]) }++ before { DiscourseWorkflows::WorkflowTag.sync!(workflow:, names: %w[shared solo]) }++ it "removes the mappings and prunes tags left without any workflow" do+ result++ expect(DiscourseWorkflows::WorkflowTagMapping.where(workflow_id: workflow.id)).to be_empty+ expect(DiscourseWorkflows::WorkflowTag.pluck(:name)).to eq(%w[shared])+ end+ endendenddiff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/list_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/list_spec.rbindex 2bc75ca11fa..4a54ed26f0b 100644--- a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/list_spec.rb+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/list_spec.rb@@ -162,6 +162,82 @@ RSpec.describe DiscourseWorkflows::Workflow::List doendend+ context "with tags filter" do+ fab!(:ops_workflow) do+ Fabricate(:discourse_workflows_workflow, name: "Ops", created_by: user, tags: %w[ops])+ end+ fab!(:ops_billing_workflow) do+ Fabricate(+ :discourse_workflows_workflow,+ name: "Ops billing",+ created_by: user,+ tags: %w[ops billing],+ )+ end+ fab!(:untagged_workflow) do+ Fabricate(:discourse_workflows_workflow, name: "Untagged", created_by: user)+ end++ let(:params) { { tags: "ops" } }++ it { is_expected.to run_successfully }++ it "returns each matching workflow once" do+ expect(result[:workflows].map(&:name)).to eq(["Ops billing", "Ops"])+ end++ it "returns filtered total rows" do+ expect(result[:total_rows]).to eq(2)+ end++ it "normalizes the tags param" do+ params[:tags] = " OPS "+ expect(result[:workflows].map(&:name)).to eq(["Ops billing", "Ops"])+ end++ context "with multiple tags" do+ let(:params) { { tags: "ops,billing" } }++ it "only returns workflows carrying all tags" do+ expect(result[:workflows].map(&:name)).to eq(["Ops billing"])+ expect(result[:total_rows]).to eq(1)+ end+ end++ context "with an unknown tag" do+ let(:params) { { tags: "nope" } }++ it "returns no workflows" do+ expect(result[:workflows]).to be_empty+ expect(result[:total_rows]).to eq(0)+ end+ end++ context "with a name filter" do+ let(:params) { { tags: "ops", filter: "billing" } }++ it "combines both filters" do+ expect(result[:workflows].map(&:name)).to eq(["Ops billing"])+ end+ end++ context "with pagination" do+ let(:params) { { tags: "ops", limit: 1 } }++ it "preserves the tags filter in the load more url" do+ expect(result[:load_more_url]).to eq(+ "/admin/plugins/discourse-workflows/workflows.json?cursor=#{ops_billing_workflow.id}&limit=1&tags=ops",+ )+ end++ it "returns the remaining tagged workflows on the next page without repeats" do+ params[:cursor] = ops_billing_workflow.id+ expect(result[:workflows].map(&:name)).to eq(["Ops"])+ expect(result[:load_more_url]).to be_nil+ end+ end+ end+context "with exclude_id" dofab!(:workflow_a) doFabricate(:discourse_workflows_workflow, name: "Alpha", created_by: user)diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/update_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/update_spec.rbindex c9cd16d9498..17371a6f6b1 100644--- a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/update_spec.rb+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/update_spec.rb@@ -28,6 +28,7 @@ RSpec.describe DiscourseWorkflows::Workflow::Update doattrs = { workflow_id: workflow.id, name:, error_workflow_id:, nodes:, connections: }attrs[:timezone] = timezone unless timezone == :not_providedattrs[:static_data] = static_data unless static_data == :not_provided+ attrs[:tags] = tags unless tags == :not_providedattrsendlet(:dependencies) { { guardian: user.guardian } }@@ -35,6 +36,7 @@ RSpec.describe DiscourseWorkflows::Workflow::Update dolet(:error_workflow_id) { nil }let(:timezone) { :not_provided }let(:static_data) { :not_provided }+ let(:tags) { :not_provided }let(:nodes) { [] }let(:connections) { {} }@@ -194,6 +196,64 @@ RSpec.describe DiscourseWorkflows::Workflow::Update doendend+ context "when too many tags are provided" do+ let(:tags) { (1..11).map { |index| "tag-#{index}" } }++ it { is_expected.to fail_a_contract }+ end++ context "when a tag contains a comma" do+ let(:tags) { ["ops,billing"] }++ it { is_expected.to fail_a_contract }+ end++ context "when tags are provided" do+ let(:nodes) { nil }+ let(:connections) { nil }+ let(:tags) { ["Ops", " billing ", "ops"] }++ it { is_expected.to run_successfully }++ it "assigns the normalized tags without creating a new version" do+ version_id = workflow.version_id++ expect { result }.not_to change { DiscourseWorkflows::WorkflowVersion.count }++ workflow.reload+ expect(workflow.tags.map(&:name)).to eq(%w[billing ops])+ expect(workflow.version_id).to eq(version_id)+ end+ end++ context "when tags are cleared" do+ let(:nodes) { nil }+ let(:connections) { nil }+ let(:tags) { [] }++ before { DiscourseWorkflows::WorkflowTag.sync!(workflow:, names: %w[ops]) }++ it "removes the tags and prunes the orphaned tag" do+ result++ expect(workflow.reload.tags).to be_empty+ expect(DiscourseWorkflows::WorkflowTag.exists?(name: "ops")).to eq(false)+ end+ end++ context "when tags are not provided" do+ let(:nodes) { nil }+ let(:connections) { nil }++ before { DiscourseWorkflows::WorkflowTag.sync!(workflow:, names: %w[ops]) }++ it "leaves the existing tags untouched" do+ result++ expect(workflow.reload.tags.map(&:name)).to eq(%w[ops])+ end+ end+context "when only static data is provided" dolet(:nodes) { nil }let(:connections) { nil }diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow_tag/list_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow_tag/list_spec.rbnew file mode 100644index 00000000000..63b75ee3a19--- /dev/null+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow_tag/list_spec.rb@@ -0,0 +1,42 @@+# frozen_string_literal: true++RSpec.describe DiscourseWorkflows::WorkflowTag::List do+ describe ".call" do+ subject(:result) { described_class.call(**dependencies) }++ fab!(:admin)+ 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 tags exist" do+ before do+ Fabricate(:discourse_workflows_workflow, created_by: admin, tags: %w[ops])+ Fabricate(:discourse_workflows_workflow, created_by: admin, tags: %w[ops billing])+ end++ it { is_expected.to run_successfully }++ it "returns tags ordered by name with workflow counts" do+ expect(+ result[:workflow_tags].map do |tag|+ [tag.name, tag.attributes["workflow_count_value"].to_i]+ end,+ ).to eq([["billing", 1], ["ops", 2]])+ end+ end++ context "when there are no tags" do+ it { is_expected.to run_successfully }++ it "returns an empty list" do+ expect(result[:workflow_tags]).to eq([])+ end+ 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 1b3c334157f..c200ad30550 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@@ -19,6 +19,21 @@ module PageObjectsselfend+ def add_tag(tag)+ find(".workflows-tags-editor__manage").click+ tag_selector =+ PageObjects::Components::SelectKit.new(".workflows-tags-editor .list-setting")+ tag_selector.expand+ tag_selector.search(tag)+ tag_selector.select_row_by_value(tag)+ find(".workflows-tags-editor__done").click+ self+ end++ def has_header_tag?(tag)+ page.has_css?(".workflows-tags-editor .d-table-badge", text: tag)+ end+def has_node_configurator?page.has_css?(".workflows-configurator-modal")enddiff --git a/plugins/discourse-workflows/spec/system/page_objects/pages/workflows.rb b/plugins/discourse-workflows/spec/system/page_objects/pages/workflows.rbindex ac595da7ea4..2ca860004fe 100644--- a/plugins/discourse-workflows/spec/system/page_objects/pages/workflows.rb+++ b/plugins/discourse-workflows/spec/system/page_objects/pages/workflows.rb@@ -29,6 +29,38 @@ module PageObjectspage.has_css?(".workflows-empty-state")end+ def has_no_workflow?(name)+ page.has_no_css?(".workflows-index__name", text: name)+ end++ def has_workflow_tag?(workflow, tag)+ page.has_css?(+ ".workflows-index__row[data-item-id='#{workflow.id}'] .workflows-index__tags .d-table-badge",+ text: tag,+ )+ end++ def click_workflow_tag(workflow, tag)+ find(+ ".workflows-index__row[data-item-id='#{workflow.id}'] .workflows-index__tags .d-table-badge",+ text: tag,+ ).click+ self+ end++ def filter_by_tag(tag)+ find(".workflows-index__tag-filter").click+ find(".d-multi-select__search-input").fill_in(with: tag)+ find(".d-multi-select__result", text: tag).click+ page.send_keys(:escape)+ self+ end++ def reset_filters+ find(".d-filter-controls__reset").click+ self+ end+def click_new_workflowfind(".workflows-index__new-btn").clickselfdiff --git a/plugins/discourse-workflows/spec/system/workflows_spec.rb b/plugins/discourse-workflows/spec/system/workflows_spec.rbindex c5cc98ddf9d..d1984094504 100644--- a/plugins/discourse-workflows/spec/system/workflows_spec.rb+++ b/plugins/discourse-workflows/spec/system/workflows_spec.rb@@ -59,6 +59,57 @@ RSpec.describe "Discourse Workflows" doexpect(workflows_page).to have_no_failed_workflow(recovered_workflow)end+ context "with workflow tags" do+ fab!(:ops_workflow) do+ Fabricate(+ :discourse_workflows_workflow,+ name: "Ops workflow",+ created_by: admin,+ tags: %w[ops],+ )+ end+ fab!(:billing_workflow) do+ Fabricate(+ :discourse_workflows_workflow,+ name: "Billing workflow",+ created_by: admin,+ tags: %w[billing],+ )+ end++ it "filters the list by tag from a row chip and from the tag filter" do+ workflows_page.visit_index++ expect(workflows_page).to have_workflow_tag(ops_workflow, "ops")+ expect(workflows_page).to have_workflow_tag(billing_workflow, "billing")++ workflows_page.click_workflow_tag(ops_workflow, "ops")+ expect(workflows_page).to have_workflow("Ops workflow")+ expect(workflows_page).to have_no_workflow("Billing workflow")+ expect(page.current_url).to include("tags=ops")++ workflows_page.reset_filters+ expect(workflows_page).to have_workflow("Billing workflow")++ workflows_page.filter_by_tag("billing")+ expect(workflows_page).to have_workflow("Billing workflow")+ expect(workflows_page).to have_no_workflow("Ops workflow")+ end++ it "adds a tag from the editor header even when core tagging is disabled" do+ SiteSetting.tagging_enabled = false++ editor_page.visit(billing_workflow.id)+ editor_page.add_tag("urgent")++ expect(editor_page).to have_header_tag("urgent")+ expect(billing_workflow.reload.tags.map(&:name)).to eq(%w[billing urgent])++ workflows_page.visit_index+ expect(workflows_page).to have_workflow_tag(billing_workflow, "urgent")+ end+ end+context "when closing the node configurator" dofab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: admin) }diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/tags-editor-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/tags-editor-test.gjsnew file mode 100644index 00000000000..e0d23830b49--- /dev/null+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/tags-editor-test.gjs@@ -0,0 +1,130 @@+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 pretender, { response } from "discourse/tests/helpers/create-pretender";+import selectKit from "discourse/tests/helpers/select-kit-helper";+import WorkflowTagsEditor from "discourse/plugins/discourse-workflows/admin/components/workflows/tags-editor";++class FakeWorkflow {+ @tracked tags;++ id = 1;++ constructor(tags) {+ this.tags = tags;+ }++ set(key, value) {+ this[key] = value;+ }+}++function workflowFor(tags) {+ return new FakeWorkflow(tags);+}++module("Integration | Component | workflows tags editor", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ pretender.get("/admin/plugins/discourse-workflows/workflow-tags.json", () =>+ response(200, {+ workflow_tags: [{ id: 1, name: "ops", workflow_count: 2 }],+ })+ );+ });++ test("renders the workflow tags as chips", async function (assert) {+ this.workflow = workflowFor(["billing", "ops"]);++ await render(+ <template><WorkflowTagsEditor @workflow={{this.workflow}} /></template>+ );++ assert.dom(".workflows-tags-editor .d-table-badge").exists({ count: 2 });+ assert.dom(".workflows-tags-editor .d-table-badge").hasText("billing");+ });++ test("selecting an existing tag persists it on the workflow", async function (assert) {+ let putBody;+ pretender.put(+ "/admin/plugins/discourse-workflows/workflows/1.json",+ (request) => {+ putBody = JSON.parse(request.requestBody);+ return response(200, {+ workflow: { id: 1, tags: putBody.workflow.tags },+ });+ }+ );++ this.workflow = workflowFor([]);++ await render(+ <template><WorkflowTagsEditor @workflow={{this.workflow}} /></template>+ );++ await click(".workflows-tags-editor__manage");++ const tagSelector = selectKit(".workflows-tags-editor .list-setting");+ await tagSelector.expand();+ await tagSelector.selectRowByValue("ops");++ assert.deepEqual(putBody.workflow.tags, ["ops"]);+ assert.deepEqual(this.workflow.tags, ["ops"]);++ await click(".workflows-tags-editor__done");+ assert.dom(".workflows-tags-editor .d-table-badge").hasText("ops");+ });++ test("creating a new tag sends it in the update", async function (assert) {+ let putBody;+ pretender.put(+ "/admin/plugins/discourse-workflows/workflows/1.json",+ (request) => {+ putBody = JSON.parse(request.requestBody);+ return response(200, { workflow: { id: 1, tags: ["urgent"] } });+ }+ );++ this.workflow = workflowFor([]);++ await render(+ <template><WorkflowTagsEditor @workflow={{this.workflow}} /></template>+ );++ await click(".workflows-tags-editor__manage");++ const tagSelector = selectKit(".workflows-tags-editor .list-setting");+ await tagSelector.expand();+ await tagSelector.fillInFilter("urgent");+ await tagSelector.selectRowByValue("urgent");++ assert.deepEqual(putBody.workflow.tags, ["urgent"]);+ assert.deepEqual(this.workflow.tags, ["urgent"]);+ });++ test("a failed update restores the previous tags", async function (assert) {+ pretender.put("/admin/plugins/discourse-workflows/workflows/1.json", () =>+ response(422, { errors: ["too many tags"] })+ );++ this.workflow = workflowFor(["billing"]);++ await render(+ <template><WorkflowTagsEditor @workflow={{this.workflow}} /></template>+ );++ await click(".workflows-tags-editor__manage");++ const tagSelector = selectKit(".workflows-tags-editor .list-setting");+ await tagSelector.expand();+ await tagSelector.selectRowByValue("ops");++ assert.deepEqual(+ this.workflow.tags,+ ["billing"],+ "failed saves roll back to the last persisted tags"+ );+ });+});diff --git a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/index-test.js b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/index-test.jsindex 27a927a1f6f..6a88a33cc14 100644--- a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/index-test.js+++ b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/index-test.js@@ -19,6 +19,48 @@ module("Unit | Component | workflows index", function () {);});+ test("tag helpers derive names, selection, and search results", async function (assert) {+ const component = Object.create(WorkflowsIndex.prototype);+ component.args = {+ workflowTags: [+ { id: 1, name: "billing", workflow_count: 1 },+ { id: 2, name: "ops", workflow_count: 2 },+ ],+ };+ component.tagFilter = ["ops"];++ assert.deepEqual(component.availableTagNames, ["billing", "ops"]);+ assert.deepEqual(component.tagSelection, [+ { id: 2, name: "ops", workflow_count: 2 },+ ]);+ assert.true(component.hasActiveFilters);++ assert.deepEqual(await component.loadTags("bil"), [+ { id: 1, name: "billing", workflow_count: 1 },+ ]);+ assert.strictEqual((await component.loadTags("")).length, 2);++ component.tagFilter = [];+ assert.false(component.hasActiveFilters);+ });++ test("normalizeTagFilter downcases and drops unknown tags", function (assert) {+ const component = Object.create(WorkflowsIndex.prototype);+ component.args = {+ workflowTags: [+ { id: 1, name: "billing", workflow_count: 1 },+ { id: 2, name: "ops", workflow_count: 2 },+ ],+ };++ assert.deepEqual(component.normalizeTagFilter("OPS, Billing, missing"), [+ "ops",+ "billing",+ ]);+ assert.deepEqual(component.normalizeTagFilter(" Ops "), ["ops"]);+ assert.deepEqual(component.normalizeTagFilter(""), []);+ });+test("status label keeps published and unpublished states distinct", function (assert) {const component = Object.create(WorkflowsIndex.prototype);