Skip to content

A platform for community discussion. Free, open, simple.

DEV: Allow multiple solutions in solved plugin (#39806)

Chris Alberti9706fb8cfbb4
diff --git a/app/assets/stylesheets/common/components/_index.scss b/app/assets/stylesheets/common/components/_index.scss
index 3bf8d4cdf2b..4949688f932 100644
--- a/app/assets/stylesheets/common/components/_index.scss
+++ b/app/assets/stylesheets/common/components/_index.scss
@@ -84,3 +84,4 @@
@import "welcome-banner";
@import "d-multi-select";
@import "d-otp";
+@import "d-post-accordion";
diff --git a/app/assets/stylesheets/common/components/d-post-accordion.scss b/app/assets/stylesheets/common/components/d-post-accordion.scss
new file mode 100644
index 00000000000..4d31712e8c0
--- /dev/null
+++ b/app/assets/stylesheets/common/components/d-post-accordion.scss
@@ -0,0 +1,170 @@
+.d-post-accordion {
+ --d-post-accordion-font-size: var(--font-down-1-rem);
+ --d-post-accordion-radius: var(--d-border-radius-large);
+ --d-post-accordion-border-color: var(--primary-low);
+ --d-post-accordion-background: var(--secondary);
+ --d-post-accordion-header-color: var(--primary);
+ --d-post-accordion-header-background: var(--secondary);
+ --d-post-accordion-header-border-color: var(--d-post-accordion-border-color);
+ --d-post-accordion-item-header-color: var(--primary-low-mid);
+ --d-post-accordion-item-header-background: var(--primary-very-low);
+ --d-post-accordion-item-link-color: var(--primary-low-mid);
+ --d-post-accordion-item-username-color: var(--primary-medium);
+ --d-post-accordion-item-control-color: var(--primary-medium);
+
+ * {
+ font-size: var(--d-post-accordion-font-size);
+ }
+
+ &__layout {
+ border-radius: var(--d-post-accordion-radius);
+ }
+
+ &__header {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ color: var(--d-post-accordion-header-color);
+ background-color: var(--d-post-accordion-header-background);
+ padding: var(--space-2) var(--space-3);
+ border: 1px solid var(--d-post-accordion-header-border-color);
+ border-bottom: 0;
+ border-radius: var(--d-post-accordion-radius) var(--d-post-accordion-radius)
+ 0 0;
+ overflow: hidden;
+ }
+
+ &__items {
+ display: flex;
+ flex-direction: column;
+ border: 1px solid var(--d-post-accordion-border-color);
+ border-top: 0;
+ border-radius: 0 0 var(--d-post-accordion-radius)
+ var(--d-post-accordion-radius);
+ overflow: hidden;
+ }
+
+ &__item {
+ border-top: 1px solid var(--d-post-accordion-border-color);
+ }
+}
+
+.d-post-accordion-item {
+ background: var(--d-post-accordion-background);
+ border-top: 1px solid var(--d-post-accordion-border-color);
+
+ &__header {
+ display: flex;
+ align-items: center;
+ gap: var(--space-1);
+ padding: var(--space-2) var(--space-3);
+ font-size: var(--font-down-1);
+ color: var(--d-post-accordion-item-header-color);
+ background: var(--d-post-accordion-item-header-background);
+ }
+
+ &__body {
+ border-top: 1px solid var(--d-post-accordion-border-color);
+ }
+
+ &__metadata {
+ display: flex;
+ align-items: center;
+ gap: var(--space-1);
+
+ a {
+ &,
+ &:hover,
+ &:visited {
+ color: var(--d-post-accordion-item-link-color);
+ }
+ }
+
+ .user-link {
+ display: flex;
+ align-items: center;
+ gap: var(--space-1);
+ color: var(--d-post-accordion-item-username-color);
+ font-weight: bold;
+
+ &,
+ &:hover,
+ &:visited {
+ color: var(--d-post-accordion-item-username-color);
+ }
+ }
+ }
+
+ &__controls {
+ margin-left: auto;
+
+ .btn {
+ padding: 0;
+
+ .d-icon {
+ color: var(--d-post-accordion-item-control-color);
+ background: transparent;
+ font-size: var(--font-down-1);
+ }
+
+ &:hover,
+ &:visited {
+ .discourse-no-touch &,
+ .discourse-touch & {
+ color: var(--d-post-accordion-item-control-color);
+ background: transparent;
+
+ .d-icon {
+ color: var(--d-post-accordion-item-control-color);
+ background: transparent;
+ }
+ }
+ }
+ }
+ }
+
+ &__content {
+ position: relative;
+ border-left: 0;
+ background: var(--d-post-accordion-background);
+ padding: var(--space-2) var(--space-3) 0 var(--space-3);
+ margin: 0;
+ max-height: calc(
+ var(--max-lines-displayed, 6) * var(--cooked-line-height) * 1em
+ ); // max-lines-displayed set in post-accordion-item.gjs
+ overflow: hidden;
+
+ .cooked {
+ padding: 0 !important;
+ }
+ }
+
+ &[data-overflowing="true"] &__content::after {
+ content: "";
+ position: absolute;
+ bottom: 0;
+ left: 0;
+ right: 0;
+ height: 100%;
+ background: linear-gradient(
+ transparent,
+ 75%,
+ var(--d-post-accordion-background)
+ );
+ pointer-events: none;
+ z-index: 1;
+ }
+
+ &__read-more {
+ padding: var(--space-3);
+ }
+
+ &:not([data-expanded]) > &__body {
+ display: none;
+ }
+
+ &:last-of-type {
+ border-radius: 0 0 var(--d-post-accordion-radius)
+ var(--d-post-accordion-radius);
+ }
+}
diff --git a/app/serializers/post_accordion_item_serializer.rb b/app/serializers/post_accordion_item_serializer.rb
new file mode 100644
index 00000000000..739f2c5ec3d
--- /dev/null
+++ b/app/serializers/post_accordion_item_serializer.rb
@@ -0,0 +1,9 @@
+# frozen_string_literal: true
+
+class PostAccordionItemSerializer < BasicPostSerializer
+ attributes :post_number, :topic_id, :url
+
+ def url
+ object&.url
+ end
+end
diff --git a/db/structure.sql b/db/structure.sql
index ba546d34ca5..a3870dd245f 100644
--- a/db/structure.sql
+++ b/db/structure.sql
@@ -4086,9 +4086,9 @@ ALTER SEQUENCE public.discourse_solved_shared_issues_id_seq OWNED BY public.disc
CREATE TABLE public.discourse_solved_solved_topics (
id bigint NOT NULL,
- topic_id integer NOT NULL,
- answer_post_id integer NOT NULL,
- accepter_user_id integer NOT NULL,
+ topic_id bigint NOT NULL,
+ answer_post_id integer,
+ accepter_user_id integer,
topic_timer_id integer,
created_at timestamp(6) without time zone NOT NULL,
updated_at timestamp(6) without time zone NOT NULL
@@ -4114,6 +4114,39 @@ CREATE SEQUENCE public.discourse_solved_solved_topics_id_seq
ALTER SEQUENCE public.discourse_solved_solved_topics_id_seq OWNED BY public.discourse_solved_solved_topics.id;
+--
+-- Name: discourse_solved_topic_answers; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.discourse_solved_topic_answers (
+ id bigint NOT NULL,
+ solved_topic_id bigint NOT NULL,
+ answer_post_id bigint NOT NULL,
+ accepter_user_id bigint NOT NULL,
+ created_at timestamp(6) without time zone NOT NULL,
+ updated_at timestamp(6) without time zone NOT NULL
+);
+
+
+--
+-- Name: discourse_solved_topic_answers_id_seq; Type: SEQUENCE; Schema: public; Owner: -
+--
+
+CREATE SEQUENCE public.discourse_solved_topic_answers_id_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+
+--
+-- Name: discourse_solved_topic_answers_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
+--
+
+ALTER SEQUENCE public.discourse_solved_topic_answers_id_seq OWNED BY public.discourse_solved_topic_answers.id;
+
+
--
-- Name: discourse_subscriptions_customers; Type: TABLE; Schema: public; Owner: -
--
@@ -12439,6 +12472,13 @@ ALTER TABLE ONLY public.discourse_solved_shared_issues ALTER COLUMN id SET DEFAU
ALTER TABLE ONLY public.discourse_solved_solved_topics ALTER COLUMN id SET DEFAULT nextval('public.discourse_solved_solved_topics_id_seq'::regclass);
+--
+-- Name: discourse_solved_topic_answers id; Type: DEFAULT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_solved_topic_answers ALTER COLUMN id SET DEFAULT nextval('public.discourse_solved_topic_answers_id_seq'::regclass);
+
+
--
-- Name: discourse_subscriptions_customers id; Type: DEFAULT; Schema: public; Owner: -
--
@@ -14669,6 +14709,14 @@ ALTER TABLE ONLY public.discourse_solved_solved_topics
ADD CONSTRAINT discourse_solved_solved_topics_pkey PRIMARY KEY (id);
+--
+-- Name: discourse_solved_topic_answers discourse_solved_topic_answers_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_solved_topic_answers
+ ADD CONSTRAINT discourse_solved_topic_answers_pkey PRIMARY KEY (id);
+
+
--
-- Name: discourse_subscriptions_customers discourse_subscriptions_customers_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
@@ -18252,6 +18300,20 @@ CREATE UNIQUE INDEX index_discourse_solved_solved_topics_on_answer_post_id ON pu
CREATE UNIQUE INDEX index_discourse_solved_solved_topics_on_topic_id ON public.discourse_solved_solved_topics USING btree (topic_id);
+--
+-- Name: index_discourse_solved_topic_answers_on_answer_post_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE UNIQUE INDEX index_discourse_solved_topic_answers_on_answer_post_id ON public.discourse_solved_topic_answers USING btree (answer_post_id);
+
+
+--
+-- Name: index_discourse_solved_topic_answers_on_solved_topic_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX index_discourse_solved_topic_answers_on_solved_topic_id ON public.discourse_solved_topic_answers USING btree (solved_topic_id);
+
+
--
-- Name: index_discourse_subscriptions_customers_on_customer_id; Type: INDEX; Schema: public; Owner: -
--
@@ -21767,6 +21829,8 @@ INSERT INTO "schema_migrations" (version) VALUES
('20260421061908'),
('20260420014648'),
('20260415082426'),
+('20260408214007'),
+('20260408165014'),
('20260407093145'),
('20260402141924'),
('20260402141912'),
diff --git a/frontend/discourse/app/ui-kit/d-post-accordion-item.gjs b/frontend/discourse/app/ui-kit/d-post-accordion-item.gjs
new file mode 100644
index 00000000000..9ac84834314
--- /dev/null
+++ b/frontend/discourse/app/ui-kit/d-post-accordion-item.gjs
@@ -0,0 +1,166 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { trustHTML } from "@ember/template";
+import PostCookedHtml from "discourse/components/post/cooked-html";
+import userPrioritizedName from "discourse/helpers/user-prioritized-name";
+import DiscourseURL from "discourse/lib/url";
+import DButton from "discourse/ui-kit/d-button";
+import DRelativeDate from "discourse/ui-kit/d-relative-date";
+import DUserLink from "discourse/ui-kit/d-user-link";
+import dBoundAvatarTemplate from "discourse/ui-kit/helpers/d-bound-avatar-template";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+import dOnResize from "discourse/ui-kit/modifiers/d-on-resize";
+import { i18n } from "discourse-i18n";
+
+export default class DPostAccordionItem extends Component {
+ @tracked measured = false;
+ @tracked isOverflowing = false;
+
+ get post() {
+ return this.args.post;
+ }
+
+ get quoteId() {
+ return `post-accordion-item-${this.post.topic_id}-${this.post.post_number}`;
+ }
+
+ get hasContent() {
+ return !!this.post?.cooked;
+ }
+
+ get userDisplayName() {
+ return userPrioritizedName({
+ username: this.post.username,
+ name: this.post.name,
+ });
+ }
+
+ get maxHeightStyle() {
+ if (this.args.linesDisplayed) {
+ return trustHTML(`--max-lines-displayed: ${this.args.linesDisplayed}`);
+ }
+ }
+
+ get overflowingAttr() {
+ return this.measured ? String(this.isOverflowing) : "true";
+ }
+
+ @action
+ onClickHeader(event) {
+ if (event.target.closest("a")) {
+ return;
+ }
+
+ if (this.hasContent) {
+ this.args.onToggleExpanded();
+ } else {
+ DiscourseURL.routeTo(this.post.url);
+ }
+ }
+
+ @action
+ checkOverflow(entries) {
+ if (!this.args.isExpanded) {
+ this.isOverflowing = false;
+ this.measured = true;
+ }
+
+ const blockquote = entries?.[0]?.target;
+ if (!blockquote) {
+ return;
+ }
+
+ this.isOverflowing = blockquote.scrollHeight > blockquote.clientHeight + 1;
+ this.measured = true;
+ }
+
+ <template>
+ {{#if this.post}}
+ <div
+ class={{dConcatClass
+ "quote d-post-accordion-item"
+ (if this.hasContent "d-post-accordion-item--has-content")
+ }}
+ style={{this.maxHeightStyle}}
+ data-expanded={{@isExpanded}}
+ data-overflowing={{this.overflowingAttr}}
+ data-username={{this.post.username}}
+ data-post={{this.post.post_number}}
+ data-topic={{this.post.topic_id}}
+ >
+ {{! eslint-disable ember/template-no-invalid-interactive }}
+ <div
+ class="d-post-accordion-item__header"
+ {{on "click" this.onClickHeader}}
+ >
+ <div class="d-post-accordion-item__metadata">
+ {{#if @hasItemMetadataBlock}}
+ {{yield this.post to="itemMetadata"}}
+ {{else}}
+ <DUserLink @username={{this.post.username}} class="user-link">
+ {{dBoundAvatarTemplate this.post.avatar_template "tiny"}}
+ <span>{{this.userDisplayName}}</span>
+ </DUserLink>
+ <span class="dot-separator"></span>
+ <a
+ href={{this.post.url}}
+ class="date-link"
+ title={{i18n "post.sr_date"}}
+ >
+ <DRelativeDate @date={{this.post.created_at}} />
+ </a>
+ {{/if}}
+ </div>
+ <div class="d-post-accordion-item__controls">
+ {{#if this.hasContent}}
+ <DButton
+ class="btn-flat d-post-accordion-item__toggle"
+ @action={{@onToggleExpanded}}
+ @ariaExpanded={{@isExpanded}}
+ @ariaLabel={{if @isExpanded "post.collapse" "expand"}}
+ @title={{if @isExpanded "post.collapse" "expand"}}
+ @icon={{if @isExpanded "chevron-up" "chevron-down"}}
+ />
+ {{else}}
+ <DButton
+ class="btn-flat d-post-accordion-item__jump"
+ @href={{this.post.url}}
+ @ariaLabel="post.follow_quote"
+ @title="post.follow_quote"
+ @icon="arrow-down"
+ />
+ {{/if}}
+ </div>
+ </div>
+
+ {{#if this.hasContent}}
+ <div class="d-post-accordion-item__body">
+ <blockquote
+ id={{this.quoteId}}
+ class="d-post-accordion-item__content"
+ {{dOnResize this.checkOverflow}}
+ >
+ {{#if @hasBeforeItemContentBlock}}
+ {{yield this.post to="beforeItemContent"}}
+ {{/if}}
+
+ <PostCookedHtml
+ @post={{this.post}}
+ @decoratorState={{@decoratorState}}
+ />
+
+ </blockquote>
+
+ <div class="d-post-accordion-item__read-more">
+ <a href={{this.post.url}} class="read-more-link">
+ {{i18n "read_more"}}
+ </a>
+ </div>
+ </div>
+ {{/if}}
+ </div>
+ {{/if}}
+ </template>
+}
diff --git a/frontend/discourse/app/ui-kit/d-post-accordion.gjs b/frontend/discourse/app/ui-kit/d-post-accordion.gjs
new file mode 100644
index 00000000000..7427856beb4
--- /dev/null
+++ b/frontend/discourse/app/ui-kit/d-post-accordion.gjs
@@ -0,0 +1,108 @@
+import Component from "@glimmer/component";
+import { fn } from "@ember/helper";
+import { action } from "@ember/object";
+import { trackedSet } from "@ember/reactive/collections";
+import didUpdate from "@ember/render-modifiers/modifiers/did-update";
+import DPostAccordionItem from "./d-post-accordion-item";
+
+export default class DPostAccordion extends Component {
+ expandedIds = trackedSet();
+
+ constructor() {
+ super(...arguments);
+
+ this.resetExpandedIds();
+ }
+
+ @action
+ resetExpandedIds() {
+ const defaultExpanded = this.args.defaultExpanded;
+
+ this.expandedIds.clear();
+
+ switch (defaultExpanded) {
+ case "all":
+ this.posts.forEach((post) => this.expandedIds.add(post.id));
+ break;
+ case "none":
+ break;
+ case "first":
+ case "":
+ default:
+ const firstPostId = this.args.posts?.[0]?.id;
+ if (firstPostId) {
+ this.expandedIds.add(firstPostId);
+ }
+ }
+ }
+
+ get posts() {
+ return this.args.posts ?? [];
+ }
+
+ get allExpanded() {
+ return this.posts.every((post) => this.expandedIds.has(post.id));
+ }
+
+ @action
+ toggleAllExpanded() {
+ if (this.allExpanded) {
+ this.resetExpandedIds();
+ } else {
+ this.posts.forEach((post) => this.expandedIds.add(post.id));
+ }
+ }
+
+ @action
+ toggleItemExpanded(postId) {
+ this.expandedIds.has(postId)
+ ? this.expandedIds.delete(postId)
+ : this.expandedIds.add(postId);
+ }
+
+ @action
+ itemIsExpanded(postId) {
+ return this.expandedIds.has(postId);
+ }
+
+ <template>
+ {{#if this.posts.length}}
+ <aside
+ class="d-post-accordion"
+ ...attributes
+ {{didUpdate this.resetExpandedIds this.posts}}
+ >
+ <div class="d-post-accordion__layout">
+ <div class="d-post-accordion__header">
+ {{#if (has-block "header")}}
+ {{yield this.posts to="header"}}
+ {{/if}}
+ </div>
+
+ <div class="d-post-accordion__items">
+ {{#each this.posts as |post|}}
+ <DPostAccordionItem
+ @decoratorState={{@decoratorState}}
+ @post={{post}}
+ @isExpanded={{this.itemIsExpanded post.id}}
+ @onToggleExpanded={{fn this.toggleItemExpanded post.id}}
+ @linesDisplayed={{@linesDisplayed}}
+ @hasItemMetadataBlock={{has-block "itemMetadata"}}
+ @hasBeforeItemContentBlock={{has-block "beforeItemContent"}}
+ >
+
+ <:itemMetadata>
+ {{yield post to="itemMetadata"}}
+ </:itemMetadata>
+
+ <:beforeItemContent>
+ {{yield post to="beforeItemContent"}}
+ </:beforeItemContent>
+ </DPostAccordionItem>
+ {{/each}}
+ </div>
+ </div>
+ </aside>
+ {{/if}}
+ </template>
+}
diff --git a/frontend/discourse/tests/integration/components/post-accordion-test.gjs b/frontend/discourse/tests/integration/components/post-accordion-test.gjs
new file mode 100644
index 00000000000..abc47c445dd
--- /dev/null
+++ b/frontend/discourse/tests/integration/components/post-accordion-test.gjs
@@ -0,0 +1,212 @@
+import { click, render, waitFor } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import DPostAccordion from "discourse/ui-kit/d-post-accordion";
+
+module("Integration | Component | DPostAccordion", function (hooks) {
+ setupRenderingTest(hooks);
+
+ const posts = [
+ {
+ id: 1,
+ topic_id: 123,
+ post_number: 2,
+ username: "user1",
+ name: "User One",
+ avatar_template: "/images/avatar.png",
+ cooked: "<p>First excerpt content</p>",
+ url: "/t/test-topic/123/2",
+ created_at: "2024-01-01T00:00:00Z",
+ },
+ {
+ id: 2,
+ topic_id: 123,
+ post_number: 3,
+ username: "user2",
+ name: "User Two",
+ avatar_template: "/images/avatar.png",
+ cooked: "<p>Second excerpt content</p>",
+ url: "/t/test-topic/123/3",
+ created_at: "2024-01-02T00:00:00Z",
+ },
+ ];
+
+ test("renders posts with default metadata section", async function (assert) {
+ await render(<template><DPostAccordion @posts={{posts}} /></template>);
+
+ assert.dom(".d-post-accordion").exists();
+ assert.dom(".d-post-accordion-item").exists({ count: 2 });
+ assert.dom(".d-post-accordion-item__header").exists({ count: 2 });
+ assert.dom(".d-post-accordion-item__body").exists({ count: 2 });
+ assert.dom(".d-post-accordion-item__content").exists({ count: 2 });
+ assert.dom(".d-post-accordion-item__read-more").exists({ count: 2 });
+
+ assert
+ .dom(":nth-child(1 of .d-post-accordion-item) .read-more-link")
+ .hasAttribute("href", posts[0].url);
+ assert
+ .dom(":nth-child(1 of .d-post-accordion-item) .date-link")
+ .hasAttribute("href", posts[0].url);
+ assert
+ .dom(":nth-child(2 of .d-post-accordion-item) .read-more-link")
+ .hasAttribute("href", posts[1].url);
+ assert
+ .dom(":nth-child(2 of .d-post-accordion-item) .date-link")
+ .hasAttribute("href", posts[1].url);
+ });
+
+ test("yields custom header", async function (assert) {
+ await render(
+ <template>
+ <DPostAccordion @posts={{posts}}>
+ <:header>
+ <div class="custom-header">Header content</div>
+ </:header>
+ </DPostAccordion>
+ </template>
+ );
+
+ assert.dom(".d-post-accordion__header .custom-header").exists();
+ assert
+ .dom(".d-post-accordion__header .custom-header")
+ .hasText("Header content");
+ });
+
+ test("yields custom itemMetadata, replacing the default", async function (assert) {
+ await render(
+ <template>
+ <DPostAccordion @posts={{posts}}>
+ <:itemMetadata>
+ <div class="custom-metadata">Metadata content</div>
+ </:itemMetadata>
+ </DPostAccordion>
+ </template>
+ );
+
+ assert.dom(".d-post-accordion-item__metadata").exists({ count: 2 });
+ assert.dom(".d-post-accordion-item__metadata .custom-metadata").exists();
+ assert
+ .dom(".d-post-accordion-item__metadata .custom-metadata")
+ .hasText("Metadata content");
+ assert.dom(".d-post-accordion-item__metadata .user-link").doesNotExist();
+ assert.dom(".d-post-accordion-item__metadata .date-link").doesNotExist();
+ });
+
+ test("yields custom beforeItemContent", async function (assert) {
+ await render(
+ <template>
+ <DPostAccordion @posts={{posts}}>
+ <:beforeItemContent>
+ <div class="custom-before-content">Before content</div>
+ </:beforeItemContent>
+ </DPostAccordion>
+ </template>
+ );
+
+ assert
+ .dom(".d-post-accordion-item__content .custom-before-content")
+ .exists({ count: 2 });
+ });
+
+ test("handles empty posts array", async function (assert) {
+ const emptyPosts = [];
+
+ await render(<template><DPostAccordion @posts={{emptyPosts}} /></template>);
+
+ assert.dom(".d-post-accordion").doesNotExist();
+ });
+
+ test("renders item without content when cooked is empty", async function (assert) {
+ const postsWithoutContent = [
+ {
+ id: 3,
+ topic_id: 123,
+ post_number: 4,
+ username: "user3",
+ name: "User Three",
+ avatar_template: "/images/avatar.png",
+ cooked: null,
+ url: "/t/test-topic/123/4",
+ created_at: "2024-01-03T00:00:00Z",
+ },
+ ];
+
+ await render(
+ <template><DPostAccordion @posts={{postsWithoutContent}} /></template>
+ );
+
+ assert.dom(".d-post-accordion-item--has-content").doesNotExist();
+ assert.dom(".d-post-accordion-item__body").doesNotExist();
+ assert.dom(".d-post-accordion-item__jump").exists();
+ assert
+ .dom(".d-post-accordion-item__jump")
+ .hasAttribute("href", postsWithoutContent[0].url);
+ });
+
+ test("first post is expanded by default, others are collapsed", async function (assert) {
+ await render(<template><DPostAccordion @posts={{posts}} /></template>);
+
+ assert
+ .dom(":nth-child(1 of .d-post-accordion-item)")
+ .hasAttribute("data-expanded");
+
+ assert
+ .dom(":nth-child(2 of .d-post-accordion-item)")
+ .doesNotHaveAttribute("data-expanded");
+ });
+
+ test("toggle button expands collapsed post and collapses expanded post", async function (assert) {
+ await render(<template><DPostAccordion @posts={{posts}} /></template>);
+
+ const firstItem = ":nth-child(1 of .d-post-accordion-item)";
+ const secondItem = ":nth-child(2 of .d-post-accordion-item)";
+
+ await click(`${secondItem} .d-post-accordion-item__toggle`);
+ assert.dom(secondItem).hasAttribute("data-expanded");
+ assert.dom(firstItem).hasAttribute("data-expanded");
+
+ await click(`${firstItem} .d-post-accordion-item__toggle`);
+ assert.dom(firstItem).doesNotHaveAttribute("data-expanded");
+ assert.dom(secondItem).hasAttribute("data-expanded");
+ });
+
+ const fiveLinePost = [
+ {
+ id: 1,
+ topic_id: 123,
+ post_number: 2,
+ username: "user1",
+ name: "User One",
+ avatar_template: "/images/avatar.png",
+ cooked: "<p>Line 1<br/>Line 2<br/>Line 3<br/>Line 4<br/>Line 5</p>",
+ url: "/t/test-topic/123/2",
+ created_at: "2024-01-01T00:00:00Z",
+ },
+ ];
+
+ test("post is truncated if longer than linesDisplayed", async function (assert) {
+ await render(
+ <template>
+ <DPostAccordion @posts={{fiveLinePost}} @linesDisplayed="2" />
+ </template>
+ );
+
+ assert
+ .dom(".d-post-accordion-item")
+ .hasAttribute("data-overflowing", "true");
+ });
+
+ test("post is not truncated if shorter than linesDisplayed", async function (assert) {
+ await render(
+ <template>
+ <DPostAccordion @posts={{fiveLinePost}} @linesDisplayed="10" />
+ </template>
+ );
+
+ await waitFor(".d-post-accordion-item[data-overflowing='false']");
+
+ assert
+ .dom(".d-post-accordion-item")
+ .hasAttribute("data-overflowing", "false");
+ });
+});
diff --git a/plugins/discourse-ai/lib/automation/report_context_generator.rb b/plugins/discourse-ai/lib/automation/report_context_generator.rb
index 6bf4a0419b1..952908631ae 100644
--- a/plugins/discourse-ai/lib/automation/report_context_generator.rb
+++ b/plugins/discourse-ai/lib/automation/report_context_generator.rb
@@ -68,10 +68,16 @@ module DiscourseAi
if defined?(DiscourseSolved)
@solutions =
- DiscourseSolved::SolvedTopic
- .where(topic_id: @posts.select(:topic_id))
- .pluck(:topic_id, :answer_post_id)
- .to_h
+ DiscourseSolved::TopicAnswer
+ .joins(:solved_topic)
+ .where("discourse_solved_solved_topics.topic_id": @posts.select(:topic_id))
+ .pluck(
+ "discourse_solved_solved_topics.topic_id",
+ "discourse_solved_topic_answers.answer_post_id",
+ )
+ .each_with_object({}) do |(topic_id, answer_post_id), h|
+ (h[topic_id] ||= []) << answer_post_id
+ end
else
@solutions = {}
end
@@ -96,7 +102,7 @@ module DiscourseAi
buffer = []
buffer << ""
buffer << "post_number: #{post.post_number}"
- buffer << "solution: true" if @solutions[post.topic_id] == post.id
+ buffer << "solution: true" if @solutions[post.topic_id]&.include?(post.id)
buffer << post.created_at.strftime("%Y-%m-%d %H:%M")
buffer << "user: #{post.user&.username}"
buffer << "likes: #{post.like_count}"
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/mark_as_solved_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/mark_as_solved_spec.rb
index 9ae84304c47..81c5d032a6f 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/mark_as_solved_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/mark_as_solved_spec.rb
@@ -9,6 +9,7 @@ RSpec.describe DiscourseAi::Agents::Tools::MarkAsSolved do
fab!(:topic)
fab!(:post) { Fabricate(:post, topic: topic) }
fab!(:reply, :post) { Fabricate(:post, topic: topic) }
+ fab!(:reply2, :post) { Fabricate(:post, topic: topic) }
before do
enable_current_plugin
@@ -29,7 +30,21 @@ RSpec.describe DiscourseAi::Agents::Tools::MarkAsSolved do
expect(result[:status]).to eq("success")
expect(topic.reload.solved).to be_present
- expect(topic.solved.answer_post).to eq(reply)
+ expect(topic.topic_answers[0].post).to eq(reply)
+ end
+
+ it "unmarks existing solution when accepting another one" do
+ result = tool(post_id: reply.id, solved: true, reason: "This answers the question").invoke
+ expect(result[:status]).to eq("success")
+ expect(topic.reload.solved).to be_present
+ expect(topic.topic_answers.length).to eq(1)
+ expect(topic.topic_answers[0].post).to eq(reply)
+
+ result = tool(post_id: reply2.id, solved: true, reason: "This answers the question").invoke
+ expect(result[:status]).to eq("success")
+ expect(topic.reload.solved).to be_present
+ expect(topic.topic_answers.length).to eq(1)
+ expect(topic.topic_answers[0].post).to eq(reply2)
end
it "unmarks a post as the accepted solution" do
@@ -68,4 +83,33 @@ RSpec.describe DiscourseAi::Agents::Tools::MarkAsSolved do
expect(result[:status]).to eq("error")
end
+
+ describe "with multiple solutions enabled" do
+ before { SiteSetting.solved_allow_multiple_solutions = true }
+
+ it "can accept/unaccept multiple solutions" do
+ result = tool(post_id: reply.id, solved: true, reason: "This answers the question").invoke
+ expect(result[:status]).to eq("success")
+ expect(topic.reload.solved).to be_present
+ expect(topic.topic_answers.length).to eq(1)
+ expect(topic.topic_answers[0].post).to eq(reply)
+
+ result = tool(post_id: reply2.id, solved: true, reason: "This answers the question").invoke
+ expect(result[:status]).to eq("success")
+ expect(topic.reload.solved).to be_present
+ expect(topic.topic_answers.length).to eq(2)
+ expect(topic.topic_answers[0].post).to eq(reply)
+ expect(topic.topic_answers[1].post).to eq(reply2)
+
+ result = tool(post_id: reply.id, solved: false, reason: "Not the right answer").invoke
+ expect(result[:status]).to eq("success")
+ expect(topic.reload.solved).to be_present
+ expect(topic.topic_answers.length).to eq(1)
+ expect(topic.topic_answers[0].post).to eq(reply2)
+
+ result = tool(post_id: reply2.id, solved: false, reason: "Not the right answer").invoke
+ expect(result[:status]).to eq("success")
+ expect(topic.reload.solved).to be_nil
+ end
+ end
end
diff --git a/plugins/discourse-assign/plugin.rb b/plugins/discourse-assign/plugin.rb
index fb5c0128e0a..03e627e3df9 100644
--- a/plugins/discourse-assign/plugin.rb
+++ b/plugins/discourse-assign/plugin.rb
@@ -1028,6 +1028,8 @@ after_initialize do
on(:unaccepted_solution) do |post|
next if SiteSetting.assignment_status_on_unsolve.blank?
+ next if post.topic.reload.solved.present?
+
assignments = Assignment.includes(:target).where(topic: post.topic)
assignments.each do |assignment|
assigned_user = User.find_by(id: assignment.assigned_to_id)
diff --git a/plugins/discourse-assign/spec/integration/solved_integration_spec.rb b/plugins/discourse-assign/spec/integration/solved_integration_spec.rb
index f35c39d3a67..3695112b475 100644
--- a/plugins/discourse-assign/spec/integration/solved_integration_spec.rb
+++ b/plugins/discourse-assign/spec/integration/solved_integration_spec.rb
@@ -30,7 +30,7 @@ RSpec.describe "Solved integration", if: defined?(DiscourseSolved) do
DiscourseSolved::AcceptAnswer.call!(params: { post_id: post.id }, guardian: user.guardian)
topic.reload
- expect(topic.solved.answer_post_id).to eq(post.id)
+ expect(topic.topic_answers[0].answer_post_id).to eq(post.id)
expect(topic.assignment.reload.status).to eq("Done")
end
@@ -48,6 +48,35 @@ RSpec.describe "Solved integration", if: defined?(DiscourseSolved) do
expect(topic.assignment.reload.status).to eq("New")
end
+ describe "with multiple solutions enabled" do
+ fab!(:post2) { Fabricate(:post, topic: topic) }
+
+ before { SiteSetting.solved_allow_multiple_solutions = true }
+
+ it "updates all assignments to assignment_status_on_unsolve status only when no accepted solutions remain" do
+ assigner = Assigner.new(topic, user)
+ result = assigner.assign(user)
+ expect(result[:success]).to eq(true)
+
+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: post.id }, guardian: user.guardian)
+ expect(topic.assignment.reload.status).to eq("Done")
+
+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: post2.id }, guardian: user.guardian)
+ expect(topic.assignment.reload.status).to eq("Done")
+
+ DiscourseSolved::UnacceptAnswer.call!(params: { post_id: post.id }, guardian: user.guardian)
+ expect(topic.assignment.reload.status).to eq("Done")
+
+ DiscourseSolved::UnacceptAnswer.call!(
+ params: {
+ post_id: post2.id,
+ },
+ guardian: user.guardian,
+ )
+ expect(topic.assignment.reload.status).to eq("New")
+ end
+ end
+
it "does not update the assignee when a post is accepted" do
user_2 = Fabricate(:user)
user_3 = Fabricate(:user)
diff --git a/plugins/discourse-gamification/lib/discourse_gamification/scorables/solutions.rb b/plugins/discourse-gamification/lib/discourse_gamification/scorables/solutions.rb
index 884bf514151..0364456be17 100644
--- a/plugins/discourse-gamification/lib/discourse_gamification/scorables/solutions.rb
+++ b/plugins/discourse-gamification/lib/discourse_gamification/scorables/solutions.rb
@@ -21,21 +21,23 @@ module DiscourseGamification
<<~SQL
SELECT
posts.user_id AS user_id,
- date_trunc('day', dsst.updated_at) AS date,
+ date_trunc('day', dsta.created_at) AS date,
COUNT(dsst.topic_id) * #{score_multiplier(leaderboard:)} AS points
FROM
discourse_solved_solved_topics dsst
INNER JOIN topics
ON dsst.topic_id = topics.id
#{category_filter(leaderboard:)}
- INNER JOIN posts
- ON posts.id = dsst.answer_post_id
+ INNER JOIN discourse_solved_topic_answers dsta
+ ON dsta.solved_topic_id = dsst.id
+ INNER JOIN posts
+ ON posts.id = dsta.answer_post_id
WHERE
posts.deleted_at IS NULL AND
topics.deleted_at IS NULL AND
topics.archetype <> 'private_message' AND
posts.user_id != topics.user_id AND
- dsst.updated_at >= :since
+ dsta.created_at >= :since
GROUP BY
1, 2
SQL
diff --git a/plugins/discourse-gamification/spec/lib/scorables/solutions_spec.rb b/plugins/discourse-gamification/spec/lib/scorables/solutions_spec.rb
index 0f5b7b58627..918265813e9 100644
--- a/plugins/discourse-gamification/spec/lib/scorables/solutions_spec.rb
+++ b/plugins/discourse-gamification/spec/lib/scorables/solutions_spec.rb
@@ -58,6 +58,65 @@ RSpec.describe DiscourseGamification::Solutions do
expect(query_results).to be_empty
end
+
+ context "with multiple solutions enabled" do
+ before { SiteSetting.solved_allow_multiple_solutions = true }
+
+ it "scores additional solutions when querying with :since after first solution" do
+ freeze_time DateTime.parse("2024-01-01 12:00")
+
+ DiscourseSolved::AcceptAnswer.call!(
+ params: {
+ post_id: answer_post.id,
+ },
+ guardian: Discourse.system_user.guardian,
+ )
+
+ freeze_time DateTime.parse("2024-01-03 12:00")
+ answer_post_2 = Fabricate(:post, topic: topic, user: answer_user)
+ DiscourseSolved::AcceptAnswer.call!(
+ params: {
+ post_id: answer_post_2.id,
+ },
+ guardian: Discourse.system_user.guardian,
+ )
+
+ expect(DB.query(described_class.query, since: 1.day.ago)).to contain_exactly(
+ have_attributes(
+ user_id: answer_user.id,
+ date: Date.parse("2024-01-03").beginning_of_day,
+ points: 5.0,
+ ),
+ )
+ end
+
+ it "scores multiple accepted solutions by the same user" do
+ freeze_time DateTime.parse("2024-01-01 12:00")
+
+ answer_post_2 = Fabricate(:post, topic: topic, user: answer_user)
+
+ DiscourseSolved::AcceptAnswer.call!(
+ params: {
+ post_id: answer_post.id,
+ },
+ guardian: Discourse.system_user.guardian,
+ )
+ DiscourseSolved::AcceptAnswer.call!(
+ params: {
+ post_id: answer_post_2.id,
+ },
+ guardian: Discourse.system_user.guardian,
+ )
+
+ expect(query_results).to contain_exactly(
+ have_attributes(
+ user_id: answer_user.id,
+ date: Time.current.beginning_of_day,
+ points: 10.0,
+ ),
+ )
+ end
+ end
end
it "is disabled when solved plugin is disabled" do
diff --git a/plugins/discourse-solved/app/controllers/discourse_solved/answer_controller.rb b/plugins/discourse-solved/app/controllers/discourse_solved/answer_controller.rb
index 63fd387f31a..1169d51112e 100644
--- a/plugins/discourse-solved/app/controllers/discourse_solved/answer_controller.rb
+++ b/plugins/discourse-solved/app/controllers/discourse_solved/answer_controller.rb
@@ -7,11 +7,16 @@ class DiscourseSolved::AnswerController < ::ApplicationController
def accept
DiscourseSolved::AcceptAnswer.call(params: { post_id: params[:id] }, guardian:) do
- on_success { |topic:| render_json_dump(topic.accepted_answer_post_info) }
+ on_success do |topic:|
+ render_json_dump(DiscourseSolved::AcceptedAnswersHelper.serialize(topic.reload, guardian))
+ end
on_model_not_found(:post) { raise Discourse::NotFound }
on_model_not_found(:topic) { raise Discourse::NotFound }
on_failed_policy(:can_accept_answer) { raise Discourse::InvalidAccess }
- on_model_errors(:solved) do |model|
+ on_model_errors(:solved_topic) do |model|
+ render_json_error(model, type: :record_invalid, status: 422)
+ end
+ on_model_errors(:topic_answer) do |model|
render_json_error(model, type: :record_invalid, status: 422)
end
on_failed_contract do |contract|
@@ -23,7 +28,9 @@ class DiscourseSolved::AnswerController < ::ApplicationController
def unaccept
DiscourseSolved::UnacceptAnswer.call(params: { post_id: params[:id] }, guardian:) do
- on_success { render json: success_json }
+ on_success do |topic:|
+ render_json_dump(DiscourseSolved::AcceptedAnswersHelper.serialize(topic.reload, guardian))
+ end
on_model_not_found(:post) { raise Discourse::NotFound }
on_model_not_found(:topic) { raise Discourse::NotFound }
on_failed_policy(:can_unaccept_answer) { raise Discourse::InvalidAccess }
diff --git a/plugins/discourse-solved/app/controllers/discourse_solved/solved_topics_controller.rb b/plugins/discourse-solved/app/controllers/discourse_solved/solved_topics_controller.rb
index ec41e38c95a..e3669c52967 100644
--- a/plugins/discourse-solved/app/controllers/discourse_solved/solved_topics_controller.rb
+++ b/plugins/discourse-solved/app/controllers/discourse_solved/solved_topics_controller.rb
@@ -21,7 +21,8 @@ class DiscourseSolved::SolvedTopicsController < ::ApplicationController
posts =
Post
.joins(
- "INNER JOIN discourse_solved_solved_topics ON discourse_solved_solved_topics.answer_post_id = posts.id",
+ "INNER JOIN discourse_solved_topic_answers ON discourse_solved_topic_answers.answer_post_id = posts.id",
+ "INNER JOIN discourse_solved_solved_topics ON discourse_solved_solved_topics.id = discourse_solved_topic_answers.solved_topic_id",
)
.joins(:topic)
.joins("LEFT JOIN categories ON categories.id = topics.category_id")
@@ -37,7 +38,7 @@ class DiscourseSolved::SolvedTopicsController < ::ApplicationController
posts =
posts
.includes(:user, topic: %i[category tags])
- .order("discourse_solved_solved_topics.created_at DESC")
+ .order("discourse_solved_topic_answers.created_at DESC")
.offset(offset)
.limit(limit)
diff --git a/plugins/discourse-solved/app/models/discourse_solved/solved_topic.rb b/plugins/discourse-solved/app/models/discourse_solved/solved_topic.rb
index 8b36c62705e..3f11e8149e5 100644
--- a/plugins/discourse-solved/app/models/discourse_solved/solved_topic.rb
+++ b/plugins/discourse-solved/app/models/discourse_solved/solved_topic.rb
@@ -4,14 +4,15 @@ module DiscourseSolved
class SolvedTopic < ActiveRecord::Base
self.table_name = "discourse_solved_solved_topics"
+ # TODO: Remove these columns fully in a future migration
+ self.ignored_columns += %i[answer_post_id accepter_user_id]
+
belongs_to :topic, class_name: "Topic"
- belongs_to :answer_post, -> { with_deleted }, class_name: "Post", foreign_key: "answer_post_id"
- belongs_to :accepter, class_name: "User", foreign_key: "accepter_user_id"
+ has_many :topic_answers, class_name: "DiscourseSolved::TopicAnswer", dependent: :destroy
+ has_many :answer_posts, through: :topic_answers, class_name: "Post", source: :post
belongs_to :topic_timer, dependent: :destroy
validates :topic_id, presence: true
- validates :answer_post_id, presence: true
- validates :accepter_user_id, presence: true
before_create :auto_close_topic_timer
@@ -36,13 +37,11 @@ end
#
# Table name: discourse_solved_solved_topics
#
-# id :bigint not null, primary key
-# created_at :datetime not null
-# updated_at :datetime not null
-# accepter_user_id :integer not null
-# answer_post_id :integer not null
-# topic_id :integer not null
-# topic_timer_id :integer
+# id :bigint not null, primary key
+# created_at :datetime not null
+# updated_at :datetime not null
+# topic_id :bigint not null
+# topic_timer_id :integer
#
# Indexes
#
diff --git a/plugins/discourse-solved/app/models/discourse_solved/topic_answer.rb b/plugins/discourse-solved/app/models/discourse_solved/topic_answer.rb
new file mode 100644
index 00000000000..2593ece7ca4
--- /dev/null
+++ b/plugins/discourse-solved/app/models/discourse_solved/topic_answer.rb
@@ -0,0 +1,32 @@
+# frozen_string_literal: true
+
+module DiscourseSolved
+ class TopicAnswer < ActiveRecord::Base
+ self.table_name = "discourse_solved_topic_answers"
+
+ belongs_to :solved_topic, class_name: "DiscourseSolved::SolvedTopic"
+ belongs_to :post, -> { with_deleted }, foreign_key: "answer_post_id"
+ belongs_to :accepter, class_name: "User", foreign_key: "accepter_user_id"
+
+ validates :solved_topic_id, presence: true
+ validates :answer_post_id, presence: true, uniqueness: true
+ validates :accepter_user_id, presence: true
+ end
+end
+
+# == Schema Information
+#
+# Table name: discourse_solved_topic_answers
+#
+# id :bigint not null, primary key
+# created_at :datetime not null
+# updated_at :datetime not null
+# accepter_user_id :bigint not null
+# answer_post_id :bigint not null
+# solved_topic_id :bigint not null
+#
+# Indexes
+#
+# index_discourse_solved_topic_answers_on_answer_post_id (answer_post_id) UNIQUE
+# index_discourse_solved_topic_answers_on_solved_topic_id (solved_topic_id)
+#
diff --git a/plugins/discourse-solved/app/serializers/concerns/discourse_solved/topic_answer_mixin.rb b/plugins/discourse-solved/app/serializers/concerns/discourse_solved/topic_answer_mixin.rb
index f2f73c066c4..ecac89d4656 100644
--- a/plugins/discourse-solved/app/serializers/concerns/discourse_solved/topic_answer_mixin.rb
+++ b/plugins/discourse-solved/app/serializers/concerns/discourse_solved/topic_answer_mixin.rb
@@ -7,7 +7,7 @@ module DiscourseSolved
end
def has_accepted_answer
- object&.solved.present?
+ object.topic_answers.any?
end
def include_has_accepted_answer?
diff --git a/plugins/discourse-solved/app/serializers/discourse_solved/accepted_answer_serializer.rb b/plugins/discourse-solved/app/serializers/discourse_solved/accepted_answer_serializer.rb
new file mode 100644
index 00000000000..6ae6f8ef3d2
--- /dev/null
+++ b/plugins/discourse-solved/app/serializers/discourse_solved/accepted_answer_serializer.rb
@@ -0,0 +1,50 @@
+# frozen_string_literal: true
+
+class DiscourseSolved::AcceptedAnswerSerializer < PostAccordionItemSerializer
+ attributes :accepter_name, :accepter_username
+
+ def answer_user
+ @answer_user ||= object.user || Discourse.system_user
+ end
+
+ def accepter_user
+ @accepter_user ||= @options[:accepter] || object.topic&.user || Discourse.system_user
+ end
+
+ def name
+ answer_user.name
+ end
+
+ def username
+ answer_user.username
+ end
+
+ def avatar_template
+ answer_user.avatar_template
+ end
+
+ def accepter_name
+ accepter_user.name
+ end
+
+ def accepter_username
+ accepter_user.username
+ end
+
+ def include_accepter_name?
+ SiteSetting.show_who_marked_solved && SiteSetting.enable_names? &&
+ SiteSetting.display_name_on_posts
+ end
+
+ def include_accepter_username?
+ SiteSetting.show_who_marked_solved
+ end
+
+ def include_cooked?
+ SiteSetting.solved_quote_length > 0
+ end
+
+ def include_name?
+ SiteSetting.enable_names? && SiteSetting.display_name_on_posts
+ end
+end
diff --git a/plugins/discourse-solved/app/serializers/discourse_solved/question_schema_serializer.rb b/plugins/discourse-solved/app/serializers/discourse_solved/question_schema_serializer.rb
index a3134e523ff..bf08f8b83c1 100644
--- a/plugins/discourse-solved/app/serializers/discourse_solved/question_schema_serializer.rb
+++ b/plugins/discourse-solved/app/serializers/discourse_solved/question_schema_serializer.rb
@@ -6,11 +6,10 @@ class DiscourseSolved::QuestionSchemaSerializer < ApplicationSerializer
def serializable_hash
hash = { "@type" => "Question" }.merge(super)
- if accepted_answer.present?
- hash["acceptedAnswer"] = DiscourseSolved::AnswerSchemaSerializer.new(
- accepted_answer,
- root: false,
- ).serializable_hash
+ if accepted_answers.present?
+ hash["acceptedAnswer"] = accepted_answers.map do |post|
+ DiscourseSolved::AnswerSchemaSerializer.new(post, root: false).serializable_hash
+ end
end
if suggested_answers.present?
hash["suggestedAnswer"] = suggested_answers.map do |post|
@@ -35,7 +34,7 @@ class DiscourseSolved::QuestionSchemaSerializer < ApplicationSerializer
end
def answerCount
- (accepted_answer.present? ? 1 : 0) + suggested_answers.to_a.size
+ accepted_answers.to_a.size + suggested_answers.to_a.size
end
def datePublished
@@ -52,8 +51,8 @@ class DiscourseSolved::QuestionSchemaSerializer < ApplicationSerializer
private
- def accepted_answer
- options[:accepted_answer]
+ def accepted_answers
+ options[:accepted_answers]
end
def suggested_answers
diff --git a/plugins/discourse-solved/app/services/discourse_solved/accept_answer.rb b/plugins/discourse-solved/app/services/discourse_solved/accept_answer.rb
index 20ad1ec55db..80b18879eeb 100644
--- a/plugins/discourse-solved/app/services/discourse_solved/accept_answer.rb
+++ b/plugins/discourse-solved/app/services/discourse_solved/accept_answer.rb
@@ -12,12 +12,14 @@ class DiscourseSolved::AcceptAnswer
model :post
model :topic
policy :can_accept_answer
+ policy :answer_is_acceptable
lock(:topic) do
transaction do
- only_if(:previous_answer_exists) { step :revoke_previous_accepted_answer }
+ only_if(:should_revoke_previous) { step :revoke_previous_accepted_answer }
step :credit_post_author
- model :solved, :mark_as_solved
+ model :solved_topic, :find_or_create_solved_topic
+ model :topic_answer, :create_topic_answer
only_if(:should_notify_post_author) { step :notify_post_author }
only_if(:should_notify_topic_owner) { step :notify_topic_owner }
model :topic_user_ids, optional: true
@@ -47,15 +49,19 @@ class DiscourseSolved::AcceptAnswer
guardian.can_accept_answer?(topic, post)
end
- def previous_answer_exists(topic:)
- topic.solved&.answer_post_id.present?
+ def should_revoke_previous(topic:)
+ topic.reload
+ !SiteSetting.solved_allow_multiple_solutions && topic.topic_answers&.any?
end
def revoke_previous_accepted_answer(topic:)
- UserAction.where(
- action_type: UserAction::SOLVED,
- target_post: topic.solved.answer_post,
- ).destroy_all
+ topic_answers = topic.topic_answers
+
+ if topic_answers.any?
+ post_ids = topic_answers.pluck(:answer_post_id)
+ UserAction.where(action_type: UserAction::SOLVED, target_post_id: post_ids).destroy_all
+ end
+
topic.solved.destroy!
end
@@ -69,10 +75,6 @@ class DiscourseSolved::AcceptAnswer
)
end
- def mark_as_solved(post:, topic:, guardian:)
- DiscourseSolved::SolvedTopic.create(topic:, answer_post: post, accepter: guardian.user)
- end
-
def should_notify_post_author(post:, guardian:)
return if guardian.user.id == post.user_id || !User.exists?(post.user_id)
return if !UserOption.exists?(user_id: post.user_id, notify_on_solved: true)
@@ -163,8 +165,8 @@ class DiscourseSolved::AcceptAnswer
Notification::Action::BulkCreate.call(records:)
end
- def topic_will_auto_close(solved:)
- solved.topic_timer.present?
+ def topic_will_auto_close(solved_topic:)
+ solved_topic.previously_new_record? && solved_topic.topic_timer.present?
end
def publish_topic_reload(topic:)
@@ -183,12 +185,27 @@ class DiscourseSolved::AcceptAnswer
WebHook.enqueue_solved_hooks(:accepted_solution, post, WebHook.generate_payload(:post, post))
end
- def publish_solution(post:, topic:)
+ def publish_solution(post:, topic:, guardian:)
DiscourseEvent.trigger(:accepted_solution, post)
MessageBus.publish(
"/topic/#{topic.id}",
- { type: :accepted_solution, accepted_answer: topic.reload.accepted_answer_post_info },
+ {
+ type: :accepted_solution,
+ accepted_answers: DiscourseSolved::AcceptedAnswersHelper.serialize(topic.reload, guardian),
+ },
topic.secure_audience_publish_messages,
)
end
+
+ def answer_is_acceptable(topic:, post:)
+ !topic.topic_answers.exists?(answer_post_id: post.id)
+ end
+
+ def find_or_create_solved_topic(topic:)
+ DiscourseSolved::SolvedTopic.find_or_create_by!(topic:)
+ end
+
+ def create_topic_answer(solved_topic:, post:, guardian:)
+ DiscourseSolved::TopicAnswer.create!(solved_topic:, post:, accepter: guardian.user)
+ end
end
diff --git a/plugins/discourse-solved/app/services/discourse_solved/build_schema_markup.rb b/plugins/discourse-solved/app/services/discourse_solved/build_schema_markup.rb
index d9acce19ff5..a2ebd363273 100644
--- a/plugins/discourse-solved/app/services/discourse_solved/build_schema_markup.rb
+++ b/plugins/discourse-solved/app/services/discourse_solved/build_schema_markup.rb
@@ -12,7 +12,7 @@ class DiscourseSolved::BuildSchemaMarkup
model :topic
policy :accepted_answers_allowed
policy :schema_markup_enabled
- model :accepted_answer, optional: true
+ model :accepted_answers, optional: true
model :suggested_answers, optional: true
policy :has_answers
model :html
@@ -31,19 +31,20 @@ class DiscourseSolved::BuildSchemaMarkup
DiscourseSolved::SchemaUtils.schema_markup_enabled?(topic)
end
- def has_answers(accepted_answer:, suggested_answers:)
- accepted_answer.present? || suggested_answers.present?
+ def has_answers(accepted_answers:, suggested_answers:)
+ accepted_answers.present? || suggested_answers.present?
end
- def fetch_accepted_answer(topic:)
- post = topic.solved&.answer_post
- return unless post.present? && Guardian.new.can_see_post?(post)
- post if post.cooked.present? && Nokogiri::HTML5.fragment(post.cooked).text.strip.present?
+ def fetch_accepted_answers(topic:, guardian:)
+ topic.topic_answers.filter_map do |ta|
+ post = ta.post
+ next unless post.present? && guardian.can_see_post?(post)
+ post if post.cooked.present? && Nokogiri::HTML5.fragment(post.cooked).text.strip.present?
+ end
end
- def fetch_suggested_answers(params:, topic:, accepted_answer:)
- excluded_ids = [topic.first_post.id]
- excluded_ids << accepted_answer.id if accepted_answer.present?
+ def fetch_suggested_answers(params:, topic:, accepted_answers:)
+ excluded_ids = [topic.first_post.id] + Array(accepted_answers).map(&:id)
scope = topic.posts.where.not(id: excluded_ids)
scope = scope.where(id: params.post_ids) if params.post_ids.present?
scope
@@ -53,12 +54,12 @@ class DiscourseSolved::BuildSchemaMarkup
.select { |p| p.cooked.present? && Nokogiri::HTML5.fragment(p.cooked).text.strip.present? }
end
- def fetch_html(topic:, accepted_answer:, suggested_answers:)
+ def fetch_html(topic:, accepted_answers:, suggested_answers:)
question_json =
DiscourseSolved::QuestionSchemaSerializer.new(
topic,
root: false,
- accepted_answer: accepted_answer,
+ accepted_answers: accepted_answers,
suggested_answers: suggested_answers,
).serializable_hash
diff --git a/plugins/discourse-solved/app/services/discourse_solved/unaccept_answer.rb b/plugins/discourse-solved/app/services/discourse_solved/unaccept_answer.rb
index 7c3865ed3e7..276c05a9938 100644
--- a/plugins/discourse-solved/app/services/discourse_solved/unaccept_answer.rb
+++ b/plugins/discourse-solved/app/services/discourse_solved/unaccept_answer.rb
@@ -11,6 +11,7 @@ class DiscourseSolved::UnacceptAnswer
model :post
model :topic
+ model :topic_answer, optional: true
policy :can_unaccept_answer
only_if(:post_is_accepted_answer) do
@@ -39,12 +40,16 @@ class DiscourseSolved::UnacceptAnswer
post.topic
end
+ def fetch_topic_answer(topic:, post:)
+ topic.topic_answers.find_by(answer_post_id: post.id)
+ end
+
def can_unaccept_answer(guardian:, topic:, post:)
guardian.can_unaccept_answer?(topic, post)
end
- def post_is_accepted_answer(topic:, post:)
- topic.solved&.answer_post == post
+ def post_is_accepted_answer(topic_answer:)
+ topic_answer.present?
end
def revoke_solved_credit(post:)
@@ -67,8 +72,10 @@ class DiscourseSolved::UnacceptAnswer
.destroy_all
end
- def unmark_as_solved(topic:)
- topic.solved.destroy!
+ def unmark_as_solved(topic:, topic_answer:)
+ topic_answer.destroy!
+ solved = topic.solved
+ solved.destroy! if solved && solved.topic_answers.none?
end
def unaccepted_solution_webhooks_active
@@ -79,11 +86,14 @@ class DiscourseSolved::UnacceptAnswer
WebHook.enqueue_solved_hooks(:unaccepted_solution, post, WebHook.generate_payload(:post, post))
end
- def publish_unaccepted(post:, topic:)
+ def publish_unaccepted(post:, topic:, guardian:)
DiscourseEvent.trigger(:unaccepted_solution, post)
MessageBus.publish(
"/topic/#{topic.id}",
- { type: :unaccepted_solution },
+ {
+ type: :unaccepted_solution,
+ accepted_answers: DiscourseSolved::AcceptedAnswersHelper.serialize(topic.reload, guardian),
+ },
topic.secure_audience_publish_messages,
)
end
diff --git a/plugins/discourse-solved/assets/javascripts/discourse/components/solved-accept-answer-button.gjs b/plugins/discourse-solved/assets/javascripts/discourse/components/solved-accept-answer-button.gjs
index 96168d4af98..7f9170d994b 100644
--- a/plugins/discourse-solved/assets/javascripts/discourse/components/solved-accept-answer-button.gjs
+++ b/plugins/discourse-solved/assets/javascripts/discourse/components/solved-accept-answer-button.gjs
@@ -5,10 +5,13 @@ import { service } from "@ember/service";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import DButton from "discourse/ui-kit/d-button";
-import setAcceptedSolution from "../lib/set-accepted-solution";
+import setAcceptedSolutions from "../lib/set-accepted-solutions";
export default class SolvedAcceptAnswerButton extends Component {
- static hidden(args) {
+ static hidden(args, context) {
+ if (context.siteSettings.solved_allow_multiple_solutions) {
+ return false;
+ }
return args.post.topic_accepted_answer;
}
@@ -58,12 +61,12 @@ async function acceptPost(post) {
const topic = post.topic;
try {
- const acceptedAnswer = await ajax("/solution/accept", {
+ const acceptedAnswers = await ajax("/solution/accept", {
type: "POST",
data: { id: post.id },
});
- setAcceptedSolution(topic, acceptedAnswer);
+ setAcceptedSolutions(topic, acceptedAnswers);
} catch (e) {
popupAjaxError(e);
}
diff --git a/plugins/discourse-solved/assets/javascripts/discourse/components/solved-accepted-answer.gjs b/plugins/discourse-solved/assets/javascripts/discourse/components/solved-accepted-answer.gjs
deleted file mode 100644
index 3a24dae9593..00000000000
--- a/plugins/discourse-solved/assets/javascripts/discourse/components/solved-accepted-answer.gjs
+++ /dev/null
@@ -1,226 +0,0 @@
-import Component from "@glimmer/component";
-import { tracked } from "@glimmer/tracking";
-import { action } from "@ember/object";
-import { service } from "@ember/service";
-import { trustHTML } from "@ember/template";
-import PostCookedHtml from "discourse/components/post/cooked-html";
-import DButton from "discourse/ui-kit/d-button";
-import DInterpolatedTranslation from "discourse/ui-kit/d-interpolated-translation";
-import DUserLink from "discourse/ui-kit/d-user-link";
-import dBoundAvatarTemplate from "discourse/ui-kit/helpers/d-bound-avatar-template";
-import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
-import dIcon from "discourse/ui-kit/helpers/d-icon";
-import dOnResize from "discourse/ui-kit/modifiers/d-on-resize";
-import { i18n } from "discourse-i18n";
-
-const CHARS_PER_LINE = 90;
-
-export default class SolvedAcceptedAnswer extends Component {
- @service siteSettings;
-
- @tracked expanded = false;
- @tracked measured = false;
- @tracked isOverflowing = false;
-
- get topic() {
- return this.args.post.topic;
- }
-
- get acceptedAnswer() {
- return this.topic.accepted_answer;
- }
-
- get quoteId() {
- return `accepted-answer-${this.topic.id}-${this.acceptedAnswer.post_number}`;
- }
-
- get hasExcerpt() {
- return !!this.acceptedAnswer.excerpt;
- }
-
- get content() {
- if (!this.hasExcerpt) {
- return "";
- }
-
- return trustHTML(this.acceptedAnswer.excerpt);
- }
-
- get showMarkedBy() {
- return this.siteSettings.show_who_marked_solved;
- }
-
- get showSolvedBy() {
- return !(!this.acceptedAnswer.username || !this.acceptedAnswer.post_number);
- }
-
- get postNumber() {
- return i18n("solved.accepted_answer_post_number", {
- post_number: this.acceptedAnswer.post_number,
- });
- }
-
- get solverUsername() {
- return this.acceptedAnswer.username;
- }
-
- get accepterUsername() {
- return this.acceptedAnswer.accepter_username;
- }
-
- get solverDisplayName() {
- const username = this.acceptedAnswer.username;
- const name = this.acceptedAnswer.name;
-
- return this.siteSettings.display_name_on_posts && name ? name : username;
- }
-
- get accepterDisplayName() {
- const username = this.acceptedAnswer.accepter_username;
- const name = this.acceptedAnswer.accepter_name;
-
- return this.siteSettings.display_name_on_posts && name ? name : username;
- }
-
- get postPath() {
- const postNumber = this.acceptedAnswer.post_number;
- return `${this.topic.url}/${postNumber}`;
- }
-
- get maxHeightStyle() {
- const chars = this.siteSettings.solved_quote_length;
- if (chars <= 0) {
- return null;
- }
-
- const lines = Math.max(1, Math.ceil(chars / CHARS_PER_LINE));
- return trustHTML(`--solved-max-lines: ${lines}`);
- }
-
- get showToggle() {
- return (
- this.hasExcerpt && this.measured && (this.isOverflowing || this.expanded)
- );
- }
-
- get overflowingAttr() {
- return this.measured ? String(this.isOverflowing) : "true";
- }
-
- @action
- toggleExpanded() {
- this.expanded = !this.expanded;
- }
-
- @action
- onClickTitle(event) {
- if (event.target.closest("a") || event.target.closest(".quote-controls")) {
- return;
- }
- this.toggleExpanded();
- }
-
- @action
- checkOverflow(entries) {
- const blockquote = entries?.[0]?.target;
- if (!blockquote || this.expanded) {
- return;
- }
- this.isOverflowing = blockquote.scrollHeight > blockquote.clientHeight + 1;
- this.measured = true;
- }
-
- <template>
- {{#if this.acceptedAnswer}}
- <aside
- class={{dConcatClass
- "quote accepted-answer d-solved-answer"
- (if this.hasExcerpt "accepted-answer--has-excerpt")
- (unless this.content "title-only")
- }}
- style={{this.maxHeightStyle}}
- {{! eslint-disable-next-line ember/template-no-unnecessary-concat }}
- data-expanded="{{this.expanded}}"
- {{! eslint-disable-next-line ember/template-no-unnecessary-concat }}
- data-overflowing="{{this.overflowingAttr}}"
- data-username={{this.acceptedAnswer.username}}
- data-post={{this.acceptedAnswer.post_number}}
- data-topic={{this.topic.id}}
- >
- <div class="d-solved-answer__header">
- <h3 class="d-solved-answer__title">
- {{dIcon "far-square-check"}}
- {{i18n "solved.title"}}</h3>
- <div class="d-solved-answer__controls">
- {{#if this.showToggle}}
- <DButton
- class="btn-flat d-solved-answer__toggle"
- @action={{this.toggleExpanded}}
- @ariaControls={{this.quoteId}}
- @ariaExpanded={{this.expanded}}
- @ariaLabel={{if this.expanded "post.collapse" "expand"}}
- @title={{if this.expanded "post.collapse" "expand"}}
- @icon={{if this.expanded "chevron-up" "chevron-down"}}
- />
- {{/if}}
- <DButton
- class="btn-flat d-solved-answer__jump"
- @href={{this.postPath}}
- @title="post.follow_quote"
- @ariaLabel="post.follow_quote"
- @icon="arrow-down"
- />
- </div>
- </div>
-
- {{#if this.content}}
- <blockquote id={{this.quoteId}} {{dOnResize this.checkOverflow}}>
- <PostCookedHtml
- @post={{@post}}
- @cooked={{this.content}}
- @decoratorState={{@decoratorState}}
- />
- </blockquote>
- {{/if}}
-
- <div class="d-solved-answer__footer">
- {{#if this.showSolvedBy}}
- <DUserLink @username={{this.solverUsername}}>
- {{dBoundAvatarTemplate
- this.acceptedAnswer.avatar_template
- "tiny"
- }}
- </DUserLink>
- <DInterpolatedTranslation
- @key="solved.accepted_answer_solver_info"
- as |Placeholder|
- >
- <Placeholder @name="user" @class="d-solved-answer__solver">
- {{this.solverDisplayName}}
- </Placeholder>
- <Placeholder @name="post">
- <a
- class="d-solved-answer__post-link"
- href={{this.postPath}}
- >{{this.postNumber}}</a>
- </Placeholder>
- </DInterpolatedTranslation>
- {{/if}}
- {{#if this.showMarkedBy}}
- <span class="dot-separator"></span>
-
- <DInterpolatedTranslation
- @key="solved.marked_solved_by"
- as |Placeholder|
- >
- <Placeholder @name="user" @class="d-solved-answer__accepter">
- {{this.accepterDisplayName}}
- </Placeholder>
- </DInterpolatedTranslation>
-
- {{/if}}
- </div>
- </aside>
- {{/if}}
- </template>
-}
diff --git a/plugins/discourse-solved/assets/javascripts/discourse/components/solved-accepted-answers.gjs b/plugins/discourse-solved/assets/javascripts/discourse/components/solved-accepted-answers.gjs
new file mode 100644
index 00000000000..6b52fdd48d7
--- /dev/null
+++ b/plugins/discourse-solved/assets/javascripts/discourse/components/solved-accepted-answers.gjs
@@ -0,0 +1,75 @@
+import Component from "@glimmer/component";
+import { service } from "@ember/service";
+import DPostAccordion from "discourse/ui-kit/d-post-accordion";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import SolvedAccordionItemMetadata from "./solved-accordion-item-metadata";
+
+const CHARS_PER_LINE = 90;
+
+export default class SolvedAcceptedAnswers extends Component {
+ static shouldRender(args) {
+ return (
+ args.post?.post_number === 1 &&
+ args.post?.topic?.accepted_answers?.length > 0
+ );
+ }
+
+ @service siteSettings;
+
+ get topic() {
+ return this.args.post.topic;
+ }
+
+ get acceptedAnswers() {
+ return this.topic.accepted_answers ?? [];
+ }
+
+ get hasAnswer() {
+ return !!this.acceptedAnswers;
+ }
+
+ get hasMultipleAnswers() {
+ return this.acceptedAnswers?.length > 1;
+ }
+
+ get linesDisplayed() {
+ const chars = this.siteSettings.solved_quote_length;
+ if (chars <= 0) {
+ return null;
+ }
+
+ return Math.max(1, Math.ceil(chars / CHARS_PER_LINE));
+ }
+
+ <template>
+ <DPostAccordion
+ @posts={{this.acceptedAnswers}}
+ @decoratorState={{@decoratorState}}
+ @linesDisplayed={{this.linesDisplayed}}
+ class="accepted-answers"
+ >
+ <:header>
+ <h3 class="accepted-answers__title">
+
+ {{#if this.hasAnswer}}
+ {{dIcon "far-square-check"}}
+ {{/if}}
+
+ {{i18n "solved.title"}}
+ </h3>
+
+ {{#if this.hasMultipleAnswers}}
+ <span class="accepted-answers__solution-count">
+ {{this.acceptedAnswers.length}}
+ {{i18n "solved.solution_summary" count=this.acceptedAnswers.length}}
+ </span>
+ {{/if}}
+ </:header>
+
+ <:itemMetadata as |post|>
+ <SolvedAccordionItemMetadata @post={{post}} />
+ </:itemMetadata>
+ </DPostAccordion>
+ </template>
+}
diff --git a/plugins/discourse-solved/assets/javascripts/discourse/components/solved-accordion-item-metadata.gjs b/plugins/discourse-solved/assets/javascripts/discourse/components/solved-accordion-item-metadata.gjs
new file mode 100644
index 00000000000..9a2553251e5
--- /dev/null
+++ b/plugins/discourse-solved/assets/javascripts/discourse/components/solved-accordion-item-metadata.gjs
@@ -0,0 +1,68 @@
+import Component from "@glimmer/component";
+import { service } from "@ember/service";
+import userPrioritizedName from "discourse/helpers/user-prioritized-name";
+import DInterpolatedTranslation from "discourse/ui-kit/d-interpolated-translation";
+import DRelativeDate from "discourse/ui-kit/d-relative-date";
+import DUserLink from "discourse/ui-kit/d-user-link";
+import dBoundAvatarTemplate from "discourse/ui-kit/helpers/d-bound-avatar-template";
+import { i18n } from "discourse-i18n";
+
+export default class SolvedAccordionItemMetadata extends Component {
+ @service siteSettings;
+
+ get post() {
+ return this.args.post;
+ }
+
+ get userDisplayName() {
+ return userPrioritizedName({
+ username: this.post.username,
+ name: this.post.name,
+ });
+ }
+
+ get accepterDisplayName() {
+ return userPrioritizedName({
+ username: this.post.accepter_username,
+ name: this.post.accepter_name,
+ });
+ }
+
+ get showAccepter() {
+ return (
+ !!this.siteSettings.show_who_marked_solved && this.post.accepter_username
+ );
+ }
+
+ <template>
+ <DUserLink @username={{this.post.username}} class="user-link">
+ {{dBoundAvatarTemplate this.post.avatar_template "tiny"}}
+ <span>{{this.userDisplayName}}</span>
+ </DUserLink>
+ <span class="dot-separator"></span>
+ <a href={{this.post.url}} class="date-link" title={{i18n "post.sr_date"}}>
+ <DRelativeDate @date={{this.post.created_at}} />
+ </a>
+
+ {{#if this.showAccepter}}
+ <span class="dot-separator"></span>
+
+ <span class="accepter-name">
+ <DInterpolatedTranslation
+ @key="solved.marked_solved_by"
+ as |Placeholder|
+ >
+ <Placeholder @name="user">
+
+ <DUserLink
+ @username={{this.post.accepter_username}}
+ class="accepter-link"
+ >
+ {{this.accepterDisplayName}}
+ </DUserLink>
+ </Placeholder>
+ </DInterpolatedTranslation>
+ </span>
+ {{/if}}
+ </template>
+}
diff --git a/plugins/discourse-solved/assets/javascripts/discourse/components/solved-shared-issue-button.gjs b/plugins/discourse-solved/assets/javascripts/discourse/components/solved-shared-issue-button.gjs
index 0c0fa38183f..00adb08cb0b 100644
--- a/plugins/discourse-solved/assets/javascripts/discourse/components/solved-shared-issue-button.gjs
+++ b/plugins/discourse-solved/assets/javascripts/discourse/components/solved-shared-issue-button.gjs
@@ -11,13 +11,17 @@ import { i18n } from "discourse-i18n";
export default class SolvedSharedIssueButton extends Component {
@service currentUser;
@service router;
+ @service siteSettings;
@tracked saving = false;
get show() {
+ const topic = this.args.post.topic;
+ const hasAcceptedAnswers = topic.accepted_answers?.length > 0;
+
return (
- this.args.post.topic.shared_issue_visible &&
- !this.args.post.topic.accepted_answer
+ topic.shared_issue_visible &&
+ (!hasAcceptedAnswers || this.siteSettings.solved_allow_multiple_solutions)
);
}
diff --git a/plugins/discourse-solved/assets/javascripts/discourse/components/solved-unaccept-answer-button.gjs b/plugins/discourse-solved/assets/javascripts/discourse/components/solved-unaccept-answer-button.gjs
index da50e85159d..fd2e2c2942b 100644
--- a/plugins/discourse-solved/assets/javascripts/discourse/components/solved-unaccept-answer-button.gjs
+++ b/plugins/discourse-solved/assets/javascripts/discourse/components/solved-unaccept-answer-button.gjs
@@ -11,7 +11,7 @@ import DInterpolatedTranslation from "discourse/ui-kit/d-interpolated-translatio
import DUserLink from "discourse/ui-kit/d-user-link";
import dIcon from "discourse/ui-kit/helpers/d-icon";
import { i18n } from "discourse-i18n";
-import setAcceptedSolution from "../lib/set-accepted-solution";
+import setAcceptedSolutions from "../lib/set-accepted-solutions";
export default class SolvedUnacceptAnswerButton extends Component {
@service appEvents;
@@ -35,20 +35,26 @@ export default class SolvedUnacceptAnswerButton extends Component {
}
}
+ get answerInfo() {
+ return this.args.post.topic.accepted_answers?.find(
+ (a) => a.post_number === this.args.post.post_number
+ );
+ }
+
get showAcceptedBy() {
return !(
!this.siteSettings.show_who_marked_solved ||
- !this.args.post.topic.accepted_answer.accepter_username
+ !this.answerInfo?.accepter_username
);
}
get acceptedByUsername() {
- return this.args.post.topic.accepted_answer.accepter_username;
+ return this.answerInfo?.accepter_username;
}
get acceptedByDisplayName() {
- const username = this.args.post.topic.accepted_answer.accepter_username;
- const name = this.args.post.topic.accepted_answer.accepter_name;
+ const username = this.answerInfo?.accepter_username;
+ const name = this.answerInfo?.accepter_name;
return this.siteSettings.display_name_on_posts && name ? name : username;
}
@@ -114,12 +120,12 @@ async function unacceptPost(post) {
const topic = post.topic;
try {
- await ajax("/solution/unaccept", {
+ const remainingAcceptedAnswers = await ajax("/solution/unaccept", {
type: "POST",
data: { id: post.id },
});
- setAcceptedSolution(topic, undefined);
+ setAcceptedSolutions(topic, remainingAcceptedAnswers);
} catch (e) {
popupAjaxError(e);
}
diff --git a/plugins/discourse-solved/assets/javascripts/discourse/connectors/topic-navigation/no-answer.gjs b/plugins/discourse-solved/assets/javascripts/discourse/connectors/topic-navigation/no-answer.gjs
index 141916ab43d..75af9a36459 100644
--- a/plugins/discourse-solved/assets/javascripts/discourse/connectors/topic-navigation/no-answer.gjs
+++ b/plugins/discourse-solved/assets/javascripts/discourse/connectors/topic-navigation/no-answer.gjs
@@ -44,7 +44,7 @@ export default class NoAnswer extends Component {
// - topic is old
// - topic has at least one reply from another user that can be accepted
if (
- !topic.accepted_answer &&
+ !topic.accepted_answers?.length &&
currentUser &&
topic.user_id === currentUser.id &&
moment() - moment(topic.created_at) > MAX_DURATION_WITH_NO_ANSWER &&
diff --git a/plugins/discourse-solved/assets/javascripts/discourse/initializers/extend-for-solved-button.gjs b/plugins/discourse-solved/assets/javascripts/discourse/initializers/extend-for-solved-button.gjs
index d3a3ac3a1b7..31ffce1f595 100644
--- a/plugins/discourse-solved/assets/javascripts/discourse/initializers/extend-for-solved-button.gjs
+++ b/plugins/discourse-solved/assets/javascripts/discourse/initializers/extend-for-solved-button.gjs
@@ -4,10 +4,10 @@ import { withPluginApi } from "discourse/lib/plugin-api";
import Category from "discourse/models/category";
import { i18n } from "discourse-i18n";
import SolvedAcceptAnswerButton from "../components/solved-accept-answer-button";
-import SolvedAcceptedAnswer from "../components/solved-accepted-answer";
+import SolvedAcceptedAnswers from "../components/solved-accepted-answers";
import SolvedSharedIssueButton from "../components/solved-shared-issue-button";
import SolvedUnacceptAnswerButton from "../components/solved-unaccept-answer-button";
-import setAcceptedSolution from "../lib/set-accepted-solution";
+import setAcceptedSolutions from "../lib/set-accepted-solutions";
function topicHasSolvedEnabled(topic) {
if (!topic) {
@@ -40,7 +40,7 @@ function initializeWithApi(api) {
}
api.addTrackedTopicProperties(
- "accepted_answer",
+ "accepted_answers",
"has_accepted_answer",
"shared_issue_count",
"user_created_shared_issue",
@@ -78,24 +78,13 @@ function customizePost(api) {
api.renderAfterWrapperOutlet(
"post-content-cooked-html",
- class extends Component {
- static shouldRender(args) {
- return (
- args.post?.post_number === 1 && args.post?.topic?.accepted_answer
- );
- }
-
- <template>
- <SolvedAcceptedAnswer
- @post={{@post}}
- @decoratorState={{@decoratorState}}
- />
- </template>
- }
+ SolvedAcceptedAnswers
);
}
function customizePostMenu(api) {
+ const siteSettings = helperContext().siteSettings;
+
api.registerValueTransformer(
"post-menu-buttons",
({
@@ -115,22 +104,30 @@ function customizePostMenu(api) {
solvedButton = SolvedAcceptAnswerButton;
}
- solvedButton &&
- dag.add(
- "solved",
- solvedButton,
- post.topic_accepted_answer && !post.accepted_answer
- ? {
- before: lastHiddenButtonKey,
- after: secondLastHiddenButtonKey,
- }
- : {
- before: [
- "assign", // button added by the assign plugin
- firstButtonKey,
- ],
- }
- );
+ if (!solvedButton) {
+ return;
+ }
+
+ const collapse =
+ !siteSettings.solved_allow_multiple_solutions &&
+ post.topic_accepted_answer &&
+ !post.accepted_answer;
+
+ dag.add(
+ "solved",
+ solvedButton,
+ collapse
+ ? {
+ before: lastHiddenButtonKey,
+ after: secondLastHiddenButtonKey,
+ }
+ : {
+ before: [
+ "assign", // button added by the assign plugin
+ firstButtonKey,
+ ],
+ }
+ );
}
);
@@ -151,7 +148,7 @@ function handleMessages(api) {
const topic = controller.model;
if (topic) {
- setAcceptedSolution(topic, message.accepted_answer);
+ setAcceptedSolutions(topic, message.accepted_answers);
}
};
diff --git a/plugins/discourse-solved/assets/javascripts/discourse/initializers/solved-category-change-confirmation.gjs b/plugins/discourse-solved/assets/javascripts/discourse/initializers/solved-category-change-confirmation.gjs
index 062e633fbbd..e1c540b957e 100644
--- a/plugins/discourse-solved/assets/javascripts/discourse/initializers/solved-category-change-confirmation.gjs
+++ b/plugins/discourse-solved/assets/javascripts/discourse/initializers/solved-category-change-confirmation.gjs
@@ -45,7 +45,11 @@ export default {
solvedStateChanged = oldAllowed !== newAllowed;
- if (model.accepted_answer && oldAllowed && !newAllowed) {
+ if (
+ model.accepted_answers?.length > 0 &&
+ oldAllowed &&
+ !newAllowed
+ ) {
const showConfirmation =
localStorage.getItem(STORAGE_KEY) !== "true";
diff --git a/plugins/discourse-solved/assets/javascripts/discourse/lib/set-accepted-solution.js b/plugins/discourse-solved/assets/javascripts/discourse/lib/set-accepted-solution.js
deleted file mode 100644
index 6c29998244b..00000000000
--- a/plugins/discourse-solved/assets/javascripts/discourse/lib/set-accepted-solution.js
+++ /dev/null
@@ -1,25 +0,0 @@
-export default function setAcceptedSolution(topic, acceptedAnswer) {
- topic.postStream?.posts?.forEach((post) => {
- if (!acceptedAnswer) {
- post.setProperties({
- accepted_answer: false,
- topic_accepted_answer: false,
- });
- } else if (post.post_number > 1) {
- post.setProperties(
- acceptedAnswer.post_number === post.post_number
- ? {
- accepted_answer: true,
- topic_accepted_answer: true,
- }
- : {
- accepted_answer: false,
- topic_accepted_answer: true,
- }
- );
- }
- });
-
- topic.accepted_answer = acceptedAnswer;
- topic.has_accepted_answer = !!acceptedAnswer;
-}
diff --git a/plugins/discourse-solved/assets/javascripts/discourse/lib/set-accepted-solutions.js b/plugins/discourse-solved/assets/javascripts/discourse/lib/set-accepted-solutions.js
new file mode 100644
index 00000000000..b48e71f7459
--- /dev/null
+++ b/plugins/discourse-solved/assets/javascripts/discourse/lib/set-accepted-solutions.js
@@ -0,0 +1,21 @@
+export default function setAcceptedSolutions(topic, acceptedAnswers) {
+ const acceptedPostNumbers = new Set(
+ acceptedAnswers?.map((answer) => answer.post_number)
+ );
+
+ const topicHasAcceptedAnswer = acceptedPostNumbers.size > 0;
+
+ topic.accepted_answers = acceptedAnswers;
+ topic.has_accepted_answer = topicHasAcceptedAnswer;
+
+ topic.postStream?.posts?.forEach((post) => {
+ if (post.post_number === 1) {
+ return;
+ }
+
+ post.setProperties({
+ accepted_answer: acceptedPostNumbers.has(post.post_number),
+ topic_accepted_answer: topicHasAcceptedAnswer,
+ });
+ });
+}
diff --git a/plugins/discourse-solved/assets/stylesheets/solutions.scss b/plugins/discourse-solved/assets/stylesheets/solutions.scss
index ee8f9d58d62..40b8342550f 100644
--- a/plugins/discourse-solved/assets/stylesheets/solutions.scss
+++ b/plugins/discourse-solved/assets/stylesheets/solutions.scss
@@ -109,140 +109,37 @@ $solved-color: var(--success);
}
}
-.d-solved-answer {
- border-radius: var(--d-border-radius-large);
- background: var(--secondary);
-
- &__header {
- display: flex;
- align-items: center;
- color: var(--secondary);
- background-color: $solved-color;
- padding-left: var(--space-3);
- border-top-left-radius: var(--d-border-radius-large);
- border-top-right-radius: var(--d-border-radius-large);
+.accepted-answers {
+ &.d-post-accordion {
+ --d-post-accordion-header-color: var(--secondary);
+ --d-post-accordion-header-background: #{$solved-color};
+ --d-post-accordion-header-border-color: #{$solved-color};
+ padding-bottom: var(--space-4);
+
+ @include viewport.from(sm) {
+ padding: var(--space-1) var(--topic-body-width-padding) var(--space-4)
+ var(--topic-body-width-padding);
+ }
}
&__title {
display: flex;
align-items: center;
gap: var(--space-2);
+ margin: 0;
text-transform: uppercase;
- font-size: var(--font-down-1);
font-weight: normal;
- margin: 0;
- }
-
- &__controls {
- margin-left: auto;
- display: flex;
- }
-
- &__toggle,
- &__jump {
- .d-icon {
- color: var(--secondary);
- background: transparent;
- font-size: var(--font-down-1-rem);
- }
-
- &:hover,
- &:visited {
- .discourse-no-touch &,
- .discourse-touch & {
- color: var(--secondary);
- background: transparent;
-
- .d-icon {
- color: var(--secondary);
- background: transparent;
- }
- }
- }
-
- &:hover {
- background-color: rgba($solved-color, 0.15);
- }
}
- &__footer {
- display: flex;
- align-items: center;
- gap: var(--space-1);
- padding: var(--space-3);
+ &__solution-count {
font-size: var(--font-down-1);
- color: var(--primary-medium);
- }
-
- &__post-link {
- font-weight: bold;
- }
-
- > blockquote {
- position: relative;
- background: var(--secondary);
- border: 0;
- padding: var(--space-3);
- max-height: calc(
- var(--solved-max-lines, 14) * var(--cooked-line-height) * 1em
- ); // solved-max-lines set in solved-accepted-answer.gjs
- overflow: hidden;
- margin: 0;
- border-left: 1px solid var(--primary-low);
- border-right: 1px solid var(--primary-low);
-
- * {
- font-size: var(--font-down-1-rem) !important;
- }
-
- .cooked {
- padding: 0 !important;
- }
-
- .anchor::before {
- content: "" !important;
- display: none;
- }
-
- &::after {
- content: "";
- position: absolute;
- bottom: 0;
- left: 0;
- right: 0;
- height: 3em;
- background: linear-gradient(transparent, var(--secondary));
- pointer-events: none;
- }
- }
-
- &__footer {
- border: 1px solid var(--primary-low);
- white-space: nowrap;
- }
-
- &__solver,
- &__accepter {
- @include ellipsis;
- }
-
- &[data-expanded="true"] > blockquote,
- &[data-overflowing="false"] > blockquote {
- max-height: none;
- overflow: visible;
-
- &::after {
- display: none;
- }
- }
-
- &:not(.accepted-answer--has-excerpt) > blockquote {
- display: none;
}
}
.solved-shared-issue-row {
- padding-left: var(--topic-body-width-padding);
+ @include viewport.from(sm) {
+ padding-left: var(--topic-body-width-padding);
+ }
}
.solved-shared-issue-row .post-action-menu__solved-shared-issue {
diff --git a/plugins/discourse-solved/config/locales/server.en.yml b/plugins/discourse-solved/config/locales/server.en.yml
index 93e6f57c63d..a19d84411c6 100644
--- a/plugins/discourse-solved/config/locales/server.en.yml
+++ b/plugins/discourse-solved/config/locales/server.en.yml
@@ -24,6 +24,7 @@ en:
site_settings:
solved_enabled: "Enable solved plugin, allow users to select solutions for topics"
+ solved_allow_multiple_solutions: "Allow multiple solutions to be accepted in each topic"
allow_solved_on_all_topics: "Allow users to select solutions on all topics (when unchecked, solutions can be enabled per category or tag)"
allow_solved_in_groups: "Allow marking solutions in group messages for these groups."
accept_all_solutions_trust_level: "Minimum trust level required to accept solutions on any topic (even when not OP)"
diff --git a/plugins/discourse-solved/config/settings.yml b/plugins/discourse-solved/config/settings.yml
index cd57cdcf550..99d81bd47ac 100644
--- a/plugins/discourse-solved/config/settings.yml
+++ b/plugins/discourse-solved/config/settings.yml
@@ -2,6 +2,10 @@ discourse_solved:
solved_enabled:
default: true
client: true
+ solved_allow_multiple_solutions:
+ default: false
+ client: true
+ hidden: true
show_who_marked_solved:
default: false
client: true
diff --git a/plugins/discourse-solved/db/fixtures/001_badges.rb b/plugins/discourse-solved/db/fixtures/001_badges.rb
index 7addd2b202e..3055ad0512c 100644
--- a/plugins/discourse-solved/db/fixtures/001_badges.rb
+++ b/plugins/discourse-solved/db/fixtures/001_badges.rb
@@ -3,10 +3,11 @@
first_solution_query = <<~SQL
SELECT post_id, user_id, created_at AS granted_at
FROM (
- SELECT p.id AS post_id, p.user_id, dsst.created_at,
- ROW_NUMBER() OVER (PARTITION BY p.user_id ORDER BY dsst.created_at) AS row_number
+ SELECT p.id AS post_id, p.user_id, dsta.created_at,
+ ROW_NUMBER() OVER (PARTITION BY p.user_id ORDER BY dsta.created_at) AS row_number
FROM discourse_solved_solved_topics dsst
- JOIN badge_posts p ON dsst.answer_post_id = p.id
+ JOIN discourse_solved_topic_answers dsta ON dsta.solved_topic_id = dsst.id
+ JOIN badge_posts p ON dsta.answer_post_id = p.id
JOIN topics t ON p.topic_id = t.id
WHERE p.user_id <> t.user_id -- ignore topics solved by OP
AND (:backfill OR p.id IN (:post_ids))
@@ -31,9 +32,10 @@ end
def solved_query_with_count(min_count)
<<~SQL
- SELECT p.user_id, MAX(dsst.created_at) AS granted_at
+ SELECT p.user_id, MAX(dsta.created_at) AS granted_at
FROM discourse_solved_solved_topics dsst
- JOIN badge_posts p ON dsst.answer_post_id = p.id
+ JOIN discourse_solved_topic_answers dsta ON dsta.solved_topic_id = dsst.id
+ JOIN badge_posts p ON dsta.answer_post_id = p.id
JOIN topics t ON p.topic_id = t.id
WHERE p.user_id <> t.user_id -- ignore topics solved by OP
AND (:backfill OR p.id IN (:post_ids))
diff --git a/plugins/discourse-solved/db/migrate/20260408165014_add_discourse_solved_topic_answers.rb b/plugins/discourse-solved/db/migrate/20260408165014_add_discourse_solved_topic_answers.rb
new file mode 100644
index 00000000000..4dc79f14c77
--- /dev/null
+++ b/plugins/discourse-solved/db/migrate/20260408165014_add_discourse_solved_topic_answers.rb
@@ -0,0 +1,185 @@
+# frozen_string_literal: true
+class AddDiscourseSolvedTopicAnswers < ActiveRecord::Migration[8.0]
+ def up
+ create_table :discourse_solved_topic_answers do |t|
+ t.bigint :solved_topic_id, null: false
+ t.bigint :answer_post_id, null: false
+ t.bigint :accepter_user_id, null: false
+ t.timestamps
+ end
+
+ add_index :discourse_solved_topic_answers, :solved_topic_id
+ add_index :discourse_solved_topic_answers, :answer_post_id, unique: true
+
+ execute <<~SQL
+ INSERT INTO discourse_solved_topic_answers
+ (solved_topic_id, answer_post_id, accepter_user_id, created_at, updated_at)
+ SELECT id, answer_post_id, accepter_user_id, created_at, updated_at
+ FROM discourse_solved_solved_topics
+ WHERE answer_post_id IS NOT NULL
+ SQL
+
+ change_column :discourse_solved_solved_topics, :topic_id, :bigint
+
+ # Allow null until post deploy migration when columns are removed
+ change_column_null :discourse_solved_solved_topics, :answer_post_id, true
+ change_column_null :discourse_solved_solved_topics, :accepter_user_id, true
+
+ execute <<~SQL
+ DROP TRIGGER IF EXISTS solved_trigger_old_answers_to_new
+ ON discourse_solved_solved_topics;
+ DROP TRIGGER IF EXISTS solved_trigger_old_answer_deletes_to_new
+ ON discourse_solved_solved_topics;
+ DROP TRIGGER IF EXISTS solved_trigger_new_answers_to_old
+ ON discourse_solved_solved_topics;
+ DROP TRIGGER IF EXISTS solved_trigger_new_answer_deletes_to_old
+ ON discourse_solved_solved_topics;
+ SQL
+
+ # Sync accepted answers in old code to the new model
+ execute <<~SQL
+ CREATE OR REPLACE FUNCTION solved_sync_old_answers_to_new()
+ RETURNS TRIGGER AS $$
+ BEGIN
+ INSERT INTO discourse_solved_topic_answers
+ (solved_topic_id, answer_post_id, accepter_user_id, created_at, updated_at)
+ VALUES
+ (NEW.id, NEW.answer_post_id, NEW.accepter_user_id, NEW.created_at, NEW.updated_at)
+ ON CONFLICT (answer_post_id) DO UPDATE SET
+ solved_topic_id = EXCLUDED.solved_topic_id,
+ accepter_user_id = EXCLUDED.accepter_user_id,
+ updated_at = now();
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql;
+ SQL
+
+ execute <<~SQL
+ CREATE TRIGGER solved_trigger_old_answers_to_new
+ AFTER INSERT OR UPDATE OF answer_post_id ON discourse_solved_solved_topics
+ FOR EACH ROW
+ WHEN (pg_trigger_depth() < 1 AND NEW.answer_post_id IS NOT NULL)
+ EXECUTE FUNCTION solved_sync_old_answers_to_new();
+ SQL
+
+ # Sync unaccepted answers in old code to the new model
+ execute <<~SQL
+ CREATE OR REPLACE FUNCTION solved_sync_old_answer_deletes_to_new()
+ RETURNS TRIGGER AS $$
+ BEGIN
+ DELETE FROM discourse_solved_topic_answers WHERE solved_topic_id = OLD.id;
+ RETURN OLD;
+ END;
+ $$ LANGUAGE plpgsql;
+ SQL
+
+ execute <<~SQL
+ CREATE TRIGGER solved_trigger_old_answer_deletes_to_new
+ AFTER DELETE ON discourse_solved_solved_topics
+ FOR EACH ROW
+ WHEN (pg_trigger_depth() < 1)
+ EXECUTE FUNCTION solved_sync_old_answer_deletes_to_new();
+ SQL
+
+ # Sync accepted answers in new code to the old model (use newest accepted answer)
+ execute <<~SQL
+ CREATE OR REPLACE FUNCTION solved_sync_new_answers_to_old()
+ RETURNS TRIGGER AS $$
+ BEGIN
+ UPDATE discourse_solved_solved_topics
+ SET answer_post_id = NEW.answer_post_id,
+ accepter_user_id = NEW.accepter_user_id
+ WHERE id = NEW.solved_topic_id;
+
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql;
+ SQL
+
+ execute <<~SQL
+ CREATE TRIGGER solved_trigger_new_answers_to_old
+ AFTER INSERT ON discourse_solved_topic_answers
+ FOR EACH ROW
+ WHEN (pg_trigger_depth() < 1)
+ EXECUTE FUNCTION solved_sync_new_answers_to_old();
+ SQL
+
+ # Sync unaccepted answers in new code to the old model
+ # If any TopicAnswers are left, store the newest one in the SolvedTopic.
+ # If not, then the SolvedTopic is about to be deleted in either
+ # UnacceptAnswer.unmark_as_solved or AcceptAnswer.revoke_previous_accepted_answer
+ execute <<~SQL
+ CREATE OR REPLACE FUNCTION solved_sync_new_answer_deletes_to_old()
+ RETURNS TRIGGER AS $$
+ BEGIN
+ UPDATE discourse_solved_solved_topics sst
+ SET answer_post_id = ta.answer_post_id,
+ accepter_user_id = ta.accepter_user_id
+ FROM (
+ SELECT answer_post_id, accepter_user_id
+ FROM discourse_solved_topic_answers
+ WHERE solved_topic_id = OLD.solved_topic_id
+ ORDER BY created_at DESC
+ LIMIT 1
+ ) ta
+ WHERE sst.id = OLD.solved_topic_id;
+
+ RETURN OLD;
+ END;
+ $$ LANGUAGE plpgsql;
+ SQL
+
+ execute <<~SQL
+ CREATE TRIGGER solved_trigger_new_answer_deletes_to_old
+ AFTER DELETE ON discourse_solved_topic_answers
+ FOR EACH ROW
+ WHEN (pg_trigger_depth() < 1)
+ EXECUTE FUNCTION solved_sync_new_answer_deletes_to_old();
+ SQL
+ end
+
+ def down
+ execute <<~SQL
+ DROP TRIGGER IF EXISTS solved_trigger_old_answers_to_new
+ ON discourse_solved_solved_topics;
+ DROP TRIGGER IF EXISTS solved_trigger_old_answer_deletes_to_new
+ ON discourse_solved_solved_topics;
+ DROP TRIGGER IF EXISTS solved_trigger_new_answers_to_old
+ ON discourse_solved_topic_answers;
+ DROP TRIGGER IF EXISTS solved_trigger_new_answer_deletes_to_old
+ ON discourse_solved_topic_answers;
+ DROP FUNCTION IF EXISTS solved_sync_old_answers_to_new();
+ DROP FUNCTION IF EXISTS solved_sync_old_answer_deletes_to_new();
+ DROP FUNCTION IF EXISTS solved_sync_new_answers_to_old();
+ DROP FUNCTION IF EXISTS solved_sync_new_answer_deletes_to_old();
+ SQL
+
+ # Backfill legacy columns from topic_answers before restoring NOT NULL.
+ # If a topic has multiple solutions, keep only the most recent.
+ execute <<~SQL
+ UPDATE discourse_solved_solved_topics st
+ SET answer_post_id = latest.answer_post_id,
+ accepter_user_id = latest.accepter_user_id
+ FROM (
+ SELECT DISTINCT ON (solved_topic_id)
+ solved_topic_id, answer_post_id, accepter_user_id
+ FROM discourse_solved_topic_answers
+ ORDER BY solved_topic_id, created_at DESC
+ ) latest
+ WHERE st.id = latest.solved_topic_id
+ SQL
+
+ # Drop any orphaned solved_topic rows with no remaining answers as a failsafe
+ # before restoring the not null constraints
+ execute <<~SQL
+ DELETE FROM discourse_solved_solved_topics
+ WHERE answer_post_id IS NULL OR accepter_user_id IS NULL
+ SQL
+
+ change_column :discourse_solved_solved_topics, :topic_id, :bigint
+ change_column_null :discourse_solved_solved_topics, :accepter_user_id, false
+ change_column_null :discourse_solved_solved_topics, :answer_post_id, false
+
+ drop_table :discourse_solved_topic_answers
+ end
+end
diff --git a/plugins/discourse-solved/db/post_migrate/20260408214007_drop_multiple_solutions_dual_write_triggers.rb b/plugins/discourse-solved/db/post_migrate/20260408214007_drop_multiple_solutions_dual_write_triggers.rb
new file mode 100644
index 00000000000..553b99590bf
--- /dev/null
+++ b/plugins/discourse-solved/db/post_migrate/20260408214007_drop_multiple_solutions_dual_write_triggers.rb
@@ -0,0 +1,157 @@
+# frozen_string_literal: true
+class DropMultipleSolutionsDualWriteTriggers < ActiveRecord::Migration[8.0]
+ def up
+ execute <<~SQL
+ DROP TRIGGER IF EXISTS solved_trigger_old_answers_to_new
+ ON discourse_solved_solved_topics;
+ DROP TRIGGER IF EXISTS solved_trigger_old_answer_deletes_to_new
+ ON discourse_solved_solved_topics;
+ DROP TRIGGER IF EXISTS solved_trigger_new_answers_to_old
+ ON discourse_solved_topic_answers;
+ DROP TRIGGER IF EXISTS solved_trigger_new_answer_deletes_to_old
+ ON discourse_solved_topic_answers;
+ DROP FUNCTION IF EXISTS solved_sync_old_answers_to_new();
+ DROP FUNCTION IF EXISTS solved_sync_old_answer_deletes_to_new();
+ DROP FUNCTION IF EXISTS solved_sync_new_answers_to_old();
+ DROP FUNCTION IF EXISTS solved_sync_new_answer_deletes_to_old();
+ SQL
+
+ # Failsafe to backfill answers which weren't caught by the triggers just in case
+ execute <<~SQL
+ INSERT INTO discourse_solved_topic_answers
+ (solved_topic_id, answer_post_id, accepter_user_id, created_at, updated_at)
+ SELECT st.id, st.answer_post_id, st.accepter_user_id, st.created_at, st.updated_at
+ FROM discourse_solved_solved_topics st
+ WHERE st.answer_post_id IS NOT NULL
+ AND NOT EXISTS (
+ SELECT 1 FROM discourse_solved_topic_answers ta
+ WHERE ta.solved_topic_id = st.id
+ AND ta.answer_post_id = st.answer_post_id
+ )
+ ON CONFLICT (answer_post_id) DO NOTHING
+ SQL
+
+ # Failsafe to clean up any orphaned topic_answers
+ execute <<~SQL
+ DELETE FROM discourse_solved_topic_answers ta
+ WHERE NOT EXISTS (
+ SELECT 1 FROM discourse_solved_solved_topics st WHERE st.id = ta.solved_topic_id
+ )
+ SQL
+ end
+
+ def down
+ # Recreate the dual write triggers, as defined in AddDiscourseSolvedTopicAnswers
+ execute <<~SQL
+ DROP TRIGGER IF EXISTS solved_trigger_old_answers_to_new
+ ON discourse_solved_solved_topics;
+ DROP TRIGGER IF EXISTS solved_trigger_old_answer_deletes_to_new
+ ON discourse_solved_solved_topics;
+ DROP TRIGGER IF EXISTS solved_trigger_new_answers_to_old
+ ON discourse_solved_solved_topics;
+ DROP TRIGGER IF EXISTS solved_trigger_new_answer_deletes_to_old
+ ON discourse_solved_solved_topics;
+ SQL
+
+ # Sync accepted answers in old code to the new model
+ execute <<~SQL
+ CREATE OR REPLACE FUNCTION solved_sync_old_answers_to_new()
+ RETURNS TRIGGER AS $$
+ BEGIN
+ INSERT INTO discourse_solved_topic_answers
+ (solved_topic_id, answer_post_id, accepter_user_id, created_at, updated_at)
+ VALUES
+ (NEW.id, NEW.answer_post_id, NEW.accepter_user_id, NEW.created_at, NEW.updated_at)
+ ON CONFLICT (answer_post_id) DO UPDATE SET
+ solved_topic_id = EXCLUDED.solved_topic_id,
+ accepter_user_id = EXCLUDED.accepter_user_id,
+ updated_at = now();
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql;
+ SQL
+
+ execute <<~SQL
+ CREATE TRIGGER solved_trigger_old_answers_to_new
+ AFTER INSERT OR UPDATE OF answer_post_id ON discourse_solved_solved_topics
+ FOR EACH ROW
+ WHEN (pg_trigger_depth() < 1 AND NEW.answer_post_id IS NOT NULL)
+ EXECUTE FUNCTION solved_sync_old_answers_to_new();
+ SQL
+
+ # Sync unaccepted answers in old code to the new model
+ execute <<~SQL
+ CREATE OR REPLACE FUNCTION solved_sync_old_answer_deletes_to_new()
+ RETURNS TRIGGER AS $$
+ BEGIN
+ DELETE FROM discourse_solved_topic_answers WHERE solved_topic_id = OLD.id;
+ RETURN OLD;
+ END;
+ $$ LANGUAGE plpgsql;
+ SQL
+
+ execute <<~SQL
+ CREATE TRIGGER solved_trigger_old_answer_deletes_to_new
+ AFTER DELETE ON discourse_solved_solved_topics
+ FOR EACH ROW
+ WHEN (pg_trigger_depth() < 1)
+ EXECUTE FUNCTION solved_sync_old_answer_deletes_to_new();
+ SQL
+
+ # Sync accepted answers in new code to the old model (use newest accepted answer)
+ execute <<~SQL
+ CREATE OR REPLACE FUNCTION solved_sync_new_answers_to_old()
+ RETURNS TRIGGER AS $$
+ BEGIN
+ UPDATE discourse_solved_solved_topics
+ SET answer_post_id = NEW.answer_post_id,
+ accepter_user_id = NEW.accepter_user_id
+ WHERE id = NEW.solved_topic_id;
+
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql;
+ SQL
+
+ execute <<~SQL
+ CREATE TRIGGER solved_trigger_new_answers_to_old
+ AFTER INSERT ON discourse_solved_topic_answers
+ FOR EACH ROW
+ WHEN (pg_trigger_depth() < 1)
+ EXECUTE FUNCTION solved_sync_new_answers_to_old();
+ SQL
+
+ # Sync unaccepted answers in new code to the old model
+ # If any TopicAnswers are left, store the newest one in the SolvedTopic.
+ # If not, then the SolvedTopic is about to be deleted in either
+ # UnacceptAnswer.unmark_as_solved or AcceptAnswer.revoke_previous_accepted_answer
+ execute <<~SQL
+ CREATE OR REPLACE FUNCTION solved_sync_new_answer_deletes_to_old()
+ RETURNS TRIGGER AS $$
+ BEGIN
+ UPDATE discourse_solved_solved_topics sst
+ SET answer_post_id = ta.answer_post_id,
+ accepter_user_id = ta.accepter_user_id
+ FROM (
+ SELECT answer_post_id, accepter_user_id
+ FROM discourse_solved_topic_answers
+ WHERE solved_topic_id = OLD.solved_topic_id
+ ORDER BY created_at DESC
+ LIMIT 1
+ ) ta
+ WHERE sst.id = OLD.solved_topic_id;
+
+ RETURN OLD;
+ END;
+ $$ LANGUAGE plpgsql;
+ SQL
+
+ execute <<~SQL
+ CREATE TRIGGER solved_trigger_new_answer_deletes_to_old
+ AFTER DELETE ON discourse_solved_topic_answers
+ FOR EACH ROW
+ WHEN (pg_trigger_depth() < 1)
+ EXECUTE FUNCTION solved_sync_new_answer_deletes_to_old();
+ SQL
+ end
+end
diff --git a/plugins/discourse-solved/lib/discourse_solved/accepted_answers_helper.rb b/plugins/discourse-solved/lib/discourse_solved/accepted_answers_helper.rb
new file mode 100644
index 00000000000..5c5d41b70a6
--- /dev/null
+++ b/plugins/discourse-solved/lib/discourse_solved/accepted_answers_helper.rb
@@ -0,0 +1,32 @@
+# frozen_string_literal: true
+
+module DiscourseSolved
+ module AcceptedAnswersHelper
+ def self.serialize(topic, guardian)
+ return nil unless topic.topic_answers&.any?
+
+ ActiveRecord::Associations::Preloader.new(
+ records: [topic.solved],
+ associations: {
+ topic_answers: [{ post: :user }, :accepter],
+ },
+ ).call
+
+ answers =
+ topic
+ .topic_answers
+ .select { |ta| ta.post.present? }
+ .sort_by { |ta| ta.post.created_at }
+ .map do |ta|
+ AcceptedAnswerSerializer.new(
+ ta.post,
+ scope: guardian,
+ root: false,
+ accepter: ta.accepter,
+ ).as_json
+ end
+
+ answers.presence
+ end
+ end
+end
diff --git a/plugins/discourse-solved/lib/discourse_solved/first_accepted_post_solution_validator.rb b/plugins/discourse-solved/lib/discourse_solved/first_accepted_post_solution_validator.rb
index ae2b4b42b43..890ec5222e1 100644
--- a/plugins/discourse-solved/lib/discourse_solved/first_accepted_post_solution_validator.rb
+++ b/plugins/discourse-solved/lib/discourse_solved/first_accepted_post_solution_validator.rb
@@ -10,8 +10,8 @@ module DiscourseSolved
return false
end
- !DiscourseSolved::SolvedTopic
- .joins(:answer_post)
+ !DiscourseSolved::TopicAnswer
+ .joins(:post)
.where("posts.user_id = ? AND posts.id != ?", post.user_id, post.id)
.exists?
end
diff --git a/plugins/discourse-solved/lib/discourse_solved/guardian_extensions.rb b/plugins/discourse-solved/lib/discourse_solved/guardian_extensions.rb
index e7574e9c1e0..33ffb3cffdf 100644
--- a/plugins/discourse-solved/lib/discourse_solved/guardian_extensions.rb
+++ b/plugins/discourse-solved/lib/discourse_solved/guardian_extensions.rb
@@ -49,13 +49,15 @@ module DiscourseSolved
end
def can_unaccept_answer?(topic, post)
- can_accept_answer?(topic, post) || (is_staff? && topic&.solved.present?)
+ can_accept_answer?(topic, post) ||
+ (is_staff? && topic&.topic_answers&.exists?(answer_post_id: post.id))
end
def can_create_shared_issue?(topic)
return false if topic.blank? || !authenticated?
return false if topic.user_id == current_user.id
- return false if topic.private_message? || topic.solved.present?
+ return false if topic.private_message?
+ return false if topic.solved.present? && !SiteSetting.solved_allow_multiple_solutions
return false unless topic_in_support_category?(topic)
return false unless current_user.upcoming_change_enabled?(:enable_solved_shared_issues)
can_see_topic?(topic)
diff --git a/plugins/discourse-solved/lib/discourse_solved/post_mover_extension.rb b/plugins/discourse-solved/lib/discourse_solved/post_mover_extension.rb
index d74f945107e..291767401be 100644
--- a/plugins/discourse-solved/lib/discourse_solved/post_mover_extension.rb
+++ b/plugins/discourse-solved/lib/discourse_solved/post_mover_extension.rb
@@ -6,21 +6,35 @@ module DiscourseSolved
# original_topic, post_ids, and user are attr_readers on PostMover
def move_posts_to(topic)
- solved_topic = DiscourseSolved::SolvedTopic.find_by(topic_id: original_topic.id)
-
- if solved_topic && post_ids.include?(solved_topic.answer_post_id)
- accepts_answers = Guardian.new(user).allow_accepted_answers?(topic)
- has_no_solution = !DiscourseSolved::SolvedTopic.exists?(topic_id: topic.id)
-
- if accepts_answers && has_no_solution
- solved_topic.update!(topic_id: topic.id)
- else
- DiscourseSolved::UnacceptAnswer.call(
- params: {
- post_id: solved_topic.answer_post_id,
- },
- guardian: Discourse.system_user.guardian,
- )
+ solved_topic = DiscourseSolved::SolvedTopic.find_by(topic: original_topic)
+
+ if solved_topic
+ topic_answers_to_move = solved_topic.topic_answers.where(answer_post_id: post_ids)
+
+ if topic_answers_to_move.any?
+ target_allows_answers = Guardian.new(user).allow_accepted_answers?(topic)
+ target_solved_topic =
+ DiscourseSolved::SolvedTopic.find_or_create_by!(topic: topic) if target_allows_answers
+
+ topic_answers_to_move.each do |ta|
+ target_can_have_more_answers =
+ SiteSetting.solved_allow_multiple_solutions ||
+ !target_solved_topic&.topic_answers&.reload.present?
+
+ if target_allows_answers && target_can_have_more_answers
+ ta.update!(solved_topic: target_solved_topic)
+ else
+ DiscourseSolved::UnacceptAnswer.call(
+ params: {
+ post_id: ta.answer_post_id,
+ },
+ guardian: Discourse.system_user.guardian,
+ )
+ end
+ end
+
+ solved_topic = DiscourseSolved::SolvedTopic.find_by(id: solved_topic.id)
+ solved_topic&.destroy! if solved_topic&.topic_answers&.none?
end
end
diff --git a/plugins/discourse-solved/lib/discourse_solved/queries.rb b/plugins/discourse-solved/lib/discourse_solved/queries.rb
index 29d66ebd729..d170cdfc2f1 100644
--- a/plugins/discourse-solved/lib/discourse_solved/queries.rb
+++ b/plugins/discourse-solved/lib/discourse_solved/queries.rb
@@ -4,7 +4,8 @@ module DiscourseSolved
module Queries
def self.solved_count(user_id)
DiscourseSolved::SolvedTopic
- .joins(answer_post: :user, topic: {})
+ .joins(topic_answers: :post)
+ .joins(:topic)
.where(posts: { user_id: user_id, deleted_at: nil })
.where(topics: { archetype: Archetype.default, deleted_at: nil })
.count
diff --git a/plugins/discourse-solved/lib/discourse_solved/schema_utils.rb b/plugins/discourse-solved/lib/discourse_solved/schema_utils.rb
index ad06db59344..36cbdb26341 100644
--- a/plugins/discourse-solved/lib/discourse_solved/schema_utils.rb
+++ b/plugins/discourse-solved/lib/discourse_solved/schema_utils.rb
@@ -49,7 +49,7 @@ module DiscourseSolved
return nil unless qa_page_schema?(topic)
return { data: { qa_question: true } } if post.is_first_post?
return {} unless eligible_answer?(post)
- if accepted_answer_visible?(topic) && topic.solved.answer_post_id == post.id
+ if accepted_answer_visible?(topic) && topic.topic_answers.exists?(answer_post_id: post.id)
{ itemprop: "acceptedAnswer", itemscope: true, itemtype: "https://schema.org/Answer" }
else
{ itemprop: "suggestedAnswer", itemscope: true, itemtype: "https://schema.org/Answer" }
@@ -72,8 +72,7 @@ module DiscourseSolved
end
private_class_method def self.accepted_answer_visible?(topic)
- post = topic.solved&.answer_post
- post.present? && Guardian.new.can_see_post?(post)
+ topic.solved&.answer_posts&.any? { |post| Guardian.new.can_see_post?(post) }
end
private_class_method def self.eligible_answers(topic)
diff --git a/plugins/discourse-solved/lib/discourse_solved/topic_extension.rb b/plugins/discourse-solved/lib/discourse_solved/topic_extension.rb
index 5dbacbd7b11..6fdfd3171c7 100644
--- a/plugins/discourse-solved/lib/discourse_solved/topic_extension.rb
+++ b/plugins/discourse-solved/lib/discourse_solved/topic_extension.rb
@@ -16,33 +16,7 @@ module DiscourseSolved::TopicExtension
hours.zero? ? SiteSetting.solved_topics_auto_close_hours : hours
end
- def accepted_answer_post_info
- return unless solved
- return unless answer_post = solved.answer_post
-
- answer_post_user = answer_post.user || Discourse.system_user
- accepter = solved.accepter || user || Discourse.system_user
-
- excerpt = SiteSetting.solved_quote_length > 0 ? answer_post.cooked : nil
-
- accepted_answer = {
- post_number: answer_post.post_number,
- username: answer_post_user.username,
- name: answer_post_user.name,
- avatar_template: answer_post_user.avatar_template,
- excerpt:,
- }
-
- if SiteSetting.show_who_marked_solved
- accepted_answer[:accepter_name] = accepter.name
- accepted_answer[:accepter_username] = accepter.username
- end
-
- if !SiteSetting.enable_names || !SiteSetting.display_name_on_posts
- accepted_answer[:name] = nil
- accepted_answer[:accepter_name] = nil
- end
-
- accepted_answer
+ def topic_answers
+ solved&.topic_answers || DiscourseSolved::TopicAnswer.none
end
end
diff --git a/plugins/discourse-solved/lib/discourse_solved/topic_posters_summary_extension.rb b/plugins/discourse-solved/lib/discourse_solved/topic_posters_summary_extension.rb
index edbed74d99d..1b523ef4cd8 100644
--- a/plugins/discourse-solved/lib/discourse_solved/topic_posters_summary_extension.rb
+++ b/plugins/discourse-solved/lib/discourse_solved/topic_posters_summary_extension.rb
@@ -7,7 +7,7 @@ module DiscourseSolved::TopicPostersSummaryExtension
if !defined?(@descriptions_by_id)
super(ids: old_user_ids)
- if id = topic.accepted_answer_user_id
+ Array(topic.accepted_answer_user_ids).each do |id|
@descriptions_by_id[id] ||= []
@descriptions_by_id[id] << I18n.t(:accepted_answer)
end
@@ -17,14 +17,11 @@ module DiscourseSolved::TopicPostersSummaryExtension
end
def last_poster_is_topic_creator?
- super || topic.accepted_answer_user_id == topic.last_post_user_id
+ super || Array(topic.accepted_answer_user_ids).include?(topic.last_post_user_id)
end
def user_ids
- if id = topic.accepted_answer_user_id
- super.insert(1, id)
- else
- super
- end
+ ids = Array(topic.accepted_answer_user_ids)
+ ids.any? ? super.insert(1, *ids) : super
end
end
diff --git a/plugins/discourse-solved/lib/discourse_solved/topic_view_serializer_extension.rb b/plugins/discourse-solved/lib/discourse_solved/topic_view_serializer_extension.rb
index d771af82ab6..42458465526 100644
--- a/plugins/discourse-solved/lib/discourse_solved/topic_view_serializer_extension.rb
+++ b/plugins/discourse-solved/lib/discourse_solved/topic_view_serializer_extension.rb
@@ -3,14 +3,13 @@
module DiscourseSolved::TopicViewSerializerExtension
extend ActiveSupport::Concern
- prepended { attributes :accepted_answer }
+ prepended { attributes :accepted_answers }
- def include_accepted_answer?
- SiteSetting.solved_enabled? && object.topic.solved.present? &&
- object.topic.solved.answer_post.present?
+ def include_accepted_answers?
+ SiteSetting.solved_enabled? && object.topic.topic_answers.any?
end
- def accepted_answer
- object.topic.accepted_answer_post_info
+ def accepted_answers
+ DiscourseSolved::AcceptedAnswersHelper.serialize(object.topic, scope)
end
end
diff --git a/plugins/discourse-solved/plugin.rb b/plugins/discourse-solved/plugin.rb
index 3631418fdea..9602495beeb 100644
--- a/plugins/discourse-solved/plugin.rb
+++ b/plugins/discourse-solved/plugin.rb
@@ -56,7 +56,7 @@ after_initialize do
::PostMover.prepend(DiscourseSolved::PostMoverExtension)
::UserSummary.prepend(DiscourseSolved::UserSummaryExtension)
- ::Topic.attr_accessor(:accepted_answer_user_id)
+ ::Topic.attr_accessor(:accepted_answer_user_ids)
::TopicPostersSummary.alias_method(:old_user_ids, :user_ids)
::TopicPostersSummary.prepend(DiscourseSolved::TopicPostersSummaryExtension)
[
@@ -68,9 +68,28 @@ after_initialize do
].each { |klass| klass.include(DiscourseSolved::TopicAnswerMixin) }
end
- register_category_list_topics_preloader_associations(:solved) if SiteSetting.solved_enabled
- register_topic_preloader_associations(:solved) if SiteSetting.solved_enabled
- Search.custom_topic_eager_load { [:solved] } if SiteSetting.solved_enabled
+ solved_topic_answer_preload = { solved: :topic_answers }
+
+ if SiteSetting.solved_enabled
+ register_category_list_topics_preloader_associations(solved_topic_answer_preload)
+ register_topic_preloader_associations(solved_topic_answer_preload)
+ Search.custom_topic_eager_load { [solved_topic_answer_preload] }
+ end
+
+ TopicView.on_preload do |topic_view|
+ next unless SiteSetting.solved_enabled
+
+ solved = topic_view.topic.solved
+ next unless solved
+
+ ActiveRecord::Associations::Preloader.new(
+ records: [solved],
+ associations: {
+ topic_answers: [{ post: :user }, :accepter],
+ },
+ ).call
+ end
+
Site.preloaded_category_custom_fields << DiscourseSolved::ENABLE_ACCEPTED_ANSWERS_CUSTOM_FIELD
Site.preloaded_category_custom_fields << DiscourseSolved::NOTIFY_ON_STAFF_ACCEPT_SOLVED_CUSTOM_FIELD
Site.preloaded_category_custom_fields << DiscourseSolved::EMPTY_BOX_ON_UNSOLVED_CUSTOM_FIELD
@@ -229,7 +248,9 @@ after_initialize do
add_to_serializer(:post, :can_unaccept_answer) do
scope.can_unaccept_answer?(topic, object) && accepted_answer
end
- add_to_serializer(:post, :accepted_answer) { topic&.solved&.answer_post_id == object.id }
+ add_to_serializer(:post, :accepted_answer) do
+ topic&.topic_answers&.any? { |topic_answer| topic_answer.answer_post_id == object.id }
+ end
add_to_serializer(:post, :topic_accepted_answer) { topic&.solved&.present? }
add_to_serializer(
@@ -291,16 +312,13 @@ after_initialize do
options[:refresh_stream] = true
if !new_allowed
- if topic.solved.present?
- post = topic.solved.answer_post
- if post
- DiscourseSolved::UnacceptAnswer.call(
- params: {
- post_id: post.id,
- },
- guardian: Discourse.system_user.guardian,
- )
- end
+ topic.topic_answers.each do |ta|
+ DiscourseSolved::UnacceptAnswer.call(
+ params: {
+ post_id: ta.answer_post_id,
+ },
+ guardian: Discourse.system_user.guardian,
+ )
end
end
end
@@ -312,23 +330,25 @@ after_initialize do
WHERE di.period_type = :period_type AND di.solutions IS NOT NULL;
WITH x AS (
- SELECT p.user_id, COUNT(DISTINCT st.id) AS solutions
+ SELECT p.user_id, COUNT(DISTINCT sta.id) AS solutions
FROM discourse_solved_solved_topics AS st
+ JOIN discourse_solved_topic_answers AS sta
+ ON sta.solved_topic_id = st.id
+ AND COALESCE(sta.created_at, :since) > :since
JOIN posts AS p
- ON p.id = st.answer_post_id
- AND COALESCE(st.created_at, :since) > :since
- AND p.deleted_at IS NULL
+ ON p.id = sta.answer_post_id
+ AND p.deleted_at IS NULL
JOIN topics AS t
- ON t.id = st.topic_id
- AND t.archetype <> 'private_message'
- AND t.deleted_at IS NULL
+ ON t.id = st.topic_id
+ AND t.archetype <> 'private_message'
+ AND t.deleted_at IS NULL
JOIN users AS u
- ON u.id = p.user_id
- WHERE u.id > 0
- AND u.active
- AND u.silenced_till IS NULL
- AND u.suspended_till IS NULL
- GROUP BY p.user_id
+ ON u.id = p.user_id
+ WHERE u.id > 0
+ AND u.active
+ AND u.silenced_till IS NULL
+ AND u.suspended_till IS NULL
+ GROUP BY p.user_id
)
UPDATE directory_items di
SET solutions = x.solutions
@@ -356,15 +376,19 @@ after_initialize do
register_topic_list_preload_user_ids do |topics, user_ids|
# [{ topic_id => answer_user_id }, ... ]
- topics_with_answer_poster =
+ topics_with_answer_users =
DiscourseSolved::SolvedTopic
- .joins(:answer_post)
+ .joins(topic_answers: :post)
.where(topic_id: topics.map(&:id))
- .pluck(:topic_id, "posts.user_id")
- .to_h
+ .distinct
+ .pluck("discourse_solved_solved_topics.topic_id", "posts.user_id")
+ .each_with_object({}) { |(topic_id, user_id), h| (h[topic_id] ||= []) << user_id }
+
+ topics.each do |topic|
+ topic.accepted_answer_user_ids = topics_with_answer_users[topic.id] || []
+ end
- topics.each { |topic| topic.accepted_answer_user_id = topics_with_answer_poster[topic.id] }
- user_ids.concat(topics_with_answer_poster.values)
+ user_ids.concat(topics_with_answer_users.values.flatten.uniq)
end
DiscourseSolved::RegisterFilters.register(self)
diff --git a/plugins/discourse-solved/spec/components/post_revisor_spec.rb b/plugins/discourse-solved/spec/components/post_revisor_spec.rb
index a70510208ba..386f16d62d3 100644
--- a/plugins/discourse-solved/spec/components/post_revisor_spec.rb
+++ b/plugins/discourse-solved/spec/components/post_revisor_spec.rb
@@ -59,7 +59,7 @@ describe PostRevisor do
topic.reload
expect(topic.solved).to be_present
- expect(topic.solved.answer_post_id).to eq(reply.id)
+ expect(topic.solved.topic_answers.first.answer_post_id).to eq(reply.id)
end
it "keeps the answer when allow_solved_on_all_topics is true" do
@@ -69,7 +69,7 @@ describe PostRevisor do
topic.reload
expect(topic.solved).to be_present
- expect(topic.solved.answer_post_id).to eq(reply.id)
+ expect(topic.solved.topic_answers.first.answer_post_id).to eq(reply.id)
end
end
@@ -112,7 +112,7 @@ describe PostRevisor do
topic.reload
expect(topic.solved).to be_present
- expect(topic.solved.answer_post_id).to eq(reply.id)
+ expect(topic.solved.topic_answers.first.answer_post_id).to eq(reply.id)
end
it "keeps answer when solved tag is removed but topic is in a solved category" do
@@ -125,7 +125,7 @@ describe PostRevisor do
topic.reload
expect(topic.solved).to be_present
- expect(topic.solved.answer_post_id).to eq(reply.id)
+ expect(topic.solved.topic_answers.first.answer_post_id).to eq(reply.id)
end
it "unaccepts answer when both category changes to unsolved and solved tag is removed" do
@@ -137,6 +137,26 @@ describe PostRevisor do
described_class.new(post).revise!(admin, { category_id: category.id, tags: [] })
expect(topic.reload.solved).to be_nil
end
+
+ describe "with multiple solutions enabled" do
+ before { SiteSetting.solved_allow_multiple_solutions = true }
+ it "unaccepts all answers when both category changes to unsolved and solved tag is removed" do
+ topic = Fabricate(:topic, category: category_solved, tags: [solved_tag])
+ post = Fabricate(:post, topic: topic)
+ reply = Fabricate(:post, topic: topic, post_number: 2)
+ reply2 = Fabricate(:post, topic: topic)
+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: reply.id }, guardian: admin.guardian)
+ DiscourseSolved::AcceptAnswer.call!(
+ params: {
+ post_id: reply2.id,
+ },
+ guardian: admin.guardian,
+ )
+
+ described_class.new(post).revise!(admin, { category_id: category.id, tags: [] })
+ expect(topic.reload.solved).to be_nil
+ end
+ end
end
describe "Allowing solved via tags" do
diff --git a/plugins/discourse-solved/spec/fabricators/solved_topic_fabricator.rb b/plugins/discourse-solved/spec/fabricators/solved_topic_fabricator.rb
index d24e47e74fb..d5604e9d991 100644
--- a/plugins/discourse-solved/spec/fabricators/solved_topic_fabricator.rb
+++ b/plugins/discourse-solved/spec/fabricators/solved_topic_fabricator.rb
@@ -1,6 +1,13 @@
# frozen_string_literal: true
Fabricator(:solved_topic, from: DiscourseSolved::SolvedTopic) do
topic
- answer_post { Fabricate(:post) }
- accepter { Fabricate(:user) }
+ transient :topic_answer, :answer_post
+
+ after_create do |solved_topic, transients|
+ if transients[:topic_answer]
+ solved_topic.topic_answers << transients[:topic_answer]
+ elsif transients[:answer_post]
+ Fabricate(:topic_answer, solved_topic:, post: transients[:answer_post])
+ end
+ end
end
diff --git a/plugins/discourse-solved/spec/fabricators/topic_answer_fabricator.rb b/plugins/discourse-solved/spec/fabricators/topic_answer_fabricator.rb
new file mode 100644
index 00000000000..f8233a53a17
--- /dev/null
+++ b/plugins/discourse-solved/spec/fabricators/topic_answer_fabricator.rb
@@ -0,0 +1,6 @@
+# frozen_string_literal: true
+Fabricator(:topic_answer, from: DiscourseSolved::TopicAnswer) do
+ solved_topic
+ post { Fabricate(:post) }
+ accepter { Fabricate(:user) }
+end
diff --git a/plugins/discourse-solved/spec/integration/solved_spec.rb b/plugins/discourse-solved/spec/integration/solved_spec.rb
index a807742b0b9..f2bd9d84309 100644
--- a/plugins/discourse-solved/spec/integration/solved_spec.rb
+++ b/plugins/discourse-solved/spec/integration/solved_spec.rb
@@ -266,7 +266,7 @@ RSpec.describe "Managing Posts solved status" do
post "/solution/accept.json", params: { id: p1.id }
expect(response.status).to eq(200)
- expect(topic.solved.answer_post_id).to eq(p1.id)
+ expect(topic.topic_answers.first.answer_post_id).to eq(p1.id)
topic.reload
@@ -288,7 +288,7 @@ RSpec.describe "Managing Posts solved status" do
post "/solution/accept.json", params: { id: post_2.id }
expect(response.status).to eq(200)
- expect(topic_2.solved.answer_post_id).to eq(post_2.id)
+ expect(topic_2.topic_answers.first.answer_post_id).to eq(post_2.id)
topic_2.reload
@@ -376,7 +376,7 @@ RSpec.describe "Managing Posts solved status" do
post "/solution/accept.json", params: { id: reply.id }
expect(response.status).to eq(200)
- expect(topic.solved.answer_post_id).to eq(reply.id)
+ expect(topic.topic_answers.first.answer_post_id).to eq(reply.id)
end
it "works when the topic author has been deleted" do
@@ -389,7 +389,7 @@ RSpec.describe "Managing Posts solved status" do
post "/solution/accept.json", params: { id: p1.id }
expect(response.status).to eq(200)
- expect(topic.solved.answer_post_id).to eq(p1.id)
+ expect(topic.topic_answers.first.answer_post_id).to eq(p1.id)
end
it "does not set a timer when the topic is closed" do
@@ -401,7 +401,7 @@ RSpec.describe "Managing Posts solved status" do
p1.reload
topic.reload
- expect(topic.solved.answer_post_id).to eq(p1.id)
+ expect(topic.topic_answers.first.answer_post_id).to eq(p1.id)
expect(topic.public_topic_timer).to eq(nil)
expect(topic.closed).to eq(true)
end
@@ -417,7 +417,7 @@ RSpec.describe "Managing Posts solved status" do
expect(response.status).to eq(200)
p1.reload
- expect(topic.solved.answer_post_id).to eq(p1.id)
+ expect(topic.topic_answers.first.answer_post_id).to eq(p1.id)
end
it "removes the solution when the post is deleted" do
@@ -426,7 +426,7 @@ RSpec.describe "Managing Posts solved status" do
post "/solution/accept.json", params: { id: reply.id }
expect(response.status).to eq(200)
- expect(topic.solved.answer_post_id).to eq(reply.id)
+ expect(topic.topic_answers.first.answer_post_id).to eq(reply.id)
PostDestroyer.new(Discourse.system_user, reply, context: "spec").destroy
reply.topic.reload
@@ -442,19 +442,19 @@ RSpec.describe "Managing Posts solved status" do
post "/solution/accept.json", params: { id: reply2.id }
expect(response.status).to eq(200)
- expect(topic.solved.answer_post_id).to eq(reply2.id)
+ expect(topic.topic_answers.first.answer_post_id).to eq(reply2.id)
PostDestroyer.new(Discourse.system_user, reply1, context: "spec").destroy
topic.reload
expect(topic.solved).to be_present
- expect(topic.solved.answer_post_id).to eq(reply2.id)
+ expect(topic.topic_answers.first.answer_post_id).to eq(reply2.id)
PostDestroyer.new(Discourse.system_user, reply3, context: "spec").destroy
topic.reload
expect(topic.solved).to be_present
- expect(topic.solved.answer_post_id).to eq(reply2.id)
+ expect(topic.topic_answers.first.answer_post_id).to eq(reply2.id)
end
it "does not allow you to accept a whisper" do
@@ -475,6 +475,136 @@ RSpec.describe "Managing Posts solved status" do
payload = JSON.parse(job_args["payload"])
expect(payload["id"]).to eq(p1.id)
end
+
+ describe "with multiple solutions enabled" do
+ let(:p2) { Fabricate(:post, topic: topic) }
+ before { SiteSetting.solved_allow_multiple_solutions = true }
+
+ it "can mark multiple posts as accepted, only creating one timer" do
+ freeze_time
+
+ post "/solution/accept.json", params: { id: p1.id }
+
+ expect(response.status).to eq(200)
+ expect(topic.topic_answers.first.answer_post_id).to eq(p1.id)
+
+ topic.reload
+
+ expect(topic.public_topic_timer.status_type).to eq(TopicTimer.types[:silent_close])
+
+ expect(topic.solved.topic_timer).to eq(topic.public_topic_timer)
+ expect(topic.public_topic_timer.execute_at).to eq_time(2.hours.from_now)
+ expect(topic.public_topic_timer.based_on_last_post).to eq(true)
+
+ topic_timer = topic.solved.topic_timer
+
+ post "/solution/accept.json", params: { id: p2.id }
+
+ expect(response.status).to eq(200)
+ expect(topic.topic_answers[0].answer_post_id).to eq(p1.id)
+ expect(topic.topic_answers[1].answer_post_id).to eq(p2.id)
+
+ topic.reload
+
+ expect(topic.public_topic_timer.status_type).to eq(TopicTimer.types[:silent_close])
+ expect(topic.solved.topic_timer).to eq(topic_timer)
+ end
+
+ it "sends notifications to correct users" do
+ user = Fabricate(:user)
+ topic = Fabricate(:topic, user: user)
+ topic.category.notify_on_staff_accept_solved = true
+ topic.category.save_custom_fields
+ post = Fabricate(:post, post_number: 2, topic: topic)
+ post2 = Fabricate(:post, post_number: 3, topic: topic)
+
+ op = topic.user
+ user = post.user
+ user2 = post2.user
+
+ expect {
+ DiscourseSolved::AcceptAnswer.call!(
+ params: {
+ post_id: post.id,
+ },
+ guardian: Discourse.system_user.guardian,
+ )
+ }.to change { user.notifications.count }.by(1) & change { op.notifications.count }.by(1) &
+ not_change { user2.notifications.count }
+
+ notification = user.notifications.last
+ expect(notification.notification_type).to eq(Notification.types[:custom])
+ expect(notification.topic_id).to eq(post.topic_id)
+ expect(notification.post_number).to eq(post.post_number)
+
+ notification = op.notifications.last
+ expect(notification.notification_type).to eq(Notification.types[:custom])
+ expect(notification.topic_id).to eq(post.topic_id)
+ expect(notification.post_number).to eq(post.post_number)
+
+ expect {
+ DiscourseSolved::AcceptAnswer.call!(
+ params: {
+ post_id: post2.id,
+ },
+ guardian: Discourse.system_user.guardian,
+ )
+ }.to change { user2.notifications.count }.by(1) & change { op.notifications.count }.by(1) &
+ not_change { user.notifications.count }
+
+ notification = user2.notifications.last
+ expect(notification.notification_type).to eq(Notification.types[:custom])
+ expect(notification.topic_id).to eq(post2.topic_id)
+ expect(notification.post_number).to eq(post2.post_number)
+
+ notification = op.notifications.last
+ expect(notification.notification_type).to eq(Notification.types[:custom])
+ expect(notification.topic_id).to eq(post2.topic_id)
+ expect(notification.post_number).to eq(post2.post_number)
+ end
+
+ it "removes the solution only when the last accepted post is deleted" do
+ reply = Fabricate(:post, post_number: 2, topic: topic)
+ reply2 = Fabricate(:post, post_number: 3, topic: topic)
+
+ post "/solution/accept.json", params: { id: reply.id }
+ expect(response.status).to eq(200)
+ post "/solution/accept.json", params: { id: reply2.id }
+ expect(response.status).to eq(200)
+
+ expect(topic.topic_answers[0].post).to eq(reply)
+ expect(topic.topic_answers[1].post).to eq(reply2)
+
+ PostDestroyer.new(Discourse.system_user, reply, context: "spec").destroy
+ reply.topic.reload
+
+ expect(topic.solved).to be_present
+ expect(topic.topic_answers.first.post).to eq(reply2)
+
+ PostDestroyer.new(Discourse.system_user, reply2, context: "spec").destroy
+ reply.topic.reload
+ expect(topic.solved).to be_nil
+ end
+
+ it "triggers multiple webhooks" do
+ Fabricate(:solved_web_hook)
+ post "/solution/accept.json", params: { id: p1.id }
+
+ job_args = Jobs::EmitWebHookEvent.jobs[0]["args"].first
+
+ expect(job_args["event_name"]).to eq("accepted_solution")
+ payload = JSON.parse(job_args["payload"])
+ expect(payload["id"]).to eq(p1.id)
+
+ post "/solution/accept.json", params: { id: p2.id }
+
+ job_args = Jobs::EmitWebHookEvent.jobs[1]["args"].first
+
+ expect(job_args["event_name"]).to eq("accepted_solution")
+ payload = JSON.parse(job_args["payload"])
+ expect(payload["id"]).to eq(p2.id)
+ end
+ end
end
describe "#unaccept" do
@@ -511,6 +641,56 @@ RSpec.describe "Managing Posts solved status" do
payload = JSON.parse(job_args["payload"])
expect(payload["id"]).to eq(p1.id)
end
+
+ describe "with multiple solutions enabled" do
+ let(:p2) { Fabricate(:post, topic: topic) }
+ before { SiteSetting.solved_allow_multiple_solutions = true }
+
+ describe "when solved_topics_auto_close_hours is enabled" do
+ before do
+ SiteSetting.solved_topics_auto_close_hours = 2
+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: p1.id }, guardian: user.guardian)
+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: p2.id }, guardian: user.guardian)
+ topic.reload
+ end
+
+ it "should unmark the post as solved only when last solution unaccepted" do
+ expect do post "/solution/unaccept.json", params: { id: p1.id } end.not_to change {
+ topic.reload.public_topic_timer
+ }
+ expect(response.status).to eq(200)
+ expect(topic.reload.solved).to be_present
+
+ expect do post "/solution/unaccept.json", params: { id: p2.id } end.to change {
+ topic.reload.public_topic_timer
+ }.to(nil)
+ expect(response.status).to eq(200)
+ expect(topic.reload.solved).to be(nil)
+ end
+ end
+
+ it "triggers multiple webhooks" do
+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: p1.id }, guardian: user.guardian)
+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: p2.id }, guardian: user.guardian)
+
+ Fabricate(:solved_web_hook)
+ post "/solution/unaccept.json", params: { id: p1.id }
+
+ job_args = Jobs::EmitWebHookEvent.jobs[0]["args"].first
+
+ expect(job_args["event_name"]).to eq("unaccepted_solution")
+ payload = JSON.parse(job_args["payload"])
+ expect(payload["id"]).to eq(p1.id)
+
+ post "/solution/unaccept.json", params: { id: p2.id }
+
+ job_args = Jobs::EmitWebHookEvent.jobs[1]["args"].first
+
+ expect(job_args["event_name"]).to eq("unaccepted_solution")
+ payload = JSON.parse(job_args["payload"])
+ expect(payload["id"]).to eq(p2.id)
+ end
+ end
end
context "with group moderators" do
@@ -559,7 +739,7 @@ RSpec.describe "Managing Posts solved status" do
DiscourseSolved::AcceptAnswer.call!(params: { post_id: p1.id }, guardian: user.guardian)
topic.reload
- expect(topic.solved.answer_post_id).to eq(p1.id)
+ expect(topic.topic_answers.first.answer_post_id).to eq(p1.id)
expect(p1.topic.assignment.reload.status).to eq("Done")
end
@@ -716,13 +896,13 @@ RSpec.describe "Managing Posts solved status" do
DiscourseSolved::AcceptAnswer.call!(params: { post_id: reply1.id }, guardian: user.guardian)
topic.reload
- expect(topic.solved.answer_post_id).to eq(reply1.id)
+ expect(topic.topic_answers.first.answer_post_id).to eq(reply1.id)
expect(topic.solved.topic_timer).to eq(topic.public_topic_timer)
DiscourseSolved::AcceptAnswer.call!(params: { post_id: reply2.id }, guardian: user.guardian)
topic.reload
- expect(topic.solved.answer_post_id).to eq(reply2.id)
+ expect(topic.topic_answers.first.answer_post_id).to eq(reply2.id)
end
end
@@ -766,6 +946,65 @@ RSpec.describe "Managing Posts solved status" do
).map(&:post_id),
).to contain_exactly p3.id
end
+
+ it "only lists most recent solution in topic" do
+ t1 = Fabricate(:topic_with_op)
+
+ p1 = Fabricate(:post, topic: t1, user:)
+ p2 = Fabricate(:post, topic: t1, user:)
+
+ DiscourseSolved::AcceptAnswer.call!(
+ params: {
+ post_id: p1.id,
+ },
+ guardian: Discourse.system_user.guardian,
+ )
+ DiscourseSolved::AcceptAnswer.call!(
+ params: {
+ post_id: p2.id,
+ },
+ guardian: Discourse.system_user.guardian,
+ )
+
+ expect(
+ UserAction.stream(
+ user_id: user.id,
+ action_types: [::UserAction::SOLVED],
+ guardian: user.guardian,
+ ).map(&:post_id),
+ ).to contain_exactly p2.id
+ end
+
+ describe "with multiple solutions enabled" do
+ before { SiteSetting.solved_allow_multiple_solutions = true }
+ it "lists all solutions in topic" do
+ t1 = Fabricate(:topic_with_op)
+
+ p1 = Fabricate(:post, topic: t1, user:)
+ p2 = Fabricate(:post, topic: t1, user:)
+
+ DiscourseSolved::AcceptAnswer.call!(
+ params: {
+ post_id: p1.id,
+ },
+ guardian: Discourse.system_user.guardian,
+ )
+ DiscourseSolved::AcceptAnswer.call!(
+ params: {
+ post_id: p2.id,
+ },
+ guardian: Discourse.system_user.guardian,
+ )
+
+ expect(
+ UserAction.stream(
+ user_id: user.id,
+ action_types: [::UserAction::SOLVED],
+ guardian: user.guardian,
+ ).map(&:post_id),
+ ).to contain_exactly(p1.id, p2.id)
+ end
+ end
end
describe "publishing messages" do
@@ -803,15 +1042,18 @@ RSpec.describe "Managing Posts solved status" do
)
accepted_message = messages.find { |m| m.data[:type] == :accepted_solution }
- expect(accepted_message.data[:accepted_answer][:post_number]).to eq(2)
- expect(accepted_message.data[:accepted_answer][:username]).to eq(user.username)
- expect(accepted_message.data[:accepted_answer][:name]).to eq(user.name)
- expect(accepted_message.data[:accepted_answer][:excerpt]).to eq(reply.cooked)
- expect(accepted_message.data[:accepted_answer][:accepter_name]).to eq(admin.name)
- expect(accepted_message.data[:accepted_answer][:accepter_username]).to eq(admin.username)
+ expect(accepted_message.data[:accepted_answers].count).to eq(1)
+
+ first_accepted_answer = accepted_message.data[:accepted_answers].first
+ expect(first_accepted_answer[:post_number]).to eq(2)
+ expect(first_accepted_answer[:username]).to eq(user.username)
+ expect(first_accepted_answer[:name]).to eq(user.name)
+ expect(first_accepted_answer[:cooked]).to eq(reply.cooked)
+ expect(first_accepted_answer[:accepter_name]).to eq(admin.name)
+ expect(first_accepted_answer[:accepter_username]).to eq(admin.username)
unaccepted_message = messages.find { |m| m.data[:type] == :unaccepted_solution }
- expect(unaccepted_message.data[:accepted_answer]).to eq(nil)
+ expect(unaccepted_message.data[:accepted_answers]).to be_nil
end
it "publishes MessageBus messages securely for PMs" do
@@ -935,7 +1177,7 @@ RSpec.describe "Managing Posts solved status" do
DiscourseSolved.accept_answer!(reply, user)
- expect(topic.reload.solved.answer_post_id).to eq(reply.id)
+ expect(topic.reload.topic_answers.first.answer_post_id).to eq(reply.id)
end
end
diff --git a/plugins/discourse-solved/spec/lib/accepted_answers_helper_spec.rb b/plugins/discourse-solved/spec/lib/accepted_answers_helper_spec.rb
new file mode 100644
index 00000000000..4e5aee02aa6
--- /dev/null
+++ b/plugins/discourse-solved/spec/lib/accepted_answers_helper_spec.rb
@@ -0,0 +1,157 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseSolved::AcceptedAnswersHelper do
+ before { SiteSetting.allow_solved_on_all_topics = true }
+
+ fab!(:topic)
+ fab!(:answer_post) { Fabricate(:post, topic:) }
+ fab!(:accepter, :user)
+ fab!(:user)
+
+ describe "#serialize" do
+ describe "with an accepted solution" do
+ fab!(:solved_topic) { Fabricate(:solved_topic, topic:) }
+ fab!(:topic_answer) { Fabricate(:topic_answer, solved_topic:, post: answer_post, accepter:) }
+
+ it "returns the accepted solution info" do
+ accepted_answers =
+ DiscourseSolved::AcceptedAnswersHelper.serialize(topic.reload, Guardian.new(user))
+
+ expect(accepted_answers.length).to eq(1)
+
+ expected_answer = {
+ id: answer_post.id,
+ username: answer_post.user.username,
+ avatar_template: answer_post.user.avatar_template,
+ created_at: answer_post.created_at,
+ cooked: answer_post.cooked,
+ post_number: answer_post.post_number,
+ topic_id: answer_post.topic_id,
+ url: answer_post.url,
+ }
+
+ expect(accepted_answers.first).to eq(expected_answer)
+ end
+
+ context "when users are deleted" do
+ it "does not crash when accepter is deleted" do
+ accepter.destroy!
+
+ accepted_answers = nil
+
+ expect {
+ accepted_answers =
+ DiscourseSolved::AcceptedAnswersHelper.serialize(topic.reload, Guardian.new(user))
+ }.not_to raise_error
+ expect(accepted_answers).not_to be_empty
+ end
+
+ it "does not crash when answer post user is deleted" do
+ answer_post.user.destroy!
+
+ accepted_answers = nil
+
+ expect {
+ accepted_answers =
+ DiscourseSolved::AcceptedAnswersHelper.serialize(topic.reload, Guardian.new(user))
+ }.not_to raise_error
+ expect(accepted_answers.first[:username]).to eq(Discourse.system_user.username)
+ end
+
+ it "falls back to system user when both accepter and topic author are deleted" do
+ SiteSetting.show_who_marked_solved = true
+ accepter.destroy!
+ topic.user.destroy!
+
+ accepted_answers = nil
+
+ expect {
+ accepted_answers =
+ DiscourseSolved::AcceptedAnswersHelper.serialize(topic.reload, Guardian.new(user))
+ }.not_to raise_error
+ expect(accepted_answers.first[:accepter_username]).to eq(Discourse.system_user.username)
+ end
+
+ it "returns nil when answer post is deleted" do
+ answer_post.destroy!
+
+ accepted_answers = nil
+
+ expect {
+ accepted_answers =
+ DiscourseSolved::AcceptedAnswersHelper.serialize(topic.reload, Guardian.new(user))
+ }.not_to raise_error
+ expect(accepted_answers).to be_nil
+ end
+ end
+ end
+
+ describe "with multiple solutions enabled" do
+ fab!(:solved_topic) { Fabricate(:solved_topic, topic:) }
+ fab!(:topic_answer) { Fabricate(:topic_answer, solved_topic:, post: answer_post, accepter:) }
+ fab!(:answer_post2) { Fabricate(:post, topic:) }
+ fab!(:topic_answer2) do
+ Fabricate(:topic_answer, solved_topic:, post: answer_post2, accepter:)
+ end
+
+ before { SiteSetting.solved_allow_multiple_solutions = true }
+
+ it "returns the accepted solution info in order" do
+ accepted_answers =
+ DiscourseSolved::AcceptedAnswersHelper.serialize(topic.reload, Guardian.new(user))
+
+ expect(accepted_answers.length).to eq(2)
+
+ expected_answers = [
+ {
+ id: answer_post.id,
+ username: answer_post.user.username,
+ avatar_template: answer_post.user.avatar_template,
+ created_at: answer_post.created_at,
+ cooked: answer_post.cooked,
+ post_number: answer_post.post_number,
+ topic_id: answer_post.topic_id,
+ url: answer_post.url,
+ },
+ {
+ id: answer_post2.id,
+ username: answer_post2.user.username,
+ avatar_template: answer_post2.user.avatar_template,
+ created_at: answer_post2.created_at,
+ cooked: answer_post2.cooked,
+ post_number: answer_post2.post_number,
+ topic_id: answer_post2.topic_id,
+ url: answer_post2.url,
+ },
+ ]
+ expect(accepted_answers).to eq(expected_answers)
+ end
+
+ context "when users are deleted" do
+ it "keeps other answer when answer post is deleted" do
+ accepted_answers = nil
+
+ expect {
+ accepted_answers =
+ DiscourseSolved::AcceptedAnswersHelper.serialize(topic.reload, Guardian.new(user))
+ }.not_to raise_error
+
+ expect(accepted_answers.length).to eq(2)
+ PostDestroyer.new(Discourse.system_user, answer_post, context: "test").destroy
+
+ expect {
+ accepted_answers =
+ DiscourseSolved::AcceptedAnswersHelper.serialize(topic.reload, Guardian.new(user))
+ }.not_to raise_error
+ expect(accepted_answers.length).to eq(1)
+ end
+ end
+ end
+
+ it "returns nil when topic is not solved" do
+ expect(
+ DiscourseSolved::AcceptedAnswersHelper.serialize(topic.reload, Guardian.new(user)),
+ ).to be_nil
+ end
+ end
+end
diff --git a/plugins/discourse-solved/spec/lib/admin_dashboard_highlights_integration_spec.rb b/plugins/discourse-solved/spec/lib/admin_dashboard_highlights_integration_spec.rb
index 121ea59f015..f95d8e6f06f 100644
--- a/plugins/discourse-solved/spec/lib/admin_dashboard_highlights_integration_spec.rb
+++ b/plugins/discourse-solved/spec/lib/admin_dashboard_highlights_integration_spec.rb
@@ -48,9 +48,12 @@ describe AdminDashboardHighlights do
fab!(:post) { Fabricate(:post, topic: topic) }
it "populates prev_period when the facet is requested" do
- DiscourseSolved::SolvedTopic.create!(
- topic: topic,
- answer_post: post,
+ solved_topic =
+ DiscourseSolved::SolvedTopic.create!(topic: topic, created_at: Time.zone.local(2026, 3, 15))
+
+ DiscourseSolved::TopicAnswer.create!(
+ solved_topic: solved_topic,
+ post: post,
accepter: user,
created_at: Time.zone.local(2026, 3, 15),
)
@@ -67,9 +70,12 @@ describe AdminDashboardHighlights do
end
it "excludes deleted topics from prev_period" do
- DiscourseSolved::SolvedTopic.create!(
- topic: topic,
- answer_post: post,
+ solved_topic =
+ DiscourseSolved::SolvedTopic.create!(topic: topic, created_at: Time.zone.local(2026, 3, 15))
+
+ DiscourseSolved::TopicAnswer.create!(
+ solved_topic: solved_topic,
+ post: post,
accepter: user,
created_at: Time.zone.local(2026, 3, 15),
)
@@ -89,9 +95,12 @@ describe AdminDashboardHighlights do
it "excludes private message topics from prev_period" do
pm = Fabricate(:private_message_topic)
pm_post = Fabricate(:post, topic: pm)
- DiscourseSolved::SolvedTopic.create!(
- topic: pm,
- answer_post: pm_post,
+ solved_topic =
+ DiscourseSolved::SolvedTopic.create!(topic: pm, created_at: Time.zone.local(2026, 3, 15))
+
+ DiscourseSolved::TopicAnswer.create!(
+ solved_topic: solved_topic,
+ post: pm_post,
accepter: user,
created_at: Time.zone.local(2026, 3, 15),
)
diff --git a/plugins/discourse-solved/spec/lib/post_mover_extension_spec.rb b/plugins/discourse-solved/spec/lib/post_mover_extension_spec.rb
index 47599d7694d..50daf6320f7 100644
--- a/plugins/discourse-solved/spec/lib/post_mover_extension_spec.rb
+++ b/plugins/discourse-solved/spec/lib/post_mover_extension_spec.rb
@@ -9,7 +9,7 @@ RSpec.describe DiscourseSolved::PostMoverExtension do
fab!(:destination_topic) { Fabricate(:topic_with_op, category: category) }
let!(:post_ids) { topic.posts.order(:post_number).pluck(:id) }
- let!(:solved) { Fabricate(:solved_topic, topic: topic, answer_post: reply) }
+ fab!(:solved) { Fabricate(:solved_topic, topic: topic, answer_post: reply) }
before { SiteSetting.allow_solved_on_all_topics = true }
@@ -17,14 +17,16 @@ RSpec.describe DiscourseSolved::PostMoverExtension do
it "transfers the solution to an existing topic" do
topic.move_posts(admin, post_ids, destination_topic_id: destination_topic.id)
- expect(solved.reload.topic_id).to eq(destination_topic.id)
+ expect(topic.reload.solved).to be_nil
+ expect(destination_topic.reload.topic_answers.first.answer_post_id).to eq(reply.id)
end
it "transfers the solution to a new topic" do
- topic.move_posts(admin, [reply.id], title: "This is a new topic for the moved post")
+ new_topic =
+ topic.move_posts(admin, [reply.id], title: "This is a new topic for the moved post")
expect(topic.reload.solved).to be_nil
- expect(solved.reload.topic_id).not_to eq(topic.id)
+ expect(new_topic.reload.topic_answers.first.answer_post_id).to eq(reply.id)
end
it "does not transfer the solution when destination topic does not allow solved" do
@@ -42,7 +44,58 @@ RSpec.describe DiscourseSolved::PostMoverExtension do
topic.move_posts(admin, post_ids, destination_topic_id: destination_topic.id)
expect(topic.reload.solved).to be_nil
- expect(destination_topic.reload.solved.answer_post_id).not_to eq(reply.id)
+ expect(destination_topic.reload.topic_answers.first.answer_post_id).not_to eq(reply.id)
+ end
+
+ it "moving multiple answers to a single topic only keeps the first accepted" do
+ Fabricate(:topic_answer, solved_topic: solved, post: another_reply)
+ target_topic = Fabricate(:topic_with_op)
+
+ topic.move_posts(admin, [reply.id, another_reply.id], destination_topic_id: target_topic.id)
+
+ expect(topic.reload.solved).to be_nil
+
+ expect(target_topic.reload.topic_answers.count).to eq(1)
+ expect(target_topic.topic_answers.first.answer_post_id).to eq(reply.id)
+ expect(target_topic.posts[1..2].map(&:id).sort).to eq([reply.id, another_reply.id])
+ expect(DiscourseSolved::TopicAnswer.find_by(answer_post_id: another_reply.id)).to be_nil
+ end
+
+ describe "with multiple solutions enabled" do
+ before { SiteSetting.solved_allow_multiple_solutions = true }
+
+ it "transfers one of many solutions to an existing topic" do
+ Fabricate(:topic_answer, solved_topic: solved, post: another_reply)
+ topic.move_posts(admin, [reply.id], destination_topic_id: destination_topic.id)
+
+ expect(topic.reload.topic_answers.first.answer_post_id).to eq(another_reply.id)
+ expect(destination_topic.reload.topic_answers.first.answer_post_id).to eq(reply.id)
+ end
+
+ it "transfers one of many solutions to a new topic" do
+ Fabricate(:topic_answer, solved_topic: solved, post: another_reply)
+ new_topic =
+ topic.move_posts(admin, [reply.id], title: "This is a new topic for the moved post")
+
+ expect(topic.reload.topic_answers.first.answer_post_id).to eq(another_reply.id)
+ expect(new_topic.reload.topic_answers.first.answer_post_id).to eq(reply.id)
+ end
+
+ it "does transfer the solution when the destination topic already has a solution" do
+ Fabricate(
+ :solved_topic,
+ topic: destination_topic,
+ answer_post: destination_topic.first_post,
+ )
+
+ topic.move_posts(admin, [reply.id], destination_topic_id: destination_topic.id)
+
+ expect(topic.reload.solved).to be_nil
+ expect(destination_topic.reload.topic_answers[0].answer_post_id).to eq(
+ destination_topic.first_post.id,
+ )
+ expect(destination_topic.reload.topic_answers[1].answer_post_id).to eq(reply.id)
+ end
end
end
@@ -65,7 +118,16 @@ RSpec.describe DiscourseSolved::PostMoverExtension do
topic.move_posts(admin, [another_reply.id], destination_topic_id: destination_topic.id)
expect(solved.reload.topic_id).to eq(topic.id)
- expect(destination_topic.reload.solved.answer_post_id).to eq(destination_topic.first_post.id)
+ expect(destination_topic.reload.topic_answers.first.answer_post_id).to eq(
+ destination_topic.first_post.id,
+ )
+ end
+
+ it "does not create a SolvedTopic when moving non-answer posts to a destination that allows answers" do
+ topic.move_posts(admin, [post_ids.first], destination_topic_id: destination_topic.id)
+
+ expect(topic.reload.solved).not_to be_nil
+ expect(destination_topic.reload.solved).to be_nil
end
end
end
diff --git a/plugins/discourse-solved/spec/lib/queries_spec.rb b/plugins/discourse-solved/spec/lib/queries_spec.rb
index 1e77543a2b7..af5ac9b39e8 100644
--- a/plugins/discourse-solved/spec/lib/queries_spec.rb
+++ b/plugins/discourse-solved/spec/lib/queries_spec.rb
@@ -67,5 +67,29 @@ describe DiscourseSolved::Queries do
expect(described_class.solved_count(user.id)).to eq(0)
expect(described_class.solved_count(admin.id)).to eq(0)
end
+
+ describe "with multiple solutions enabled" do
+ before { SiteSetting.solved_allow_multiple_solutions = true }
+
+ it "returns the correct count of solved topics for a user when topics have multiple solutions" do
+ expect(described_class.solved_count(user.id)).to eq(0)
+
+ topic1 = Fabricate(:topic)
+ Fabricate(:post, topic: topic1)
+ post1 = Fabricate(:post, topic: topic1, user: user)
+ post2 = Fabricate(:post, topic: topic1, user: user)
+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: post1.id }, guardian: admin.guardian)
+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: post2.id }, guardian: admin.guardian)
+
+ expect(described_class.solved_count(user.id)).to eq(2)
+
+ topic2 = Fabricate(:topic)
+ Fabricate(:post, topic: topic2)
+ post3 = Fabricate(:post, topic: topic2, user: user)
+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: post3.id }, guardian: admin.guardian)
+
+ expect(described_class.solved_count(user.id)).to eq(3)
+ end
+ end
end
end
diff --git a/plugins/discourse-solved/spec/lib/topic_extension_user_deletion_spec.rb b/plugins/discourse-solved/spec/lib/topic_extension_user_deletion_spec.rb
deleted file mode 100644
index f73c782d3f4..00000000000
--- a/plugins/discourse-solved/spec/lib/topic_extension_user_deletion_spec.rb
+++ /dev/null
@@ -1,55 +0,0 @@
-# frozen_string_literal: true
-
-RSpec.describe DiscourseSolved::TopicExtension do
- before { SiteSetting.allow_solved_on_all_topics = true }
-
- fab!(:topic)
- fab!(:answer_post) { Fabricate(:post, topic:) }
- fab!(:accepter, :user)
-
- describe "#accepted_answer_post_info" do
- let(:solved_topic) { Fabricate(:solved_topic, topic:, answer_post:, accepter:) }
-
- context "when users are deleted" do
- it "does not crash when accepter is deleted" do
- solved_topic
- accepter.destroy!
-
- expect { topic.reload.accepted_answer_post_info }.not_to raise_error
- expect(topic.accepted_answer_post_info).to be_present
- end
-
- it "does not crash when answer post user is deleted" do
- solved_topic
- answer_post.user.destroy!
-
- expect { topic.reload.accepted_answer_post_info }.not_to raise_error
- expect(topic.accepted_answer_post_info[:username]).to eq(Discourse.system_user.username)
- end
-
- it "falls back to system user when both accepter and topic author are deleted" do
- SiteSetting.show_who_marked_solved = true
- solved_topic
- accepter.destroy!
- topic.user.destroy!
-
- expect { topic.reload.accepted_answer_post_info }.not_to raise_error
- expect(topic.accepted_answer_post_info[:accepter_username]).to eq(
- Discourse.system_user.username,
- )
- end
-
- it "returns nil when answer post is deleted" do
- solved_topic
- answer_post.destroy!
-
- expect { topic.reload.accepted_answer_post_info }.not_to raise_error
- expect(topic.accepted_answer_post_info).to be_nil
- end
- end
-
- it "returns nil when topic is not solved" do
- expect(topic.accepted_answer_post_info).to be_nil
- end
- end
-end
diff --git a/plugins/discourse-solved/spec/models/copy_solved_topic_custom_field_spec.rb b/plugins/discourse-solved/spec/models/copy_solved_topic_custom_field_spec.rb
deleted file mode 100644
index 574f04960ed..00000000000
--- a/plugins/discourse-solved/spec/models/copy_solved_topic_custom_field_spec.rb
+++ /dev/null
@@ -1,42 +0,0 @@
-# frozen_string_literal: true
-
-require_relative "../../db/migrate/20250318024953_copy_solved_topic_custom_field_to_discourse_solved_solved_topics"
-
-RSpec.describe CopySolvedTopicCustomFieldToDiscourseSolvedSolvedTopics, type: :migration do
- let(:migration) { described_class.new }
-
- describe "handling duplicates" do
- it "ensures only unique topic_id and answer_post_id are inserted" do
- topic = Fabricate(:topic)
- topic1 = Fabricate(:topic)
- post1 = Fabricate(:post, topic: topic)
- TopicCustomField.create!(
- topic_id: topic.id,
- name: "accepted_answer_post_id",
- value: post1.id.to_s,
- )
- # explicit duplicate
- TopicCustomField.create!(
- topic_id: topic1.id,
- name: "accepted_answer_post_id",
- value: post1.id.to_s,
- )
-
- second_topic = Fabricate(:topic)
- post2 = Fabricate(:post, topic: second_topic)
- TopicCustomField.create!(
- topic_id: second_topic.id,
- name: "accepted_answer_post_id",
- value: post2.id.to_s,
- )
-
- migration.up
- expected_count = DiscourseSolved::SolvedTopic.count
-
- expect(expected_count).to eq(2)
-
- expect(DiscourseSolved::SolvedTopic.where(topic_id: topic.id).count).to eq(1)
- expect(DiscourseSolved::SolvedTopic.where(answer_post_id: post1.id).count).to eq(1)
- end
- end
-end
diff --git a/plugins/discourse-solved/spec/models/directory_item_spec.rb b/plugins/discourse-solved/spec/models/directory_item_spec.rb
index d5fc1733406..5a0ef4b4588 100644
--- a/plugins/discourse-solved/spec/models/directory_item_spec.rb
+++ b/plugins/discourse-solved/spec/models/directory_item_spec.rb
@@ -145,6 +145,36 @@ describe DirectoryItem, type: :model do
).to eq(1)
end
+ describe "with multiple solutions enabled" do
+ fab!(:topic1_additional_post) { Fabricate(:post, topic: topic1, user:) }
+ before { SiteSetting.solved_allow_multiple_solutions = true }
+
+ it "includes multiple accepted solutions from same topic" do
+ DiscourseSolved::AcceptAnswer.call!(
+ params: {
+ post_id: topic_post1.id,
+ },
+ guardian: admin.guardian,
+ )
+
+ DiscourseSolved::AcceptAnswer.call!(
+ params: {
+ post_id: topic1_additional_post.id,
+ },
+ guardian: admin.guardian,
+ )
+
+ DirectoryItem.refresh!
+
+ expect(
+ DirectoryItem.find_by(
+ user_id: user.id,
+ period_type: DirectoryItem.period_types[:daily],
+ ).solutions,
+ ).to eq(2)
+ end
+ end
+
context "when refreshing across dates" do
it "updates the user's solution count from 1 to 0" do
freeze_time 40.days.ago
diff --git a/plugins/discourse-solved/spec/models/discourse_solved/solved_topic_spec.rb b/plugins/discourse-solved/spec/models/discourse_solved/solved_topic_spec.rb
index cd2cb4d89ff..09483575467 100644
--- a/plugins/discourse-solved/spec/models/discourse_solved/solved_topic_spec.rb
+++ b/plugins/discourse-solved/spec/models/discourse_solved/solved_topic_spec.rb
@@ -9,20 +9,18 @@ RSpec.describe DiscourseSolved::SolvedTopic do
describe "Associations" do
it { is_expected.to belong_to(:topic) }
- it { is_expected.to belong_to(:answer_post) }
- it { is_expected.to belong_to(:accepter) }
+ it { is_expected.to have_many(:topic_answers) }
+ it { is_expected.to have_many(:answer_posts) }
it { is_expected.to belong_to(:topic_timer).dependent(:destroy) }
end
describe "Validations" do
it { is_expected.to validate_presence_of(:topic_id) }
- it { is_expected.to validate_presence_of(:answer_post_id) }
- it { is_expected.to validate_presence_of(:accepter_user_id) }
end
describe "Callbacks" do
describe "#auto_close_topic_timer" do
- subject(:solved) { described_class.create(topic:, answer_post: post, accepter: user) }
+ subject(:solved) { described_class.create(topic:) }
context "when auto close hours is greater than zero" do
before { SiteSetting.solved_topics_auto_close_hours = 2 }
@@ -67,6 +65,28 @@ RSpec.describe DiscourseSolved::SolvedTopic do
expect(solved.topic_timer).to have_attributes(duration_minutes: 300)
end
end
+
+ describe "with multiple solutions enabled" do
+ fab!(:post2) { Fabricate(:post, topic: topic) }
+ before do
+ SiteSetting.solved_allow_multiple_solutions = true
+ SiteSetting.solved_topics_auto_close_hours = 2
+ end
+
+ it "only creates one timer" do
+ expect(solved.topic_timer).to have_attributes(
+ topic:,
+ status_type: TopicTimer.types[:silent_close],
+ based_on_last_post: true,
+ duration_minutes: 120,
+ )
+
+ topic_timer_id = solved.topic_timer.id
+ Fabricate(:topic_answer, solved_topic: solved, post: post2)
+
+ expect(solved.reload.topic_timer.id).to eq(topic_timer_id)
+ end
+ end
end
end
end
diff --git a/plugins/discourse-solved/spec/models/discourse_solved/topic_answer_spec.rb b/plugins/discourse-solved/spec/models/discourse_solved/topic_answer_spec.rb
new file mode 100644
index 00000000000..476dd34b4b6
--- /dev/null
+++ b/plugins/discourse-solved/spec/models/discourse_solved/topic_answer_spec.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseSolved::TopicAnswer do
+ fab!(:topic, :topic_with_op)
+ fab!(:post) { Fabricate(:post, topic: topic) }
+ fab!(:user)
+ fab!(:solved_topic) { Fabricate(:solved_topic, topic:) }
+
+ before { SiteSetting.allow_solved_on_all_topics = true }
+
+ describe "Associations" do
+ it { is_expected.to belong_to(:solved_topic) }
+ it { is_expected.to belong_to(:post) }
+ it { is_expected.to belong_to(:accepter) }
+ end
+
+ describe "Validations" do
+ it { is_expected.to validate_presence_of(:solved_topic_id) }
+ it { is_expected.to validate_presence_of(:answer_post_id) }
+ it { is_expected.to validate_presence_of(:accepter_user_id) }
+ end
+end
diff --git a/plugins/discourse-solved/spec/models/remove_duplicates_from_discourse_solved_solved_topics_spec.rb b/plugins/discourse-solved/spec/models/remove_duplicates_from_discourse_solved_solved_topics_spec.rb
deleted file mode 100644
index 3df83b6ac5a..00000000000
--- a/plugins/discourse-solved/spec/models/remove_duplicates_from_discourse_solved_solved_topics_spec.rb
+++ /dev/null
@@ -1,52 +0,0 @@
-# frozen_string_literal: true
-
-require_relative "../../db/migrate/20250318024954_remove_duplicates_from_discourse_solved_solved_topics"
-
-RSpec.describe RemoveDuplicatesFromDiscourseSolvedSolvedTopics, type: :migration do
- let(:migration) { described_class.new }
-
- before do
- # temp drop unique constraints to allow testing duplicate entries
- ActiveRecord::Base.connection.execute(
- "DROP INDEX IF EXISTS index_discourse_solved_solved_topics_on_topic_id;",
- )
- ActiveRecord::Base.connection.execute(
- "DROP INDEX IF EXISTS index_discourse_solved_solved_topics_on_answer_post_id;",
- )
- end
-
- after do
- DiscourseSolved::SolvedTopic.delete_all
-
- # reapply unique indexes
- ActiveRecord::Base.connection.execute(
- "CREATE UNIQUE INDEX index_discourse_solved_solved_topics_on_topic_id ON discourse_solved_solved_topics (topic_id);",
- )
- ActiveRecord::Base.connection.execute(
- "CREATE UNIQUE INDEX index_discourse_solved_solved_topics_on_answer_post_id ON discourse_solved_solved_topics (answer_post_id);",
- )
- end
-
- describe "removal of duplicate answer_post_ids" do
- it "keeps only the earliest record for each answer_post_id" do
- topic1 = Fabricate(:topic)
- post1 = Fabricate(:post, topic: topic1)
- topic2 = Fabricate(:topic)
- post2 = Fabricate(:post, topic: topic2)
-
- earlier = Fabricate(:solved_topic, topic: topic1, answer_post: post1, created_at: 2.days.ago)
- Fabricate(:solved_topic, topic: topic1, answer_post: post1, created_at: 1.day.ago)
- Fabricate(:solved_topic, topic: topic1, answer_post: post1, created_at: Date.today)
- another = Fabricate(:solved_topic, topic: topic2, answer_post: post2, created_at: Date.today)
-
- expect(DiscourseSolved::SolvedTopic.count).to eq(4)
- migration.up
-
- expect(DiscourseSolved::SolvedTopic.count).to eq(2)
- expect(DiscourseSolved::SolvedTopic.pluck(:id, :answer_post_id)).to contain_exactly(
- [earlier.id, post1.id],
- [another.id, post2.id],
- )
- end
- end
-end
diff --git a/plugins/discourse-solved/spec/requests/answer_controller_spec.rb b/plugins/discourse-solved/spec/requests/answer_controller_spec.rb
index 1d69daa721d..7cf2a8f56eb 100644
--- a/plugins/discourse-solved/spec/requests/answer_controller_spec.rb
+++ b/plugins/discourse-solved/spec/requests/answer_controller_spec.rb
@@ -53,7 +53,7 @@ RSpec.describe DiscourseSolved::AnswerController do
post "/solution/accept.json", params: { id: solution_post.id }
expect(response.status).to eq(200)
- post "/solution/accept.json", params: { id: solution_post.id }
+ post "/solution/unaccept.json", params: { id: solution_post.id }
expect(response.status).to eq(200)
# Unregister the modifier using DiscoursePluginRegistry
@@ -64,6 +64,45 @@ RSpec.describe DiscourseSolved::AnswerController do
)
end
end
+
+ it "returns single accepted answer in an array" do
+ sign_in(user)
+
+ post "/solution/accept.json", params: { id: solution_post.id }
+
+ expect(response.status).to eq(200)
+ result = response.parsed_body
+ expect(result).to be_an(Array)
+ expect(result.length).to eq(1)
+ expect(result[0]["id"]).to eq(solution_post.id)
+ end
+
+ context "with multiple solutions enabled" do
+ fab!(:solution_post2) { Fabricate(:post, topic: topic) }
+
+ before { SiteSetting.solved_allow_multiple_solutions = true }
+
+ it "returns an array with multiple accepted answers" do
+ sign_in(user)
+
+ post "/solution/accept.json", params: { id: solution_post.id }
+
+ expect(response.status).to eq(200)
+ result = response.parsed_body
+ expect(result).to be_an(Array)
+ expect(result.length).to eq(1)
+ expect(result[0]["id"]).to eq(solution_post.id)
+
+ post "/solution/accept.json", params: { id: solution_post2.id }
+
+ expect(response.status).to eq(200)
+ result = response.parsed_body
+ expect(result).to be_an(Array)
+ expect(result.length).to eq(2)
+ expect(result[0]["id"]).to eq(solution_post.id)
+ expect(result[1]["id"]).to eq(solution_post2.id)
+ end
+ end
end
describe "#unaccept" do
@@ -83,5 +122,38 @@ RSpec.describe DiscourseSolved::AnswerController do
post "/solution/unaccept.json", params: { id: solution_post.id }
expect(response.status).to eq(429)
end
+
+ it "returns an empty array of accepted answers after unaccepting" do
+ sign_in(user)
+
+ post "/solution/unaccept.json", params: { id: solution_post.id }
+
+ expect(response.status).to eq(200)
+ result = response.parsed_body
+ expect(result).to be_nil
+ end
+
+ context "with multiple solutions enabled" do
+ fab!(:solution_post2) { Fabricate(:post, topic: topic) }
+
+ before do
+ SiteSetting.solved_allow_multiple_solutions = true
+ sign_in(user)
+ post "/solution/accept.json", params: { id: solution_post2.id }
+ sign_out
+ end
+
+ it "returns remaining accepted answers as an array" do
+ sign_in(user)
+
+ post "/solution/unaccept.json", params: { id: solution_post.id }
+
+ expect(response.status).to eq(200)
+ result = response.parsed_body
+ expect(result).to be_an(Array)
+ expect(result.length).to eq(1)
+ expect(result[0]["id"]).to eq(solution_post2.id)
+ end
+ end
end
end
diff --git a/plugins/discourse-solved/spec/requests/list_controller_spec.rb b/plugins/discourse-solved/spec/requests/list_controller_spec.rb
index 9515f0f6a39..00df73ac649 100644
--- a/plugins/discourse-solved/spec/requests/list_controller_spec.rb
+++ b/plugins/discourse-solved/spec/requests/list_controller_spec.rb
@@ -18,4 +18,24 @@ RSpec.describe ListController do
expect(posters[1]["description"]).to include("Accepted Answer")
expect(posters[2]["user_id"]).to eq(p2.user_id)
end
+
+ describe "with multiple solutions enabled" do
+ fab!(:p4) { Fabricate(:post, topic: p1.topic) }
+ before { SiteSetting.solved_allow_multiple_solutions = true }
+ it "shows the user who posted the accepted answers second" do
+ TopicFeaturedUsers.ensure_consistency!
+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: p3.id }, guardian: p1.user.guardian)
+ DiscourseSolved::AcceptAnswer.call!(params: { post_id: p4.id }, guardian: p1.user.guardian)
+
+ get "/latest.json"
+ posters = response.parsed_body["topic_list"]["topics"].first["posters"]
+ expect(posters[0]["user_id"]).to eq(p1.user_id)
+
+ accepted_user_ids =
+ posters.filter_map { |p| p["description"].include?("Accepted Answer") ? p["user_id"] : nil }
+ expect(accepted_user_ids).to include(p3.user_id, p4.user_id)
+
+ expect(posters[3]["user_id"]).to eq(p2.user_id)
+ end
+ end
end
diff --git a/plugins/discourse-solved/spec/requests/solved_topics_controller_spec.rb b/plugins/discourse-solved/spec/requests/solved_topics_controller_spec.rb
index f536943d0eb..e45fb236fb0 100644
--- a/plugins/discourse-solved/spec/requests/solved_topics_controller_spec.rb
+++ b/plugins/discourse-solved/spec/requests/solved_topics_controller_spec.rb
@@ -65,6 +65,25 @@ describe DiscourseSolved::SolvedTopicsController do
result = response.parsed_body
expect(result["user_solved_posts"].length).to eq(1)
end
+
+ describe "with multiple solutions enabled" do
+ fab!(:answer_post2) { Fabricate(:post, topic:, user:) }
+ fab!(:topic_answer2) { Fabricate(:topic_answer, solved_topic:, post: answer_post2) }
+ before { SiteSetting.solved_allow_multiple_solutions = true }
+
+ it "returns multiple solved posts from the same topic for the specified user" do
+ sign_in(admin)
+
+ get "/solution/by_user.json", params: { username: user.username }
+
+ expect(response.status).to eq(200)
+ result = response.parsed_body
+ expect(result["user_solved_posts"]).to be_present
+ expect(result["user_solved_posts"].length).to eq(2)
+ expect(result["user_solved_posts"][0]["post_id"]).to eq(answer_post2.id)
+ expect(result["user_solved_posts"][1]["post_id"]).to eq(answer_post.id)
+ end
+ end
end
context "when accessing without username" do
diff --git a/plugins/discourse-solved/spec/requests/topics_controller_spec.rb b/plugins/discourse-solved/spec/requests/topics_controller_spec.rb
index a643fa2caa8..d660d5a7f4e 100644
--- a/plugins/discourse-solved/spec/requests/topics_controller_spec.rb
+++ b/plugins/discourse-solved/spec/requests/topics_controller_spec.rb
@@ -5,22 +5,28 @@ RSpec.describe TopicsController do
let(:topic) { p1.topic }
let(:p2) { Fabricate(:post, like_count: 2, topic:, user: Fabricate(:user)) }
- def expected_schema_json
- answer_json =
- ',"acceptedAnswer":{"@type":"Answer","author":{"@type":"Person","name":"%{username2}","url":"%{user2_url}"},"dateModified":"%{answer_modified}","datePublished":"%{answered_at}","text":"%{answer_text}","upvoteCount":%{answer_likes},"url":"%{answer_url}"}' %
- {
- answer_text: p2.excerpt,
- answer_likes: p2.like_count,
- answered_at: p2.created_at.as_json,
- answer_modified: (p2.last_version_at || p2.created_at).as_json,
- answer_url: p2.full_url,
- username2: p2.user&.username,
- user2_url: p2.user&.full_url,
- }
-
- '<script type="application/ld+json">{"@context":"http://schema.org","@type":"QAPage","name":"%{title}","datePublished":"%{created_at}","mainEntity":{"@type":"Question","answerCount":1,"author":{"@type":"Person","name":"%{username1}","url":"%{user1_url}"},"dateModified":"%{question_modified}","datePublished":"%{created_at}","name":"%{title}","text":"%{question_text}","upvoteCount":%{question_likes}%{answer_json}}}</script>' %
+ def answer_json(post)
+ '{"@type":"Answer","author":{"@type":"Person","name":"%{username2}","url":"%{user2_url}"},"dateModified":"%{answer_modified}","datePublished":"%{answered_at}","text":"%{answer_text}","upvoteCount":%{answer_likes},"url":"%{answer_url}"}' %
+ {
+ answer_text: post.excerpt,
+ answer_likes: post.like_count,
+ answered_at: post.created_at.as_json,
+ answer_modified: (post.last_version_at || post.created_at).as_json,
+ answer_url: post.full_url,
+ username2: post.user&.username,
+ user2_url: post.user&.full_url,
+ }
+ end
+
+ def p2_single_answer_json
+ ',"acceptedAnswer":[%{answer_json}]' % { answer_json: answer_json(p2) }
+ end
+
+ def expected_schema_json(answer_json, answer_count = 1)
+ '<script type="application/ld+json">{"@context":"http://schema.org","@type":"QAPage","name":"%{title}","datePublished":"%{created_at}","mainEntity":{"@type":"Question","answerCount":%{answer_count},"author":{"@type":"Person","name":"%{username1}","url":"%{user1_url}"},"dateModified":"%{question_modified}","datePublished":"%{created_at}","name":"%{title}","text":"%{question_text}","upvoteCount":%{question_likes}%{answer_json}}}</script>' %
# rubocop:enable Layout/LineLength
{
+ answer_count:,
title: topic.title,
question_text: p1.excerpt,
question_likes: p1.like_count,
@@ -46,7 +52,7 @@ RSpec.describe TopicsController do
get "/t/#{topic.slug}/#{topic.id}"
- expect(response.body).to include(expected_schema_json)
+ expect(response.body).to include(expected_schema_json(p2_single_answer_json))
end
it "should include quoted content in schema information" do
@@ -66,25 +72,27 @@ RSpec.describe TopicsController do
SiteSetting.display_name_on_posts = true
SiteSetting.show_who_marked_solved = true
accepter = Fabricate(:user)
- Fabricate(:solved_topic, topic:, answer_post: p2, accepter:)
+ Fabricate(:solved_topic, topic:, topic_answer: Fabricate(:topic_answer, post: p2, accepter:))
get "/t/#{topic.slug}/#{topic.id}.json"
- expect(response.parsed_body["accepted_answer"]["name"]).to eq(p2.user.name)
- expect(response.parsed_body["accepted_answer"]["username"]).to eq(p2.user.username)
- expect(response.parsed_body["accepted_answer"]["accepter_name"]).to eq(accepter.name)
- expect(response.parsed_body["accepted_answer"]["accepter_username"]).to eq(accepter.username)
+ expect(response.parsed_body["accepted_answers"][0]["name"]).to eq(p2.user.name)
+ expect(response.parsed_body["accepted_answers"][0]["username"]).to eq(p2.user.username)
+ expect(response.parsed_body["accepted_answers"][0]["accepter_name"]).to eq(accepter.name)
+ expect(response.parsed_body["accepted_answers"][0]["accepter_username"]).to eq(
+ accepter.username,
+ )
SiteSetting.show_who_marked_solved = false
get "/t/#{topic.slug}/#{topic.id}.json"
- expect(response.parsed_body["accepted_answer"]["accepter_name"]).to eq(nil)
- expect(response.parsed_body["accepted_answer"]["accepter_username"]).to eq(nil)
+ expect(response.parsed_body["accepted_answers"][0]["accepter_name"]).to eq(nil)
+ expect(response.parsed_body["accepted_answers"][0]["accepter_username"]).to eq(nil)
# enable_names is default ON, this ensures disabling it also disables names here
SiteSetting.enable_names = false
get "/t/#{topic.slug}/#{topic.id}.json"
- expect(response.parsed_body["accepted_answer"]["name"]).to eq(nil)
- expect(response.parsed_body["accepted_answer"]["accepter_name"]).to eq(nil)
+ expect(response.parsed_body["accepted_answers"][0]["name"]).to eq(nil)
+ expect(response.parsed_body["accepted_answers"][0]["accepter_name"]).to eq(nil)
end
it "should not include user name when site setting is disabled" do
@@ -93,8 +101,38 @@ RSpec.describe TopicsController do
get "/t/#{topic.slug}/#{topic.id}.json"
- expect(response.parsed_body["accepted_answer"]["name"]).to eq(nil)
- expect(response.parsed_body["accepted_answer"]["username"]).to eq(p2.user.username)
+ expect(response.parsed_body["accepted_answers"][0]["name"]).to eq(nil)
+ expect(response.parsed_body["accepted_answers"][0]["username"]).to eq(p2.user.username)
+ end
+
+ describe "with multiple solutions enabled" do
+ before { SiteSetting.solved_allow_multiple_solutions = true }
+
+ describe "when topic has two accepted answers and one not accepted" do
+ let(:p3) { Fabricate(:post, topic:) }
+ let(:p4) { Fabricate(:post, topic:) }
+ let(:solved_topic) { Fabricate(:solved_topic, topic:) }
+
+ before do
+ Fabricate(:topic_answer, solved_topic:, post: p2)
+ Fabricate(:topic_answer, solved_topic:, post: p3)
+ p4
+ end
+
+ it "should include correct schema information " do
+ get "/t/#{topic.slug}/#{topic.id}"
+
+ two_accepted_answers_json =
+ ',"acceptedAnswer":[%{answer_p2},%{answer_p3}]' %
+ { answer_p2: answer_json(p2), answer_p3: answer_json(p3) }
+ suggested_answer_json =
+ ',"suggestedAnswer":[%{answer_p4}]' % { answer_p4: answer_json(p4) }
+
+ answers_json = "#{two_accepted_answers_json}#{suggested_answer_json}"
+
+ expect(response.body).to include(expected_schema_json(answers_json, 3))
+ end
+ end
end
end
@@ -208,6 +246,76 @@ RSpec.describe TopicsController do
expect(ineligible_node.css("[itemprop]")).to be_empty
end
+ describe "with multiple solutions enabled" do
+ let(:p3) { Fabricate(:post, topic:, cooked: "p3 cooked") }
+ let(:p4) { Fabricate(:post, topic:, cooked: "p4 cooked") }
+ let(:solved_topic) { Fabricate(:solved_topic, topic:) }
+
+ before do
+ SiteSetting.solved_allow_multiple_solutions = true
+ Fabricate(:topic_answer, solved_topic:, post: p2)
+ Fabricate(:topic_answer, solved_topic:, post: p3)
+ p4
+ end
+
+ it "should include two acceptedAnswers and a suggestedAnswer in qaschema" do
+ get "/t/#{topic.slug}/#{topic.id}", env: crawler_env
+ doc = parsed_crawler_body
+
+ qa_page = doc.at_css('[itemtype*="QAPage"]')
+ expect(qa_page).to be_present
+ expect(qa_page.at_css('> [itemprop="name"]')["content"]).to eq(topic.title)
+
+ question = doc.at_css('[itemtype*="Question"]')
+ expect(question).to be_present
+ expect(question.at_css('[itemprop="name"]')["content"]).to eq(topic.title)
+ expect(question.at_css('[itemprop="datePublished"]')["content"]).to be_present
+ expect(question.at_css('[itemprop="answerCount"]')["content"]).to eq("3")
+ expect(question.at_css('[itemprop="upvoteCount"]')["content"]).to eq(p1.like_count.to_s)
+ expect(question.at_css('[itemprop="text"]')).to be_present
+ expect(question.at_css('[itemprop="author"] [itemprop="name"]')).to be_present
+
+ accepted = doc.at_css("#post_#{p2.post_number}")
+ expect(accepted["itemprop"]).to eq("acceptedAnswer")
+ expect(accepted["itemtype"]).to include("Answer")
+ expect(accepted.at_css('[itemprop="text"]')).to be_present
+ expect(accepted.at_css('[itemprop="datePublished"]')).to be_present
+ expect(accepted.at_css('[itemprop="author"] [itemprop="name"]')).to be_present
+ expect(accepted.at_css('[itemprop="author"] [itemprop="url"]')["content"]).to include(
+ p2.user.username,
+ )
+ expect(accepted.at_css('[itemprop="upvoteCount"]')["content"]).to eq(p2.like_count.to_s)
+ accepted_urls = accepted.css('meta[itemprop="url"]').map { |el| el["content"] }
+ expect(accepted_urls).to include(p2.full_url)
+
+ accepted = doc.at_css("#post_#{p3.post_number}")
+ expect(accepted["itemprop"]).to eq("acceptedAnswer")
+ expect(accepted["itemtype"]).to include("Answer")
+ expect(accepted.at_css('[itemprop="text"]')).to be_present
+ expect(accepted.at_css('[itemprop="datePublished"]')).to be_present
+ expect(accepted.at_css('[itemprop="author"] [itemprop="name"]')).to be_present
+ expect(accepted.at_css('[itemprop="author"] [itemprop="url"]')["content"]).to include(
+ p3.user.username,
+ )
+ expect(accepted.at_css('[itemprop="upvoteCount"]')["content"]).to eq(p3.like_count.to_s)
+ accepted_urls = accepted.css('meta[itemprop="url"]').map { |el| el["content"] }
+ expect(accepted_urls).to include(p3.full_url)
+
+ suggested = doc.at_css("#post_#{p4.post_number}")
+ expect(suggested["itemprop"]).to eq("suggestedAnswer")
+ expect(suggested["itemtype"]).to include("Answer")
+ expect(suggested.at_css('[itemprop="text"]')).to be_present
+ expect(suggested.at_css('[itemprop="datePublished"]')).to be_present
+ expect(suggested.at_css('[itemprop="author"] [itemprop="name"]')).to be_present
+ expect(suggested.at_css('[itemprop="author"] [itemprop="url"]')["content"]).to include(
+ p4.user.username,
+ )
+ expect(suggested.at_css('[itemprop="upvoteCount"]')["content"]).to eq(p4.like_count.to_s)
+ suggested_urls = suggested.css('meta[itemprop="url"]').map { |el| el["content"] }
+ expect(suggested_urls).to include(p4.full_url)
+ end
+ end
+
it "does not modify schema for topics without solved enabled" do
SiteSetting.allow_solved_on_all_topics = false
@@ -262,7 +370,7 @@ RSpec.describe TopicsController do
get "/t/#{topic.slug}/#{topic.id}"
- expect(response.body).to include(expected_schema_json)
+ expect(response.body).to include(expected_schema_json(p2_single_answer_json))
end
it "doesn't include solved schema information when the topic has a different tag" do
@@ -273,7 +381,7 @@ RSpec.describe TopicsController do
get "/t/#{topic.slug}/#{topic.id}"
- expect(response.body).not_to include(expected_schema_json)
+ expect(response.body).not_to include(expected_schema_json(p2_single_answer_json))
end
end
end
diff --git a/plugins/discourse-solved/spec/serializers/discourse_solved/accepted_answer_serializer_spec.rb b/plugins/discourse-solved/spec/serializers/discourse_solved/accepted_answer_serializer_spec.rb
new file mode 100644
index 00000000000..73d5fd41834
--- /dev/null
+++ b/plugins/discourse-solved/spec/serializers/discourse_solved/accepted_answer_serializer_spec.rb
@@ -0,0 +1,75 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseSolved::AcceptedAnswerSerializer do
+ fab!(:user)
+ fab!(:accepter, :user)
+ fab!(:post) { Fabricate(:post, user: user, like_count: 3) }
+
+ subject(:json) do
+ described_class.new(post, root: false, accepter:).serializable_hash.deep_stringify_keys
+ end
+
+ it "includes expected default attributes" do
+ expect(json["id"]).to eq(post.id)
+ expect(json["post_number"]).to eq(post.post_number)
+ expect(json["topic_id"]).to eq(post.topic_id)
+ expect(json["url"]).to eq(post.url)
+ expect(json["username"]).to eq(user.username)
+ expect(json["created_at"]).to eq(post.created_at)
+ expect(json["cooked"]).to eq(post.cooked)
+ expect(json).not_to have_key("name")
+ expect(json).not_to have_key("accepter_name")
+ expect(json).not_to have_key("accepter_username")
+ end
+
+ context "when the answer post user is deleted" do
+ before do
+ user.destroy!
+ post.reload
+ end
+
+ it "falls back to the system user identity" do
+ expect(json["username"]).to eq(Discourse.system_user.username)
+ expect(json["avatar_template"]).to eq(Discourse.system_user.avatar_template)
+ end
+
+ context "when display_name_on_posts is set" do
+ before { SiteSetting.display_name_on_posts = true }
+
+ it "falls back to the system user name" do
+ expect(json["name"]).to eq(Discourse.system_user.name)
+ end
+ end
+ end
+
+ context "when display_name_on_posts is set" do
+ before { SiteSetting.display_name_on_posts = true }
+ it "also includes the poster's name" do
+ expect(json["name"]).to eq(user.name)
+ end
+ end
+
+ context "when show_who_marked_solved is enabled" do
+ before { SiteSetting.show_who_marked_solved = true }
+
+ it "includes the username" do
+ expect(json).not_to have_key("accepter_name")
+ end
+
+ context "when display_name_on_posts is set" do
+ before { SiteSetting.display_name_on_posts = true }
+ it "also includes the accepter name" do
+ expect(json["accepter_username"]).to eq(accepter.username)
+ expect(json["accepter_name"]).to eq(accepter.name)
+ end
+ end
+ end
+
+ context "when solved_quote_length is disabled" do
+ before { SiteSetting.solved_quote_length = 0 }
+
+ it "does not include cooked content" do
+ expect(json).not_to have_key("cooked")
+ end
+ end
+end
diff --git a/plugins/discourse-solved/spec/serializers/discourse_solved/question_schema_serializer_spec.rb b/plugins/discourse-solved/spec/serializers/discourse_solved/question_schema_serializer_spec.rb
index cf92e2a6ec5..21941343398 100644
--- a/plugins/discourse-solved/spec/serializers/discourse_solved/question_schema_serializer_spec.rb
+++ b/plugins/discourse-solved/spec/serializers/discourse_solved/question_schema_serializer_spec.rb
@@ -39,7 +39,7 @@ RSpec.describe DiscourseSolved::QuestionSchemaSerializer do
subject(:json) do
described_class
- .new(topic, root: false, accepted_answer: answer_post)
+ .new(topic, root: false, accepted_answers: [answer_post])
.serializable_hash
.deep_stringify_keys
end
@@ -48,8 +48,8 @@ RSpec.describe DiscourseSolved::QuestionSchemaSerializer do
expect(json["answerCount"]).to eq(1)
end
- it "includes the accepted answer" do
- accepted = json["acceptedAnswer"]
+ it "includes accepted answer as an array of Answer objects" do
+ accepted = json["acceptedAnswer"].sole
expect(accepted["@type"]).to eq("Answer")
expect(accepted["text"]).to be_present
expect(accepted["datePublished"]).to be_present
@@ -67,7 +67,12 @@ RSpec.describe DiscourseSolved::QuestionSchemaSerializer do
subject(:json) do
described_class
- .new(topic, root: false, accepted_answer: answer_post, suggested_answers: [suggested_post])
+ .new(
+ topic,
+ root: false,
+ accepted_answers: [answer_post],
+ suggested_answers: [suggested_post],
+ )
.serializable_hash
.deep_stringify_keys
end
diff --git a/plugins/discourse-solved/spec/serializers/topic_view_serializer_spec.rb b/plugins/discourse-solved/spec/serializers/topic_view_serializer_spec.rb
index b3332145442..a1b698b2531 100644
--- a/plugins/discourse-solved/spec/serializers/topic_view_serializer_spec.rb
+++ b/plugins/discourse-solved/spec/serializers/topic_view_serializer_spec.rb
@@ -13,23 +13,42 @@ describe TopicViewSerializer do
Fabricate(:solved_topic, topic: topic, answer_post: post2)
serializer = TopicViewSerializer.new(TopicView.new(topic), scope: Guardian.new(user))
serialized = serializer.as_json
- expect(serialized[:topic_view][:accepted_answer][:post_number]).to eq(post2.post_number)
+ expect(serialized[:topic_view][:accepted_answers][0][:post_number]).to eq(post2.post_number)
end
it "returns nil when the topic does not have an accepted answer" do
unsolved_topic = Fabricate(:topic)
serializer = TopicViewSerializer.new(TopicView.new(unsolved_topic), scope: Guardian.new(user))
serialized = serializer.as_json
- expect(serialized[:accepted_answer]).to be_nil
+ expect(serialized[:topic_view][:accepted_answers]).to be_nil
end
it "returns nil when the accepted answer post does not exist" do
weird_topic = Fabricate(:solved_topic)
- weird_topic.update!(answer_post_id: 19_238_319)
+ Fabricate(:topic_answer, solved_topic: weird_topic)
+ weird_topic.topic_answers.first.update!(answer_post_id: 19_238_319)
serializer =
TopicViewSerializer.new(TopicView.new(weird_topic.topic), scope: Guardian.new(user))
serialized = serializer.as_json
- expect(serialized[:accepted_answer]).to be_nil
+ expect(serialized[:topic_view][:accepted_answers]).to be_nil
+ end
+
+ describe "with multiple solutions enabled" do
+ fab!(:post3) { Fabricate(:post, topic:, user:) }
+ fab!(:solved_topic) { Fabricate(:solved_topic, topic:) }
+ before do
+ SiteSetting.solved_allow_multiple_solutions = true
+ Fabricate(:topic_answer, solved_topic:, post: post2)
+ Fabricate(:topic_answer, solved_topic:, post: post3)
+ end
+
+ it "returns all answer posts when the topic has accepted answers" do
+ serializer = TopicViewSerializer.new(TopicView.new(topic), scope: Guardian.new(user))
+ serialized = serializer.as_json
+ expect(serialized[:topic_view][:accepted_answers].length).to eq(2)
+ expect(serialized[:topic_view][:accepted_answers][0][:post_number]).to eq(post2.post_number)
+ expect(serialized[:topic_view][:accepted_answers][1][:post_number]).to eq(post3.post_number)
+ end
end
end
end
diff --git a/plugins/discourse-solved/spec/serializers/user_card_serializer_spec.rb b/plugins/discourse-solved/spec/serializers/user_card_serializer_spec.rb
index e01981f8e38..b0a5a1653f0 100644
--- a/plugins/discourse-solved/spec/serializers/user_card_serializer_spec.rb
+++ b/plugins/discourse-solved/spec/serializers/user_card_serializer_spec.rb
@@ -16,8 +16,7 @@ describe UserCardSerializer do
it "returns the correct count" do
expect(serializer.as_json[:accepted_answers]).to eq(0)
- topic = Fabricate(:topic)
- Fabricate(:post, topic:)
+ topic = Fabricate(:topic_with_op)
post = Fabricate(:post, topic:, user:)
DiscourseSolved::AcceptAnswer.call!(
params: {
@@ -28,5 +27,45 @@ describe UserCardSerializer do
expect(serializer.as_json[:accepted_answers]).to eq(1)
end
+
+ describe "with multiple solutions enabled" do
+ before { SiteSetting.solved_allow_multiple_solutions = true }
+
+ it "returns the correct count" do
+ expect(serializer.as_json[:accepted_answers]).to eq(0)
+
+ topic = Fabricate(:topic_with_op)
+ post = Fabricate(:post, topic:, user:)
+ DiscourseSolved::AcceptAnswer.call!(
+ params: {
+ post_id: post.id,
+ },
+ guardian: Discourse.system_user.guardian,
+ )
+
+ expect(serializer.as_json[:accepted_answers]).to eq(1)
+
+ post2 = Fabricate(:post, topic:, user:)
+ DiscourseSolved::AcceptAnswer.call!(
+ params: {
+ post_id: post2.id,
+ },
+ guardian: Discourse.system_user.guardian,
+ )
+
+ expect(serializer.as_json[:accepted_answers]).to eq(2)
+
+ topic2 = Fabricate(:topic_with_op)
+ post3 = Fabricate(:post, topic: topic2, user:)
+ DiscourseSolved::AcceptAnswer.call!(
+ params: {
+ post_id: post3.id,
+ },
+ guardian: Discourse.system_user.guardian,
+ )
+
+ expect(serializer.as_json[:accepted_answers]).to eq(3)
+ end
+ end
end
end
diff --git a/plugins/discourse-solved/spec/serializers/user_summary_serializer_spec.rb b/plugins/discourse-solved/spec/serializers/user_summary_serializer_spec.rb
index e241fb89b7e..0c2c54b9990 100644
--- a/plugins/discourse-solved/spec/serializers/user_summary_serializer_spec.rb
+++ b/plugins/discourse-solved/spec/serializers/user_summary_serializer_spec.rb
@@ -19,8 +19,7 @@ describe UserSummarySerializer do
it "returns the correct count" do
expect(serializer.as_json[:solved_count]).to eq(0)
- topic = Fabricate(:topic)
- Fabricate(:post, topic:)
+ topic = Fabricate(:topic_with_op)
post = Fabricate(:post, topic:, user:)
DiscourseSolved::AcceptAnswer.call!(
params: {
@@ -31,5 +30,45 @@ describe UserSummarySerializer do
expect(serializer.as_json[:solved_count]).to eq(1)
end
+
+ describe "with multiple solutions enabled" do
+ before { SiteSetting.solved_allow_multiple_solutions = true }
+
+ it "returns the correct count" do
+ expect(serializer.as_json[:solved_count]).to eq(0)
+
+ topic = Fabricate(:topic_with_op)
+ post = Fabricate(:post, topic:, user:)
+ DiscourseSolved::AcceptAnswer.call!(
+ params: {
+ post_id: post.id,
+ },
+ guardian: Discourse.system_user.guardian,
+ )
+
+ expect(serializer.as_json[:solved_count]).to eq(1)
+
+ post2 = Fabricate(:post, topic:, user:)
+ DiscourseSolved::AcceptAnswer.call!(
+ params: {
+ post_id: post2.id,
+ },
+ guardian: Discourse.system_user.guardian,
+ )
+
+ expect(serializer.as_json[:solved_count]).to eq(2)
+
+ topic2 = Fabricate(:topic_with_op)
+ post3 = Fabricate(:post, topic: topic2, user:)
+ DiscourseSolved::AcceptAnswer.call!(
+ params: {
+ post_id: post3.id,
+ },
+ guardian: Discourse.system_user.guardian,
+ )
+
+ expect(serializer.as_json[:solved_count]).to eq(3)
+ end
+ end
end
end
diff --git a/plugins/discourse-solved/spec/services/discourse_solved/accept_answer_spec.rb b/plugins/discourse-solved/spec/services/discourse_solved/accept_answer_spec.rb
index 8237a87cf82..6ff3e8fc243 100644
--- a/plugins/discourse-solved/spec/services/discourse_solved/accept_answer_spec.rb
+++ b/plugins/discourse-solved/spec/services/discourse_solved/accept_answer_spec.rb
@@ -66,8 +66,14 @@ RSpec.describe DiscourseSolved::AcceptAnswer do
it { is_expected.to run_successfully }
context "when a previous answer was already accepted" do
- fab!(:existing_solved) do
- Fabricate(:solved_topic, topic:, answer_post: post_1, accepter: acting_user)
+ fab!(:existing_solved) { Fabricate(:solved_topic, topic:) }
+ fab!(:existing_topic_answer) do
+ Fabricate(
+ :topic_answer,
+ solved_topic: existing_solved,
+ post: post_1,
+ accepter: acting_user,
+ )
end
fab!(:previous_user_action) do
UserAction.log_action!(
@@ -80,11 +86,13 @@ RSpec.describe DiscourseSolved::AcceptAnswer do
end
it "keeps only one solution per topic" do
- expect { result }.not_to change { DiscourseSolved::SolvedTopic.count }
+ expect { result }.not_to change { DiscourseSolved::TopicAnswer.count }
end
it "replaces the accepted answer" do
- expect { result }.to change { topic.reload.solved.answer_post }.from(post_1).to(post)
+ expect { result }.to change { topic.reload.topic_answers.first.post }.from(post_1).to(
+ post,
+ )
end
it "revokes the previous answer's solved credit" do
@@ -92,6 +100,65 @@ RSpec.describe DiscourseSolved::AcceptAnswer do
UserAction.where(action_type: UserAction::SOLVED, target_post: post_1).count
}.by(-1)
end
+
+ describe "with multiple solutions enabled" do
+ before { SiteSetting.solved_allow_multiple_solutions = true }
+ it "keeps both solutions" do
+ expect { result }.to change { DiscourseSolved::TopicAnswer.count }.by(1)
+ end
+
+ it "does not replace the accepted answer" do
+ expect { result }.not_to change { topic.reload.topic_answers[0].post }
+ expect(topic.topic_answers[0].post).to eq(post_1)
+ expect(topic.topic_answers[1].post).to eq(post)
+ end
+
+ it "does not revoke the previous answer's solved credit" do
+ expect { result }.to not_change {
+ UserAction.where(action_type: UserAction::SOLVED, target_post: post_1).count
+ }.and change {
+ UserAction.where(action_type: UserAction::SOLVED, target_post: post).count
+ }.by(1)
+ end
+ end
+
+ context "with multiple solutions disabled after two solutions were already accepted" do
+ fab!(:post_2, :post) { Fabricate(:post, topic:) }
+
+ before do
+ UserAction.log_action!(
+ action_type: UserAction::SOLVED,
+ user_id: post_2.user_id,
+ acting_user_id: acting_user.id,
+ target_post_id: post_2.id,
+ target_topic_id: topic.id,
+ )
+ Fabricate(
+ :topic_answer,
+ solved_topic: existing_solved,
+ post: post_2,
+ accepter: acting_user,
+ )
+ end
+
+ it "revokes all existing topic answers and user actions" do
+ expect { result }.to change { topic.reload.topic_answers.count }.from(2).to(
+ 1,
+ ).and change {
+ UserAction.where(action_type: UserAction::SOLVED, target_post: post_1).count
+ }.by(-1).and change {
+ UserAction.where(
+ action_type: UserAction::SOLVED,
+ target_post: post_2,
+ ).count
+ }.by(-1)
+ end
+ end
+
+ it "replacing an accepted answer destroys the old SolvedTopic and creates a new one" do
+ old_solved_topic_id = topic.solved.id
+ expect { result }.to change { topic.reload.solved.id }.from(old_solved_topic_id)
+ end
end
it "credits the post author with a solved action" do
@@ -101,9 +168,11 @@ RSpec.describe DiscourseSolved::AcceptAnswer do
end
it "marks the topic as solved" do
- expect(result[:solved]).to have_attributes(
- topic: topic,
- answer_post: post,
+ expect { result }.to change { DiscourseSolved::SolvedTopic.count }.by(1)
+ expect(result[:solved_topic]).to have_attributes(topic: topic)
+ expect(result[:topic_answer]).to have_attributes(
+ solved_topic_id: result[:solved_topic].id,
+ post: post,
accepter: acting_user,
)
end
diff --git a/plugins/discourse-solved/spec/services/discourse_solved/build_schema_markup_spec.rb b/plugins/discourse-solved/spec/services/discourse_solved/build_schema_markup_spec.rb
index 4ddc9d8b619..b94e8f4c350 100644
--- a/plugins/discourse-solved/spec/services/discourse_solved/build_schema_markup_spec.rb
+++ b/plugins/discourse-solved/spec/services/discourse_solved/build_schema_markup_spec.rb
@@ -108,6 +108,44 @@ RSpec.describe DiscourseSolved::BuildSchemaMarkup do
end
end
+ describe "with multiple solutions enabled" do
+ before { SiteSetting.solved_allow_multiple_solutions = true }
+
+ describe "when topic has two accepted answers and one not accepted" do
+ fab!(:answer_post_1) { Fabricate(:post, topic:) }
+ fab!(:answer_post_2) { Fabricate(:post, topic:) }
+ fab!(:non_answer_post) { Fabricate(:post, topic:) }
+ fab!(:solved_topic) { Fabricate(:solved_topic, topic:) }
+
+ before do
+ Fabricate(:topic_answer, solved_topic:, post: answer_post_1)
+ Fabricate(:topic_answer, solved_topic:, post: answer_post_2)
+ end
+
+ it "builds QAPage markup with both acceptedAnswers and suggestedAnswer" do
+ html = result[:html]
+ expect(html).to include('"@type":"QAPage"')
+ expect(html).to include('"answerCount":3')
+ expect(html).to include('"acceptedAnswer"')
+ expect(html).to include('"suggestedAnswer"')
+
+ accepted_answer_index = html.index("acceptedAnswer")
+ suggested_answer_index = html.index("suggestedAnswer")
+
+ accepted_answer_part = html[accepted_answer_index..suggested_answer_index]
+ accepted_answer_part_split = accepted_answer_part.split("},{")
+ expect(accepted_answer_part_split[0]).to include('"@type":"Answer"')
+ expect(accepted_answer_part_split[0]).to include(answer_post_1.url)
+ expect(accepted_answer_part_split[1]).to include('"@type":"Answer"')
+ expect(accepted_answer_part_split[1]).to include(answer_post_2.url)
+
+ suggested_answer_part = html[suggested_answer_index..]
+ expect(accepted_answer_part).to include('"@type":"Answer"')
+ expect(suggested_answer_part).to include(non_answer_post.url)
+ end
+ end
+ end
+
context "with a non-text post" do
before { SiteSetting.solved_add_schema_markup = "always" }
diff --git a/plugins/discourse-solved/spec/services/discourse_solved/shared_issue/toggle_spec.rb b/plugins/discourse-solved/spec/services/discourse_solved/shared_issue/toggle_spec.rb
index 83536874616..a13884fbfbd 100644
--- a/plugins/discourse-solved/spec/services/discourse_solved/shared_issue/toggle_spec.rb
+++ b/plugins/discourse-solved/spec/services/discourse_solved/shared_issue/toggle_spec.rb
@@ -48,9 +48,24 @@ RSpec.describe DiscourseSolved::SharedIssue::Toggle do
context "when the topic is already solved" do
fab!(:answer_post) { Fabricate(:post, topic:) }
- before { Fabricate(:solved_topic, topic:, answer_post:, accepter: author) }
+ before do
+ solved_topic = Fabricate(:solved_topic, topic:)
+ Fabricate(:topic_answer, solved_topic:, post: answer_post, accepter: author)
+ end
it { is_expected.to fail_a_policy(:can_create_shared_issue) }
+
+ context "when allow_multiple_solutions is enabled" do
+ before { SiteSetting.solved_allow_multiple_solutions = true }
+
+ it { is_expected.to run_successfully }
+
+ it "creates a shared issue record" do
+ expect { result }.to change {
+ DiscourseSolved::SharedIssue.where(topic:, user: acting_user).count
+ }.by(1)
+ end
+ end
end
context "when the acting user is the topic author" do
diff --git a/plugins/discourse-solved/spec/services/discourse_solved/unaccept_answer_spec.rb b/plugins/discourse-solved/spec/services/discourse_solved/unaccept_answer_spec.rb
index ba74f8afbf0..e877685d784 100644
--- a/plugins/discourse-solved/spec/services/discourse_solved/unaccept_answer_spec.rb
+++ b/plugins/discourse-solved/spec/services/discourse_solved/unaccept_answer_spec.rb
@@ -74,12 +74,13 @@ RSpec.describe DiscourseSolved::UnacceptAnswer do
it { is_expected.to run_successfully }
it "does not mark the topic as unsolved" do
- expect { result }.not_to change { DiscourseSolved::SolvedTopic.count }
+ expect { result }.not_to change { DiscourseSolved::TopicAnswer.count }
end
end
context "when the post is the accepted answer" do
- fab!(:solved_topic) { Fabricate(:solved_topic, topic:, answer_post: post, accepter: user) }
+ fab!(:solved_topic) { Fabricate(:solved_topic, topic:) }
+ fab!(:topic_answer) { Fabricate(:topic_answer, solved_topic:, post: post, accepter: user) }
let(:messages) { MessageBus.track_publish("/topic/#{topic.id}") { result } }
let(:events) { DiscourseEvent.track_events(:unaccepted_solution) { result } }
@@ -177,16 +178,50 @@ RSpec.describe DiscourseSolved::UnacceptAnswer do
before { post.trash! }
it "still marks the topic as unsolved" do
- expect { result }.to change { DiscourseSolved::SolvedTopic.count }.by(-1)
+ expect { result }.to change { DiscourseSolved::TopicAnswer.count }.by(-1)
end
end
context "when a different post is the accepted answer" do
- before { solved_topic.update!(answer_post: post_1) }
+ before { solved_topic.topic_answers.first.update!(post: post_1) }
+
+ it "does not mark the topic as unsolved" do
+ expect { result }.not_to change { DiscourseSolved::TopicAnswer.count }
+ end
+ end
+
+ describe "with multiple solutions enabled and another existing solution" do
+ fab!(:post2) { Fabricate(:post, topic:) }
+ fab!(:topic_answer2) do
+ Fabricate(:topic_answer, solved_topic:, post: post2, accepter: user)
+ end
+
+ before { SiteSetting.solved_allow_multiple_solutions = true }
+
+ it "revokes the post author's solved credit" do
+ expect { result }.to change {
+ UserAction.where(action_type: UserAction::SOLVED, target_post: post).count
+ }.by(-1)
+ end
+
+ it "removes the accepted answer notification" do
+ expect { result }.to change {
+ Notification.where(
+ notification_type: Notification.types[:custom],
+ user: post.user,
+ topic: post.topic,
+ post_number: post.post_number,
+ ).count
+ }.by(-1)
+ end
it "does not mark the topic as unsolved" do
expect { result }.not_to change { DiscourseSolved::SolvedTopic.count }
end
+
+ it "removes one TopicAnswer" do
+ expect { result }.to change { DiscourseSolved::TopicAnswer.count }.by(-1)
+ end
end
end
end
diff --git a/plugins/discourse-solved/spec/system/shared_issue_spec.rb b/plugins/discourse-solved/spec/system/shared_issue_spec.rb
index e798aa1c90f..bacc1781b68 100644
--- a/plugins/discourse-solved/spec/system/shared_issue_spec.rb
+++ b/plugins/discourse-solved/spec/system/shared_issue_spec.rb
@@ -48,7 +48,8 @@ describe "Solved | Shared issue button" do
it "hides the button once the topic is solved" do
answer_post = Fabricate(:post, topic:)
- Fabricate(:solved_topic, topic:, answer_post:, accepter: author)
+ solved_topic = Fabricate(:solved_topic, topic:)
+ Fabricate(:topic_answer, solved_topic:, post: answer_post, accepter: author)
sign_in(member)
topic_page.visit_topic(topic)
@@ -67,11 +68,11 @@ describe "Solved | Shared issue button" do
within("#post_#{answer_post.post_number}") do
find(".post-action-menu__solved-unaccepted").click
end
- expect(page).to have_css(".accepted-answer")
+ expect(page).to have_css(".accepted-answers")
expect(shared_issue_button).to have_no_shared_issue_button
within("#post_#{answer_post.post_number}") { find(".post-action-menu__solved-accepted").click }
- expect(page).to have_no_css(".accepted-answer")
+ expect(page).to have_no_css(".accepted-answers")
expect(shared_issue_button).to have_shared_issue_button
end
@@ -110,4 +111,32 @@ describe "Solved | Shared issue button" do
expect(shared_issue_button).to have_read_only
expect(shared_issue_button).to have_count(0)
end
+
+ describe "with multiple solutions enabled" do
+ before { SiteSetting.solved_allow_multiple_solutions = true }
+
+ it "shows the button even after a solution is accepted" do
+ answer_post = Fabricate(:post, topic:)
+ solved_topic = Fabricate(:solved_topic, topic:)
+ Fabricate(:topic_answer, solved_topic:, post: answer_post, accepter: author)
+
+ sign_in(member)
+ topic_page.visit_topic(topic)
+
+ expect(shared_issue_button).to have_shared_issue_button
+ end
+
+ it "lets a member create a shared issue on a solved topic" do
+ answer_post = Fabricate(:post, topic:)
+ solved_topic = Fabricate(:solved_topic, topic:)
+ Fabricate(:topic_answer, solved_topic:, post: answer_post, accepter: author)
+
+ sign_in(member)
+ topic_page.visit_topic(topic)
+
+ shared_issue_button.click
+ expect(shared_issue_button).to have_active
+ expect(shared_issue_button).to have_count(1)
+ end
+ end
end
diff --git a/plugins/discourse-solved/spec/system/solved_spec.rb b/plugins/discourse-solved/spec/system/solved_spec.rb
index b2137f09df4..4f0422bdbfa 100644
--- a/plugins/discourse-solved/spec/system/solved_spec.rb
+++ b/plugins/discourse-solved/spec/system/solved_spec.rb
@@ -15,10 +15,12 @@ describe "Solved" do
UNACCEPTED_BUTTON_SELECTOR = ".post-action-menu__solved-unaccepted"
ACCEPTED_BUTTON_SELECTOR = ".post-action-menu__solved-accepted"
- ACCEPTED_ANSWER_QUOTE_SELECTOR = "aside.accepted-answer.quote"
- SOLVER_INFO_SELECTOR = ".d-solved-answer__footer .d-solved-answer__solver"
- ACCEPTER_INFO_SELECTOR = ".d-solved-answer__footer .d-solved-answer__accepter"
- QUOTE_TOGGLE_SELECTOR = "aside.accepted-answer.quote button.d-solved-answer__toggle"
+ ACCEPTED_ANSWER_SELECTOR = ".accepted-answers .d-post-accordion-item"
+ ACCEPTED_ANSWER_CONTENT_SELECTOR = ".d-post-accordion-item__content"
+ SOLVER_SELECTOR = ".d-post-accordion-item__metadata .user-link"
+ ACCEPTER_SELECTOR = ".d-post-accordion-item__metadata .accepter-link"
+ QUOTE_TOGGLE_SELECTOR = ".d-post-accordion-item__toggle"
+ QUOTE_JUMP_SELECTOR = ".d-post-accordion-item__jump"
before do
SiteSetting.solved_enabled = true
@@ -30,59 +32,105 @@ describe "Solved" do
it "accepts post as solution and shows in OP" do
sign_in(accepter)
- visit_solver_post
-
- verify_solution_unaccepted_state
- accept_solution
- verify_solution_accepted_state
- verify_solution_quote_content
- verify_solver_and_accepter_info
- expand_solution_quote
+ visit_solver_post(2)
+
+ verify_solution_unaccepted_state(2)
+ accept_solution(2)
+ verify_solution_accepted_state(2)
+ verify_solution_content(2, "The answer is 42")
+ verify_solver_and_accepter_info(2, solver, accepter)
+ verify_solution_excerpt_expanded(2)
+ toggle_solution_excerpt(2)
+ verify_solution_excerpt_collapsed(2)
end
it "accepts and unaccepts post as solution" do
sign_in(accepter)
- visit_solver_post
+ visit_solver_post(2)
- verify_solution_unaccepted_state
- accept_solution
- verify_solution_accepted_state
+ verify_solution_unaccepted_state(2)
+ accept_solution(2)
+ verify_solution_accepted_state(2)
verify_solution_info_present
- unaccept_solution
- verify_solution_unaccepted_state
+ unaccept_solution(2)
+ verify_solution_unaccepted_state(2)
verify_solution_info_absent
end
it "shows the solved post in user activity at /my/activity/solved" do
- Fabricate(:solved_topic, topic:, answer_post: solver_post, accepter:)
+ solved_topic = Fabricate(:solved_topic, topic:)
+ Fabricate(:topic_answer, solved_topic:, post: solver_post, accepter:)
sign_in(solver)
visit "/my/activity/solved"
expect(page.find(".post-list")).to have_content("The answer is 42")
end
- describe "solution excerpt expand toggle" do
- it "shows the toggle when the answer overflows the preview" do
- Fabricate(:solved_topic, topic:, answer_post: solver_post, accepter:)
+ describe "hidden overflow" do
+ before do
+ solved_topic = Fabricate(:solved_topic, topic:)
+ Fabricate(:topic_answer, solved_topic:, post: solver_post, accepter:)
+ end
- sign_in(accepter)
- topic_page.visit_topic(topic)
+ describe "when solved_quote_length = 0" do
+ before { SiteSetting.solved_quote_length = 0 }
+
+ it "hides content, displays jump button" do
+ sign_in(solver)
+ topic_page.visit_topic(topic)
- expect(topic_page).to have_css(QUOTE_TOGGLE_SELECTOR)
+ within("#{ACCEPTED_ANSWER_SELECTOR}[data-post='2']") do
+ expect(page).not_to have_css(QUOTE_TOGGLE_SELECTOR)
+ expect(page).not_to have_css(".d-post-accordion-item__body")
+ expect(page).to have_css(QUOTE_JUMP_SELECTOR)
+ find(QUOTE_JUMP_SELECTOR).click
+ end
+ end
end
- it "hides the toggle when the answer fits within the preview" do
- short_post = Fabricate(:post, topic:, user: solver, cooked: "<p>The answer is 42.</p>")
- Fabricate(:solved_topic, topic:, answer_post: short_post, accepter:)
+ describe "when solved_quote_length is short" do
+ before { SiteSetting.solved_quote_length = 1 }
- sign_in(accepter)
- topic_page.visit_topic(topic)
+ it "sets the overflowing data element" do
+ sign_in(solver)
+ topic_page.visit_topic(topic)
+
+ expect(page).to have_css(
+ "#{ACCEPTED_ANSWER_SELECTOR}[data-post='2'][data-overflowing='true']",
+ )
+ expect(page).to have_css(".d-post-accordion-item__body")
+ end
+ end
- expect(topic_page).to have_css(ACCEPTED_ANSWER_QUOTE_SELECTOR)
- expect(topic_page).to have_no_css(QUOTE_TOGGLE_SELECTOR)
+ describe "when solved_quote_length is long" do
+ before { SiteSetting.solved_quote_length = 99_999_999 }
+
+ it "does not set the overflowing data element" do
+ sign_in(solver)
+ topic_page.visit_topic(topic)
+
+ expect(page).to have_css(
+ "#{ACCEPTED_ANSWER_SELECTOR}[data-post='2'][data-overflowing='false']",
+ )
+ expect(page).to have_css(".d-post-accordion-item__body")
+ end
end
end
+ it "should collapse/expand the solution when clicking the toggle" do
+ solved_topic = Fabricate(:solved_topic, topic:)
+ Fabricate(:topic_answer, solved_topic:, post: solver_post, accepter:)
+
+ sign_in(accepter)
+ topic_page.visit_topic(topic)
+
+ verify_solution_excerpt_expanded(2)
+ toggle_solution_excerpt(2)
+ verify_solution_excerpt_collapsed(2)
+ toggle_solution_excerpt(2)
+ verify_solution_excerpt_expanded(2)
+ end
+
describe "solution excerpt formatting" do
it "preserves code blocks in the solution excerpt" do
raw = <<~RAW
@@ -97,12 +145,12 @@ describe "Solved" do
Hope this helps!
RAW
code_solution_post = Fabricate(:post, topic:, user: admin, raw:)
- Fabricate(:solved_topic, topic:, answer_post: code_solution_post, accepter:)
-
+ solved_topic = Fabricate(:solved_topic, topic:)
+ Fabricate(:topic_answer, solved_topic:, post: code_solution_post, accepter:)
sign_in(accepter)
topic_page.visit_topic(topic)
- within("#{ACCEPTED_ANSWER_QUOTE_SELECTOR} blockquote") do
+ within(ACCEPTED_ANSWER_CONTENT_SELECTOR) do
expect(page).to have_css("pre code.lang-ruby")
expect(page).to have_content("def hello")
expect(page).to have_content('puts "world"')
@@ -113,63 +161,174 @@ describe "Solved" do
upload = Fabricate(:upload)
raw = "Check this image: ![test image](#{upload.short_url})"
image_solution_post = Fabricate(:post, topic:, user: admin, raw:)
- Fabricate(:solved_topic, topic:, answer_post: image_solution_post, accepter:)
+ solved_topic = Fabricate(:solved_topic, topic:)
+ Fabricate(:topic_answer, solved_topic:, post: image_solution_post, accepter:)
sign_in(accepter)
topic_page.visit_topic(topic)
- within("#{ACCEPTED_ANSWER_QUOTE_SELECTOR} blockquote") { expect(page).to have_css("img") }
+ within(ACCEPTED_ANSWER_CONTENT_SELECTOR) { expect(page).to have_css("img") }
+ end
+ end
+
+ describe "with multiple solutions enabled" do
+ fab!(:solver2, :user)
+ fab!(:accepter2, :user)
+ fab!(:solver_post2) do
+ Fabricate(:post, topic:, user: solver2, cooked: "The answer is over 9000")
+ end
+
+ before { SiteSetting.solved_allow_multiple_solutions = true }
+
+ it "accepts two posts as solutions and shows in OP" do
+ sign_in(accepter)
+ visit_solver_post(2)
+
+ verify_solution_info_absent
+ verify_solution_unaccepted_state(2)
+ verify_solution_unaccepted_state(3)
+
+ accept_solution(2)
+
+ verify_solution_info_present
+ verify_solution_accepted_state(2)
+ verify_solution_unaccepted_state(3)
+ verify_solution_excerpt_expanded(2)
+ verify_solution_content(2, "The answer is 42")
+ verify_solver_and_accepter_info(2, solver, accepter)
+
+ sign_in(accepter2)
+ visit_solver_post(3)
+
+ verify_solution_info_present
+ verify_solution_accepted_state(2)
+ verify_solution_unaccepted_state(3)
+
+ accept_solution(3)
+
+ verify_solution_info_present
+ verify_solution_accepted_state(2)
+ verify_solution_accepted_state(3)
+ verify_solution_excerpt_expanded(2)
+ verify_solution_excerpt_collapsed(3)
+ verify_solver_and_accepter_info(2, solver, accepter)
+ verify_solver_and_accepter_info(3, solver2, accepter2)
+ verify_solution_content(2, "The answer is 42")
+ verify_solution_content_missing(3)
+ toggle_solution_excerpt(3)
+ verify_solution_excerpt_expanded(3)
+ verify_solution_content(3, "The answer is over 9000")
+ end
+
+ it "correctly updates excerpts when removing one of many accepted solutions" do
+ sign_in(accepter)
+ visit_solver_post(2)
+
+ verify_solution_info_absent
+
+ accept_solution(2)
+ accept_solution(3)
+
+ verify_solution_info_present
+ verify_solution_accepted_state(2)
+ verify_solution_accepted_state(3)
+ verify_solution_excerpt_expanded(2)
+ verify_solution_excerpt_collapsed(3)
+ verify_solver_and_accepter_info(2, solver, accepter)
+ verify_solver_and_accepter_info(3, solver2, accepter)
+ verify_solution_content(2, "The answer is 42")
+ verify_solution_content_missing(3)
+ toggle_solution_excerpt(3)
+ verify_solution_excerpt_expanded(3)
+ verify_solution_content(3, "The answer is over 9000")
+
+ unaccept_solution(2)
+
+ verify_solution_info_present
+ verify_solution_unaccepted_state(2)
+ verify_solution_accepted_state(3)
+ verify_solver_and_accepter_info(3, solver2, accepter)
+ verify_solution_content(3, "The answer is over 9000")
+
+ unaccept_solution(3)
+ verify_solution_info_absent
end
end
private
- def visit_solver_post
- topic_page.visit_topic(topic, post_number: 2)
+ def visit_solver_post(post_number)
+ topic_page.visit_topic(topic, post_number:)
end
- def accept_solution
- find(UNACCEPTED_BUTTON_SELECTOR).click
+ def accept_solution(post_number)
+ within("article#post_#{post_number}") { find(UNACCEPTED_BUTTON_SELECTOR).click }
end
- def unaccept_solution
- find(ACCEPTED_BUTTON_SELECTOR).click
+ def unaccept_solution(post_number)
+ within("article#post_#{post_number}") { find(ACCEPTED_BUTTON_SELECTOR).click }
end
- def verify_solution_accepted_state
- expect(topic_page).to have_css(ACCEPTED_BUTTON_SELECTOR)
- expect(topic_page).to have_css("#{ACCEPTED_ANSWER_QUOTE_SELECTOR}[data-expanded='false']")
+ def verify_solution_accepted_state(post_number)
+ within("article#post_#{post_number}") do
+ expect(topic_page).to have_css(ACCEPTED_BUTTON_SELECTOR)
+ end
+
+ expect(topic_page).to have_css("#{ACCEPTED_ANSWER_SELECTOR}[data-post='#{post_number}']")
end
- def verify_solution_unaccepted_state
- expect(topic_page).to have_css(UNACCEPTED_BUTTON_SELECTOR)
+ def verify_solution_unaccepted_state(post_number)
+ within("article#post_#{post_number}") do
+ expect(topic_page).to have_css(UNACCEPTED_BUTTON_SELECTOR)
+ end
end
- def verify_solution_quote_content
- expect(topic_page.find("#{ACCEPTED_ANSWER_QUOTE_SELECTOR} blockquote")).to have_content(
- "The answer is 42",
- )
+ def verify_solution_content(post_number, content)
+ within("#{ACCEPTED_ANSWER_SELECTOR}[data-post='#{post_number}']") do
+ expect(find(ACCEPTED_ANSWER_CONTENT_SELECTOR)).to have_content(content)
+ end
end
- def verify_solver_and_accepter_info
- expect(topic_page.find(SOLVER_INFO_SELECTOR)).to have_content(solver.name)
- expect(topic_page.find(ACCEPTER_INFO_SELECTOR)).to have_content(accepter.name)
+ def verify_solution_content_missing(post_number)
+ within("#{ACCEPTED_ANSWER_SELECTOR}[data-post='#{post_number}']") do
+ expect(page).not_to have_css(ACCEPTED_ANSWER_CONTENT_SELECTOR)
+ end
+ end
+
+ def verify_solver_and_accepter_info(post_number, solver, accepter)
+ within("#{ACCEPTED_ANSWER_SELECTOR}[data-post='#{post_number}']") do
+ expect(find(SOLVER_SELECTOR)).to have_content(solver.username)
+ expect(find(ACCEPTER_SELECTOR)).to have_content(accepter.username)
+ end
end
def verify_solution_info_present
- expect(topic_page).to have_css(ACCEPTED_ANSWER_QUOTE_SELECTOR)
- expect(topic_page).to have_css(SOLVER_INFO_SELECTOR)
- expect(topic_page).to have_css(ACCEPTER_INFO_SELECTOR)
+ expect(topic_page).to have_css(ACCEPTED_ANSWER_SELECTOR)
+ expect(topic_page).to have_css(SOLVER_SELECTOR)
+ expect(topic_page).to have_css(ACCEPTER_SELECTOR)
end
def verify_solution_info_absent
- expect(topic_page).to have_no_css(ACCEPTED_ANSWER_QUOTE_SELECTOR)
- expect(topic_page).to have_no_css(SOLVER_INFO_SELECTOR)
- expect(topic_page).to have_no_css(ACCEPTER_INFO_SELECTOR)
+ expect(topic_page).to have_no_css(ACCEPTED_ANSWER_SELECTOR)
+ expect(topic_page).to have_no_css(SOLVER_SELECTOR)
+ expect(topic_page).to have_no_css(ACCEPTER_SELECTOR)
end
- def expand_solution_quote
- topic_page.find(QUOTE_TOGGLE_SELECTOR).click
- expect(topic_page).to have_css("#{ACCEPTED_ANSWER_QUOTE_SELECTOR}[data-expanded='true']")
+ def toggle_solution_excerpt(post_number)
+ within("#{ACCEPTED_ANSWER_SELECTOR}[data-post='#{post_number}']") do
+ find(QUOTE_TOGGLE_SELECTOR).click
+ end
+ end
+
+ def verify_solution_excerpt_expanded(post_number)
+ expect(topic_page).to have_css(
+ "#{ACCEPTED_ANSWER_SELECTOR}[data-post='#{post_number}'][data-expanded]",
+ )
+ end
+
+ def verify_solution_excerpt_collapsed(post_number)
+ expect(topic_page).to have_css(
+ "#{ACCEPTED_ANSWER_SELECTOR}[data-post='#{post_number}']:not([data-expanded])",
+ )
end
end
diff --git a/plugins/discourse-solved/spec/system/solved_with_tags_spec.rb b/plugins/discourse-solved/spec/system/solved_with_tags_spec.rb
index 7686ed3d883..840a2b667f3 100644
--- a/plugins/discourse-solved/spec/system/solved_with_tags_spec.rb
+++ b/plugins/discourse-solved/spec/system/solved_with_tags_spec.rb
@@ -55,9 +55,8 @@ describe "Solved with tags" do
fab!(:other_tag, :tag)
fab!(:topic_with_solved_tag) { Fabricate(:topic_with_op, user: admin, tags: [tag, other_tag]) }
fab!(:answer) { Fabricate(:post, topic: topic_with_solved_tag) }
- fab!(:solved_record) do
- Fabricate(:solved_topic, topic: topic_with_solved_tag, answer_post: answer)
- end
+ fab!(:solved_record) { Fabricate(:solved_topic, topic: topic_with_solved_tag) }
+ fab!(:topic_answer) { Fabricate(:topic_answer, solved_topic: solved_record, post: answer) }
it "shows confirmation when removing the solved tag from a topic with an accepted answer" do
sign_in(admin)
diff --git a/plugins/discourse-solved/test/javascripts/acceptance/discourse-solved-post-menu-test.js b/plugins/discourse-solved/test/javascripts/acceptance/discourse-solved-post-menu-test.js
index 9c9a6c73016..166b912f2c3 100644
--- a/plugins/discourse-solved/test/javascripts/acceptance/discourse-solved-post-menu-test.js
+++ b/plugins/discourse-solved/test/javascripts/acceptance/discourse-solved-post-menu-test.js
@@ -1,4 +1,4 @@
-import { click, visit } from "@ember/test-helpers";
+import { click, triggerEvent, visit } from "@ember/test-helpers";
import { test } from "qunit";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
import { i18n } from "discourse-i18n";
@@ -14,9 +14,11 @@ acceptance("Post Menu | Accept and Unaccept", function (needs) {
needs.pretender((server, helper) => {
server.post("/solution/accept", () =>
- helper.response(postStreamWithAcceptedAnswerExcerpt(null).accepted_answer)
+ helper.response(
+ postStreamWithAcceptedAnswerExcerpt(null).accepted_answers
+ )
);
- server.post("/solution/unaccept", () => helper.response({ success: "OK" }));
+ server.post("/solution/unaccept", () => helper.response([]));
server.get("/t/12.json", () =>
helper.response(postStreamWithAcceptedAnswerExcerpt(null))
@@ -43,4 +45,59 @@ acceptance("Post Menu | Accept and Unaccept", function (needs) {
.dom("#post_2 .post-action-menu__solved-accepted")
.exists("Unaccept button is visible again");
});
+
+ test("hides/shows the accepting user based on setting", async function (assert) {
+ await visit("/t/without-excerpt/12");
+
+ assert
+ .dom("#post_2 .post-action-menu__solved-accepted")
+ .exists("Unaccept button is visible")
+ .hasText(i18n("solved.solution"), "Unaccept button has correct text");
+
+ assert
+ .dom(
+ "#post_2 .fk-d-tooltip__trigger-container .post-action-menu__solved-accepted"
+ )
+ .doesNotExist();
+
+ this.siteSettings.show_who_marked_solved = true;
+ await visit("/t/without-excerpt/12");
+
+ assert
+ .dom(
+ "#post_2 .fk-d-tooltip__trigger-container .post-action-menu__solved-accepted"
+ )
+ .exists();
+
+ await triggerEvent(
+ "#post_2 .post-action-menu__solved-accepted",
+ "pointermove"
+ );
+
+ assert
+ .dom(
+ "#post_2 .fk-d-tooltip__content[data-identifier='post-action-menu__solved-accepted-tooltip']"
+ )
+ .hasText(i18n("solved.marked_solved_by", { user: "tomtom" }));
+
+ this.siteSettings.display_name_on_posts = true;
+ await visit("/t/without-excerpt/12");
+
+ assert
+ .dom(
+ "#post_2 .fk-d-tooltip__trigger-container .post-action-menu__solved-accepted"
+ )
+ .exists();
+
+ await triggerEvent(
+ "#post_2 .post-action-menu__solved-accepted",
+ "pointermove"
+ );
+
+ assert
+ .dom(
+ "#post_2 .fk-d-tooltip__content[data-identifier='post-action-menu__solved-accepted-tooltip']"
+ )
+ .hasText(i18n("solved.marked_solved_by", { user: "Tomtom" }));
+ });
});
diff --git a/plugins/discourse-solved/test/javascripts/acceptance/discourse-solved-test.js b/plugins/discourse-solved/test/javascripts/acceptance/discourse-solved-test.js
index 18468a7b0aa..8189ff7a016 100644
--- a/plugins/discourse-solved/test/javascripts/acceptance/discourse-solved-test.js
+++ b/plugins/discourse-solved/test/javascripts/acceptance/discourse-solved-test.js
@@ -9,6 +9,11 @@ import { acceptance } from "discourse/tests/helpers/qunit-helpers";
import { postStreamWithAcceptedAnswerExcerpt } from "../helpers/discourse-solved-helpers";
acceptance(`Discourse Solved Plugin`, function (needs) {
+ const ITEM_SELECTOR = ".accepted-answers .d-post-accordion-item";
+ const BODY_SELECTOR = ".d-post-accordion-item__body";
+ const CONTENT_SELECTOR = ".d-post-accordion-item__content";
+ const ACCEPTER_SELECTOR = ".accepter-link";
+
needs.user();
test("A topic with an accepted answer shows an excerpt of the answer, if provided", async function (assert) {
@@ -22,15 +27,90 @@ acceptance(`Discourse Solved Plugin`, function (needs) {
await visit("/t/with-excerpt/11");
- assert.dom(".quote.accepted-answer blockquote").exists();
+ assert.dom(`${ITEM_SELECTOR} ${CONTENT_SELECTOR}`).exists();
assert
- .dom(".quote.accepted-answer blockquote")
+ .dom(`${ITEM_SELECTOR} ${CONTENT_SELECTOR}`)
.hasText("this is an excerpt");
await visit("/t/without-excerpt/12");
- assert.dom(".quote.accepted-answer.title-only").exists();
- assert.dom(".quote.accepted-answer blockquote").doesNotExist();
+ assert
+ .dom(`${ITEM_SELECTOR} .d-post-accordion-item--has-content`)
+ .doesNotExist();
+ assert.dom(`${ITEM_SELECTOR} ${BODY_SELECTOR}`).doesNotExist();
+ });
+
+ test("A topic with an accepted answer shows/hides the accepter based on site setting", async function (assert) {
+ pretender.get("/t/11.json", () =>
+ response(postStreamWithAcceptedAnswerExcerpt("this is an excerpt"))
+ );
+
+ await visit("/t/with-excerpt/11");
+
+ assert.dom(`${ITEM_SELECTOR} ${ACCEPTER_SELECTOR}`).doesNotExist();
+
+ this.siteSettings.show_who_marked_solved = true;
+ await visit("/t/with-excerpt/11");
+
+ assert.dom(`${ITEM_SELECTOR} ${ACCEPTER_SELECTOR}`).exists();
+ assert.dom(`${ITEM_SELECTOR} ${ACCEPTER_SELECTOR}`).hasText("tomtom");
+ });
+
+ test("A topic with an accepted answer shows an excerpt of the answer, if provided", async function (assert) {
+ pretender.get("/t/11.json", () =>
+ response(postStreamWithAcceptedAnswerExcerpt("this is an excerpt"))
+ );
+
+ pretender.get("/t/12.json", () =>
+ response(postStreamWithAcceptedAnswerExcerpt(null))
+ );
+
+ await visit("/t/with-excerpt/11");
+
+ assert.dom(`${ITEM_SELECTOR} ${CONTENT_SELECTOR}`).exists();
+ assert
+ .dom(`${ITEM_SELECTOR} ${CONTENT_SELECTOR}`)
+ .hasText("this is an excerpt");
+
+ await visit("/t/without-excerpt/12");
+
+ assert
+ .dom(`${ITEM_SELECTOR} .d-post-accordion-item--has-content`)
+ .doesNotExist();
+ assert.dom(`${ITEM_SELECTOR} ${BODY_SELECTOR}`).doesNotExist();
+ });
+
+ test("A topic with multiple accepted answers shows an excerpt for each", async function (assert) {
+ pretender.get("/t/11.json", () => {
+ let postStreamWithMultipleAcceptedAnswers =
+ postStreamWithAcceptedAnswerExcerpt("this is an excerpt");
+
+ postStreamWithMultipleAcceptedAnswers.accepted_answers.push({
+ id: 22,
+ name: null,
+ username: "kzh",
+ avatar_template: "/letter_avatar_proxy/v2/letter/k/ac91a4/{size}.png",
+ created_at: "2017-08-08T20:12:04.657Z",
+ cooked: "<p>another excerpt</p>",
+ post_number: 3,
+ topic_id: 23,
+ url: "/t/with-excerpt/11/3",
+ accepter_username: "tomtom",
+ accepter_name: "Tomtom",
+ });
+
+ return response(postStreamWithMultipleAcceptedAnswers);
+ });
+
+ await visit("/t/with-excerpt/11");
+
+ assert.dom(ITEM_SELECTOR).exists({ count: 2 });
+ assert
+ .dom(`${ITEM_SELECTOR}[data-post='2'] .d-post-accordion-item__content`)
+ .hasText("this is an excerpt");
+ assert
+ .dom(`${ITEM_SELECTOR}[data-post='3'] .d-post-accordion-item__content`)
+ .hasText("another excerpt");
});
test("Full page search displays solved status", async function (assert) {
diff --git a/plugins/discourse-solved/test/javascripts/acceptance/no-answer-prompt-test.js b/plugins/discourse-solved/test/javascripts/acceptance/no-answer-prompt-test.js
index d12c4767e1f..7f7e9a15d20 100644
--- a/plugins/discourse-solved/test/javascripts/acceptance/no-answer-prompt-test.js
+++ b/plugins/discourse-solved/test/javascripts/acceptance/no-answer-prompt-test.js
@@ -3,7 +3,10 @@ import { test } from "qunit";
import sinon from "sinon";
import pretender, { response } from "discourse/tests/helpers/create-pretender";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
-import { topicWithNoAnswer } from "../helpers/discourse-solved-helpers";
+import {
+ postStreamWithAcceptedAnswerExcerpt,
+ topicWithNoAnswer,
+} from "../helpers/discourse-solved-helpers";
acceptance("No Answer Prompt", function (needs) {
needs.user({ id: 1 });
@@ -24,6 +27,12 @@ acceptance("No Answer Prompt", function (needs) {
);
});
+ needs.hooks.beforeEach(function () {
+ pretender.get("/t/23.json", () =>
+ response(postStreamWithAcceptedAnswerExcerpt("excerpt"))
+ );
+ });
+
test("hides the no answer prompt when clicking the solution button", async function (assert) {
await visit("/t/test-topic-no-answer/100");
@@ -38,6 +47,14 @@ acceptance("No Answer Prompt", function (needs) {
.doesNotExist("no answer prompt is hidden after accepting solution");
});
+ test("hides the no answer prompt when there's already a solution", async function (assert) {
+ await visit("/t/23");
+
+ assert
+ .dom(".topic-navigation-popup")
+ .doesNotExist("no answer prompt is not displayed");
+ });
+
test("shows confetti when accepting a solution", async function (assert) {
await visit("/t/test-topic-no-answer/100");
diff --git a/plugins/discourse-solved/test/javascripts/acceptance/solved-removal-confirmation-test.js b/plugins/discourse-solved/test/javascripts/acceptance/solved-removal-confirmation-test.js
index e3e63c552c5..41023e5c835 100644
--- a/plugins/discourse-solved/test/javascripts/acceptance/solved-removal-confirmation-test.js
+++ b/plugins/discourse-solved/test/javascripts/acceptance/solved-removal-confirmation-test.js
@@ -15,7 +15,7 @@ function solvedTopicFixture(overrides = {}) {
function unsolvedTopicFixture() {
const topic = cloneJSON(postStreamWithAcceptedAnswerExcerpt("an answer"));
topic.category_id = 100;
- topic.accepted_answer = null;
+ topic.accepted_answers = [];
topic.post_stream.posts.forEach((p) => {
p.accepted_answer = false;
p.can_accept_answer = false;
diff --git a/plugins/discourse-solved/test/javascripts/helpers/discourse-solved-helpers.js b/plugins/discourse-solved/test/javascripts/helpers/discourse-solved-helpers.js
index 739ec4f032f..add77c38c0e 100644
--- a/plugins/discourse-solved/test/javascripts/helpers/discourse-solved-helpers.js
+++ b/plugins/discourse-solved/test/javascripts/helpers/discourse-solved-helpers.js
@@ -197,13 +197,21 @@ export const postStreamWithAcceptedAnswerExcerpt = (excerpt) => ({
featured_link: null,
topic_timer: null,
message_bus_last_id: 0,
- accepted_answer: {
- post_number: 2,
- username: "kzh",
- excerpt: excerpt ? `<p>${excerpt}</p>` : excerpt,
- accepter_username: "tomtom",
- accepter_name: "Tomtom",
- },
+ accepted_answers: [
+ {
+ id: 22,
+ name: null,
+ username: "kzh",
+ avatar_template: "/letter_avatar_proxy/v2/letter/k/ac91a4/{size}.png",
+ created_at: "2017-08-08T20:12:04.657Z",
+ cooked: excerpt ? `<p>${excerpt}</p>` : excerpt,
+ post_number: 2,
+ topic_id: 23,
+ url: "/t/with-excerpt/11/2",
+ accepter_username: "tomtom",
+ accepter_name: "Tomtom",
+ },
+ ],
});
export function topicWithNoAnswer(currentUserId) {
@@ -255,7 +263,6 @@ export function topicWithNoAnswer(currentUserId) {
draft: null,
draft_key: "topic_100",
draft_sequence: 0,
- accepted_answer: null,
details: {
created_by: {
id: currentUserId,
diff --git a/script/bulk_import/base.rb b/script/bulk_import/base.rb
index b953f26335f..72ef2fce77d 100644
--- a/script/bulk_import/base.rb
+++ b/script/bulk_import/base.rb
@@ -880,7 +880,8 @@ class BulkImport::Base
GAMIFICATION_SCORE_EVENT_COLUMNS = %i[user_id date points description created_at updated_at]
- SOLVED_TOPIC_COLUMNS = %i[topic_id answer_post_id accepter_user_id created_at updated_at]
+ SOLVED_TOPIC_COLUMNS = %i[topic_id created_at updated_at]
+ TOPIC_ANSWER_COLUMNS = %i[solved_topic_id answer_post_id accepter_user_id created_at updated_at]
POST_EVENT_COLUMNS = %i[
id
@@ -1206,6 +1207,10 @@ class BulkImport::Base
create_records(rows, "discourse_solved_solved_topics", SOLVED_TOPIC_COLUMNS, &block)
end
+ def create_topic_answers(rows, &block)
+ create_records(rows, "discourse_solved_topic_answers", TOPIC_ANSWER_COLUMNS, &block)
+ end
+
def create_post_events(rows, &block)
create_records(rows, "discourse_post_event_events", POST_EVENT_COLUMNS, &block)
end
@@ -1969,10 +1974,16 @@ class BulkImport::Base
def process_discourse_solved_solved_topics(solved_topic)
solved_topic[:created_at] ||= NOW
solved_topic[:updated_at] ||= NOW
- solved_topic[:accepter_user_id] ||= Discourse::SYSTEM_USER_ID
solved_topic
end
+ def process_discourse_solved_topic_answers(topic_answer)
+ topic_answer[:created_at] ||= NOW
+ topic_answer[:updated_at] ||= NOW
+ topic_answer[:accepter_user_id] ||= Discourse::SYSTEM_USER_ID
+ topic_answer
+ end
+
def process_discourse_post_event_events(post_event)
post_event
end
diff --git a/script/bulk_import/generic_bulk.rb b/script/bulk_import/generic_bulk.rb
index eb67276024a..a635a866088 100644
--- a/script/bulk_import/generic_bulk.rb
+++ b/script/bulk_import/generic_bulk.rb
@@ -2467,19 +2467,35 @@ class BulkImport::Generic < BulkImport::Base
SQL
existing_solved_topics = DiscourseSolved::SolvedTopic.pluck(:topic_id).to_set
+ inserted_topic_ids = []
create_solved_topic(solutions) do |row|
- post_id = post_id_from_imported_id(row["post_id"])
topic_id = topic_id_from_imported_id(row["topic_id"])
- accepter_user_id = user_id_from_imported_id(row["acting_user_id"])
+ next unless topic_id && existing_solved_topics.add?(topic_id)
+
+ inserted_topic_ids << topic_id
+ { topic_id:, created_at: to_datetime(row["created_at"]) }
+ end
+
+ puts "", "Importing solutions into discourse_solved_topic_answers..."
+
+ solved_topic_id_by_topic_id =
+ DiscourseSolved::SolvedTopic.where(topic_id: inserted_topic_ids).pluck(:topic_id, :id).to_h
+
+ solutions.reset
+
+ create_topic_answers(solutions) do |row|
+ topic_id = topic_id_from_imported_id(row["topic_id"])
+ solved_topic_id = solved_topic_id_by_topic_id[topic_id]
+ next unless solved_topic_id
- next unless post_id && topic_id
- next unless existing_solved_topics.add?(topic_id)
+ post_id = post_id_from_imported_id(row["post_id"])
+ next unless post_id
{
- topic_id: topic_id,
+ solved_topic_id:,
answer_post_id: post_id,
- accepter_user_id: accepter_user_id,
+ accepter_user_id: user_id_from_imported_id(row["acting_user_id"]),
created_at: to_datetime(row["created_at"]),
}
end