A platform for community discussion. Free, open, simple.
FEATURE: make shared issues optional per-category (#40501)
Krisc894e2f722a8
diff --git a/app/assets/stylesheets/common/base/edit-category.scss b/app/assets/stylesheets/common/base/edit-category.scssindex ee1cd13317b..263d247b447 100644--- a/app/assets/stylesheets/common/base/edit-category.scss+++ b/app/assets/stylesheets/common/base/edit-category.scss@@ -453,6 +453,21 @@ div.edit-category {flex-direction: column;gap: 1em;}++ .schema-site-text {+ display: flex;+ gap: var(--space-2);+ align-items: center;++ .schema-site-text__locale {+ flex: 0 0 auto;+ width: auto;+ }++ .form-kit__control-input-wrapper {+ flex: 1 1 auto;+ }+ }}}diff --git a/app/services/categories/types/base.rb b/app/services/categories/types/base.rbindex 58d829cd444..20ce60439b2 100644--- a/app/services/categories/types/base.rb+++ b/app/services/categories/types/base.rb@@ -28,6 +28,12 @@ module Categories"$ref" => "#/$defs/field_config",},},+ "site_texts" => {+ "type" => "object",+ "additionalProperties" => {+ "$ref" => "#/$defs/site_text_field_config",+ },+ },},"$defs" => {"general_field_config" => {@@ -78,6 +84,10 @@ module Categories"required" => {"type" => "boolean",},+ "depends_on" => {+ "type" => "string",+ "minLength" => 1,+ },"show_on_create" => {"type" => "boolean",},@@ -86,6 +96,24 @@ module Categories},},},+ "site_text_field_config" => {+ "type" => "object",+ "required" => %w[label],+ "additionalProperties" => false,+ "properties" => {+ "label" => {+ "type" => "string",+ "minLength" => 1,+ },+ "description" => {+ "type" => "string",+ },+ "depends_on" => {+ "type" => "string",+ "minLength" => 1,+ },+ },+ },},}.freeze@@ -206,6 +234,19 @@ module Categories# category_settings: {# # Same structure as category_custom_fields above.# },+ #+ # site_texts: {+ # # Fields backed by a translation override (site text), not stored+ # # on the category. Each key is the i18n key to edit. The value is+ # # a config Hash:+ # # label: (required) String — FormKit label shown in UI.+ # # description: (optional) String — FormKit help text.+ # # depends_on: (optional) String — only show when this sibling+ # # custom field / setting is truthy.+ # "js.solved.shared_issue.label" => {+ # label: "Shared issue label",+ # },+ # },# }## Use +validate_schema!+ to verify a schema conforms to this contract.@@ -353,6 +394,7 @@ module Categoriessite_settings: [],category_settings: [],category_custom_fields: [],+ site_texts: [],}schema[:general_category_settings]&.each do |setting_name, config|@@ -415,7 +457,7 @@ module Categoriesendschema[:category_custom_fields]&.each do |field_name, config|- entries[:category_custom_fields] << {+ entry = {key: field_name.to_s,default: config[:default],type: config[:type].to_s,@@ -427,6 +469,26 @@ module Categoriesshow_on_create: config[:show_on_create].nil? ? true : config[:show_on_create],show_on_edit: config[:show_on_edit].nil? ? true : config[:show_on_edit],}+ entry[:depends_on] = config[:depends_on].to_s if config[:depends_on]+ entries[:category_custom_fields] << entry+ end++ schema[:site_texts]&.each do |text_key, config|+ entry = {+ key: text_key.to_s,+ # FormKit parses "." and "-" in field names as nested paths, so the+ # form binds to this separator-free +name+ (already namespaced by+ # the parent site_texts object) while +key+ stays the i18n key used+ # by the site_texts API.+ name: text_key.to_s.gsub(/\W/, "_"),+ label: config[:label],+ description: config[:description],+ current: I18n.with_locale(SiteSetting.default_locale) { I18n.t(text_key) },+ show_on_create: true,+ show_on_edit: true,+ }+ entry[:depends_on] = config[:depends_on].to_s if config[:depends_on]+ entries[:site_texts] << entryendentriesdiff --git a/frontend/discourse/admin/controllers/edit-category/tabs.js b/frontend/discourse/admin/controllers/edit-category/tabs.jsindex 01792d5ce33..46e098afeaa 100644--- a/frontend/discourse/admin/controllers/edit-category/tabs.js+++ b/frontend/discourse/admin/controllers/edit-category/tabs.js@@ -3,6 +3,7 @@ import Controller from "@ember/controller";import { action, computed, getProperties } from "@ember/object";import { next } from "@ember/runloop";import { service } from "@ember/service";+import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";import { AUTO_GROUPS } from "discourse/lib/constants";import { registeredEditCategoryTabs } from "discourse/lib/edit-category-tabs";@@ -83,6 +84,10 @@ export default class EditCategoryTabsController extends Controller {@tracked formData;@tracked selectedTab = "general";@tracked formApi = null;+ @tracked siteTextsLocale = this.siteSettings.default_locale;+ @tracked isLoadingSiteTextsLocale = false;+ @tracked siteTextEdits = {};+ @tracked siteTextOriginals = {};@autoTrackedArray panels = [];saving = false;deleting = false;@@ -130,6 +135,7 @@ export default class EditCategoryTabsController extends Controller {data.category_type_settings = {...(this.model.category_type_settings ?? {}),};+ data.site_texts = {};data.category_types = Object.keys(this.model.categoryTypes ?? {});Object.values(this.model.categoryTypes ?? {}).forEach((categoryType) => {@@ -148,11 +154,29 @@ export default class EditCategoryTabsController extends Controller {? setting.current: setting.default;});++ // Site texts are translation overrides, not stored on the category. The+ // server provides the current value (default locale) so we can seed the+ // field without an extra request, then diff against it on save. Keyed by+ // the dot-free form name (the i18n key itself is not FormKit-safe).+ categoryType.configuration_schema.site_texts?.forEach((text) => {+ data.site_texts[text.name] = text.current ?? "";+ });});+ // Customizable text is always seeded with the default locale's value, so+ // reset the editing language to match whenever the form is (re)initialized.+ const defaultLocale = this.siteSettings.default_locale;+ this.siteTextsLocale = defaultLocale;+ this.siteTextOriginals = { [defaultLocale]: { ...data.site_texts } };+ this.siteTextEdits = { [defaultLocale]: { ...data.site_texts } };this.formData = data;}+ get availableLocales() {+ return this.siteSettings.available_locales;+ }+@computed("saving", "deleting")get deleteDisabled() {return this.deleting || this.saving || false;@@ -190,7 +214,33 @@ export default class EditCategoryTabsController extends Controller {}get isFormDirty() {- return this.formApi?.isDirty ?? false;+ return (this.formApi?.isDirty ?? false) || this.hasPendingSiteTextChanges;+ }++ // True when any locale (visible or stashed) has customizable text that+ // differs from its saved value. The form's own dirty flag only reflects the+ // locale currently on screen, so we track the rest ourselves.+ get hasPendingSiteTextChanges() {+ const entries = this._siteTextEntries;+ if (entries.length === 0) {+ return false;+ }++ const edits = {+ ...this.siteTextEdits,+ [this.siteTextsLocale]: this._visibleSiteTexts,+ };++ return Object.entries(edits).some(([locale, values]) => {+ const originals = this.siteTextOriginals[locale] ?? {};+ return entries.some(+ (entry) => (values[entry.name] ?? "") !== (originals[entry.name] ?? "")+ );+ });+ }++ get _visibleSiteTexts() {+ return this.formApi?.get("site_texts") ?? {};}@action@@ -287,6 +337,18 @@ export default class EditCategoryTabsController extends Controller {@actiononFormReset() {this.afterResetCallbacks.forEach((callback) => callback());++ const restored = {};+ for (const [locale, values] of Object.entries(this.siteTextOriginals)) {+ restored[locale] = { ...values };+ }+ this.siteTextEdits = restored;++ const current = this.siteTextOriginals[this.siteTextsLocale] ?? {};+ this._siteTextEntries.forEach((entry) => {+ this.formApi?.set(`site_texts.${entry.name}`, current[entry.name] ?? "");+ });+ this.formApi?.commitField("site_texts");}@action@@ -350,6 +412,7 @@ export default class EditCategoryTabsController extends Controller {Object.keys(this.model.categoryTypes ?? {}));const result = await this.model.save();+ const siteTextsChanged = await this._saveSiteTexts();const updatedModel = this.site.updateCategory(result.category);updatedModel.setupGroupsAndPermissions();@@ -360,7 +423,8 @@ export default class EditCategoryTabsController extends Controller {const newTypes = Object.keys(result.category.category_types ?? {});const typeWasAdded = newTypes.some((t) => !previousTypes.has(t));- if (typeWasAdded) {+ // A reload is needed when site texts change+ if (typeWasAdded || siteTextsChanged) {if (this.model.id) {window.location.reload();} else {@@ -398,6 +462,109 @@ export default class EditCategoryTabsController extends Controller {}}+ @action+ async switchSiteTextsLocale(locale) {+ if (locale === this.siteTextsLocale) {+ return;+ }++ this._stashVisibleSiteTexts();++ this.isLoadingSiteTextsLocale = true;+ const previousLocale = this.siteTextsLocale;+ this.siteTextsLocale = locale;++ try {+ let values = this.siteTextEdits[locale];+ if (!values) {+ values = await this._fetchSiteTexts(locale);+ this.siteTextOriginals = {+ ...this.siteTextOriginals,+ [locale]: { ...values },+ };+ this.siteTextEdits = { ...this.siteTextEdits, [locale]: { ...values } };+ }++ this._siteTextEntries.forEach((entry) => {+ this.formApi?.set(`site_texts.${entry.name}`, values[entry.name] ?? "");+ });+ this.formApi?.commitField("site_texts");+ } catch (error) {+ this.siteTextsLocale = previousLocale;+ popupAjaxError(error);+ } finally {+ this.isLoadingSiteTextsLocale = false;+ }+ }++ _stashVisibleSiteTexts() {+ this.siteTextEdits = {+ ...this.siteTextEdits,+ [this.siteTextsLocale]: { ...this._visibleSiteTexts },+ };+ }++ async _fetchSiteTexts(locale) {+ const entries = this._siteTextEntries;+ const responses = await Promise.all(+ entries.map((entry) =>+ ajax(+ `/admin/customize/site_texts/${encodeURIComponent(entry.key)}.json`,+ { data: { locale } }+ ).catch(() => ({ site_text: { value: "" } }))+ )+ );++ const values = {};+ entries.forEach((entry, index) => {+ values[entry.name] = responses[index].site_text?.value ?? "";+ });+ return values;+ }++ async _saveSiteTexts() {+ this._stashVisibleSiteTexts();++ const entries = this._siteTextEntries;+ let changed = false;++ for (const [locale, values] of Object.entries(this.siteTextEdits)) {+ const originals = this.siteTextOriginals[locale] ?? {};++ for (const entry of entries) {+ const newValue = values[entry.name] ?? "";+ if (newValue === (originals[entry.name] ?? "")) {+ continue;+ }++ const url = `/admin/customize/site_texts/${encodeURIComponent(+ entry.key+ )}?locale=${encodeURIComponent(locale)}`;+ if (newValue.trim() === "") {+ await ajax(url, { type: "DELETE" });+ } else {+ await ajax(url, {+ type: "PUT",+ data: { site_text: { value: newValue, locale } },+ });+ }+ changed = true;+ }+ }++ return changed;+ }++ get _siteTextEntries() {+ const entries = [];+ Object.values(this.model?.categoryTypes ?? {}).forEach((categoryType) => {+ categoryType.configuration_schema.site_texts?.forEach((entry) =>+ entries.push(entry)+ );+ });+ return entries;+ }+@actiondeleteCategory() {if (this.deleteDisabled) {diff --git a/frontend/discourse/admin/templates/edit-category/tabs.gjs b/frontend/discourse/admin/templates/edit-category/tabs.gjsindex ad1dacbd9f8..3ef537f2f36 100644--- a/frontend/discourse/admin/templates/edit-category/tabs.gjs+++ b/frontend/discourse/admin/templates/edit-category/tabs.gjs@@ -96,6 +96,10 @@ export default class Tabs extends Component {@transientData={{transientData}}@form={{form}}@setSelectedTab={{@controller.setSelectedTab}}+ @availableLocales={{@controller.availableLocales}}+ @siteTextsLocale={{@controller.siteTextsLocale}}+ @switchSiteTextsLocale={{@controller.switchSiteTextsLocale}}+ @isLoadingSiteTextsLocale={{@controller.isLoadingSiteTextsLocale}}/>{{/let}}</form.Section>diff --git a/frontend/discourse/app/components/edit-category-type-schema-fields.gjs b/frontend/discourse/app/components/edit-category-type-schema-fields.gjsindex a098b926db3..692aa7d8a6f 100644--- a/frontend/discourse/app/components/edit-category-type-schema-fields.gjs+++ b/frontend/discourse/app/components/edit-category-type-schema-fields.gjs@@ -1,7 +1,8 @@import Component from "@glimmer/component";-import { fn, get } from "@ember/helper";+import { fn, get, hash } from "@ember/helper";import { service } from "@ember/service";import { bind } from "discourse/lib/decorators";+import ComboBox from "discourse/select-kit/components/combo-box";import GroupChooser from "discourse/select-kit/components/group-chooser";import { eq } from "discourse/truth-helpers";import DRelativeTimePicker from "discourse/ui-kit/d-relative-time-picker";@@ -140,16 +141,20 @@ export default class EditCategoryTypeSchemaFields extends Component {get hasCustomFields() {return this.schema.category_custom_fields?.some((entry) =>- this.shouldDisplayField(entry)+ this.isFieldVisible(entry));}get hasCategorySettings() {return this.schema.category_settings?.some((entry) =>- this.shouldDisplayField(entry)+ this.isFieldVisible(entry));}+ get hasSiteTexts() {+ return this.schema.site_texts?.some((entry) => this.isFieldVisible(entry));+ }+get className() {let classes = ["edit-category-type-schema-fields",@@ -192,13 +197,33 @@ export default class EditCategoryTypeSchemaFields extends Component {return entry.show_on_create;}+ @bind+ dependencyMet(entry) {+ if (!entry.depends_on) {+ return true;+ }++ const data = this.args.transientData ?? {};+ const value =+ data.custom_fields?.[entry.depends_on] ??+ data.category_type_site_settings?.[entry.depends_on] ??+ data.category_type_settings?.[entry.depends_on];++ return value === true || value === "true";+ }++ @bind+ isFieldVisible(entry) {+ return this.shouldDisplayField(entry) && this.dependencyMet(entry);+ }+<template><div class={{this.className}}>{{#if this.hasCustomFields}}<@form.Section><@form.Object @name="custom_fields" as |customFields|>{{#each this.schema.category_custom_fields as |entry|}}- {{#if (this.shouldDisplayField entry)}}+ {{#if (this.isFieldVisible entry)}}<SchemaFormField@category={{@category}}@entry={{entry}}@@ -214,7 +239,7 @@ export default class EditCategoryTypeSchemaFields extends Component {<@form.Section><@form.Object @name="category_type_settings" as |categorySettings|>{{#each this.schema.category_settings as |entry|}}- {{#if (this.shouldDisplayField entry)}}+ {{#if (this.isFieldVisible entry)}}<SchemaFormField@category={{@category}}@entry={{entry}}@@ -232,6 +257,39 @@ export default class EditCategoryTypeSchemaFields extends Component {@title={{i18n "category.type_settings_schema.site_settings"}}@subtitle={{i18n "category.settings_apply_to_all_of_type_warning"}}>+ {{#if this.hasSiteTexts}}+ <@form.Object @name="site_texts" as |siteTexts|>+ {{#each this.schema.site_texts as |entry|}}+ {{#if (this.isFieldVisible entry)}}+ <siteTexts.Field+ @name={{entry.name}}+ @type="input"+ @title={{entry.label}}+ @description={{entry.description}}+ @disabled={{@isLoadingSiteTextsLocale}}+ @labelFormat="full"+ @format="large"+ as |field|+ >+ <div class="schema-site-text">+ {{#if @availableLocales}}+ <ComboBox+ @valueProperty="value"+ @content={{@availableLocales}}+ @value={{@siteTextsLocale}}+ @onChange={{@switchSiteTextsLocale}}+ @options={{hash filterable=true}}+ class="schema-site-text__locale"+ />+ {{/if}}+ <field.Control />+ </div>+ </siteTexts.Field>+ {{/if}}+ {{/each}}+ </@form.Object>+ {{/if}}+<@form.Object@name="category_type_site_settings"as |siteSettings data|diff --git a/frontend/discourse/tests/unit/controllers/edit-category-tabs-test.js b/frontend/discourse/tests/unit/controllers/edit-category-tabs-test.jsindex f9fe6a2dd9c..8af238793de 100644--- a/frontend/discourse/tests/unit/controllers/edit-category-tabs-test.js+++ b/frontend/discourse/tests/unit/controllers/edit-category-tabs-test.js@@ -1,6 +1,28 @@import { getOwner } from "@ember/owner";import { setupTest } from "ember-qunit";import { module, test } from "qunit";+import pretender, {+ parsePostData,+} from "discourse/tests/helpers/create-pretender";++function fakeFormApi(siteTexts = {}) {+ const data = { site_texts: { ...siteTexts } };+ return {+ isDirty: false,+ get(name) {+ return name.split(".").reduce((value, part) => value?.[part], data);+ },+ set(name, value) {+ const parts = name.split(".");+ let target = data;+ while (parts.length > 1) {+ target = target[parts.shift()];+ }+ target[parts[0]] = value;+ },+ commitField() {},+ };+}module("Unit | Controller | edit-category-tabs", function (hooks) {setupTest(hooks);@@ -86,4 +108,57 @@ module("Unit | Controller | edit-category-tabs", function (hooks) {"validator can call removeError");});++ test("saving writes customizable text for every edited language at once", async function (assert) {+ const key = "js.solved.shared_issue.label";+ const name = "st_label";++ this.controller.model = {+ id: 1,+ categoryTypes: {+ support: { configuration_schema: { site_texts: [{ key, name }] } },+ },+ };++ this.controller.siteTextsLocale = "en";+ this.controller.siteTextOriginals = { en: { [name]: "Mark as similar" } };+ this.controller.siteTextEdits = { en: { [name]: "Mark as similar" } };+ this.controller.formApi = fakeFormApi({ [name]: "Mark as similar" });++ pretender.get(`/admin/customize/site_texts/${key}.json`, () => [+ 200,+ { "Content-Type": "application/json" },+ JSON.stringify({ site_text: { id: key, value: "Moi aussi" } }),+ ]);++ const saved = [];+ pretender.put(`/admin/customize/site_texts/${key}`, (request) => {+ saved.push({+ locale: request.queryParams.locale,+ value: parsePostData(request.requestBody).site_text.value,+ });+ return [+ 200,+ { "Content-Type": "application/json" },+ JSON.stringify({ site_text: {} }),+ ];+ });++ // Edit English, switch to French, edit French, then save once.+ this.controller.formApi.set(`site_texts.${name}`, "Me too");+ await this.controller.switchSiteTextsLocale("fr");+ this.controller.formApi.set(`site_texts.${name}`, "Moi aussi (edited)");++ const changed = await this.controller._saveSiteTexts();++ assert.true(changed, "reports that customizable text changed");+ assert.deepEqual(+ saved.sort((a, b) => a.locale.localeCompare(b.locale)),+ [+ { locale: "en", value: "Me too" },+ { locale: "fr", value: "Moi aussi (edited)" },+ ],+ "writes the edited value for both languages in a single save"+ );+ });});diff --git a/plugins/discourse-solved/app/services/discourse_solved/categories/types/support.rb b/plugins/discourse-solved/app/services/discourse_solved/categories/types/support.rbindex a245b0df441..61549cf6c3e 100644--- a/plugins/discourse-solved/app/services/discourse_solved/categories/types/support.rb+++ b/plugins/discourse-solved/app/services/discourse_solved/categories/types/support.rb@@ -29,6 +29,7 @@ module DiscourseSolvedconfiguration_values.reverse_merge!(DiscourseSolved::NOTIFY_ON_STAFF_ACCEPT_SOLVED_CUSTOM_FIELD => "true",DiscourseSolved::EMPTY_BOX_ON_UNSOLVED_CUSTOM_FIELD => "true",+ DiscourseSolved::SHARED_ISSUES_ENABLED_CUSTOM_FIELD => "true",)configuration_values.merge!(DiscourseSolved::ENABLE_ACCEPTED_ANSWERS_CUSTOM_FIELD => "true",@@ -106,6 +107,21 @@ module DiscourseSolvedtype: :bool,label: I18n.t("discourse_solved.category_type.empty_box_on_unsolved.label"),},+ DiscourseSolved::SHARED_ISSUES_ENABLED_CUSTOM_FIELD => {+ default: true,+ type: :bool,+ label: I18n.t("discourse_solved.category_type.enable_shared_issues.label"),+ description:+ I18n.t("discourse_solved.category_type.enable_shared_issues.description"),+ },+ },+ site_texts: {+ "js.solved.shared_issue.label" => {+ label: I18n.t("discourse_solved.category_type.shared_issue_label.label"),+ description:+ I18n.t("discourse_solved.category_type.shared_issue_label.description"),+ depends_on: DiscourseSolved::SHARED_ISSUES_ENABLED_CUSTOM_FIELD,+ },},}enddiff --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.gjsindex 00adb08cb0b..806876a7fe8 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@@ -42,10 +42,14 @@ export default class SolvedSharedIssueButton extends Component {}get label() {+ const label = i18n("solved.shared_issue.label");if (this.count === 0) {- return i18n("solved.shared_issue.label_zero");+ return label;}- return i18n("solved.shared_issue.label", { count: this.count });+ return i18n("solved.shared_issue.label_with_count", {+ label,+ count: this.count,+ });}@actiondiff --git a/plugins/discourse-solved/config/locales/client.en.yml b/plugins/discourse-solved/config/locales/client.en.ymlindex 7e16cc80599..434598f20a2 100644--- a/plugins/discourse-solved/config/locales/client.en.yml+++ b/plugins/discourse-solved/config/locales/client.en.yml@@ -60,10 +60,8 @@ en:confirm_solved_removal_cancel: "Cancel"shared_issue:- label_zero: "Me too"- label:- one: "Me too (%{count})"- other: "Me too (%{count})"+ label: "Me too"+ label_with_count: "%{label} (%{count})"title: "I am also experiencing this issue"author_title: "You started this topic"diff --git a/plugins/discourse-solved/config/locales/server.en.yml b/plugins/discourse-solved/config/locales/server.en.ymlindex 003dd51bb2b..109bb299fa1 100644--- a/plugins/discourse-solved/config/locales/server.en.yml+++ b/plugins/discourse-solved/config/locales/server.en.yml@@ -21,6 +21,12 @@ en:solved_topics_auto_close_duration:label: "Auto close solved topics"description: "Automatically close solved topics after this duration from the last reply. Set to 0 to disable."+ enable_shared_issues:+ label: "Enable shared issues"+ description: "Adds a button to unsolved topics in this category that members can use to signal they're experiencing the same issue and opt in to notifications about the solution."+ shared_issue_label:+ label: "Shared issue label"+ description: "The label shown on the shared issue button."site_settings:solved_enabled: "Enable solved plugin, allow users to select solutions for topics"@@ -40,7 +46,7 @@ en:enable_solved_tags: "Tags that will allow users to select solutions."prioritize_solved_topics_in_search: "Prioritize solved topics in search results."enable_support_category_type_setup: "Enables the Support category type option during category creation setup. Note that {{setting:enable_simplified_category_creation}} must be enabled for this to take effect."- enable_solved_shared_issues: "Adds a “Me too” button to unsolved topics in support categories, letting members signal they’re experiencing the same issue and opt into notifications about the topic's solution. Note: You must enable the “Enable support type category setup” upcoming change to use this feature."+ enable_solved_shared_issues: "Adds a “Me too” button to unsolved topics in support categories, letting members signal they’re experiencing the same issue and opt in to notifications about the topic's solution. Note: You must enable the “Enable support type category setup” upcoming change to use this feature."show_who_marked_solved: "Show who marked the topic as solved. This is indicated in the topic's first post, and the answer post in a tooltip."keywords:diff --git a/plugins/discourse-solved/lib/discourse_solved/category_extension.rb b/plugins/discourse-solved/lib/discourse_solved/category_extension.rbindex f3cd07d22e8..8867c94c54e 100644--- a/plugins/discourse-solved/lib/discourse_solved/category_extension.rb+++ b/plugins/discourse-solved/lib/discourse_solved/category_extension.rb@@ -38,6 +38,14 @@ module DiscourseSolved::CategoryExtensioncustom_fields[DiscourseSolved::EMPTY_BOX_ON_UNSOLVED_CUSTOM_FIELD] = coerce_boolean_value(value)end+ def shared_issues_enabled?+ custom_fields[DiscourseSolved::SHARED_ISSUES_ENABLED_CUSTOM_FIELD] != "false"+ end++ def shared_issues_enabled=(value)+ custom_fields[DiscourseSolved::SHARED_ISSUES_ENABLED_CUSTOM_FIELD] = coerce_boolean_value(value)+ end+privatedef coerce_boolean_value(value)diff --git a/plugins/discourse-solved/lib/discourse_solved/guardian_extensions.rb b/plugins/discourse-solved/lib/discourse_solved/guardian_extensions.rbindex 33ffb3cffdf..d87438c545a 100644--- a/plugins/discourse-solved/lib/discourse_solved/guardian_extensions.rb+++ b/plugins/discourse-solved/lib/discourse_solved/guardian_extensions.rb@@ -59,6 +59,7 @@ module DiscourseSolvedreturn false if topic.private_message?return false if topic.solved.present? && !SiteSetting.solved_allow_multiple_solutionsreturn false unless topic_in_support_category?(topic)+ return false unless shared_issues_enabled_for_category?(topic)return false unless current_user.upcoming_change_enabled?(:enable_solved_shared_issues)can_see_topic?(topic)end@@ -67,12 +68,17 @@ module DiscourseSolvedreturn false if topic.blank?return false if topic.private_message?return false unless topic_in_support_category?(topic)+ return false unless shared_issues_enabled_for_category?(topic)unless UpcomingChanges.enabled_for_user?(:enable_solved_shared_issues, current_user)return falseendtrueend+ def shared_issues_enabled_for_category?(topic)+ topic.category&.shared_issues_enabled?+ end+def topic_in_support_category?(topic)return false if topic.category_id.blank?diff --git a/plugins/discourse-solved/plugin.rb b/plugins/discourse-solved/plugin.rbindex 9602495beeb..49399b3c06a 100644--- a/plugins/discourse-solved/plugin.rb+++ b/plugins/discourse-solved/plugin.rb@@ -20,6 +20,7 @@ module ::DiscourseSolvedENABLE_ACCEPTED_ANSWERS_CUSTOM_FIELD = "enable_accepted_answers"NOTIFY_ON_STAFF_ACCEPT_SOLVED_CUSTOM_FIELD = "notify_on_staff_accept_solved"EMPTY_BOX_ON_UNSOLVED_CUSTOM_FIELD = "empty_box_on_unsolved"+ SHARED_ISSUES_ENABLED_CUSTOM_FIELD = "enable_shared_issues"MAX_AUTO_CLOSE_HOURS = 20.years.to_i / 1.hour.to_idef self.accept_answer!(post, acting_user, topic: nil)@@ -93,6 +94,7 @@ after_initialize doSite.preloaded_category_custom_fields << DiscourseSolved::ENABLE_ACCEPTED_ANSWERS_CUSTOM_FIELDSite.preloaded_category_custom_fields << DiscourseSolved::NOTIFY_ON_STAFF_ACCEPT_SOLVED_CUSTOM_FIELDSite.preloaded_category_custom_fields << DiscourseSolved::EMPTY_BOX_ON_UNSOLVED_CUSTOM_FIELD+ Site.preloaded_category_custom_fields << DiscourseSolved::SHARED_ISSUES_ENABLED_CUSTOM_FIELDadd_api_key_scope(:solved,diff --git a/plugins/discourse-solved/spec/models/discourse_solved/categories_types_support_spec.rb b/plugins/discourse-solved/spec/models/discourse_solved/categories_types_support_spec.rbindex b30d67240f3..189a646e26c 100644--- a/plugins/discourse-solved/spec/models/discourse_solved/categories_types_support_spec.rb+++ b/plugins/discourse-solved/spec/models/discourse_solved/categories_types_support_spec.rb@@ -98,6 +98,44 @@ RSpec.describe DiscourseSolved::Categories::Types::Support do"true",)end++ it "enables shared issues by default" do+ described_class.configure_category(category, guardian: admin.guardian)++ expect(category.custom_fields[DiscourseSolved::SHARED_ISSUES_ENABLED_CUSTOM_FIELD]).to eq(+ "true",+ )+ expect(category.shared_issues_enabled?).to eq(true)+ end++ it "uses provided configuration_values for shared issues" do+ described_class.configure_category(+ category,+ guardian: admin.guardian,+ configuration_values: {+ DiscourseSolved::SHARED_ISSUES_ENABLED_CUSTOM_FIELD => "false",+ },+ )++ expect(category.shared_issues_enabled?).to eq(false)+ end+ end++ describe "configuration_schema" do+ it "passes schema validation with the shared issues fields" do+ expect { described_class.validate_schema! }.not_to raise_error+ end++ it "declares the shared issues toggle as a category custom field" do+ keys = described_class.configuration_schema[:category_custom_fields].keys+ expect(keys).to include(DiscourseSolved::SHARED_ISSUES_ENABLED_CUSTOM_FIELD)+ end++ it "declares the shared issue label as a dependent site text" do+ label = described_class.configuration_schema[:site_texts]["js.solved.shared_issue.label"]+ expect(label[:label]).to be_present+ expect(label[:depends_on]).to eq(DiscourseSolved::SHARED_ISSUES_ENABLED_CUSTOM_FIELD)+ endenddescribe ".unconfigure_category" dodiff --git a/plugins/discourse-solved/spec/requests/discourse_solved/shared_issue_controller_spec.rb b/plugins/discourse-solved/spec/requests/discourse_solved/shared_issue_controller_spec.rbindex d6e8b7aa373..a8e487ca93b 100644--- a/plugins/discourse-solved/spec/requests/discourse_solved/shared_issue_controller_spec.rb+++ b/plugins/discourse-solved/spec/requests/discourse_solved/shared_issue_controller_spec.rb@@ -56,6 +56,14 @@ RSpec.describe DiscourseSolved::SharedIssueController doexpect(response.status).to eq(403)end+ it "rejects when shared issues are disabled for the category" do+ category.upsert_custom_fields(+ DiscourseSolved::SHARED_ISSUES_ENABLED_CUSTOM_FIELD => "false",+ )+ post "/solution/shared_issue.json", params: { topic_id: topic.id }+ expect(response.status).to eq(403)+ end+it "returns 404 for unknown topic" dopost "/solution/shared_issue.json", params: { topic_id: -1 }expect(response.status).to eq(404)diff --git a/plugins/discourse-solved/spec/system/shared_issue_spec.rb b/plugins/discourse-solved/spec/system/shared_issue_spec.rbindex bacc1781b68..f59f3cee059 100644--- a/plugins/discourse-solved/spec/system/shared_issue_spec.rb+++ b/plugins/discourse-solved/spec/system/shared_issue_spec.rb@@ -85,6 +85,17 @@ describe "Solved | Shared issue button" doexpect(shared_issue_button).to have_no_shared_issue_buttonend+ it "hides the button when shared issues are disabled for the category" do+ support_category.upsert_custom_fields(+ DiscourseSolved::SHARED_ISSUES_ENABLED_CUSTOM_FIELD => "false",+ )++ sign_in(member)+ topic_page.visit_topic(topic)++ expect(shared_issue_button).to have_no_shared_issue_button+ end+it "prompts anonymous visitors to log in" dotopic_page.visit_topic(topic)diff --git a/plugins/discourse-solved/spec/system/support_category_type_setup_spec.rb b/plugins/discourse-solved/spec/system/support_category_type_setup_spec.rbindex a0d3da7e1d0..a6b182ee2b6 100644--- a/plugins/discourse-solved/spec/system/support_category_type_setup_spec.rb+++ b/plugins/discourse-solved/spec/system/support_category_type_setup_spec.rb@@ -10,6 +10,10 @@ RSpec.describe "Support Category Type Setup" dolet(:dialog) { PageObjects::Components::Dialog.new }let(:toast) { PageObjects::Components::Toasts.new }+ # The form binds site-text fields by a separator-free version of the i18n key+ # (dots and dashes aren't FormKit-safe), so derive it the same way.+ let(:shared_issue_field) { "site_texts.#{"js.solved.shared_issue.label".gsub(/\W/, "_")}" }+before { sign_in(admin) }it "works with correct defaults and configures site settings and category custom field automatically" do@@ -120,6 +124,35 @@ RSpec.describe "Support Category Type Setup" doexpect(SiteSetting.show_who_marked_solved).to eq(true)end+ it "edits the shared issue label as a translation override when enabled" do+ visit("/c/#{category.slug}/edit/support")++ expect(form.field("custom_fields.enable_shared_issues").value).to be_truthy+ expect(form.field(shared_issue_field).value).to eq("Me too")++ form.field(shared_issue_field).fill_in("We have this too")+ banner.click_save++ expect(form.field(shared_issue_field).value).to eq("We have this too")++ override =+ TranslationOverride.find_by(+ locale: SiteSetting.default_locale,+ translation_key: "js.solved.shared_issue.label",+ )+ expect(override.value).to eq("We have this too")+ end++ it "hides the shared issue label field when shared issues are disabled" do+ visit("/c/#{category.slug}/edit/support")++ expect(form).to have_field_with_name(shared_issue_field)++ form.field("custom_fields.enable_shared_issues").toggle++ expect(form).to have_no_field_with_name(shared_issue_field)+ end+it "can remove the support category type" dovisit("/c/#{category.slug}/edit")category_type_selector = PageObjects::Components::DMenu.new(".category-type-selector")diff --git a/spec/services/categories/types/base_spec.rb b/spec/services/categories/types/base_spec.rbindex 767ac0c4d1b..1d3c63a08c5 100644--- a/spec/services/categories/types/base_spec.rb+++ b/spec/services/categories/types/base_spec.rb@@ -181,6 +181,45 @@ RSpec.describe Categories::Types::Base doendexpect { test_type.validate_schema! }.to raise_error(ArgumentError)end++ it "accepts a category custom field with depends_on" do+ test_type =+ Class.new(described_class) do+ def self.configuration_schema+ {+ category_custom_fields: {+ my_field: {+ default: false,+ type: :bool,+ label: "My Field",+ depends_on: "other_field",+ },+ },+ }+ end+ end+ expect { test_type.validate_schema! }.not_to raise_error+ end++ it "accepts a valid site_texts field" do+ test_type =+ Class.new(described_class) do+ def self.configuration_schema+ { site_texts: { "js.some.key" => { label: "Some label", depends_on: "other_field" } } }+ end+ end+ expect { test_type.validate_schema! }.not_to raise_error+ end++ it "raises when a site_texts field is missing :label" do+ test_type =+ Class.new(described_class) do+ def self.configuration_schema+ { site_texts: { "js.some.key" => { description: "No label here" } } }+ end+ end+ expect { test_type.validate_schema! }.to raise_error(ArgumentError)+ endenddescribe "all registered category types" do@@ -204,7 +243,13 @@ RSpec.describe Categories::Types::Base doschema = test_type.send(:resolved_configuration_schema)expect(schema.keys).to eq(- %i[general_category_settings site_settings category_settings category_custom_fields],+ %i[+ general_category_settings+ site_settings+ category_settings+ category_custom_fields+ site_texts+ ],)entry = schema[:site_settings].first@@ -226,7 +271,13 @@ RSpec.describe Categories::Types::Base doschema = test_type.send(:resolved_configuration_schema)expect(schema.keys).to eq(- %i[general_category_settings site_settings category_settings category_custom_fields],+ %i[+ general_category_settings+ site_settings+ category_settings+ category_custom_fields+ site_texts+ ],)entry = schema[:category_settings].first@@ -323,6 +374,51 @@ RSpec.describe Categories::Types::Base doexpect(title_entry).not_to have_key(:depends_on)expect(dependent_entry[:depends_on]).to eq("allow_user_locale")end++ it "resolves depends_on for category custom fields" do+ test_type =+ Class.new(described_class) do+ type_id :test_custom_field_depends_on++ def self.configuration_schema+ {+ category_custom_fields: {+ my_field: {+ default: false,+ type: :bool,+ label: "My Field",+ depends_on: "other_field",+ },+ },+ }+ end+ end++ schema = test_type.send(:resolved_configuration_schema)+ entry = schema[:category_custom_fields].first+ expect(entry[:depends_on]).to eq("other_field")+ end++ it "resolves site_texts entries with the current translation value" do+ test_type =+ Class.new(described_class) do+ type_id :test_site_texts++ def self.configuration_schema+ { site_texts: { "js.some.key" => { label: "Some label", depends_on: "other_field" } } }+ end+ end++ I18n.backend.store_translations(:en, js: { some: { key: "Hello" } })++ schema = test_type.send(:resolved_configuration_schema)+ entry = schema[:site_texts].first+ expect(entry[:key]).to eq("js.some.key")+ expect(entry[:name]).to eq("js_some_key")+ expect(entry[:label]).to eq("Some label")+ expect(entry[:current]).to eq("Hello")+ expect(entry[:depends_on]).to eq("other_field")+ endenddescribe ".configure_site_settings" do