diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml index da24e7d8f..665a4facc 100644 --- a/config/locales/server.en.yml +++ b/config/locales/server.en.yml @@ -61,9 +61,28 @@ en: error_messages: wizard_replacing_composer: "Category not allowed for topic creation." + system_messages: + custom_wizard_revise_queued_topic: + title: "Feedback on your topic" + subject_template: 'Feedback on new topic titled "%{topic_title}"' + text_body_template: | + Hi %{username}, + + We've reviewed your new topic titled "%{topic_title}" and have some feedback for you. + + Reason: %{reason} + + Feedback: %{feedback} + + Your answers have been saved: [open the "%{wizard_name}" wizard](%{wizard_url}), make the suggested changes and submit it again. You don't need to fill it in from scratch. + + Thanks, + %{site_name} Moderators + site_settings: custom_wizard_enabled: "Enable custom wizards." wizard_redirect_exclude_paths: "Routes excluded from wizard redirects." wizard_recognised_image_upload_formats: "File types which will result in upload displaying an image preview" wizard_apis_enabled: "Enable API features (experimental)." wizard_critical_notices_on_dashboard: "Show critical notices about the custom wizard plugin on the admin dashboard." + custom_wizard_reopen_on_revise: 'When a moderator chooses "Revise" on a queued wizard topic, reopen the wizard prefilled with the author''s answers instead of sending them the raw post. The wizard must save submissions and allow multiple submissions.' diff --git a/config/locales/server.it.yml b/config/locales/server.it.yml index 9b59829c7..d80a500c4 100644 --- a/config/locales/server.it.yml +++ b/config/locales/server.it.yml @@ -61,9 +61,28 @@ it: error_messages: wizard_replacing_composer: "Categoria non consentita per la creazione di argomenti." + system_messages: + custom_wizard_revise_queued_topic: + title: "Feedback sul tuo argomento" + subject_template: 'Feedback sul nuovo argomento intitolato "%{topic_title}"' + text_body_template: | + Ciao %{username}, + + Abbiamo esaminato il tuo nuovo argomento intitolato "%{topic_title}" e abbiamo un feedback per te. + + Motivo: %{reason} + + Feedback: %{feedback} + + Le tue risposte sono state salvate: [apri il wizard "%{wizard_name}"](%{wizard_url}), apporta le modifiche suggerite e invialo di nuovo. Non devi compilarlo da capo. + + Grazie, + I moderatori di %{site_name} + site_settings: custom_wizard_enabled: "Abilita i wizard personalizzati." wizard_redirect_exclude_paths: "Percorsi esclusi dai reindirizzamenti dei wizard." wizard_recognised_image_upload_formats: "Tipi di file per cui il caricamento mostra l'anteprima dell'immagine" wizard_apis_enabled: "Abilita le funzioni API (sperimentale)." wizard_critical_notices_on_dashboard: "Mostra nella dashboard di amministrazione gli avvisi critici sul plugin Custom Wizard." + custom_wizard_reopen_on_revise: 'Quando un moderatore sceglie "Revisione" su un argomento del wizard in coda, riapri il wizard precompilato con le risposte dell''autore invece di inviargli il post grezzo. Il wizard deve salvare gli invii e consentire invii multipli.' diff --git a/config/settings.yml b/config/settings.yml index 7698fd9cd..8211c5482 100644 --- a/config/settings.yml +++ b/config/settings.yml @@ -18,6 +18,8 @@ plugins: wizard_important_notices_on_dashboard: client: true default: true + custom_wizard_reopen_on_revise: + default: false wizard_subscription_product_key: hidden: true default: '' diff --git a/lib/custom_wizard/action.rb b/lib/custom_wizard/action.rb index 9c6e4680f..ae88dfe39 100644 --- a/lib/custom_wizard/action.rb +++ b/lib/custom_wizard/action.rb @@ -613,6 +613,8 @@ def queue_topic(params, reason) topic: params.dig(:topic_opts, :custom_fields), post: params[:custom_fields], }, + # Lets a moderator's "revise" reopen this wizard (see CustomWizardReviewableQueuedPost). + wizard_id: @wizard.id, ), ) diff --git a/lib/custom_wizard/extensions/reviewable_queued_post.rb b/lib/custom_wizard/extensions/reviewable_queued_post.rb new file mode 100644 index 000000000..3ca1546e9 --- /dev/null +++ b/lib/custom_wizard/extensions/reviewable_queued_post.rb @@ -0,0 +1,46 @@ +# frozen_string_literal: true + +# When a moderator asks the author to revise a queued wizard topic, core sends the raw post +# and asks the author to post it again with the composer, which loses the wizard's structure. +# If enabled, reopen the wizard prefilled with the author's answers and link to it instead. +module CustomWizardReviewableQueuedPost + def perform_revise_and_reject_post(performed_by, args) + draft = custom_wizard_revision_draft + return super if draft.blank? + + wizard = draft.wizard + + SystemMessage.create( + target_created_by, + :custom_wizard_revise_queued_topic, + **Dsa::AppealInstructions.message_options, + topic_title: payload["title"], + reason: args[:revise_custom_reason].presence || args[:revise_reason], + feedback: args[:revise_feedback], + wizard_name: wizard.name, + wizard_url: "#{Discourse.base_url}/w/#{wizard.id.dasherize}", + ) + + StaffActionLogger.new(performed_by).log_post_rejected(self, DateTime.now) if performed_by.staff? + create_result(:success, :rejected) + end + + private + + def custom_wizard_revision_draft + return if !SiteSetting.custom_wizard_enabled || !SiteSetting.custom_wizard_reopen_on_revise + return if topic.present? || target_created_by.blank? + + wizard_id = payload["wizard_id"] + submission_id = payload.dig("wizard_custom_fields", "topic", "wizard_submission_id") + return if wizard_id.blank? || submission_id.blank? + + CustomWizard::Submission.reopen(target_created_by, wizard_id, submission_id) + rescue StandardError => e + Discourse.warn_exception( + e, + message: "Custom Wizard: failed to reopen wizard for reviewable #{id}", + ) + nil + end +end diff --git a/lib/custom_wizard/submission.rb b/lib/custom_wizard/submission.rb index 98028741e..d0bc30d88 100644 --- a/lib/custom_wizard/submission.rb +++ b/lib/custom_wizard/submission.rb @@ -92,6 +92,28 @@ def remove end end + # Copies the answers of a submitted wizard into a new draft, so the wizard opens prefilled + # and the user can correct and resubmit it. Returns the draft, or nil if the wizard can't be + # reopened for the user, or if the user already has a draft with answers, which is never + # overwritten. + def self.reopen(user, wizard_id, submission_id) + wizard = CustomWizard::Wizard.create(wizard_id, user) + return if !wizard&.save_submissions || !wizard.can_access? + + submissions = list(wizard).submissions + drafts = submissions.reject(&:submitted?) + return if drafts.any? { |draft| draft.fields.present? } + + original = submissions.find { |submission| submission.id == submission_id } + return if original.blank? + + drafts.each(&:remove) + + draft = new(wizard, original.fields.slice(*wizard.field_ids)) + draft.save + draft + end + def self.cleanup_incomplete_submissions(wizard) all_submissions = list(wizard) sorted_submissions = diff --git a/plugin.rb b/plugin.rb index ed511c6b5..648e86587 100644 --- a/plugin.rb +++ b/plugin.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true # name: discourse-custom-wizard # about: Forms for Discourse. Better onboarding, structured posting, data enrichment, automated actions and much more. -# version: 2.18.18 +# version: 2.18.19 # authors: Angus McLeod, Faizaan Gagan, Robert Barrow, Keegan George, Kaitlin Maddever, Marcos Gutierrez # url: https://github.com/paviliondev/discourse-custom-wizard # contact_emails: development@pavilion.tech @@ -92,6 +92,7 @@ require_relative "lib/custom_wizard/extensions/invites_controller.rb" require_relative "lib/custom_wizard/extensions/users_controller.rb" require_relative "lib/custom_wizard/extensions/guardian.rb" + require_relative "lib/custom_wizard/extensions/reviewable_queued_post.rb" require_relative "lib/custom_wizard/extensions/custom_field/preloader.rb" require_relative "lib/custom_wizard/extensions/custom_field/serializer.rb" require_relative "lib/custom_wizard/extensions/custom_field/extension.rb" @@ -183,6 +184,7 @@ ::InvitesController.prepend InvitesControllerCustomWizard ::UsersController.prepend CustomWizardUsersController ::Guardian.prepend CustomWizardGuardian + ::ReviewableQueuedPost.prepend CustomWizardReviewableQueuedPost full_path = "#{Rails.root}/plugins/discourse-custom-wizard/assets/stylesheets/wizard/wizard_custom.scss" diff --git a/spec/extensions/reviewable_queued_post_spec.rb b/spec/extensions/reviewable_queued_post_spec.rb new file mode 100644 index 000000000..38e22a99c --- /dev/null +++ b/spec/extensions/reviewable_queued_post_spec.rb @@ -0,0 +1,369 @@ +# frozen_string_literal: true + +describe CustomWizardReviewableQueuedPost, type: :request do + fab!(:user) { Fabricate(:user, trust_level: TrustLevel[2]) } + fab!(:moderator) + fab!(:category) + + let(:wizard_template) { get_wizard_fixture("wizard") } + let(:wizard_path) { "/w/super-mega-fun-wizard" } + + before do + SiteSetting.custom_wizard_reopen_on_revise = true + category.update!(topic_posting_review_mode: :everyone) + wizard_template["multiple_submissions"] = true + wizard_template["actions"][0]["visible"][0]["output"] = "false" + wizard_template["actions"][0]["category"] = [ + { + type: "assignment", + output: category.id.to_s, + output_type: "text", + output_connector: "set", + }, + ] + CustomWizard::Template.save(wizard_template, skip_jobs: true) + sign_in(user) + end + + def submit_step(step_id, fields = {}) + # Same as the client, which sends the step fields as JSON. + put "#{wizard_path}/steps/#{step_id}.json", params: { fields: fields }, as: :json + expect(response.status).to eq(200) + end + + def complete_wizard(title: "Topic Title", body: "topic body") + submit_step("step_1", step_1_field_1: title, step_1_field_2: body) + submit_step("step_2") + submit_step("step_3") + end + + def queued_topic + ReviewableQueuedPost.find_by(target_created_by: user, status: :pending) + end + + def revise(reviewable) + reviewable.reload.perform( + moderator, + :revise_and_reject_post, + revise_reason: "Needs more detail", + revise_feedback: "Please describe the outcome.", + ) + end + + def wizard + CustomWizard::Builder.new("super_mega_fun_wizard", user).build + end + + def field_value(field_id) + wizard.steps.flat_map(&:fields).find { |field| field.id == field_id }.value + end + + def last_message + Topic.private_messages_for_user(user).order(:created_at).last&.first_post&.raw + end + + def expect_core_message + expect(last_message).to include("Please describe the outcome.") + expect(last_message).to include("topic body") + expect(last_message).not_to include("#{wizard_path}") + end + + it "reopens the wizard with the submitted answers and links to it" do + complete_wizard + reviewable = queued_topic + expect(reviewable.payload["wizard_id"]).to eq("super_mega_fun_wizard") + + result = revise(reviewable) + + expect(result.success?).to eq(true) + expect(reviewable.reload.status).to eq("rejected") + expect(last_message).to include("Please describe the outcome.") + expect(last_message).to include("#{Discourse.base_url}#{wizard_path}") + expect(wizard.start).to eq("step_1") + expect(field_value("step_1_field_1")).to eq("Topic Title") + expect(field_value("step_1_field_2")).to eq("topic body") + end + + it "queues the corrected topic again when the reopened wizard is submitted" do + complete_wizard + revise(queued_topic) + + complete_wizard(body: "corrected body") + + pending = ReviewableQueuedPost.where(target_created_by: user, status: :pending) + expect(pending.count).to eq(1) + expect(pending.first.payload["title"]).to eq("Topic Title") + expect(pending.first.payload["raw"]).to eq("corrected body") + expect(pending.first.category_id).to eq(category.id) + end + + it "sends the core message when the setting is disabled" do + SiteSetting.custom_wizard_reopen_on_revise = false + complete_wizard + + revise(queued_topic) + + expect_core_message + end + + it "sends the core message when the topic was queued without the wizard id" do + complete_wizard + reviewable = queued_topic + reviewable.update!(payload: reviewable.payload.except("wizard_id")) + + revise(reviewable) + + expect_core_message + end + + it "sends the core message when the wizard can't be submitted again" do + wizard_template["multiple_submissions"] = false + CustomWizard::Template.save(wizard_template, skip_jobs: true) + complete_wizard + + revise(queued_topic) + + expect_core_message + end + + it "keeps a draft with answers and sends the core message" do + complete_wizard + reviewable = queued_topic + submit_step("step_1", step_1_field_1: "Another Title", step_1_field_2: "work in progress") + + revise(reviewable) + + expect_core_message + expect(field_value("step_1_field_2")).to eq("work in progress") + end + + it "leaves other queued topics to core" do + reviewable = + NewPostManager + .new(user, title: "A regular topic title", raw: "regular body " * 5, category: category.id) + .perform + .reviewable + + revise(reviewable) + + expect(last_message).to include("regular body") + expect(last_message).not_to include("/w/") + end + + context "when a moderator uses the review queue" do + def perform_in_queue(reviewable, action, params = {}) + sign_in(moderator) + put "/review/#{reviewable.id}/perform/#{action}.json", + params: { version: reviewable.reload.version }.merge(params) + expect(response.status).to eq(200) + sign_in(user) + end + + let(:revise_params) do + { revise_reason: "Other", revise_custom_reason: "Wrong date", revise_feedback: "" } + end + + it "reopens the wizard when revising" do + complete_wizard + reviewable = queued_topic + + perform_in_queue(reviewable, :revise_and_reject_post, revise_params) + + expect(reviewable.reload.status).to eq("rejected") + expect(last_message).to include("Wrong date") + expect(last_message).to include("#{Discourse.base_url}#{wizard_path}") + expect(field_value("step_1_field_2")).to eq("topic body") + end + + it "reopens the wizard when revising with DSA reporting enabled" do + enable_dsa_reporting( + community_rules: [{ ground: "Be accurate", explanation: "Dates must be correct." }], + ) + complete_wizard + reviewable = queued_topic + + perform_in_queue( + reviewable, + :revise_and_reject_post, + revise_params.merge( + dsa_classification: { + community_rule: DsaStatementOfRecord.community_rules.first.fetch("id"), + category: "STATEMENT_CATEGORY_OTHER_VIOLATION_TC", + }, + ), + ) + + expect(reviewable.reload.status).to eq("rejected") + expect(last_message).to include("#{Discourse.base_url}#{wizard_path}") + end + + it "approves wizard topics" do + complete_wizard + reviewable = queued_topic + + perform_in_queue(reviewable, :approve_post) + + expect(reviewable.reload.status).to eq("approved") + topic = Topic.find_by(title: "Topic Title", category_id: category.id) + expect(topic.first_post.raw).to eq("topic body") + expect(topic.custom_fields["wizard_submission_id"]).to be_present + end + + it "rejects wizard topics without reopening the wizard" do + complete_wizard + reviewable = queued_topic + + perform_in_queue(reviewable, :reject_post) + + expect(reviewable.reload.status).to eq("rejected") + expect(field_value("step_1_field_2")).to be_blank + end + end + + it "sends the core message when reopening the wizard fails" do + complete_wizard + CustomWizard::Submission.stubs(:reopen).raises(StandardError, "reopen failed") + + result = revise(queued_topic) + + expect(result.success?).to eq(true) + expect(queued_topic).to be_nil + expect_core_message + end + + context "when the topic is posted as another user" do + fab!(:poster) { Fabricate(:user, trust_level: TrustLevel[2]) } + + before do + wizard_template["actions"][0]["poster"] = [ + { + type: "assignment", + output: poster.username, + output_type: "text", + output_connector: "set", + }, + ] + CustomWizard::Template.save(wizard_template, skip_jobs: true) + end + + it "sends the core message to the poster and doesn't reopen anyone's wizard" do + complete_wizard + reviewable = ReviewableQueuedPost.find_by(target_created_by: poster, status: :pending) + + revise(reviewable) + + message = Topic.private_messages_for_user(poster).order(:created_at).last.first_post.raw + expect(message).to include("topic body") + expect(message).not_to include(wizard_path) + expect(PluginStore.get("super_mega_fun_wizard_submissions", poster.id)).to be_blank + expect(field_value("step_1_field_2")).to be_blank + end + end + + context "with upload, category, tag and composer fields" do + fab!(:tag) + fab!(:upload) { Fabricate(:upload, user: user, original_filename: "image.png") } + + let(:wizard_path) { "/w/revise-wizard" } + + def mapped(field_id) + [ + { + type: "assignment", + output: field_id, + output_type: "wizard_field", + output_connector: "set", + }, + ] + end + + def wizard + CustomWizard::Builder.new("revise_wizard", user).build + end + + def complete_wizard(body: "topic body") + submit_step( + "step_1", + title: "Topic Title", + body: body, + attachment: upload.as_json(only: %i[id url original_filename extension]), + category: [category.id], + tags: [tag.name], + ) + end + + before do + enable_subscription("standard") + CustomWizard::Template.save( + { + id: "revise_wizard", + name: "Revise wizard", + save_submissions: true, + multiple_submissions: true, + steps: [ + { + id: "step_1", + fields: [ + { id: "title", type: "text", label: "Title" }, + { id: "body", type: "composer", label: "Body" }, + { id: "attachment", type: "upload", label: "Attachment", file_types: ".png" }, + { id: "category", type: "category", label: "Category", limit: 1, property: "id" }, + { id: "tags", type: "tag", label: "Tags" }, + ], + }, + ], + actions: [ + { + id: "action_1", + type: "create_topic", + run_after: "step_1", + skip_redirect: true, + title: mapped("title"), + post: "body", + category: mapped("category"), + tags: mapped("tags"), + }, + ], + }.as_json, + skip_jobs: true, + ) + end + + it "prefills the reopened wizard with the submitted values" do + complete_wizard + reviewable = queued_topic + expect(reviewable.payload["tags"]).to eq([tag.name]) + submitted = PluginStore.get("revise_wizard_submissions", user.id).sole + + revise(reviewable) + + get "#{wizard_path}.json" + expect(response.status).to eq(200) + values = + response.parsed_body["steps"] + .flat_map { |step| step["fields"] } + .to_h { |field| [field["id"], field["value"]] } + + %w[title body attachment category tags].each do |field_id| + expect(values[field_id]).to eq(submitted[field_id]) + end + expect(values["attachment"]["id"]).to eq(upload.id) + expect(values["category"]).to eq([category.id]) + expect(values["tags"]).to eq([tag.name]) + end + + it "queues the corrected topic with the same upload, category and tags" do + complete_wizard + revise(queued_topic) + + complete_wizard(body: "corrected body") + + reviewable = queued_topic + expect(reviewable.payload["raw"]).to eq("corrected body") + expect(reviewable.category_id).to eq(category.id) + expect(reviewable.payload["tags"]).to eq([tag.name]) + submission = PluginStore.get("revise_wizard_submissions", user.id).last + expect(submission["attachment"]["id"]).to eq(upload.id) + end + end +end diff --git a/spec/system/revise_queued_topic_spec.rb b/spec/system/revise_queued_topic_spec.rb new file mode 100644 index 000000000..9ab446803 --- /dev/null +++ b/spec/system/revise_queued_topic_spec.rb @@ -0,0 +1,115 @@ +# frozen_string_literal: true + +describe "Revising a queued wizard topic" do + fab!(:user) { Fabricate(:user, trust_level: TrustLevel[2]) } + fab!(:moderator) + fab!(:category) { Fabricate(:category, name: "Information documents") } + fab!(:tag) { Fabricate(:tag, name: "public-notice") } + fab!(:upload) { Fabricate(:upload, user: user, original_filename: "notice.png") } + + let(:review_page) { PageObjects::Pages::Review.new } + let(:revise_modal) { PageObjects::Modals::ReviseAndRejectPost.new } + + def mapped(field_id) + [{ type: "assignment", output: field_id, output_type: "wizard_field", output_connector: "set" }] + end + + before do + enable_subscription("standard") + SiteSetting.custom_wizard_reopen_on_revise = true + category.update!(topic_posting_review_mode: :everyone) + + CustomWizard::Template.save( + { + id: "revise_wizard", + name: "Revise wizard", + save_submissions: true, + multiple_submissions: true, + steps: [ + { + id: "step_1", + fields: [ + { id: "title", type: "text", label: "Title" }, + { id: "body", type: "composer", label: "Body" }, + { id: "attachment", type: "upload", label: "Attachment", file_types: ".png" }, + { id: "category", type: "category", label: "Category", limit: 1, property: "id" }, + { id: "tags", type: "tag", label: "Tags" }, + ], + }, + ], + actions: [ + { + id: "action_1", + type: "create_topic", + run_after: "step_1", + skip_redirect: true, + title: mapped("title"), + post: "body", + category: mapped("category"), + tags: mapped("tags"), + }, + ], + }.as_json, + skip_jobs: true, + ) + end + + # Submits the wizard as the steps controller does, which queues the topic. + def submit_wizard + wizard = CustomWizard::Builder.new("revise_wizard", user).build + wizard.create_updater( + "step_1", + title: "Notice about the road closure", + body: "The road is closed on the wrong date.", + attachment: upload.as_json(only: %i[id url original_filename extension]), + category: [category.id], + tags: [tag.name], + ).update + CustomWizard::Builder.new("revise_wizard", user).build.cleanup_on_complete! + end + + it "lets the author fix the topic in the prefilled wizard and queues it again" do + submit_wizard + reviewable = ReviewableQueuedPost.find_by(target_created_by: user) + + sign_in(moderator) + review_page.visit_reviewable(reviewable) + expect(page).to have_content("Notice about the road closure") + review_page.select_bundled_action(reviewable, "revise_and_reject_post") + expect(revise_modal).to be_open + PageObjects::Components::SelectKit.new( + ".revise-and-reject-reviewable__reason", + ).select_row_by_value("other_reason") + revise_modal.fill_reason("Wrong date") + revise_modal.fill_feedback("Please correct the date.") + revise_modal.click_primary_button + expect(review_page).to have_reviewable_with_problem_confirmed_status(reviewable) + expect(reviewable.reload).to be_rejected + + sign_in(user) + message = Topic.private_messages_for_user(user).order(:created_at).last + expect(message.first_post.raw).to include("Wrong date") + visit(message.relative_url) + find(".cooked a[href$='/w/revise-wizard']").click + + expect(page).to have_field(with: "Notice about the road closure") + expect(find(".wizard-field.body .d-editor-input").value).to eq( + "The road is closed on the wrong date.", + ) + expect(page).to have_css(".wizard-field.attachment", text: "notice.png") + expect(page).to have_css(".wizard-field.category", text: category.name) + expect(page).to have_css(".wizard-field.tags", text: tag.name) + + find(".wizard-field.body .d-editor-input").fill_in(with: "The road is closed on Monday.") + find(".wizard-btn.done").click + + expect(page).to have_no_css(".wizard-btn.done") + reviewable = ReviewableQueuedPost.find_by(target_created_by: user, status: :pending) + expect(reviewable.payload["raw"]).to eq("The road is closed on Monday.") + expect(reviewable.payload["title"]).to eq("Notice about the road closure") + expect(reviewable.category_id).to eq(category.id) + expect(reviewable.payload["tags"]).to eq([tag.name]) + submission = PluginStore.get("revise_wizard_submissions", user.id).last + expect(submission["attachment"]["id"]).to eq(upload.id) + end +end