A platform for community discussion. Free, open, simple.
DEV: move solved schema data to service (#38109)
David Battersbya2ec5720ceb7
diff --git a/plugins/discourse-solved/app/serializers/discourse_solved/answer_schema_serializer.rb b/plugins/discourse-solved/app/serializers/discourse_solved/answer_schema_serializer.rbnew file mode 100644index 00000000000..c51384eae54--- /dev/null+++ b/plugins/discourse-solved/app/serializers/discourse_solved/answer_schema_serializer.rb@@ -0,0 +1,31 @@+# frozen_string_literal: true++class DiscourseSolved::AnswerSchemaSerializer < ApplicationSerializer+ # attributes are camelCase as the Q&A schema spec requires it+ attributes :text, :upvoteCount, :datePublished, :url, :author++ def serializable_hash+ { "@type" => "Answer" }.merge(super)+ end++ def text+ object.excerpt(nil, keep_onebox_body: true).presence ||+ object.excerpt(nil, keep_onebox_body: true, keep_quotes: true)+ end++ def upvoteCount+ object.like_count+ end++ def datePublished+ object.created_at+ end++ def url+ object.full_url+ end++ def author+ { "@type" => "Person", "name" => object.user&.username, "url" => object.user&.full_url }+ end+enddiff --git a/plugins/discourse-solved/app/serializers/discourse_solved/question_schema_serializer.rb b/plugins/discourse-solved/app/serializers/discourse_solved/question_schema_serializer.rbnew file mode 100644index 00000000000..d85627e0312--- /dev/null+++ b/plugins/discourse-solved/app/serializers/discourse_solved/question_schema_serializer.rb@@ -0,0 +1,49 @@+# frozen_string_literal: true++class DiscourseSolved::QuestionSchemaSerializer < ApplicationSerializer+ # attributes are camelCase as the Q&A schema spec requires it+ attributes :name, :text, :upvoteCount, :answerCount, :datePublished, :author++ def serializable_hash+ hash = { "@type" => "Question" }.merge(super)+ if accepted_answer.present?+ hash["acceptedAnswer"] = DiscourseSolved::AnswerSchemaSerializer.new(+ accepted_answer,+ root: false,+ ).serializable_hash+ end+ hash+ end++ def name+ object.title+ end++ def text+ first_post = object.first_post+ first_post.excerpt(nil, keep_onebox_body: true).presence ||+ first_post.excerpt(nil, keep_onebox_body: true, keep_quotes: true)+ end++ def upvoteCount+ object.first_post.like_count+ end++ def answerCount+ accepted_answer.present? ? 1 : 0+ end++ def datePublished+ object.created_at+ end++ def author+ { "@type" => "Person", "name" => object.user&.username, "url" => object.user&.full_url }+ end++ private++ def accepted_answer+ options[:accepted_answer]+ end+enddiff --git a/plugins/discourse-solved/app/services/discourse_solved/build_schema_markup.rb b/plugins/discourse-solved/app/services/discourse_solved/build_schema_markup.rbnew file mode 100644index 00000000000..e32d2869ec8--- /dev/null+++ b/plugins/discourse-solved/app/services/discourse_solved/build_schema_markup.rb@@ -0,0 +1,63 @@+# frozen_string_literal: true++class DiscourseSolved::BuildSchemaMarkup+ include Service::Base++ params do+ attribute :topic_id, :integer+ validates :topic_id, presence: true+ end++ model :topic+ policy :accepted_answers_allowed+ model :accepted_answer, optional: true+ policy :schema_markup_enabled+ model :html++ private++ def fetch_topic(params:)+ Topic.find_by(id: params.topic_id)+ end++ def accepted_answers_allowed(guardian:, topic:)+ guardian.allow_accepted_answers?(topic)+ end++ def fetch_accepted_answer(topic:)+ topic.solved&.answer_post+ end++ def schema_markup_enabled(accepted_answer:)+ case SiteSetting.solved_add_schema_markup+ when "never"+ false+ when "answered only"+ accepted_answer.present?+ else+ true+ end+ end++ def fetch_html(topic:, accepted_answer:)+ question_json =+ DiscourseSolved::QuestionSchemaSerializer.new(+ topic,+ root: false,+ accepted_answer: accepted_answer,+ ).serializable_hash++ json =+ MultiJson+ .dump(+ "@context" => "http://schema.org",+ "@type" => "QAPage",+ "name" => topic.title,+ "mainEntity" => question_json,+ )+ .gsub("</", "<\\/")+ .html_safe++ "<script type=\"application/ld+json\">#{json}</script>"+ end+enddiff --git a/plugins/discourse-solved/lib/discourse_solved/before_head_close.rb b/plugins/discourse-solved/lib/discourse_solved/before_head_close.rbdeleted file mode 100644index 8752d70d065..00000000000--- a/plugins/discourse-solved/lib/discourse_solved/before_head_close.rb+++ /dev/null@@ -1,81 +0,0 @@-# frozen_string_literal: true--class DiscourseSolved::BeforeHeadClose- attr_reader :controller-- def initialize(controller)- @controller = controller- end-- def html- return "" if !controller.instance_of? TopicsController-- topic_view = controller.instance_variable_get(:@topic_view)- topic = topic_view&.topic- return "" if !topic- # note, we have canonicals so we only do this for page 1 at the moment- # it can get confusing to have this on every page and it should make page 1- # a bit more prominent + cut down on pointless work-- return "" if SiteSetting.solved_add_schema_markup == "never"-- allowed = controller.guardian.allow_accepted_answers?(topic)- return "" if !allowed-- first_post = topic_view.posts&.first- return "" if first_post&.post_number != 1-- question_json = {- "@type" => "Question",- "name" => topic.title,- "text" => get_schema_text(first_post),- "upvoteCount" => first_post.like_count,- "answerCount" => 0,- "datePublished" => topic.created_at,- "author" => {- "@type" => "Person",- "name" => topic.user&.username,- "url" => topic.user&.full_url,- },- }-- if accepted_answer = topic.solved&.answer_post- question_json["answerCount"] = 1- question_json[:acceptedAnswer] = {- "@type" => "Answer",- "text" => get_schema_text(accepted_answer),- "upvoteCount" => accepted_answer.like_count,- "datePublished" => accepted_answer.created_at,- "url" => accepted_answer.full_url,- "author" => {- "@type" => "Person",- "name" => accepted_answer.user&.username,- "url" => accepted_answer.user&.full_url,- },- }- else- return "" if SiteSetting.solved_add_schema_markup == "answered only"- end-- [- '<script type="application/ld+json">',- MultiJson- .dump(- "@context" => "http://schema.org",- "@type" => "QAPage",- "name" => topic&.title,- "mainEntity" => question_json,- )- .gsub("</", "<\\/")- .html_safe,- "</script>",- ].join("")- end-- private-- def get_schema_text(post)- post.excerpt(nil, keep_onebox_body: true).presence ||- post.excerpt(nil, keep_onebox_body: true, keep_quotes: true)- end-enddiff --git a/plugins/discourse-solved/plugin.rb b/plugins/discourse-solved/plugin.rbindex a259011ba99..72e30271028 100644--- a/plugins/discourse-solved/plugin.rb+++ b/plugins/discourse-solved/plugin.rb@@ -61,11 +61,27 @@ after_initialize do)register_html_builder("server:before-head-close-crawler") do |controller|- DiscourseSolved::BeforeHeadClose.new(controller).html+ topic_id = controller.instance_variable_get(:@topic_view)&.topic&.id+ result =+ DiscourseSolved::BuildSchemaMarkup.call(+ params: {+ topic_id: topic_id,+ },+ guardian: controller.guardian,+ )+ result[:html] if result.success?endregister_html_builder("server:before-head-close") do |controller|- DiscourseSolved::BeforeHeadClose.new(controller).html+ topic_id = controller.instance_variable_get(:@topic_view)&.topic&.id+ result =+ DiscourseSolved::BuildSchemaMarkup.call(+ params: {+ topic_id: topic_id,+ },+ guardian: controller.guardian,+ )+ result[:html] if result.success?endReport.add_report("accepted_solutions") do |report|diff --git a/plugins/discourse-solved/spec/serializers/discourse_solved/answer_schema_serializer_spec.rb b/plugins/discourse-solved/spec/serializers/discourse_solved/answer_schema_serializer_spec.rbnew file mode 100644index 00000000000..358c1706a5e--- /dev/null+++ b/plugins/discourse-solved/spec/serializers/discourse_solved/answer_schema_serializer_spec.rb@@ -0,0 +1,24 @@+# frozen_string_literal: true++RSpec.describe DiscourseSolved::AnswerSchemaSerializer do+ fab!(:post) { Fabricate(:post, like_count: 5) }++ subject(:json) { described_class.new(post, root: false).serializable_hash.deep_stringify_keys }++ it "includes the Answer @type" do+ expect(json["@type"]).to eq("Answer")+ end++ it "serializes the post attributes" do+ expect(json["text"]).to be_present+ expect(json["upvoteCount"]).to eq(5)+ expect(json["datePublished"]).to eq(post.created_at)+ expect(json["url"]).to eq(post.full_url)+ end++ it "serializes the author" do+ expect(json["author"]).to eq(+ { "@type" => "Person", "name" => post.user.username, "url" => post.user.full_url },+ )+ end+enddiff --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.rbnew file mode 100644index 00000000000..a7d10b4faba--- /dev/null+++ b/plugins/discourse-solved/spec/serializers/discourse_solved/question_schema_serializer_spec.rb@@ -0,0 +1,58 @@+# frozen_string_literal: true++RSpec.describe DiscourseSolved::QuestionSchemaSerializer do+ fab!(:user)+ fab!(:topic) { Fabricate(:topic, user: user) }+ fab!(:post) { Fabricate(:post, topic: topic, user: user, like_count: 2) }++ context "without an accepted answer" do+ subject(:json) { described_class.new(topic, root: false).serializable_hash.deep_stringify_keys }++ it "includes the Question @type" do+ expect(json["@type"]).to eq("Question")+ end++ it "serializes the topic attributes" do+ expect(json["name"]).to eq(topic.title)+ expect(json["text"]).to be_present+ expect(json["upvoteCount"]).to eq(2)+ expect(json["answerCount"]).to eq(0)+ expect(json["datePublished"]).to eq(topic.created_at)+ end++ it "serializes the author" do+ expect(json["author"]).to eq(+ { "@type" => "Person", "name" => user.username, "url" => user.full_url },+ )+ end++ it "does not include acceptedAnswer" do+ expect(json).not_to have_key("acceptedAnswer")+ end+ end++ context "with an accepted answer" do+ fab!(:answer_user, :user)+ fab!(:answer_post) { Fabricate(:post, topic: topic, user: answer_user, like_count: 7) }++ subject(:json) do+ described_class+ .new(topic, root: false, accepted_answer: answer_post)+ .serializable_hash+ .deep_stringify_keys+ end++ it "sets answerCount to 1" do+ expect(json["answerCount"]).to eq(1)+ end++ it "includes the accepted answer" do+ accepted = json["acceptedAnswer"]+ expect(accepted["@type"]).to eq("Answer")+ expect(accepted["upvoteCount"]).to eq(7)+ expect(accepted["author"]).to eq(+ { "@type" => "Person", "name" => answer_user.username, "url" => answer_user.full_url },+ )+ end+ end+enddiff --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.rbnew file mode 100644index 00000000000..8c231d09ad7--- /dev/null+++ b/plugins/discourse-solved/spec/services/discourse_solved/build_schema_markup_spec.rb@@ -0,0 +1,79 @@+# frozen_string_literal: true++RSpec.describe DiscourseSolved::BuildSchemaMarkup do+ describe described_class::Contract, type: :model do+ it { is_expected.to validate_presence_of(:topic_id) }+ end++ describe ".call" do+ subject(:result) { described_class.call(params:, **dependencies) }++ fab!(:user)+ fab!(:topic) { Fabricate(:topic, user: user) }+ fab!(:post) { Fabricate(:post, topic: topic, user: user, like_count: 1) }+ let(:guardian) { Guardian.new(user) }+ let(:params) { { topic_id: topic.id } }+ let(:dependencies) { { guardian: guardian } }++ before { SiteSetting.allow_solved_on_all_topics = true }++ context "when topic_id is nil" do+ let(:params) { { topic_id: nil } }++ it { is_expected.to fail_a_contract }+ end++ context "when accepted answers are not allowed on the topic" do+ before { SiteSetting.allow_solved_on_all_topics = false }++ it { is_expected.to fail_a_policy(:accepted_answers_allowed) }+ end++ context "when schema markup is disabled" do+ before { SiteSetting.solved_add_schema_markup = "never" }++ it { is_expected.to fail_a_policy(:schema_markup_enabled) }+ end++ context "when setting is 'answered only' and there is no accepted answer" do+ before { SiteSetting.solved_add_schema_markup = "answered only" }++ it { is_expected.to fail_a_policy(:schema_markup_enabled) }+ end++ context "when setting is 'always' and there is no accepted answer" do+ before { SiteSetting.solved_add_schema_markup = "always" }++ it { is_expected.to run_successfully }++ it "builds QAPage markup without an answer" do+ html = result[:html]+ expect(html).to include("application/ld+json")+ expect(html).to include('"@type":"QAPage"')+ expect(html).to include('"answerCount":0')+ expect(html).not_to include('"acceptedAnswer"')+ end+ end++ context "when there is an accepted answer" do+ fab!(:answer_user, :user)+ fab!(:answer_post) { Fabricate(:post, topic: topic, user: answer_user, like_count: 3) }++ before do+ SiteSetting.solved_add_schema_markup = "always"+ Fabricate(:solved_topic, topic: topic, answer_post: answer_post)+ end++ it { is_expected.to run_successfully }++ it "builds QAPage markup with the accepted answer" do+ html = result[:html]+ expect(html).to include('"@type":"QAPage"')+ expect(html).to include('"answerCount":1')+ expect(html).to include('"acceptedAnswer"')+ expect(html).to include('"@type":"Answer"')+ expect(html).to include(answer_user.username)+ end+ end+ end+end