A platform for community discussion. Free, open, simple.
FEATURE: lists all workflow versions (#40982)
Joffrey JAFFEUXc289ca17b24a
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/version/manager.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/version/manager.gjsnew file mode 100644index 00000000000..550f5291195--- /dev/null+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/version/manager.gjs@@ -0,0 +1,145 @@+import { fn } from "@ember/helper";+import { action } from "@ember/object";+import { service } from "@ember/service";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import { userPath } from "discourse/lib/url";+import DButton from "discourse/ui-kit/d-button";+import dAvatar from "discourse/ui-kit/helpers/d-avatar";+import dFormatDate from "discourse/ui-kit/helpers/d-format-date";+import { i18n } from "discourse-i18n";+import AdminTable from "../admin-table";+import EmptyState from "../empty-state";+import PaginatedListManager from "../paginated-list-manager";++export default class VersionsManager extends PaginatedListManager {+ @service router;+ @service store;+ @service toasts;++ get collectionKey() {+ return "versions";+ }++ get basePath() {+ return `/admin/plugins/discourse-workflows/workflows/${this.args.workflow.id}/versions`;+ }++ @action+ revert(version) {+ this.dialog.yesNoConfirm({+ message: i18n("discourse_workflows.versions.revert_confirm", {+ version: version.version_number,+ }),+ didConfirm: async () => {+ try {+ await ajax(`${this.basePath}/${version.version_id}/restore.json`, {+ type: "POST",+ });+ // Refresh the cached workflow record so the editor reflects the+ // restored draft when we transition back to it.+ await this.store.find(+ "discourse-workflows-workflow",+ this.args.workflow.id+ );+ this.toasts.success({+ duration: "short",+ data: {+ message: i18n("discourse_workflows.versions.reverted", {+ version: version.version_number,+ }),+ },+ });+ this.router.transitionTo(+ "adminPlugins.show.discourse-workflows.show.index",+ this.args.workflow.id+ );+ } catch (e) {+ popupAjaxError(e);+ }+ },+ });+ }++ <template>+ <AdminTable+ @items={{this.items}}+ @itemKey="version_id"+ @isLoading={{this.isLoading}}+ @canLoadMore={{this.canLoadMore}}+ @loadMore={{this.loadMore}}+ @loadingMore={{this.loadingMore}}+ class="workflows-versions-manager"+ >+ <:empty>+ <EmptyState+ @emoji="floppy_disk"+ @title={{i18n "discourse_workflows.versions.empty_title"}}+ @description={{i18n "discourse_workflows.versions.empty_description"}}+ />+ </:empty>+ <:head>+ <th class="d-table__header-cell">{{i18n+ "discourse_workflows.versions.version"+ }}</th>+ <th class="d-table__header-cell">{{i18n+ "discourse_workflows.versions.author"+ }}</th>+ <th class="d-table__header-cell">{{i18n+ "discourse_workflows.versions.changed_at"+ }}</th>+ <th class="d-table__header-cell"></th>+ </:head>+ <:row as |version|>+ <td class="d-table__cell --overview">+ <strong class="d-table__overview-name">{{i18n+ "discourse_workflows.versions.version_number"+ number=version.version_number+ }}</strong>+ {{#if version.is_current}}+ <span class="workflows-versions__badge --current">{{i18n+ "discourse_workflows.versions.current"+ }}</span>+ {{/if}}+ {{#if version.is_active}}+ <span class="workflows-versions__badge --live">{{i18n+ "discourse_workflows.versions.live"+ }}</span>+ {{/if}}+ </td>+ <td class="d-table__cell --detail">+ <div class="d-table__mobile-label">+ {{i18n "discourse_workflows.versions.author"}}+ </div>+ {{#if version.created_by}}+ <a+ href={{userPath version.created_by.username}}+ class="workflows-versions__author"+ >+ {{dAvatar version.created_by imageSize="tiny"}}+ <span>{{version.created_by.username}}</span>+ </a>+ {{/if}}+ </td>+ <td class="d-table__cell --detail">+ <div class="d-table__mobile-label">+ {{i18n "discourse_workflows.versions.changed_at"}}+ </div>+ {{dFormatDate version.created_at format="medium"}}+ </td>+ <td class="d-table__cell --controls">+ <div class="d-table__cell-actions">+ {{#unless version.is_current}}+ <DButton+ @action={{fn this.revert version}}+ @label="discourse_workflows.versions.revert"+ @icon="arrow-rotate-left"+ class="btn-default btn-small workflows-versions__revert"+ />+ {{/unless}}+ </div>+ </td>+ </:row>+ </AdminTable>+ </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 15022eb7958..0a9efecc07d 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@@ -9,6 +9,7 @@ export default {this.route("show", { path: "/:execution_id" });});this.route("settings");+ this.route("versions");});});this.route("discourse-workflows-templates", { path: "templates" });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 52f36533fcb..938ecf47898 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@@ -62,6 +62,10 @@ class WorkflowShowPage extends Component {@route="adminPlugins.show.discourse-workflows.show.settings"@label="discourse_workflows.tabs.settings"/>+ <DNavItem+ @route="adminPlugins.show.discourse-workflows.show.versions"+ @label="discourse_workflows.tabs.versions"+ /></DHorizontalOverflowNav></div>diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/versions.gjs b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/versions.gjsnew file mode 100644index 00000000000..405dba349db--- /dev/null+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/versions.gjs@@ -0,0 +1,8 @@+import DBreadcrumbsItem from "discourse/ui-kit/d-breadcrumbs-item";+import { i18n } from "discourse-i18n";+import VersionsManager from "discourse/plugins/discourse-workflows/admin/components/workflows/version/manager";++export default <template>+ <DBreadcrumbsItem @label={{i18n "discourse_workflows.tabs.versions"}} />+ <VersionsManager @workflow={{@controller.model.workflow}} />+</template>diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/workflow_versions_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/workflow_versions_controller.rbnew file mode 100644index 00000000000..3ba4749b6fa--- /dev/null+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/workflow_versions_controller.rb@@ -0,0 +1,51 @@+# frozen_string_literal: true++module DiscourseWorkflows+ class WorkflowVersionsController < ::Admin::AdminController+ requires_plugin DiscourseWorkflows::PLUGIN_NAME++ def index+ DiscourseWorkflows::WorkflowVersion::List.call(service_params) do |result|+ on_success do |workflow:, versions:, total_rows:, load_more_url:|+ render json: {+ versions:+ serialize_data(+ versions,+ DiscourseWorkflows::WorkflowVersionSerializer,+ current_version_id: workflow.version_id,+ active_version_id: workflow.active_version_id,+ ),+ meta: { total_rows: total_rows, load_more_url: load_more_url }.compact,+ }+ end+ on_failure { render(json: failed_json, status: :unprocessable_entity) }+ on_model_not_found(:workflow) { raise Discourse::NotFound }+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }+ end+ end++ def restore+ DiscourseWorkflows::Workflow::RevertToVersion.call(service_params) do |result|+ on_success do |workflow:|+ render_serialized(workflow, DiscourseWorkflows::WorkflowSerializer, root: "workflow")+ end+ on_failure { render(json: failed_json, status: :unprocessable_entity) }+ 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(:version) { raise Discourse::NotFound }+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }+ on_model_errors(:workflow) do |model|+ render(+ json: failed_json.merge(errors: model.errors.full_messages),+ status: :unprocessable_entity,+ )+ end+ end+ end+ end+enddiff --git a/plugins/discourse-workflows/app/serializers/discourse_workflows/workflow_version_serializer.rb b/plugins/discourse-workflows/app/serializers/discourse_workflows/workflow_version_serializer.rbnew file mode 100644index 00000000000..9d76a44764b--- /dev/null+++ b/plugins/discourse-workflows/app/serializers/discourse_workflows/workflow_version_serializer.rb@@ -0,0 +1,21 @@+# frozen_string_literal: true++module DiscourseWorkflows+ class WorkflowVersionSerializer < ApplicationSerializer+ attributes :version_id, :version_number, :name, :autosaved, :created_at, :is_current, :is_active++ attribute :created_by++ def created_by+ BasicUserSerializer.new(object.created_by, root: false).as_json+ end++ def is_current+ @options[:current_version_id] == object.version_id+ end++ def is_active+ @options[:active_version_id] == object.version_id+ end+ end+enddiff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/discard_draft.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/discard_draft.rbindex e3eb264a714..20235a72cf8 100644--- a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/discard_draft.rb+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/discard_draft.rb@@ -12,12 +12,9 @@ module DiscourseWorkflowspolicy :can_manage_workflows, class_name: Policy::CanManageWorkflows- lock(:workflow_id) do- model :workflow- model :active_version- step :restore_published_version- end-+ model :workflow+ model :active_version+ step :restore_published_versionstep :expire_workflow_cachesprivatediff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/revert_to_version.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/revert_to_version.rbnew file mode 100644index 00000000000..d8b4496a70f--- /dev/null+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/revert_to_version.rb@@ -0,0 +1,40 @@+# frozen_string_literal: true++module DiscourseWorkflows+ class Workflow::RevertToVersion+ include Service::Base++ params do+ attribute :workflow_id, :integer+ attribute :version_id, :string++ validates :workflow_id, presence: true+ validates :version_id, presence: true+ end++ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows++ model :workflow+ model :version+ step :restore_version+ step :expire_workflow_caches++ private++ def fetch_workflow(params:)+ DiscourseWorkflows::Workflow.find_by(id: params.workflow_id)+ end++ def fetch_version(workflow:, params:)+ workflow.workflow_versions.find_by(version_id: params.version_id)+ end++ def restore_version(workflow:, version:, guardian:)+ workflow.restore_from_version!(version, user: guardian.user)+ end++ def expire_workflow_caches+ Workflow::Action::ExpireCaches.call+ end+ end+enddiff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow_version/list.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow_version/list.rbnew file mode 100644index 00000000000..a679a217052--- /dev/null+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow_version/list.rb@@ -0,0 +1,51 @@+# frozen_string_literal: true++module DiscourseWorkflows+ class WorkflowVersion::List+ include Service::Base++ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows++ params do+ attribute :workflow_id, :integer+ attribute :cursor, :integer+ attribute :limit, :integer++ validates :workflow_id, presence: true++ after_validation { self.limit = DiscourseWorkflows::Pagination.normalize_limit(limit) }+ end++ model :workflow+ model :versions, optional: true+ model :total_rows, :count_total_rows+ model :load_more_url, :build_load_more_url, optional: true++ private++ def fetch_workflow(params:)+ DiscourseWorkflows::Workflow.find_by(id: params.workflow_id)+ end++ def fetch_versions(workflow:, params:)+ scope = workflow.workflow_versions.includes(:created_by).order(version_number: :desc)++ context[:page] = DiscourseWorkflows::Pagination.cursor_page(+ scope: scope,+ cursor: params.cursor,+ limit: params.limit,+ path: "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/versions.json",+ column: :version_number,+ )+ context[:page].records+ end++ def count_total_rows+ context[:page].total_rows+ end++ def build_load_more_url+ context[:page].load_more_url+ end+ end+enddiff --git a/plugins/discourse-workflows/assets/stylesheets/common/index.scss b/plugins/discourse-workflows/assets/stylesheets/common/index.scssindex d2704338743..28559f300c7 100644--- a/plugins/discourse-workflows/assets/stylesheets/common/index.scss+++ b/plugins/discourse-workflows/assets/stylesheets/common/index.scss@@ -13,6 +13,7 @@@import "context/schema-field";@import "variable/variable-input";@import "variable/variables-manager";+@import "version/versions-manager";@import "executions/executions";@import "executions/executions-manager";@import "executions/execution-detail";diff --git a/plugins/discourse-workflows/assets/stylesheets/common/version/versions-manager.scss b/plugins/discourse-workflows/assets/stylesheets/common/version/versions-manager.scssnew file mode 100644index 00000000000..05dd0fa19f4--- /dev/null+++ b/plugins/discourse-workflows/assets/stylesheets/common/version/versions-manager.scss@@ -0,0 +1,26 @@+.workflows-versions {+ &__author {+ display: inline-flex;+ align-items: center;+ gap: var(--space-1);+ }++ &__badge {+ display: inline-block;+ margin-inline-start: var(--space-1);+ padding: 0 var(--space-1);+ border-radius: var(--d-border-radius);+ font-size: var(--font-down-2);+ line-height: var(--line-height-large);++ &.--current {+ background: var(--primary-low);+ color: var(--primary-medium);+ }++ &.--live {+ background: var(--success-low);+ color: var(--success);+ }+ }+}diff --git a/plugins/discourse-workflows/config/locales/client.en.yml b/plugins/discourse-workflows/config/locales/client.en.ymlindex 04c9637d380..4a1fd65f22b 100644--- a/plugins/discourse-workflows/config/locales/client.en.yml+++ b/plugins/discourse-workflows/config/locales/client.en.yml@@ -77,6 +77,7 @@ en:workflow: "Workflow"executions: "Executions"settings: "Settings"+ versions: "Versions"data_tables: "Data tables"templates: "Templates"credentials: "Credentials"@@ -92,6 +93,19 @@ en:timezone_description: "Schedule triggers 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."+ versions:+ title: "Versions"+ version: "Version"+ version_number: "Version %{number}"+ author: "Author"+ changed_at: "Changed"+ current: "Current"+ live: "Live"+ revert: "Revert"+ revert_confirm: "Revert the draft to version %{version}? You can review it in the editor and publish when ready."+ reverted: "Reverted to version %{version}"+ empty_title: "No versions yet"+ empty_description: "Each time you save changes, a new version is recorded here."add_node:title: "Add step"first_step: "Add first step"diff --git a/plugins/discourse-workflows/config/routes.rb b/plugins/discourse-workflows/config/routes.rbindex f2e97f7ca1d..7cb62406186 100644--- a/plugins/discourse-workflows/config/routes.rb+++ b/plugins/discourse-workflows/config/routes.rb@@ -21,6 +21,7 @@ DiscourseWorkflows::Engine.routes.draw doexecution_id: /\d+/,}get "/workflows/:id/settings" => "admin#index", :constraints => { id: /\d+/ }+ get "/workflows/:id/versions" => "admin#index", :constraints => { id: /\d+/ }endscope format: :json do@@ -43,6 +44,11 @@ DiscourseWorkflows::Engine.routes.draw dopost "/executions" => "executions#create"get "/executions" => "executions#index"get "/workflows/:workflow_id/executions" => "executions#index"+ get "/workflows/:workflow_id/versions" => "workflow_versions#index"+ post "/workflows/:workflow_id/versions/:version_id/restore" => "workflow_versions#restore",+ :constraints => {+ version_id: /[0-9a-f-]{36}/,+ }delete "/executions" => "executions#destroy"get "/executions/:id" => "executions#show"get "/stats" => "stats#index"diff --git a/plugins/discourse-workflows/lib/discourse_workflows/pagination.rb b/plugins/discourse-workflows/lib/discourse_workflows/pagination.rbindex 76edbb8f422..f5070bd8d02 100644--- a/plugins/discourse-workflows/lib/discourse_workflows/pagination.rb+++ b/plugins/discourse-workflows/lib/discourse_workflows/pagination.rb@@ -11,8 +11,8 @@ module DiscourseWorkflows(limit || DEFAULT_LIMIT).clamp(1, MAX_LIMIT)end- def self.cursor_page(scope:, cursor:, limit:, path:, query: {})- paginated_scope = cursor ? scope.where("id < ?", cursor) : scope+ def self.cursor_page(scope:, cursor:, limit:, path:, query: {}, column: :id)+ paginated_scope = cursor ? scope.where("#{column} < ?", cursor) : scoperecords = paginated_scope.limit(limit + 1).to_ahas_more = records.size > limitrecords = records.first(limit) if has_more@@ -20,14 +20,15 @@ module DiscourseWorkflowsPage.new(records: records,total_rows: scope.count,- load_more_url: build_load_more_url(path, records, limit, query, has_more),+ load_more_url: build_load_more_url(path, records, limit, query, has_more, column),)end- def self.build_load_more_url(path, records, limit, query, has_more)+ def self.build_load_more_url(path, records, limit, query, has_more, column = :id)return if !has_more || records.empty?- "#{path}?#{query.merge(cursor: records.last.id, limit: limit).compact_blank.to_query}"+ cursor = records.last.public_send(column)+ "#{path}?#{query.merge(cursor: cursor, limit: limit).compact_blank.to_query}"endendenddiff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/pagination_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/pagination_spec.rbindex 8e7faf73c6f..7c87a845d4c 100644--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/pagination_spec.rb+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/pagination_spec.rb@@ -66,4 +66,44 @@ RSpec.describe DiscourseWorkflows::Pagination doexpect(page.load_more_url).to be_nilendend++ describe ".cursor_page with a custom column" do+ fab!(:workflow, :discourse_workflows_workflow)++ before do+ workflow.snapshot!(user: workflow.created_by) # version 2+ workflow.snapshot!(user: workflow.created_by) # version 3+ end++ let(:scope) { workflow.workflow_versions.order(version_number: :desc) }++ it "paginates and builds the cursor URL using the given column" do+ page =+ described_class.cursor_page(+ scope: scope,+ cursor: nil,+ limit: 2,+ path: "/versions.json",+ column: :version_number,+ )++ expect(page.records.map(&:version_number)).to eq([3, 2])+ expect(page.total_rows).to eq(3)+ expect(page.load_more_url).to eq("/versions.json?cursor=2&limit=2")+ end++ it "applies the cursor using the given column" do+ page =+ described_class.cursor_page(+ scope: scope,+ cursor: 2,+ limit: 10,+ path: "/versions.json",+ column: :version_number,+ )++ expect(page.records.map(&:version_number)).to eq([1])+ expect(page.load_more_url).to be_nil+ end+ endenddiff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/workflow_versions_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/workflow_versions_controller_spec.rbnew file mode 100644index 00000000000..147e71fe737--- /dev/null+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/workflow_versions_controller_spec.rb@@ -0,0 +1,99 @@+# frozen_string_literal: true++RSpec.describe DiscourseWorkflows::WorkflowVersionsController 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" do+ get "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/versions.json"+ expect(response).to have_http_status(:not_found)+ end+ end++ describe "GET /admin/plugins/discourse-workflows/workflows/:workflow_id/versions" do+ it "returns versions newest first with author and metadata" do+ second_version = workflow.snapshot!(user: admin)++ get "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/versions.json"++ expect(response).to have_http_status(:ok)+ json = response.parsed_body+ expect(json["versions"].map { |version| version["version_number"] }).to eq([2, 1])+ expect(json["versions"][0]).to include(+ "version_id" => second_version.version_id,+ "is_current" => true,+ )+ expect(json["versions"][0]["created_by"]["username"]).to eq(admin.username)+ expect(json["meta"]["total_rows"]).to eq(2)+ end++ it "returns 404 when the workflow does not exist" do+ get "/admin/plugins/discourse-workflows/workflows/-1/versions.json"+ expect(response).to have_http_status(:not_found)+ end++ it "paginates with the version_number cursor" do+ workflow.snapshot!(user: admin) # version 2+ workflow.snapshot!(user: admin) # version 3++ get "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/versions.json",+ params: {+ cursor: 2,+ limit: 10,+ }++ json = response.parsed_body+ expect(json["versions"].map { |version| version["version_number"] }).to eq([1])+ end++ it "returns a load_more_url when there are more results" do+ workflow.snapshot!(user: admin) # version 2++ get "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/versions.json",+ params: {+ limit: 1,+ }++ json = response.parsed_body+ expect(json["versions"].length).to eq(1)+ expect(json["meta"]["load_more_url"]).to be_present+ end+ end++ describe "POST /admin/plugins/discourse-workflows/workflows/:workflow_id/versions/:version_id/restore" do+ it "reverts the draft to the chosen version" do+ first_version_id = workflow.version_id+ original_nodes = workflow.nodes++ graph = build_workflow_graph { |builder| builder.node "draft-1", "trigger:manual" }+ workflow.update!(nodes: graph[:nodes], connections: graph[:connections])+ workflow.snapshot!(user: admin)++ post "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/versions/#{first_version_id}/restore.json"++ expect(response).to have_http_status(:ok)+ expect(workflow.reload.version_id).to eq(first_version_id)+ expect(workflow.nodes).to eq(original_nodes)+ end++ it "returns 404 for an unknown version" do+ post "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/versions/#{SecureRandom.uuid}/restore.json"+ expect(response).to have_http_status(:not_found)+ end++ it "returns 404 for a version belonging to another workflow" do+ other_workflow = Fabricate(:discourse_workflows_workflow, created_by: admin)++ post "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/versions/#{other_workflow.version_id}/restore.json"++ expect(response).to have_http_status(:not_found)+ end+ end+enddiff --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.rbnew file mode 100644index 00000000000..977ee497355--- /dev/null+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/revert_to_version_spec.rb@@ -0,0 +1,92 @@+# frozen_string_literal: true++RSpec.describe DiscourseWorkflows::Workflow::RevertToVersion do+ describe described_class::Contract, type: :model do+ it { is_expected.to validate_presence_of(:workflow_id) }+ it { is_expected.to validate_presence_of(:version_id) }+ end++ describe ".call" do+ subject(:result) { described_class.call(params:, **dependencies) }++ fab!(:user, :admin)+ fab!(:workflow) do+ graph = build_workflow_graph { |builder| builder.node "v1-1", "trigger:manual" }+ Fabricate(:discourse_workflows_workflow, created_by: user, **graph)+ end++ let!(:first_version) { workflow.workflow_versions.order(:version_number).first }++ let(:params) { { workflow_id: workflow.id, version_id: first_version.version_id } }+ let(:dependencies) { { guardian: user.guardian } }++ before do+ graph = build_workflow_graph { |builder| builder.node "v2-1", "trigger:schedule" }+ workflow.update!(+ name: "Draft workflow",+ nodes: graph[:nodes],+ connections: graph[:connections],+ settings: {+ "timezone" => "Europe/Paris",+ },+ )+ workflow.snapshot!(user: user)+ end++ context "when the contract is invalid" do+ let(:params) { { workflow_id: workflow.id, version_id: nil } }++ it { is_expected.to fail_a_contract }+ end++ context "when the workflow is not found" do+ let(:params) { { workflow_id: -1, version_id: first_version.version_id } }++ it { is_expected.to fail_to_find_a_model(:workflow) }+ end++ context "when the version is not found" do+ let(:params) { { workflow_id: workflow.id, version_id: SecureRandom.uuid } }++ it { is_expected.to fail_to_find_a_model(:version) }+ end++ context "when the version belongs to another workflow" do+ fab!(:other_workflow) { Fabricate(:discourse_workflows_workflow, created_by: user) }++ let(:params) { { workflow_id: workflow.id, version_id: other_workflow.version_id } }++ it { is_expected.to fail_to_find_a_model(:version) }+ end++ context "when the user cannot manage workflows" do+ fab!(:non_admin, :user)++ let(:dependencies) { { guardian: non_admin.guardian } }++ it { is_expected.to fail_a_policy(:can_manage_workflows) }+ end++ context "when everything's ok" do+ it { is_expected.to run_successfully }++ it "restores the chosen version into the draft" do+ result++ expect(workflow.reload).to have_attributes(+ name: first_version.name,+ nodes: first_version.nodes,+ connections: first_version.connections,+ settings: first_version.settings,+ version_id: first_version.version_id,+ )+ end++ it "does not create a new version" do+ expect { result }.not_to change { workflow.workflow_versions.count }+ end++ it_behaves_like "expires workflow caches"+ end+ end+enddiff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow_version/list_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow_version/list_spec.rbnew file mode 100644index 00000000000..09f4d44223c--- /dev/null+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow_version/list_spec.rb@@ -0,0 +1,90 @@+# frozen_string_literal: true++RSpec.describe DiscourseWorkflows::WorkflowVersion::List do+ describe described_class::Contract, type: :model do+ it { is_expected.to validate_presence_of(:workflow_id) }+ end++ describe ".call" do+ subject(:result) { described_class.call(params:, **dependencies) }++ fab!(:admin)+ fab!(:user)+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: admin) }++ let(:params) { { workflow_id: workflow.id } }+ let(:dependencies) { { guardian: admin.guardian } }++ context "when the contract is invalid" do+ let(:params) { { workflow_id: nil } }++ it { is_expected.to fail_a_contract }+ end++ context "when the workflow is not found" do+ let(:params) { { workflow_id: -1 } }++ it { is_expected.to fail_to_find_a_model(:workflow) }+ end++ context "when the user cannot manage workflows" do+ let(:dependencies) { { guardian: user.guardian } }++ it { is_expected.to fail_a_policy(:can_manage_workflows) }+ end++ context "when everything's ok" do+ it { is_expected.to run_successfully }++ it "returns versions newest first with the total count" do+ second_version = workflow.snapshot!(user: admin)++ expect(result[:versions].map(&:version_number)).to eq([2, 1])+ expect(result[:versions].first.version_id).to eq(second_version.version_id)+ expect(result[:total_rows]).to eq(2)+ end++ it "does not return a load more url when all results fit" do+ expect(result[:load_more_url]).to be_nil+ end+ end++ context "with pagination" do+ let(:params) { { workflow_id: workflow.id, limit: 1 } }++ before { workflow.snapshot!(user: admin) } # version 2++ it "returns only the requested number of versions" do+ expect(result[:versions].size).to eq(1)+ end++ it "returns a load more url keyed on version_number" do+ expect(result[:load_more_url]).to eq(+ "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/versions.json?cursor=2&limit=1",+ )+ end++ it "returns the total count of all versions" do+ expect(result[:total_rows]).to eq(2)+ end++ context "when using a cursor" do+ let(:params) { { workflow_id: workflow.id, limit: 10, cursor: 2 } }++ it "returns versions before the cursor" do+ expect(result[:versions].map(&:version_number)).to eq([1])+ end+ end+ end++ context "when other workflows have versions" do+ fab!(:other_workflow) { Fabricate(:discourse_workflows_workflow, created_by: admin) }++ it "only returns versions for the requested workflow" do+ other_workflow.snapshot!(user: admin)++ expect(result[:versions].map(&:workflow_id).uniq).to eq([workflow.id])+ end+ end+ end+enddiff --git a/plugins/discourse-workflows/spec/system/page_objects/pages/workflow_versions.rb b/plugins/discourse-workflows/spec/system/page_objects/pages/workflow_versions.rbnew file mode 100644index 00000000000..438aee44bb5--- /dev/null+++ b/plugins/discourse-workflows/spec/system/page_objects/pages/workflow_versions.rb@@ -0,0 +1,40 @@+# frozen_string_literal: true++module PageObjects+ module Pages+ module DiscourseWorkflows+ class WorkflowVersions < PageObjects::Pages::Base+ def visit(workflow_id)+ page.visit("/admin/plugins/discourse-workflows/workflows/#{workflow_id}/versions")+ self+ end++ def has_versions?(count)+ page.has_css?(".workflows-versions-manager tbody .d-table__row", count: count)+ end++ def has_author?(username)+ page.has_css?(".workflows-versions__author", text: username)+ end++ def has_version?(version)+ row_for(version)+ true+ end++ def revert(version)+ within(row_for(version)) { find(".workflows-versions__revert").click }+ self+ end++ private++ def row_for(version)+ find(+ ".workflows-versions-manager tbody .d-table__row[data-item-id='#{version.version_id}']",+ )+ end+ end+ end+ end+enddiff --git a/plugins/discourse-workflows/spec/system/workflow_versions_spec.rb b/plugins/discourse-workflows/spec/system/workflow_versions_spec.rbnew file mode 100644index 00000000000..f9dcddc9216--- /dev/null+++ b/plugins/discourse-workflows/spec/system/workflow_versions_spec.rb@@ -0,0 +1,34 @@+# frozen_string_literal: true++RSpec.describe "Discourse Workflows - Versions" do+ fab!(:admin)+ fab!(:workflow) do+ graph = build_workflow_graph { |builder| builder.node "v1-1", "trigger:manual" }+ Fabricate(:discourse_workflows_workflow, created_by: admin, **graph)+ end++ let(:versions_page) { PageObjects::Pages::DiscourseWorkflows::WorkflowVersions.new }+ let(:dialog) { PageObjects::Components::Dialog.new }++ before { sign_in(admin) }++ it "lists versions with their author and reverts the draft to an older version" do+ first_version = workflow.workflow_versions.order(:version_number).first++ graph = build_workflow_graph { |builder| builder.node "v2-1", "trigger:schedule" }+ workflow.update!(nodes: graph[:nodes], connections: graph[:connections])+ workflow.snapshot!(user: admin)++ versions_page.visit(workflow.id)++ expect(versions_page).to have_versions(2)+ expect(versions_page).to have_author(admin.username)++ versions_page.revert(first_version)+ dialog.click_yes++ expect(page).to have_current_path("/admin/plugins/discourse-workflows/workflows/#{workflow.id}")+ expect(workflow.reload.version_id).to eq(first_version.version_id)+ expect(workflow.nodes).to eq(first_version.nodes)+ end+end