A platform for community discussion. Free, open, simple.
FEATURE: dynamic poll support (#34368)
Samf0fc5646dc9b
diff --git a/plugins/poll/app/models/poll.rb b/plugins/poll/app/models/poll.rbindex f9ab6674fab..26c2fc7f508 100644--- a/plugins/poll/app/models/poll.rb+++ b/plugins/poll/app/models/poll.rb@@ -101,22 +101,23 @@ end# Table name: polls## id :bigint not null, primary key-# post_id :bigint-# name :string default("poll"), not null+# anonymous_voters :integer+# chart_type :integer default("bar"), not null# close_at :datetime-# type :integer default("regular"), not null-# status :integer default("open"), not null-# results :integer default("always"), not null-# visibility :integer default("secret"), not null-# min :integer+# dynamic :boolean default(FALSE), not null+# groups :string# max :integer+# min :integer+# name :string default("poll"), not null+# results :integer default("always"), not null+# status :integer default("open"), not null# step :integer-# anonymous_voters :integer+# title :string+# type :integer default("regular"), not null+# visibility :integer default("secret"), not null# created_at :datetime not null# updated_at :datetime not null-# chart_type :integer default("bar"), not null-# groups :string-# title :string+# post_id :bigint## Indexes#diff --git a/plugins/poll/app/serializers/poll_serializer.rb b/plugins/poll/app/serializers/poll_serializer.rbindex a780f1eb9c9..ca34bab12fc 100644--- a/plugins/poll/app/serializers/poll_serializer.rb+++ b/plugins/poll/app/serializers/poll_serializer.rb@@ -6,6 +6,7 @@ class PollSerializer < ApplicationSerializer:type,:status,:public,+ :dynamic,:results,:min,:max,diff --git a/plugins/poll/assets/javascripts/discourse/components/modal/poll-ui-builder.gjs b/plugins/poll/assets/javascripts/discourse/components/modal/poll-ui-builder.gjsindex 99ed47185ce..fc42cb29287 100644--- a/plugins/poll/assets/javascripts/discourse/components/modal/poll-ui-builder.gjs+++ b/plugins/poll/assets/javascripts/discourse/components/modal/poll-ui-builder.gjs@@ -50,6 +50,7 @@ export default class PollUiBuilderModal extends Component {pollResult = ALWAYS_POLL_RESULT;chartType = BAR_CHART_TYPE;publicPoll = this.siteSettings.poll_default_public;+ dynamic = false;@or("showAdvanced", "isNumber") showNumber;@or("showAdvanced", "isRankedChoice") showRankedChoice;@@ -148,6 +149,7 @@ export default class PollUiBuilderModal extends Component {"pollType","pollResult","publicPoll",+ "dynamic","pollTitle","pollMin",@@ -161,6 +163,7 @@ export default class PollUiBuilderModal extends Component {pollType,pollResult,publicPoll,+ dynamic,pollTitle,pollOptions,pollMin,@@ -205,6 +208,9 @@ export default class PollUiBuilderModal extends Component {if (chartType && pollType !== NUMBER_POLL_TYPE) {pollHeader += ` chartType=${chartType}`;}+ if (dynamic) {+ pollHeader += ` dynamic=true`;+ }if (pollGroups && pollGroups.length > 0) {pollHeader += ` groups=${pollGroups}`;}@@ -590,6 +596,14 @@ export default class PollUiBuilderModal extends Component {</div>{{#if this.showAdvanced}}+ <div class="input-group poll-dynamic">+ <DToggleSwitch+ @state={{this.dynamic}}+ @label="poll.ui_builder.poll_dynamic.label"+ class="poll-toggle-dynamic"+ {{on "click" (fn (mut this.dynamic) (not this.dynamic))}}+ />+ </div><div class="input-group poll-allowed-groups"><label class="input-group-label">{{i18n"poll.ui_builder.poll_groups.label"diff --git a/plugins/poll/assets/javascripts/discourse/components/poll-info.gjs b/plugins/poll/assets/javascripts/discourse/components/poll-info.gjsindex 0e67e116485..5ec48bd67ce 100644--- a/plugins/poll/assets/javascripts/discourse/components/poll-info.gjs+++ b/plugins/poll/assets/javascripts/discourse/components/poll-info.gjs@@ -152,7 +152,8 @@ export default class PollInfoComponent extends Component {this.resultsOnVote ||this.resultsOnClose ||this.resultsStaffOnly ||- this.publicTitle+ this.publicTitle ||+ this.args.isDynamic);}@@ -172,6 +173,12 @@ export default class PollInfoComponent extends Component {</div>{{#if this.showInstructionsSection}}<ul class="poll-info_instructions">+ {{#if (if @isDynamic true this.poll.dynamic)}}+ <li class="is-dynamic">+ {{icon "shuffle"}}+ <span>{{i18n "poll.dynamic.enabled_hint"}}</span>+ </li>+ {{/if}}{{#if this.showMultipleHelpText}}<li class="multiple-help-text">{{icon "list-ul"}}diff --git a/plugins/poll/assets/javascripts/discourse/components/poll.gjs b/plugins/poll/assets/javascripts/discourse/components/poll.gjsindex 68e1ff19845..86030fa2b64 100644--- a/plugins/poll/assets/javascripts/discourse/components/poll.gjs+++ b/plugins/poll/assets/javascripts/discourse/components/poll.gjs@@ -730,6 +730,7 @@ export default class PollComponent extends Component {@showResults={{this.showResults}}@postUserId={{this.poll.post.user_id}}@isPublic={{this.poll.public}}+ @isDynamic={{if @isDynamic true this.poll.dynamic}}@hasVoted={{this.hasVoted}}@voters={{this.voters}}/>diff --git a/plugins/poll/assets/javascripts/discourse/initializers/extend-for-poll.gjs b/plugins/poll/assets/javascripts/discourse/initializers/extend-for-poll.gjsindex 79582cbc0f1..36c72009a86 100644--- a/plugins/poll/assets/javascripts/discourse/initializers/extend-for-poll.gjs+++ b/plugins/poll/assets/javascripts/discourse/initializers/extend-for-poll.gjs@@ -33,6 +33,7 @@ function attachPolls(elem, helper) {if (poll) {const titleHTML = pollNode.querySelector(".poll-title")?.outerHTML;+ const isDynamic = pollNode.dataset.pollDynamic === "true";const newPollNode = document.createElement("div");Object.assign(newPollNode.dataset, {@@ -48,7 +49,12 @@ function attachPolls(elem, helper) {helper.renderGlimmer(newPollNode,<template>- <Poll @poll={{poll}} @post={{post}} @titleHTML={{titleHTML}} />+ <Poll+ @poll={{poll}}+ @post={{post}}+ @titleHTML={{titleHTML}}+ @isDynamic={{if isDynamic true poll.dynamic}}+ /></template>);}diff --git a/plugins/poll/assets/javascripts/lib/discourse-markdown/poll.js b/plugins/poll/assets/javascripts/lib/discourse-markdown/poll.jsindex 23af3a2fc80..cde81a39cdd 100644--- a/plugins/poll/assets/javascripts/lib/discourse-markdown/poll.js+++ b/plugins/poll/assets/javascripts/lib/discourse-markdown/poll.js@@ -16,6 +16,7 @@ const ALLOWED_ATTRIBUTES = ["status","step","type",+ "dynamic",];function addNumberListItems(state, pollTokens, min, max, step) {diff --git a/plugins/poll/assets/javascripts/lib/rich-editor-extension.js b/plugins/poll/assets/javascripts/lib/rich-editor-extension.jsindex 56deb1da060..9836ecbd0d4 100644--- a/plugins/poll/assets/javascripts/lib/rich-editor-extension.js+++ b/plugins/poll/assets/javascripts/lib/rich-editor-extension.js@@ -12,6 +12,7 @@ const extension = {groups: { default: null },max: { default: null },min: { default: null },+ dynamic: { default: null },},content: "heading? bullet_list poll_info?",group: "block",@@ -29,6 +30,7 @@ const extension = {chartType: dom.getAttribute("data-poll-chart-type"),close: dom.getAttribute("data-poll-close"),groups: dom.getAttribute("data-poll-groups"),+ dynamic: dom.getAttribute("data-poll-dynamic"),max: dom.getAttribute("data-poll-max"),min: dom.getAttribute("data-poll-min"),}),@@ -45,6 +47,7 @@ const extension = {"data-poll-chart-type": node.attrs.chartType,"data-poll-close": node.attrs.close,"data-poll-groups": node.attrs.groups,+ "data-poll-dynamic": node.attrs.dynamic,"data-poll-max": node.attrs.max,"data-poll-min": node.attrs.min,},diff --git a/plugins/poll/config/locales/client.en.yml b/plugins/poll/config/locales/client.en.ymlindex 79121dd77cb..ac25a9fc958 100644--- a/plugins/poll/config/locales/client.en.yml+++ b/plugins/poll/config/locales/client.en.yml@@ -6,6 +6,8 @@ en:poll: "Discourse Poll"js:poll:+ dynamic:+ enabled_hint: "This poll is dynamic. Options can be edited after posting."voters:one: "voter"other: "voters"@@ -161,6 +163,8 @@ en:step: Steppoll_public:label: Show who voted+ poll_dynamic:+ label: Allow editing options after posting (dynamic poll)poll_title:label: Title (optional)poll_options:diff --git a/plugins/poll/config/locales/server.en.yml b/plugins/poll/config/locales/server.en.ymlindex 5d7860f7064..47dd4c07f52 100644--- a/plugins/poll/config/locales/server.en.yml+++ b/plugins/poll/config/locales/server.en.yml@@ -44,6 +44,8 @@ en:edit_window_expired:cannot_edit_default_poll_with_votes: "You cannot change a poll after the first %{minutes} minutes."cannot_edit_named_poll_with_votes: "You cannot change the poll named <strong>${name}</strong> after the first %{minutes} minutes."+ dynamic_poll:+ enabled_hint: "This poll is dynamic. Options can be edited after posting."no_poll_with_this_name: "No poll named <strong>%{name}</strong> associated with this post."diff --git a/plugins/poll/db/migrate/20250817090000_add_dynamic_to_polls.rb b/plugins/poll/db/migrate/20250817090000_add_dynamic_to_polls.rbnew file mode 100644index 00000000000..266c5cad589--- /dev/null+++ b/plugins/poll/db/migrate/20250817090000_add_dynamic_to_polls.rb@@ -0,0 +1,11 @@+# frozen_string_literal: true++class AddDynamicToPolls < ActiveRecord::Migration[7.0]+ def up+ add_column :polls, :dynamic, :boolean, default: false, null: false+ end++ def down+ remove_column :polls, :dynamic+ end+enddiff --git a/plugins/poll/lib/poll.rb b/plugins/poll/lib/poll.rbindex de1f2b8eb9e..691d8aca5df 100644--- a/plugins/poll/lib/poll.rb+++ b/plugins/poll/lib/poll.rb@@ -402,6 +402,7 @@ class DiscoursePoll::Pollstep: poll["step"],chart_type: poll["charttype"] || "bar",groups: poll["groups"],+ dynamic: poll["dynamic"].to_s == "true",)poll["options"].each do |option|diff --git a/plugins/poll/lib/polls_updater.rb b/plugins/poll/lib/polls_updater.rbindex 1b802a70ee5..fe40c850cab 100644--- a/plugins/poll/lib/polls_updater.rb+++ b/plugins/poll/lib/polls_updater.rb@@ -9,124 +9,183 @@ module DiscoursePollhas_changed = falseedit_window = SiteSetting.poll_edit_window_mins- old_poll_names = ::Poll.where(post: post).pluck(:name)- new_poll_names = polls.keys+ deleted_poll_names, created_poll_names = compute_name_diffs(post, polls)- deleted_poll_names = old_poll_names - new_poll_names- created_poll_names = new_poll_names - old_poll_names+ delete_polls(post, deleted_poll_names) if deleted_poll_names.present?- # delete polls- if deleted_poll_names.present?- ::Poll.where(post: post, name: deleted_poll_names).destroy_all- end-- # create pollsif created_poll_names.present?+ create_polls(post, polls.slice(*created_poll_names))has_changed = true- polls.slice(*created_poll_names).values.each { |poll| Poll.create!(post.id, poll) }end- # update polls- ::Poll- .includes(:poll_votes, :poll_options)- .where(post: post)- .find_each do |old_poll|- new_poll = polls[old_poll.name]- new_poll_options = new_poll["options"]-- attributes = new_poll.slice(*POLL_ATTRIBUTES)- attributes["visibility"] = new_poll["public"] == "true" ? "everyone" : "secret"- attributes["close_at"] = begin- Time.zone.parse(new_poll["close"])- rescue StandardError- nil- end- attributes["status"] = old_poll["status"]- attributes["groups"] = new_poll["groups"]- poll = ::Poll.new(attributes)-- if is_different?(old_poll, poll, new_poll_options)- # only prevent changes when there's at least 1 vote- if old_poll.poll_votes.size > 0- # can't change after edit window (when enabled)- if edit_window > 0 && old_poll.created_at < edit_window.minutes.ago- error =- (- if poll.name == DiscoursePoll::DEFAULT_POLL_NAME- I18n.t(- "poll.edit_window_expired.cannot_edit_default_poll_with_votes",- minutes: edit_window,- )- else- I18n.t(- "poll.edit_window_expired.cannot_edit_named_poll_with_votes",- minutes: edit_window,- name: poll.name,- )- end- )-- post.errors.add(:base, error)- # rubocop:disable Lint/NonLocalExitFromIterator- return- # rubocop:enable Lint/NonLocalExitFromIterator- end- end-- # update poll- POLL_ATTRIBUTES.each do |attr|- old_poll.public_send("#{attr}=", poll.public_send(attr))- end-- old_poll.save!-- # keep track of anonymous votes- anonymous_votes =- old_poll.poll_options.map { |pv| [pv.digest, pv.anonymous_votes] }.to_h-- # destroy existing options & votes- ::PollOption.where(poll: old_poll).destroy_all-- # create new options- new_poll_options.each do |option|- ::PollOption.create!(- poll: old_poll,- digest: option["id"],- html: option["html"].strip,- anonymous_votes: anonymous_votes[option["id"]],- )- end-- has_changed = true- end- end-- if ::Poll.exists?(post: post)- post.custom_fields[HAS_POLLS] = true- else- post.custom_fields.delete(HAS_POLLS)- end+ result = update_existing_polls(post, polls, edit_window)+ return if result == :abort+ has_changed ||= result- post.save_custom_fields(true)-- if has_changed- polls = ::Poll.includes(poll_options: :poll_votes).where(post: post)- polls =- ActiveModel::ArraySerializer.new(- polls,- each_serializer: PollSerializer,- root: false,- scope: Guardian.new(nil),- ).as_json- post.publish_message!("/polls/#{post.topic_id}", post_id: post.id, polls: polls)- end+ update_post_custom_fields(post)+ publish_changes(post) if has_changedendendprivate+ def self.compute_name_diffs(post, polls)+ old_poll_names = ::Poll.where(post: post).pluck(:name)+ new_poll_names = polls.keys+ deleted_poll_names = old_poll_names - new_poll_names+ created_poll_names = new_poll_names - old_poll_names+ [deleted_poll_names, created_poll_names]+ end++ def self.delete_polls(post, names)+ ::Poll.where(post: post, name: names).destroy_all+ end++ def self.create_polls(post, polls_hash)+ polls_hash.each { |name, poll| Poll.create!(post.id, poll) }+ end++ def self.update_existing_polls(post, polls, edit_window)+ has_changed = false++ existing_polls_for(post).find_each do |old_poll|+ result = process_poll_update(post, old_poll, polls[old_poll.name], edit_window)+ return :abort if result == :abort+ has_changed ||= result+ end++ has_changed+ end++ def self.existing_polls_for(post)+ ::Poll.includes(:poll_votes, :poll_options).where(post: post)+ end++ def self.process_poll_update(post, old_poll, new_poll_hash, edit_window)+ new_options = new_poll_hash["options"]+ attributes = extract_poll_attributes(new_poll_hash, old_poll)+ dynamic_flag = compute_dynamic_flag(new_poll_hash, old_poll)+ candidate = ::Poll.new(attributes)++ return false unless is_different?(old_poll, candidate, new_options)++ if votes_present_and_restricted?(old_poll, dynamic_flag) &&+ edit_window_expired?(old_poll, edit_window)+ post.errors.add(:base, build_edit_window_error(candidate.name, edit_window))+ return :abort+ end++ apply_poll_attribute_updates(old_poll, candidate)+ update_poll_options(old_poll, new_options, dynamic_flag)++ true+ end++ def self.votes_present_and_restricted?(old_poll, dynamic_flag)+ old_poll.poll_votes.size > 0 && !dynamic_flag+ end++ def self.edit_window_expired?(old_poll, edit_window)+ edit_window > 0 && old_poll.created_at < edit_window.minutes.ago+ end++ def self.build_edit_window_error(poll_name, edit_window)+ if poll_name == DiscoursePoll::DEFAULT_POLL_NAME+ I18n.t("poll.edit_window_expired.cannot_edit_default_poll_with_votes", minutes: edit_window)+ else+ I18n.t(+ "poll.edit_window_expired.cannot_edit_named_poll_with_votes",+ minutes: edit_window,+ name: poll_name,+ )+ end+ end++ def self.apply_poll_attribute_updates(old_poll, candidate)+ POLL_ATTRIBUTES.each { |attr| old_poll.public_send("#{attr}=", candidate.public_send(attr)) }+ old_poll.save!+ end++ def self.update_poll_options(old_poll, new_options, dynamic_flag)+ if dynamic_flag+ dynamic_update_options(old_poll, new_options)+ else+ nondynamic_replace_options(old_poll, new_options)+ end+ end++ def self.extract_poll_attributes(new_poll, old_poll)+ attributes = new_poll.slice(*POLL_ATTRIBUTES)+ attributes["visibility"] = new_poll["public"] == "true" ? "everyone" : "secret"+ attributes["close_at"] = begin+ Time.zone.parse(new_poll["close"])+ rescue StandardError+ nil+ end+ attributes["status"] = old_poll["status"]+ attributes["groups"] = new_poll["groups"]+ attributes+ end++ def self.compute_dynamic_flag(new_poll, old_poll)+ dynamic_flag = new_poll["dynamic"].to_s == "true"+ was_dynamic_before = old_poll.respond_to?(:dynamic) ? old_poll.dynamic : false+ dynamic_flag = false if !was_dynamic_before && dynamic_flag && old_poll.persisted?+ dynamic_flag+ end++ def self.dynamic_update_options(old_poll, new_poll_options)+ old_options_by_digest = old_poll.poll_options.index_by(&:digest)+ new_option_digests = new_poll_options.map { |o| o["id"] }.to_set++ to_delete = old_options_by_digest.keys - new_option_digests.to_a+ ::PollOption.where(poll: old_poll, digest: to_delete).destroy_all if to_delete.present?++ new_poll_options.each do |option|+ next if old_options_by_digest.key?(option["id"])++ ::PollOption.create!(poll: old_poll, digest: option["id"], html: option["html"].strip)+ end+ end++ def self.nondynamic_replace_options(old_poll, new_poll_options)+ anonymous_votes = old_poll.poll_options.map { |pv| [pv.digest, pv.anonymous_votes] }.to_h++ ::PollOption.where(poll: old_poll).destroy_all++ new_poll_options.each do |option|+ ::PollOption.create!(+ poll: old_poll,+ digest: option["id"],+ html: option["html"].strip,+ anonymous_votes: anonymous_votes[option["id"]],+ )+ end+ end++ def self.update_post_custom_fields(post)+ if ::Poll.exists?(post: post)+ post.custom_fields[HAS_POLLS] = true+ else+ post.custom_fields.delete(HAS_POLLS)+ end++ post.save_custom_fields(true)+ end++ def self.publish_changes(post)+ polls = ::Poll.includes(poll_options: :poll_votes).where(post: post)+ polls =+ ActiveModel::ArraySerializer.new(+ polls,+ each_serializer: PollSerializer,+ root: false,+ scope: Guardian.new(nil),+ ).as_json+ post.publish_message!("/polls/#{post.topic_id}", post_id: post.id, polls: polls)+ end+def self.is_different?(old_poll, new_poll, new_options)- # an attribute was changed?POLL_ATTRIBUTES.each do |attr|return true if old_poll.public_send(attr) != new_poll.public_send(attr)enddiff --git a/plugins/poll/lib/post_extension.rb b/plugins/poll/lib/post_extension.rbindex 6f7fc8ebc93..8ff5745052c 100644--- a/plugins/poll/lib/post_extension.rb+++ b/plugins/poll/lib/post_extension.rb@@ -16,7 +16,8 @@ module DiscoursePollpost = self::Poll.transaction do- polls.values.each { |poll| DiscoursePoll::Poll.create!(post.id, poll) }+ polls.each { |name, poll| DiscoursePoll::Poll.create!(post.id, poll) }+post.custom_fields[DiscoursePoll::HAS_POLLS] = truepost.save_custom_fields(true)enddiff --git a/plugins/poll/spec/lib/polls_updater_spec.rb b/plugins/poll/spec/lib/polls_updater_spec.rbindex be71634c4f7..c5f0bd01d6f 100644--- a/plugins/poll/spec/lib/polls_updater_spec.rb+++ b/plugins/poll/spec/lib/polls_updater_spec.rb@@ -103,6 +103,42 @@ RSpec.describe DiscoursePoll::PollsUpdater doenddescribe "updates polls" do+ it "allows updating options after window when dynamic" do+ post = Fabricate(:post, raw: <<~RAW)+ [poll dynamic=true]+ * A+ * B+ [/poll]+ RAW++ polls = DiscoursePoll::PollsValidator.new(post).validate_polls+ DiscoursePoll::PollsUpdater.update(post, polls)++ poll_record = Poll.find_by(post: post)+ # dynamic is not persisted in DB; behavior is allowed via flag in updater++ # cast a vote+ user = Fabricate(:user)+ DiscoursePoll::Poll.vote(user, post.id, "poll", [polls["poll"]["options"][0]["id"]])++ edit_window = SiteSetting.poll_edit_window_mins+ freeze_time (edit_window + 10).minutes.from_now++ new_post = Fabricate(:post, raw: <<~RAW)+ [poll dynamic=true]+ * A+ * C+ [/poll]+ RAW++ new_polls = DiscoursePoll::PollsValidator.new(new_post).validate_polls+ DiscoursePoll::PollsUpdater.update(post, new_polls)++ poll_record.reload+ digests = poll_record.poll_options.pluck(:digest)+ expect(digests.size).to eq(2)+ expect(poll_record.poll_votes.count).to eq(1)+ enddescribe "when there are no votes" doit "at any time" dopost # create the post@@ -184,6 +220,45 @@ RSpec.describe DiscoursePoll::PollsUpdater do)endend++ it "does not allow converting an existing poll to dynamic after creation" do+ # Create a regular poll+ post = Fabricate(:post, raw: <<~RAW)+ [poll]+ * A+ * B+ [/poll]+ RAW++ polls = DiscoursePoll::PollsValidator.new(post).validate_polls+ DiscoursePoll::PollsUpdater.update(post, polls)++ # cast a vote so updates would normally be blocked outside window+ voter = Fabricate(:user)+ DiscoursePoll::Poll.vote(voter, post.id, "poll", [polls["poll"]["options"][0]["id"]])++ # Advance time and attempt to convert to dynamic while changing options+ edit_window = SiteSetting.poll_edit_window_mins+ freeze_time (edit_window + 10).minutes.from_now++ new_post = Fabricate(:post, raw: <<~RAW)+ [poll dynamic=true]+ * A+ * C+ [/poll]+ RAW++ new_polls = DiscoursePoll::PollsValidator.new(new_post).validate_polls+ DiscoursePoll::PollsUpdater.update(post, new_polls)++ poll_record = Poll.find_by(post: post)+ digests = poll_record.poll_options.pluck(:digest)+ # Conversion should be ignored; options should remain unchanged+ expect(digests.size).to eq(2)+ expect(digests).to match_array(polls["poll"]["options"].map { |o| o["id"] })+ # Vote should still be present+ expect(poll_record.poll_votes.count).to eq(1)+ endendenddiff --git a/plugins/poll/spec/lib/pretty_text_spec.rb b/plugins/poll/spec/lib/pretty_text_spec.rbindex 57fcf429840..1661da50742 100644--- a/plugins/poll/spec/lib/pretty_text_spec.rb+++ b/plugins/poll/spec/lib/pretty_text_spec.rb@@ -19,6 +19,17 @@ RSpec.describe PrettyText do)end+ it "supports dynamic attribute passthrough" do+ cooked = PrettyText.cook <<~MD+ [poll dynamic=true]+ * A+ * B+ [/poll]+ MD++ expect(cooked).to include('data-poll-dynamic="true"')+ end+it "can dynamically generate a poll" docooked = PrettyText.cook <<~MD[poll type=number min=1 max=20 step=1]diff --git a/plugins/poll/spec/system/dynamic_polls_spec.rb b/plugins/poll/spec/system/dynamic_polls_spec.rbnew file mode 100644index 00000000000..30ee1c47db0--- /dev/null+++ b/plugins/poll/spec/system/dynamic_polls_spec.rb@@ -0,0 +1,62 @@+# frozen_string_literal: true++describe "Dynamic polls", type: :system do+ fab!(:admin)+ fab!(:topic)++ let(:topic_page) { PageObjects::Pages::Topic.new }+ let(:poll_page) { PageObjects::Pages::Poll.new(topic_page: topic_page) }++ before do+ sign_in admin+ SiteSetting.poll_create_allowed_groups = Group::AUTO_GROUPS[:admins].to_s+ end++ def cook_poll(raw)+ PostCreator.create!(admin, topic_id: topic.id, raw: raw)+ end++ it "allows editing poll options after window while preserving votes on existing options" do+ post = cook_poll(<<~MD)+ [poll dynamic=true]+ * A+ * B+ [/poll]+ MD++ topic_page.visit_topic(topic)+ expect(poll_page).to have_poll_for_post(post)++ poll_page.vote_for_option(post, "A")++ expect(poll_page).to have_vote_count(post, 1)++ # Advance time beyond edit window+ freeze_time (SiteSetting.poll_edit_window_mins + 1).minutes.from_now++ # Edit the poll: add C, remove B, keep A (vote should stay)+ new_raw = <<~MD+ [poll dynamic=true]+ * A+ * C+ [/poll]+ MD++ PostRevisor.new(post, post.topic).revise!(admin, { raw: new_raw }, revised_at: Time.zone.now)++ visit(current_url)++ # Ensure A still exists, B removed, C added+ expect(poll_page).to have_poll_for_post(post)+ expect(poll_page).to have_option(post, "A")+ expect(poll_page).to have_option(post, "C")+ expect(poll_page).to have_no_option(post, "B")++ expect(poll_page).to have_vote_count(post, 1)++ expect(poll_page.find_poll_for_post(post)).to have_css(+ ".poll-info_instructions li.is-dynamic",+ text: I18n.t("js.poll.dynamic.enabled_hint"),+ )+ end+enddiff --git a/plugins/poll/spec/system/page_objects/pages/poll.rb b/plugins/poll/spec/system/page_objects/pages/poll.rbnew file mode 100644index 00000000000..29a17a7ed7f--- /dev/null+++ b/plugins/poll/spec/system/page_objects/pages/poll.rb@@ -0,0 +1,39 @@+# frozen_string_literal: true++module PageObjects+ module Pages+ class Poll < PageObjects::Pages::Base+ def initialize(topic_page: nil)+ @topic_page = topic_page || PageObjects::Pages::Topic.new+ end++ def has_poll_for_post?(post)+ @topic_page.post_by_number(post.post_number).has_css?(".poll")+ end++ def find_poll_for_post(post)+ @topic_page.post_by_number(post.post_number).find(".poll")+ end++ def has_option?(post, option)+ post_element = @topic_page.post_by_number(post.post_number)+ post_element.has_css?(".poll .option-text", text: option)+ end++ def has_no_option?(post, option)+ post_element = @topic_page.post_by_number(post.post_number)+ post_element.has_no_css?(".poll .option-text", text: option)+ end++ def vote_for_option(post, option)+ post_element = @topic_page.post_by_number(post.post_number)+ post_element.find("li[data-poll-option-id] button", text: option).click+ end++ def has_vote_count?(post, count)+ post_element = @topic_page.post_by_number(post.post_number)+ post_element.has_css?(".poll .info-number", text: count.to_s)+ end+ end+ end+enddiff --git a/plugins/poll/test/javascripts/component/poll-ui-builder-test.gjs b/plugins/poll/test/javascripts/component/poll-ui-builder-test.gjsindex 63a602984fb..5faa18d9767 100644--- a/plugins/poll/test/javascripts/component/poll-ui-builder-test.gjs+++ b/plugins/poll/test/javascripts/component/poll-ui-builder-test.gjs@@ -150,6 +150,15 @@ module("Poll | Component | poll-ui-builder", function (hooks) {"can be set to private");+ await click(".poll-toggle-dynamic");+ await click(".insert-poll");+ assert.strictEqual(+ results[results.length - 1],+ "[poll type=regular results=always public=false chartType=bar dynamic=true]\n* a\n* b\n[/poll]\n",+ "includes dynamic=true when enabled"+ );++ await click(".poll-toggle-dynamic");const groupChooser = selectKit(".group-chooser");await groupChooser.expand();await groupChooser.selectRowByName("custom_group");