A platform for community discussion. Free, open, simple.
FEATURE: Add "Events" category type for Calendar plugin (#39727)
Renato Atilioeaca2d8a597d
diff --git a/app/controllers/categories_controller.rb b/app/controllers/categories_controller.rbindex e68e92b732c..7ba236ae44b 100644--- a/app/controllers/categories_controller.rb+++ b/app/controllers/categories_controller.rb@@ -185,13 +185,20 @@ class CategoriesController < ApplicationControllerif category_type.present? &&UpcomingChanges.enabled_for_user?(:enable_simplified_category_creation, current_user)+ type_class = Categories::TypeRegistry.get(category_type.to_sym)+ allowed_setting_keys = type_class&.configuration_schema_keys(:category_settings) || []+ type_settings = params[:category_type_settings]&.slice(*allowed_setting_keys)&.permit!+Categories::Configure.call(guardian:,params: {category_id: @category.id,category_type:,site_setting_configuration_values: params[:category_type_site_settings],- category_configuration_values: category_params[:custom_fields],+ category_configuration_values: [+ category_params[:custom_fields],+ type_settings,+ ].compact.reduce(:merge),},) do |result|on_failed_policy(:type_is_available) do@@ -240,6 +247,26 @@ class CategoriesController < ApplicationControllercat.reloadend+ if UpcomingChanges.enabled_for_user?(:enable_simplified_category_creation, current_user) &&+ params[:category_type_settings].present?+ # Re-run configure_category for each matching type so per-type+ # category_settings (e.g. events_calendar_default_view) are persisted on+ # edit, not just on create. Each type only sees its own keys so it+ # cannot be invoked spuriously for other types' settings.+ cat.category_types.each_key do |type_id|+ type_class = Categories::TypeRegistry.get(type_id)+ next unless type_class++ type_values =+ params[:category_type_settings].slice(+ *type_class.configuration_schema_keys(:category_settings),+ )+ next if type_values.empty?++ type_class.configure_category(cat, guardian:, configuration_values: type_values)+ end+ end+merge_pending_custom_fields!(cat, pending_custom_fields)# properly null the value so the database constraint doesn't catch usdiff --git a/app/serializers/category_serializer.rb b/app/serializers/category_serializer.rbindex d394d276c2a..2096ab4919a 100644--- a/app/serializers/category_serializer.rb+++ b/app/serializers/category_serializer.rb@@ -44,6 +44,7 @@ class CategorySerializer < SiteCategorySerializer:emoji,:icon,:category_types,+ :category_type_settings,:available_category_typeshas_one :category_setting, serializer: CategorySettingSerializer, embed: :objects@@ -162,6 +163,17 @@ class CategorySerializer < SiteCategorySerializerobject.category_typesend+ def category_type_settings+ return {} if !SiteSetting.enable_simplified_category_creation+ Categories::TypeRegistry+ .all+ .values+ .reduce({}) do |result, type_klass|+ next result unless type_klass.category_matches?(object)+ result.merge(type_klass.read_category_settings(object))+ end+ end+def available_category_typesreturn [] if !SiteSetting.enable_simplified_category_creationCategories::TypeRegistry.list(only_visible: true)diff --git a/app/services/categories/types/base.rb b/app/services/categories/types/base.rbindex 12a08efa8d9..58d829cd444 100644--- a/app/services/categories/types/base.rb+++ b/app/services/categories/types/base.rb@@ -10,7 +10,7 @@ module Categories"general_category_settings" => {"type" => "object","additionalProperties" => {- "$ref" => "#/$defs/field_config",+ "$ref" => "#/$defs/general_field_config",},},"site_settings" => {@@ -30,6 +30,27 @@ module Categories},},"$defs" => {+ "general_field_config" => {+ "type" => "object",+ "required" => %w[default type],+ "additionalProperties" => false,+ "properties" => {+ "default" => true,+ "type" => {+ "type" => "string",+ "minLength" => 1,+ },+ "required" => {+ "type" => "boolean",+ },+ "show_on_create" => {+ "type" => "boolean",+ },+ "show_on_edit" => {+ "type" => "boolean",+ },+ },+ },"field_config" => {"type" => "object","required" => %w[default type label],@@ -51,6 +72,12 @@ module Categories"description" => {"type" => "string",},+ "choices" => {+ "type" => "array",+ },+ "required" => {+ "type" => "boolean",+ },"show_on_create" => {"type" => "boolean",},@@ -115,6 +142,16 @@ module Categoriesraise NotImplementedErrorend+ # Returns the current per-category +category_settings+ values for+ # the given category. Used by the serializer to preload the edit+ # form with stored values instead of schema defaults.+ #+ # This SHOULD be overridden by category types that declare+ # +category_settings+.+ def read_category_settings(category)+ {}+ end+# Returns a hash describing the configuration schema for this category type.# This schema drives both the UI (what settings are shown to admins in the# category creator) and the site-setting update allowlist.@@ -242,8 +279,11 @@ module Categories## This SHOULD NOT be overridden by category types.def configure_custom_fields(category, guardian:, configuration_values: {})+ if configuration_values.is_a?(Hash)+ configuration_values = configuration_values.symbolize_keys+ endconfiguration_schema[:category_custom_fields]&.each do |field_name, config|- value = configuration_values.fetch(field_name.to_s, config[:default])+ value = configuration_values.fetch(field_name.to_sym, config[:default])category.custom_fields[field_name.to_s] = value.to_send@@ -257,12 +297,15 @@ module Categories## This SHOULD NOT be overridden by category types.def configure_site_settings(category, guardian:, configuration_values: {})+ if configuration_values.is_a?(Hash)+ configuration_values = configuration_values.symbolize_keys+ endcategory_type_settings =configuration_schema[:site_settings]&.map do |setting_name, config|default_value = config.is_a?(Hash) ? config[:default] : config{setting_name: setting_name.to_s,- value: configuration_values.fetch(setting_name.to_s, default_value),+ value: configuration_values.fetch(setting_name.to_sym, default_value),}end@@ -327,9 +370,13 @@ module Categoriesif target_value.is_a?(Hash)default = target_value[:default]custom_label = target_value[:label]+ custom_type = target_value[:type]+ custom_choices = target_value[:choices]elsedefault = target_valuecustom_label = nil+ custom_type = nil+ custom_choices = nilendmeta = SiteSetting.setting_metadata_hash(setting_name)@@ -338,8 +385,9 @@ module Categorieskey: setting_name.to_s,default:,current: SiteSetting.public_send(setting_name),- type: meta[:type],+ type: custom_type || meta[:type],label: custom_label || meta[:humanized_name],+ choices: custom_choices || meta[:choices],description: meta[:description],required: false,show_on_create: true,@@ -358,6 +406,7 @@ module Categoriestype: config[:type].to_s,label: config[:label],subtype: config[:subtype]&.to_s,+ choices: config[:choices],description: config[:description],required: config[:required],show_on_create: config[:show_on_create].nil? ? true : config[:show_on_create],@@ -373,6 +422,7 @@ module Categoriessubtype: config[:subtype]&.to_s,label: config[:label],description: config[:description],+ choices: config[:choices],required: config[:required],show_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],diff --git a/frontend/discourse/admin/controllers/edit-category/tabs.js b/frontend/discourse/admin/controllers/edit-category/tabs.jsindex 76a335e6203..f5ec11794a7 100644--- a/frontend/discourse/admin/controllers/edit-category/tabs.js+++ b/frontend/discourse/admin/controllers/edit-category/tabs.js@@ -156,6 +156,9 @@ export default class EditCategoryTabsController extends Controller {data.custom_fields = { ...(this.model.custom_fields ?? {}) };data.category_type_site_settings = {};+ data.category_type_settings = {+ ...(this.model.category_type_settings ?? {}),+ };data.category_types = Object.keys(this.model.categoryTypes ?? {});Object.values(this.model.categoryTypes ?? {}).forEach((categoryType) => {@@ -165,6 +168,12 @@ export default class EditCategoryTabsController extends Controller {});+ categoryType.configuration_schema.category_settings?.forEach(+ (field) => {+ data.category_type_settings[field.key] ??= field.default;+ }+ );+categoryType.configuration_schema.site_settings?.forEach((setting) => {data.category_type_site_settings[setting.key] = this.model.id? setting.current@@ -370,6 +379,9 @@ export default class EditCategoryTabsController extends Controller {this.set("saving", true);try {+ const previousTypes = new Set(+ Object.keys(this.model.categoryTypes ?? {})+ );const result = await this.model.save();const updatedModel = this.site.updateCategory(result.category);updatedModel.setupGroupsAndPermissions();@@ -379,6 +391,22 @@ export default class EditCategoryTabsController extends Controller {return;}+ if (this.siteSettings.enable_simplified_category_creation) {+ const newTypes = Object.keys(result.category.category_types ?? {});+ const typeWasAdded = newTypes.some((t) => !previousTypes.has(t));+ if (typeWasAdded) {+ if (this.model.id) {+ window.location.reload();+ } else {+ window.location = this.router.urlFor(+ "editCategory",+ Category.slugFor(updatedModel)+ );+ }+ return;+ }+ }+this.set("saving", false);this.initFormData();diff --git a/frontend/discourse/app/components/edit-category-type-schema-fields.gjs b/frontend/discourse/app/components/edit-category-type-schema-fields.gjsindex c9d7297e938..a098b926db3 100644--- a/frontend/discourse/app/components/edit-category-type-schema-fields.gjs+++ b/frontend/discourse/app/components/edit-category-type-schema-fields.gjs@@ -1,6 +1,8 @@import Component from "@glimmer/component";-import { get } from "@ember/helper";+import { fn, get } from "@ember/helper";+import { service } from "@ember/service";import { bind } from "discourse/lib/decorators";+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";import { i18n } from "discourse-i18n";@@ -9,62 +11,124 @@ import { i18n } from "discourse-i18n";// here rather than this custom implementation. We are also only supporting a small// subset of site setting types / category field types for now, we can expand this as// needed.-const SchemaFormField = <template>- {{#if (eq @entry.type "bool")}}- <@formObject.Field- @name={{@entry.key}}- @type="checkbox"- @title={{@entry.label}}- @validation={{if @entry.required "required"}}- @format="full"- @showTitle={{false}}- as |field|- >- <field.Control>{{@entry.description}}</field.Control>- </@formObject.Field>- {{else if (eq @entry.subtype "duration")}}- <@formObject.Field- @name={{@entry.key}}- @title={{@entry.label}}- @description={{@entry.description}}- @validation={{if @entry.required "required"}}- @format="full"- @type="custom"- as |field|- >- <DRelativeTimePicker- @durationHours={{field.value}}- @durationOutputUnit="hours"- @onChange={{field.set}}- />- </@formObject.Field>- {{else if (eq @entry.type "integer")}}- <@formObject.Field- @name={{@entry.key}}- @title={{@entry.label}}- @description={{@entry.description}}- @validation={{if @entry.required "required"}}- @format="full"- @type="input-number"- as |field|- >- <field.Control min={{@entry.min}} max={{@entry.max}} />- </@formObject.Field>- {{else}}- <@formObject.Field- @name={{@entry.key}}- @type="input"- @title={{@entry.label}}- @description={{@entry.description}}- @validation={{if @entry.required "required"}}- @labelFormat="full"- @format="large"- as |field|- >- <field.Control />- </@formObject.Field>- {{/if}}-</template>;+class SchemaFormField extends Component {+ @service site;++ get groupContent() {+ return this.site.groups;+ }++ toGroupIdArray(value) {+ if (Array.isArray(value)) {+ return value.map(Number);+ }+ if (typeof value === "string" && value.length) {+ return value.split("|").map(Number);+ }+ return [];+ }++ @bind+ setGroupIdString(field, ids) {+ field.set((ids ?? []).join("|"));+ }++ <template>+ {{#if (eq @entry.type "bool")}}+ <@formObject.Field+ @name={{@entry.key}}+ @type="checkbox"+ @title={{@entry.label}}+ @validation={{if @entry.required "required"}}+ @format="full"+ @showTitle={{false}}+ as |field|+ >+ <field.Control>{{@entry.description}}</field.Control>+ </@formObject.Field>+ {{else if (eq @entry.subtype "duration")}}+ <@formObject.Field+ @name={{@entry.key}}+ @title={{@entry.label}}+ @description={{@entry.description}}+ @validation={{if @entry.required "required"}}+ @format="full"+ @type="custom"+ as |field|+ >+ <DRelativeTimePicker+ @durationHours={{field.value}}+ @durationOutputUnit="hours"+ @onChange={{field.set}}+ />+ </@formObject.Field>+ {{else if (eq @entry.type "enum")}}+ <@formObject.Field+ @name={{@entry.key}}+ @title={{@entry.label}}+ @description={{@entry.description}}+ @validation={{if @entry.required "required"}}+ @labelFormat="full"+ @format="large"+ @type="select"+ as |field|+ >+ <field.Control as |select|>+ {{#each @entry.choices as |choice|}}+ <select.Option @value={{choice.value}}>+ {{choice.name}}+ </select.Option>+ {{/each}}+ </field.Control>+ </@formObject.Field>+ {{else if (eq @entry.type "group_list")}}+ <@formObject.Field+ @name={{@entry.key}}+ @title={{@entry.label}}+ @description={{@entry.description}}+ @validation={{if @entry.required "required"}}+ @labelFormat="full"+ @format="large"+ @type="custom"+ as |field|+ >+ <field.Control>+ <GroupChooser+ @content={{this.groupContent}}+ @value={{this.toGroupIdArray field.value}}+ @labelProperty="name"+ @onChange={{fn this.setGroupIdString field}}+ />+ </field.Control>+ </@formObject.Field>+ {{else if (eq @entry.type "integer")}}+ <@formObject.Field+ @name={{@entry.key}}+ @title={{@entry.label}}+ @description={{@entry.description}}+ @validation={{if @entry.required "required"}}+ @format="full"+ @type="input-number"+ as |field|+ >+ <field.Control min={{@entry.min}} max={{@entry.max}} />+ </@formObject.Field>+ {{else}}+ <@formObject.Field+ @name={{@entry.key}}+ @type="input"+ @title={{@entry.label}}+ @description={{@entry.description}}+ @validation={{if @entry.required "required"}}+ @labelFormat="full"+ @format="large"+ as |field|+ >+ <field.Control />+ </@formObject.Field>+ {{/if}}+ </template>+}export default class EditCategoryTypeSchemaFields extends Component {get schema() {@@ -80,6 +144,12 @@ export default class EditCategoryTypeSchemaFields extends Component {);}+ get hasCategorySettings() {+ return this.schema.category_settings?.some((entry) =>+ this.shouldDisplayField(entry)+ );+ }+get className() {let classes = ["edit-category-type-schema-fields",@@ -88,7 +158,7 @@ export default class EditCategoryTypeSchemaFields extends Component {if (this.args.active) {classes.push("active");}- if (!this.hasCustomFields) {+ if (!this.hasCustomFields && !this.hasCategorySettings) {classes.push("--site-settings-only");}return classes.join(" ");@@ -140,6 +210,22 @@ export default class EditCategoryTypeSchemaFields extends Component {</@form.Section>{{/if}}+ {{#if this.hasCategorySettings}}+ <@form.Section>+ <@form.Object @name="category_type_settings" as |categorySettings|>+ {{#each this.schema.category_settings as |entry|}}+ {{#if (this.shouldDisplayField entry)}}+ <SchemaFormField+ @category={{@category}}+ @entry={{entry}}+ @formObject={{categorySettings}}+ />+ {{/if}}+ {{/each}}+ </@form.Object>+ </@form.Section>+ {{/if}}+{{yield to="beforeSiteSettings"}}<@form.Emphasisdiff --git a/frontend/discourse/app/models/category.js b/frontend/discourse/app/models/category.jsindex 21cdcd364e5..dbd7f6f5492 100644--- a/frontend/discourse/app/models/category.js+++ b/frontend/discourse/app/models/category.js@@ -858,6 +858,7 @@ export default class Category extends RestModel {_categoryTypeSaveProperties(id) {const props = {category_type_site_settings: this.category_type_site_settings,+ category_type_settings: this.category_type_settings,};if (!id && this.categoryTypes) {diff --git a/plugins/discourse-calendar/app/services/discourse_calendar/categories/types/events.rb b/plugins/discourse-calendar/app/services/discourse_calendar/categories/types/events.rbnew file mode 100644index 00000000000..324ce7c29f5--- /dev/null+++ b/plugins/discourse-calendar/app/services/discourse_calendar/categories/types/events.rb@@ -0,0 +1,241 @@+# frozen_string_literal: true++module DiscourseCalendar+ module Categories+ module Types+ class Events < ::Categories::Types::Base+ type_id :events++ class << self+ def visible?+ SiteSetting.enable_events_category_type_setup+ end++ def enable_plugin+ SiteSetting.calendar_enabled = true+ SiteSetting.discourse_post_event_enabled = true+ end++ def category_matches?(category)+ events_calendar_category_ids.include?(category.id)+ end++ def find_matches+ Category.where(id: events_calendar_category_ids)+ end++ def configure_category(category, guardian:, configuration_values: {})+ add_to_events_calendar_categories(category)+ # Fall back to stored values when a key is absent so partial+ # updates preserve the other setting. Block form of fetch lets+ # this work with both Hash and ActionController::Parameters.+ current = read_category_settings(category)+ update_calendar_categories_entry(+ category,+ default_view:+ configuration_values+ .fetch(:events_calendar_default_view) do+ current.fetch(:events_calendar_default_view, "month")+ end+ .to_s,+ display_weekends:+ ActiveModel::Type::Boolean.new.cast(+ configuration_values.fetch(:events_calendar_display_weekends) do+ current.fetch(:events_calendar_display_weekends, true)+ end,+ ),+ )+ end++ def unconfigure_category(category, guardian:)+ remove_from_events_calendar_categories(category)+ remove_calendar_categories_entry(category)+ end++ # Parses the legacy +calendar_categories+ string format+ # ("categoryId=42;weekends=true;defaultView=month|...") to recover+ # this category's stored values. Modernizing the storage to a+ # structured SiteSetting type would let this and the helpers+ # below collapse to direct lookups.+ def read_category_settings(category)+ entry =+ SiteSetting+ .calendar_categories+ .split("|")+ .find { |e| e.split(";").include?("categoryId=#{category.id}") }+ return {} unless entry++ parts =+ entry+ .split(";")+ .each_with_object({}) do |part, hash|+ key, value = part.split("=", 2)+ hash[key] = value if key && value+ end++ {+ events_calendar_default_view: parts["defaultView"] || "month",+ events_calendar_display_weekends: parts["weekends"] != "false",+ }+ end++ def configuration_schema+ {+ general_category_settings: {+ name: {+ default: I18n.t("category_types.events.name"),+ type: :string,+ },+ style_type: {+ default: "emoji",+ type: :string,+ },+ emoji: {+ default: "spiral_calendar",+ type: :string,+ },+ },+ category_settings: {+ events_calendar_default_view: {+ default: "month",+ type: :enum,+ required: true,+ choices: [+ {+ name: I18n.t("discourse_calendar.category_type.default_calendar_view.day"),+ value: "day",+ },+ {+ name: I18n.t("discourse_calendar.category_type.default_calendar_view.week"),+ value: "week",+ },+ {+ name: I18n.t("discourse_calendar.category_type.default_calendar_view.month"),+ value: "month",+ },+ {+ name: I18n.t("discourse_calendar.category_type.default_calendar_view.year"),+ value: "year",+ },+ ],+ label: I18n.t("discourse_calendar.category_type.default_calendar_view.label"),+ },+ events_calendar_display_weekends: {+ default: true,+ type: :bool,+ label: I18n.t("discourse_calendar.category_type.display_weekends.label"),+ },+ },+ site_settings: {+ discourse_post_event_allowed_on_groups: {+ default: "",+ type: :group_list,+ label:+ I18n.t(+ "discourse_calendar.category_type.discourse_post_event_allowed_on_groups.label",+ ),+ },+ use_local_event_date: {+ default: false,+ type: :enum,+ required: true,+ choices: [+ {+ name: I18n.t("discourse_calendar.category_type.use_local_event_date.local"),+ value: true,+ },+ {+ name:+ I18n.t("discourse_calendar.category_type.use_local_event_date.relative"),+ value: false,+ },+ ],+ label: I18n.t("discourse_calendar.category_type.use_local_event_date.label"),+ },+ sort_categories_by_event_start_date_enabled: {+ default: true,+ type: :enum,+ required: true,+ choices: [+ {+ name:+ I18n.t(+ "discourse_calendar.category_type.sort_categories_by_event_start_date_enabled.event_date",+ ),+ value: true,+ },+ {+ name:+ I18n.t(+ "discourse_calendar.category_type.sort_categories_by_event_start_date_enabled.latest_post",+ ),+ value: false,+ },+ ],+ label:+ I18n.t(+ "discourse_calendar.category_type.sort_categories_by_event_start_date_enabled.label",+ ),+ },+ sidebar_show_upcoming_events: {+ default: true,+ type: :bool,+ label:+ I18n.t("discourse_calendar.category_type.sidebar_show_upcoming_events.label"),+ },+ },+ }+ end++ def icon+ "spiral_calendar"+ end++ private++ def events_calendar_category_ids+ SiteSetting.events_calendar_categories_map+ end++ def add_to_events_calendar_categories(category)+ ids = events_calendar_category_ids+ return if ids.include?(category.id)++ SiteSetting.events_calendar_categories = (ids << category.id).join("|")+ end++ def remove_from_events_calendar_categories(category)+ ids = events_calendar_category_ids - [category.id]+ SiteSetting.events_calendar_categories = ids.join("|")+ end++ def update_calendar_categories_entry(category, default_view:, display_weekends:)+ entry =+ "categoryId=#{category.id};weekends=#{display_weekends};defaultView=#{default_view}"++ entries = SiteSetting.calendar_categories.split("|")+ existing_index =+ entries.find_index { |e| e.split(";").include?("categoryId=#{category.id}") }++ if existing_index+ entries[existing_index] = entry+ else+ entries << entry+ end++ SiteSetting.calendar_categories = entries.join("|")+ end++ def remove_calendar_categories_entry(category)+ entries =+ SiteSetting+ .calendar_categories+ .split("|")+ .reject { |e| e.split(";").include?("categoryId=#{category.id}") }+ SiteSetting.calendar_categories = entries.join("|")+ end+ end+ end+ end+ end+enddiff --git a/plugins/discourse-calendar/config/locales/server.en.yml b/plugins/discourse-calendar/config/locales/server.en.ymlindex f79a0b9197d..08b31401226 100644--- a/plugins/discourse-calendar/config/locales/server.en.yml+++ b/plugins/discourse-calendar/config/locales/server.en.yml@@ -1,4 +1,10 @@en:+ category_types:+ events:+ name: "Events"+ title: "events"+ description: "Where members can find and discuss upcoming events on a shared calendar."+user_api_key:scopes:"discourse-calendar:events_calendar": "Read calendar events feed"@@ -66,6 +72,27 @@ en:enable_events_category_type_setup: "Enables the Events category type option during category creation setup. Note that 'enable simplified category creation' must be enabled for this to take effect."discourse_calendar:+ category_type:+ default_calendar_view:+ label: "Default calendar view"+ day: "Day"+ week: "Week"+ month: "Month"+ year: "Year"+ display_weekends:+ label: "Display weekends"+ discourse_post_event_allowed_on_groups:+ label: "Groups that can create events"+ use_local_event_date:+ label: "Event date format"+ local: "Local date (e.g., April 20)"+ relative: "Relative time (e.g., in 2 days)"+ sort_categories_by_event_start_date_enabled:+ label: "Topic sorting"+ event_date: "Event date"+ latest_post: "Latest post activity"+ sidebar_show_upcoming_events:+ label: 'Show "Upcoming events" link in navigation menu'calendar_subscriptions:all_events_feed_name: "%{site_title} - All events"my_events_feed_name: "%{site_title} - My events"diff --git a/plugins/discourse-calendar/plugin.rb b/plugins/discourse-calendar/plugin.rbindex 5278cd3526d..3b0027adfb1 100644--- a/plugins/discourse-calendar/plugin.rb+++ b/plugins/discourse-calendar/plugin.rb@@ -84,6 +84,7 @@ Dirafter_initialize doreloadable_patch do+ register_category_type(DiscourseCalendar::Categories::Types::Events)Category.register_custom_field_type("sort_topics_by_event_start_date", :boolean)Category.register_custom_field_type("disable_topic_resorting", :boolean)register_preloaded_category_custom_fields("sort_topics_by_event_start_date")diff --git a/plugins/discourse-calendar/spec/requests/categories_controller_spec.rb b/plugins/discourse-calendar/spec/requests/categories_controller_spec.rbnew file mode 100644index 00000000000..22612ff88a9--- /dev/null+++ b/plugins/discourse-calendar/spec/requests/categories_controller_spec.rb@@ -0,0 +1,79 @@+# frozen_string_literal: true++describe CategoriesController do+ fab!(:admin)+ fab!(:category)++ before do+ SiteSetting.enable_simplified_category_creation = true+ SiteSetting.enable_events_category_type_setup = true+ SiteSetting.calendar_enabled = true+ SiteSetting.discourse_post_event_enabled = true+ DiscourseCalendar::Categories::Types::Events.configure_category(+ category,+ guardian: admin.guardian,+ )+ sign_in(admin)+ end++ describe "#update" do+ it "persists category_type_settings into calendar_categories" do+ put "/categories/#{category.id}.json",+ params: {+ category_type_settings: {+ events_calendar_default_view: "week",+ events_calendar_display_weekends: false,+ },+ }++ expect(response.status).to eq(200)+ expect(SiteSetting.calendar_categories).to include(+ "categoryId=#{category.id};weekends=false;defaultView=week",+ )+ end++ it "leaves calendar_categories untouched when category_type_settings is absent" do+ original = SiteSetting.calendar_categories++ put "/categories/#{category.id}.json", params: { name: "Renamed Events" }++ expect(response.status).to eq(200)+ expect(SiteSetting.calendar_categories).to eq(original)+ end++ it "preserves unspecified category_type_settings when only one key is sent" do+ DiscourseCalendar::Categories::Types::Events.configure_category(+ category,+ guardian: admin.guardian,+ configuration_values: {+ events_calendar_default_view: "year",+ events_calendar_display_weekends: false,+ },+ )++ put "/categories/#{category.id}.json",+ params: {+ category_type_settings: {+ events_calendar_default_view: "week",+ },+ }++ expect(response.status).to eq(200)+ expect(SiteSetting.calendar_categories).to include(+ "categoryId=#{category.id};weekends=false;defaultView=week",+ )+ end++ it "persists site setting edits via category_type_site_settings" do+ put "/categories/#{category.id}.json",+ params: {+ category_type_site_settings: {+ sidebar_show_upcoming_events: false,+ },+ }++ expect(response.status).to eq(200)+ expect(SiteSetting.sidebar_show_upcoming_events).to eq(false)+ end+ end+enddiff --git a/plugins/discourse-calendar/spec/services/discourse_calendar/categories/types/events_spec.rb b/plugins/discourse-calendar/spec/services/discourse_calendar/categories/types/events_spec.rbnew file mode 100644index 00000000000..f329076791e--- /dev/null+++ b/plugins/discourse-calendar/spec/services/discourse_calendar/categories/types/events_spec.rb@@ -0,0 +1,219 @@+# frozen_string_literal: true++RSpec.describe DiscourseCalendar::Categories::Types::Events do+ fab!(:admin)+ fab!(:category)++ describe ".visible?" do+ it "returns true when enable_events_category_type_setup is true" do+ SiteSetting.enable_events_category_type_setup = true+ expect(described_class.visible?).to eq(true)+ end++ it "returns false when enable_events_category_type_setup is false" do+ SiteSetting.enable_events_category_type_setup = false+ expect(described_class.visible?).to eq(false)+ end+ end++ describe ".enable_plugin" do+ it "enables calendar and post-event site settings" do+ SiteSetting.calendar_enabled = false+ SiteSetting.discourse_post_event_enabled = false++ described_class.enable_plugin++ expect(SiteSetting.calendar_enabled).to eq(true)+ expect(SiteSetting.discourse_post_event_enabled).to eq(true)+ end+ end++ describe ".category_matches?" do+ it "returns true when the category id is in events_calendar_categories" do+ SiteSetting.events_calendar_categories = category.id.to_s+ expect(described_class.category_matches?(category)).to eq(true)+ end++ it "returns false when the category id is not in events_calendar_categories" do+ SiteSetting.events_calendar_categories = ""+ expect(described_class.category_matches?(category)).to eq(false)+ end+ end++ describe ".find_matches" do+ fab!(:other_category, :category)++ it "returns categories listed in events_calendar_categories" do+ SiteSetting.events_calendar_categories = "#{category.id}|#{other_category.id}"+ expect(described_class.find_matches).to contain_exactly(category, other_category)+ end++ it "returns no categories when the setting is blank" do+ SiteSetting.events_calendar_categories = ""+ expect(described_class.find_matches).to be_empty+ end+ end++ describe ".configure_category" do+ it "appends the category to events_calendar_categories" do+ SiteSetting.events_calendar_categories = ""+ described_class.configure_category(category, guardian: admin.guardian)+ expect(SiteSetting.events_calendar_categories).to eq(category.id.to_s)+ end++ it "does not duplicate the category id when called twice" do+ SiteSetting.events_calendar_categories = ""+ 2.times { described_class.configure_category(category, guardian: admin.guardian) }+ expect(SiteSetting.events_calendar_categories).to eq(category.id.to_s)+ end++ it "writes a calendar_categories entry with the chosen view and weekends" do+ described_class.configure_category(+ category,+ guardian: admin.guardian,+ configuration_values: {+ events_calendar_default_view: "week",+ events_calendar_display_weekends: false,+ },+ )++ expect(SiteSetting.calendar_categories).to include(+ "categoryId=#{category.id};weekends=false;defaultView=week",+ )+ end++ it "uses defaults when configuration values are not provided" do+ described_class.configure_category(category, guardian: admin.guardian)++ expect(SiteSetting.calendar_categories).to include(+ "categoryId=#{category.id};weekends=true;defaultView=month",+ )+ end++ it "replaces an existing calendar_categories entry for the same category" do+ SiteSetting.calendar_categories = "categoryId=#{category.id};weekends=true;defaultView=month"++ described_class.configure_category(+ category,+ guardian: admin.guardian,+ configuration_values: {+ events_calendar_default_view: "year",+ events_calendar_display_weekends: false,+ },+ )++ expect(SiteSetting.calendar_categories).to eq(+ "categoryId=#{category.id};weekends=false;defaultView=year",+ )+ end+ end++ describe ".unconfigure_category" do+ before { described_class.configure_category(category, guardian: admin.guardian) }++ it "removes the category from events_calendar_categories" do+ expect(SiteSetting.events_calendar_categories.split("|")).to include(category.id.to_s)++ described_class.unconfigure_category(category, guardian: admin.guardian)++ expect(SiteSetting.events_calendar_categories.split("|")).not_to include(category.id.to_s)+ end++ it "removes the category's entry from calendar_categories" do+ expect(SiteSetting.calendar_categories).to include("categoryId=#{category.id};")++ described_class.unconfigure_category(category, guardian: admin.guardian)++ expect(SiteSetting.calendar_categories).not_to include("categoryId=#{category.id};")+ end++ it "leaves other categories' calendar_categories entries untouched" do+ other = Fabricate(:category)+ described_class.configure_category(other, guardian: admin.guardian)++ described_class.unconfigure_category(category, guardian: admin.guardian)++ expect(SiteSetting.calendar_categories).to include("categoryId=#{other.id};")+ end+ end++ describe ".read_category_settings" do+ it "returns the stored values when the category has a calendar_categories entry" do+ described_class.configure_category(+ category,+ guardian: admin.guardian,+ configuration_values: {+ events_calendar_default_view: "year",+ events_calendar_display_weekends: false,+ },+ )++ expect(described_class.read_category_settings(category)).to eq(+ events_calendar_default_view: "year",+ events_calendar_display_weekends: false,+ )+ end++ it "returns an empty hash when the category has no entry" do+ expect(described_class.read_category_settings(category)).to eq({})+ end+ end++ describe ".configuration_schema" do+ it "exposes the expected top-level groups" do+ schema = described_class.configuration_schema+ expect(schema.keys).to contain_exactly(+ :general_category_settings,+ :category_settings,+ :site_settings,+ )+ end++ it "presets the prefilled name and emoji" do+ schema = described_class.configuration_schema+ expect(schema[:general_category_settings][:name][:default]).to eq("Events")+ expect(schema[:general_category_settings][:emoji][:default]).to eq("spiral_calendar")+ end++ it "is valid against CONFIGURATION_SCHEMA_DEFINITION" do+ expect { described_class.validate_schema! }.not_to raise_error+ end+ end++ describe "via Categories::Configure" do+ it "wires plugin enable, site settings, and category configuration end-to-end" do+ SiteSetting.enable_events_category_type_setup = true++ result =+ Categories::Configure.call(+ guardian: admin.guardian,+ params: {+ category_id: category.id,+ category_type: "events",+ category_configuration_values: {+ "events_calendar_default_view" => "week",+ "events_calendar_display_weekends" => false,+ },+ site_setting_configuration_values: {+ discourse_post_event_allowed_on_groups: "1|2",+ use_local_event_date: true,+ sort_categories_by_event_start_date_enabled: false,+ sidebar_show_upcoming_events: false,+ },+ },+ )++ expect(result).to be_a_success+ expect(SiteSetting.calendar_enabled).to eq(true)+ expect(SiteSetting.discourse_post_event_enabled).to eq(true)+ expect(SiteSetting.events_calendar_categories).to include(category.id.to_s)+ expect(SiteSetting.discourse_post_event_allowed_on_groups).to eq("1|2")+ expect(SiteSetting.use_local_event_date).to eq(true)+ expect(SiteSetting.sort_categories_by_event_start_date_enabled).to eq(false)+ expect(SiteSetting.sidebar_show_upcoming_events).to eq(false)+ expect(SiteSetting.calendar_categories).to include(+ "categoryId=#{category.id};weekends=false;defaultView=week",+ )+ end+ end+enddiff --git a/plugins/discourse-calendar/spec/system/events_category_type_setup_spec.rb b/plugins/discourse-calendar/spec/system/events_category_type_setup_spec.rbnew file mode 100644index 00000000000..d7e129a4687--- /dev/null+++ b/plugins/discourse-calendar/spec/system/events_category_type_setup_spec.rb@@ -0,0 +1,134 @@+# frozen_string_literal: true++RSpec.describe "Events Category Type Setup" do+ fab!(:admin)++ let(:form) { PageObjects::Components::FormKit.new(".form-kit") }+ let(:category_type_card) { PageObjects::Components::CategoryTypeCard.new }+ let(:banner) { PageObjects::Components::AdminChangesBanner.new }+ let(:toast) { PageObjects::Components::Toasts.new }++ before do+ SiteSetting.enable_simplified_category_creation = true+ SiteSetting.enable_events_category_type_setup = true+ SiteSetting.calendar_enabled = true+ SiteSetting.discourse_post_event_enabled = true+ sign_in(admin)+ end++ it "preloads defaults and configures site settings + calendar_categories on save" do+ visit("/new-category/setup")+ category_type_card.find_type_card("events").click+ expect(page).to have_content(I18n.t("js.category.create_with_type", typeName: "events"))++ expect(form.field("name").value).to eq("Events")+ expect(+ form.field("style_type").find(".form-kit__control-radio[type='radio'][value='emoji']")[+ "checked"+ ],+ ).to eq(true)+ expect(form.field("style_type").find("#control-emoji").find("img.emoji")["title"]).to eq(+ "spiral_calendar",+ )++ expect(banner).to be_visible+ banner.click_save++ expect(page).to have_content(I18n.t("js.category.edit_dialog_title", categoryName: "Events"))+ expect(page).to have_css(".d-nav-submenu__tabs .edit-category-events")+ expect(SiteSetting.calendar_enabled).to eq(true)+ expect(SiteSetting.discourse_post_event_enabled).to eq(true)++ category = Category.find_by(name: "Events")+ expect(SiteSetting.events_calendar_categories.split("|")).to include(category.id.to_s)+ expect(SiteSetting.calendar_categories).to include(+ "categoryId=#{category.id};weekends=true;defaultView=month",+ )+ end++ context "when the events category type setup is disabled" do+ before { SiteSetting.enable_events_category_type_setup = false }++ it "does not show the events category type" do+ visit("/new-category/setup")+ expect(page).to have_no_css(".category-type-cards__card.--category-type-events")+ end++ it "does not show the tab for the events category type when editing an existing category" do+ events_category = Fabricate(:category, name: "Events")+ DiscourseCalendar::Categories::Types::Events.configure_category(+ events_category,+ guardian: admin.guardian,+ )+ visit("/c/#{events_category.slug}/edit/events")+ expect(page).to have_no_css(".d-nav-submenu__tabs .edit-category-events")+ end+ end++ context "when there is an events category already configured" do+ fab!(:category)++ before do+ DiscourseCalendar::Categories::Types::Events.configure_category(+ category,+ guardian: admin.guardian,+ )+ end++ it "does not preload basic data for the events category type" do+ visit("/new-category/setup")+ category_type_card.find_type_card("events").click++ expect(page).to have_content(I18n.t("js.category.create_with_type", typeName: "events"))+ expect(form.field("name").value).to eq("")+ expect(+ form.field("style_type").find(".form-kit__control-radio[type='radio'][value='emoji']")[+ "checked"+ ],+ ).to eq(nil)+ end++ it "persists category_settings edits (Default calendar view, Display weekends)" do+ visit("/c/#{category.slug}/edit/events")++ form.field("category_type_settings.events_calendar_default_view").select("week")+ form.field("category_type_settings.events_calendar_display_weekends").toggle++ banner.click_save+ expect(toast).to have_success(I18n.t("js.saved"))++ expect(SiteSetting.calendar_categories).to include(+ "categoryId=#{category.id};weekends=false;defaultView=week",+ )+ end++ it "preloads stored category_settings values onto the edit form" do+ DiscourseCalendar::Categories::Types::Events.configure_category(+ category,+ guardian: admin.guardian,+ configuration_values: {+ events_calendar_default_view: "year",+ events_calendar_display_weekends: false,+ },+ )++ visit("/c/#{category.slug}/edit/events")++ expect(form.field("category_type_settings.events_calendar_default_view").value).to eq("year")+ expect(form.field("category_type_settings.events_calendar_display_weekends").value).to eq(+ false,+ )+ end++ it "persists site_settings edits on the Events tab" do+ visit("/c/#{category.slug}/edit/events")++ form.field("category_type_site_settings.sidebar_show_upcoming_events").toggle++ banner.click_save+ expect(toast).to have_success(I18n.t("js.saved"))++ expect(SiteSetting.sidebar_show_upcoming_events).to eq(false)+ end+ end+enddiff --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 4668c3c17b8..752fc3513a3 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@@ -83,7 +83,6 @@ RSpec.describe "Support Category Type Setup" docategory_type_selector.expandcategory_type_selector.option(".category-type-selector__result.--category-type-support").clickbanner.click_save- expect(toast).to have_success(I18n.t("js.saved"))expect(page).to have_css(".nav-pills .edit-category-support")category.reloadexpect(category.category_types.keys).to eq(%i[discussion support])diff --git a/spec/requests/api/schemas/json/category_create_response.json b/spec/requests/api/schemas/json/category_create_response.jsonindex b670563f08f..74b607e9d2c 100644--- a/spec/requests/api/schemas/json/category_create_response.json+++ b/spec/requests/api/schemas/json/category_create_response.json@@ -356,6 +356,9 @@"category_types": {"type": "object"},+ "category_type_settings": {+ "type": "object"+ },"available_category_types": {"type": "array","items": {diff --git a/spec/requests/api/schemas/json/category_update_response.json b/spec/requests/api/schemas/json/category_update_response.jsonindex 792e069f23f..3abc0526861 100644--- a/spec/requests/api/schemas/json/category_update_response.json+++ b/spec/requests/api/schemas/json/category_update_response.json@@ -359,6 +359,9 @@"category_types": {"type": "object"},+ "category_type_settings": {+ "type": "object"+ },"available_category_types": {"type": "array","items": {diff --git a/spec/serializers/category_serializer_spec.rb b/spec/serializers/category_serializer_spec.rbindex f2dc074ed6e..0ab27cd0246 100644--- a/spec/serializers/category_serializer_spec.rb+++ b/spec/serializers/category_serializer_spec.rb@@ -316,4 +316,59 @@ RSpec.describe CategorySerializer do)endend++ describe "#category_type_settings" do+ let(:type_a) do+ Class.new(Categories::Types::Base) do+ type_id :test_type_a++ def self.category_matches?(_category)+ true+ end++ def self.read_category_settings(_category)+ { foo: "from_a" }+ end+ end+ end++ let(:type_b) do+ Class.new(Categories::Types::Base) do+ type_id :test_type_b++ def self.category_matches?(_category)+ true+ end++ def self.read_category_settings(_category)+ { bar: "from_b" }+ end+ end+ end++ let(:non_matching_type) do+ Class.new(Categories::Types::Base) do+ type_id :test_type_off++ def self.category_matches?(_category)+ false+ end++ def self.read_category_settings(_category)+ { baz: "should_not_appear" }+ end+ end+ end++ before do+ SiteSetting.enable_simplified_category_creation = true+ Categories::TypeRegistry.stubs(:all).returns(a: type_a, b: type_b, off: non_matching_type)+ end++ it "merges values from each matching type and skips non-matching types" do+ json = described_class.new(category, scope: admin.guardian, root: false).as_json++ expect(json[:category_type_settings]).to eq(foo: "from_a", bar: "from_b")+ end+ endenddiff --git a/spec/services/categories/types/base_spec.rb b/spec/services/categories/types/base_spec.rbindex 919ba037521..c84a6e85b09 100644--- a/spec/services/categories/types/base_spec.rb+++ b/spec/services/categories/types/base_spec.rb@@ -73,7 +73,7 @@ RSpec.describe Categories::Types::Base docategory,guardian: admin.guardian,configuration_values: {- "title" => "Override",+ title: "Override",},)expect(SiteSetting.title).to eq("Override")