A platform for community discussion. Free, open, simple.
DEV: Add `datetime` type for site settings / object settings (#36849)
Isaac Janzenc53b34eaef1e
diff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex b4804a0bdec..18689a4c4b0 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -156,6 +156,9 @@ en:humanize_not_valid_string_value: "The property at JSON Pointer '%{property_json_pointer}' must be a string."not_valid_string_value: "must be a string"+ humanize_not_valid_datetime_value: "The property at JSON Pointer '%{property_json_pointer}' must be a valid datetime."+ not_valid_datetime_value: "must be a valid datetime"+humanize_not_valid_integer_value: "The property at JSON Pointer '%{property_json_pointer}' must be an integer."not_valid_integer_value: "must be an integer"@@ -2757,6 +2760,7 @@ en:errors:invalid_css_color: "Invalid color. Enter a color name or hex value."+ invalid_datetime: "Invalid datetime format. Please ensure you've entered a valid date and time."invalid_email: "Invalid email address."invalid_username: "There's no user with that username."valid_username: "There's a user with that username."diff --git a/frontend/discourse/admin/components/schema-setting/field.gjs b/frontend/discourse/admin/components/schema-setting/field.gjsindex cd94b54d1c6..5ea980c202a 100644--- a/frontend/discourse/admin/components/schema-setting/field.gjs+++ b/frontend/discourse/admin/components/schema-setting/field.gjs@@ -3,6 +3,7 @@ import { cached } from "@glimmer/tracking";import { htmlSafe } from "@ember/template";import BooleanField from "discourse/admin/components/schema-setting/types/boolean";import CategoriesField from "discourse/admin/components/schema-setting/types/categories";+import DatetimeField from "discourse/admin/components/schema-setting/types/datetime";import EnumField from "discourse/admin/components/schema-setting/types/enum";import FloatField from "discourse/admin/components/schema-setting/types/float";import GroupsField from "discourse/admin/components/schema-setting/types/groups";@@ -34,6 +35,8 @@ export default class SchemaSettingField extends Component {return GroupsField;case "upload":return UploadField;+ case "datetime":+ return DatetimeField;default:throw new Error(`unknown type ${type}`);}diff --git a/frontend/discourse/admin/components/schema-setting/types/datetime.gjs b/frontend/discourse/admin/components/schema-setting/types/datetime.gjsnew file mode 100644index 00000000000..08fc78a456e--- /dev/null+++ b/frontend/discourse/admin/components/schema-setting/types/datetime.gjs@@ -0,0 +1,68 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { Input } from "@ember/component";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import FieldInputDescription from "discourse/admin/components/schema-setting/field-input-description";+import { and, not } from "discourse/truth-helpers";+import { i18n } from "discourse-i18n";++export default class SchemaSettingTypeDatetime extends Component {+ @tracked touched = false;+ @tracked value = this.args.value || "";+ @tracked+ localTime = this.args.value+ ? moment(this.args.value).local().format(moment.HTML5_FMT.DATETIME_LOCAL)+ : "";+ required = this.args.spec.required;++ @action+ onInput(event) {+ this.touched = true;+ const datetime = event.currentTarget.value;+ this.localTime = datetime;++ if (!datetime) {+ this.args.onChange("");+ this.value = "";+ return;+ }++ // Convert to UTC ISO string for storage+ const utcValue = moment(datetime).utc().format();+ this.args.onChange(utcValue);+ this.value = utcValue;+ }++ get validationErrorMessage() {+ if (!this.touched) {+ return;+ }++ if (this.value.length === 0 && this.required) {+ return i18n("admin.customize.schema.fields.required");+ }+ }++ <template>+ <Input+ @type="datetime-local"+ class="--datetime"+ @value={{this.localTime}}+ {{on "input" this.onInput}}+ required={{this.required}}+ />++ <div class="schema-field__input-supporting-text">+ {{#if (and @description (not this.validationErrorMessage))}}+ <FieldInputDescription @description={{@description}} />+ {{/if}}++ {{#if this.validationErrorMessage}}+ <div class="schema-field__input-error">+ {{this.validationErrorMessage}}+ </div>+ {{/if}}+ </div>+ </template>+}diff --git a/frontend/discourse/admin/components/site-setting.gjs b/frontend/discourse/admin/components/site-setting.gjsindex 40d3c098916..949accd5ec4 100644--- a/frontend/discourse/admin/components/site-setting.gjs+++ b/frontend/discourse/admin/components/site-setting.gjs@@ -27,6 +27,7 @@ import { i18n } from "discourse-i18n";const CUSTOM_TYPES = ["bool",+ "datetime","integer","enum","list",diff --git a/frontend/discourse/admin/components/site-settings/datetime.gjs b/frontend/discourse/admin/components/site-settings/datetime.gjsnew file mode 100644index 00000000000..df9c3dbd667--- /dev/null+++ b/frontend/discourse/admin/components/site-settings/datetime.gjs@@ -0,0 +1,57 @@+import Component from "@glimmer/component";+import { Input } from "@ember/component";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import DButton from "discourse/components/d-button";++export default class Datetime extends Component {+ @action+ convertToUniversalTime(event) {+ const datetime = event.target.value;+ if (!datetime) {+ this.args.changeValueCallback("");+ return;+ }++ // Convert local datetime-local to UTC ISO string+ const utcValue = moment(datetime).utc().format();+ this.args.changeValueCallback(utcValue);+ }++ @action+ reset() {+ this.args.changeValueCallback("");+ }++ get localTime() {+ if (!this.args.value) {+ return "";+ }++ // Convert UTC ISO string to local datetime-local format+ return moment(this.args.value)+ .local()+ .format(moment.HTML5_FMT.DATETIME_LOCAL);+ }++ <template>+ <div class="date-time-setting">+ <Input+ @type="datetime-local"+ @value={{this.localTime}}+ @disabled={{@disabled}}+ class="input-setting-date"+ {{on "input" this.convertToUniversalTime}}+ />++ {{#if @value}}+ <DButton+ @icon="trash-can"+ @action={{this.reset}}+ @disabled={{@disabled}}+ class="btn-small"+ />+ {{/if}}+ </div>+ </template>+}diff --git a/lib/schema_settings_object_validator.rb b/lib/schema_settings_object_validator.rbindex 4501c7bda42..bdf16573ced 100644--- a/lib/schema_settings_object_validator.rb+++ b/lib/schema_settings_object_validator.rb@@ -132,7 +132,7 @@ class SchemaSettingsObjectValidatoris_value_valid =case type- when "string"+ when "string", "datetime"value.is_a?(String)when "integer", "topic", "post"value.is_a?(Integer)@@ -200,6 +200,21 @@ class SchemaSettingsObjectValidatoradd_error(property_name, :"#{type}_value_not_valid_max", count: max)return falseend+ when "datetime"+ return true if value.blank?+ begin+ # DateTime.iso8601 checks the format but does not enforce timezone presence+ # so we need to do an additional check for the presence of timezone info.+ DateTime.iso8601(value)+ if value.include?("T") && (value.end_with?("Z") || value.match?(/[+-]\d{2}:\d{2}$/))+ return true+ end+ add_error(property_name, :not_valid_datetime_value)+ return false+ rescue ArgumentError, TypeError+ add_error(property_name, :not_valid_datetime_value)+ return false+ endwhen "string"if (min = validations&.dig(:min_length)) && value.length < minadd_error(property_name, :string_value_not_valid_min, count: min)diff --git a/lib/site_settings/type_supervisor.rb b/lib/site_settings/type_supervisor.rbindex 838a622d87c..7d4ad239e44 100644--- a/lib/site_settings/type_supervisor.rb+++ b/lib/site_settings/type_supervisor.rb@@ -64,6 +64,7 @@ class SiteSettings::TypeSupervisorobjects: 28,locale_enum: 29,topic: 30,+ datetime: 31,)end@@ -170,7 +171,7 @@ class SiteSettings::TypeSupervisornilwhen self.class.types[:enum]@defaults_provider[name].is_a?(Integer) ? value.to_i : value.to_s- when self.class.types[:string]+ when self.class.types[:string], self.class.types[:datetime]value.to_selsereturn value if self.class.types[type]@@ -355,6 +356,8 @@ class SiteSettings::TypeSupervisorHostListSettingValidatorwhen self.class.types[:topic]TopicSettingValidator+ when self.class.types[:datetime]+ DatetimeSettingValidatorelsenilenddiff --git a/lib/validators/datetime_setting_validator.rb b/lib/validators/datetime_setting_validator.rbnew file mode 100644index 00000000000..b1a2817292a--- /dev/null+++ b/lib/validators/datetime_setting_validator.rb@@ -0,0 +1,21 @@+# frozen_string_literal: true++class DatetimeSettingValidator+ def initialize(opts = {})+ @opts = opts+ end++ def valid_value?(val)+ return true if val.blank?+ # DateTime.iso8601 checks the format but does not enforce timezone presence+ # so we need to do an additional check for the presence of timezone info.+ DateTime.iso8601(val)+ val.include?("T") && (val.end_with?("Z") || val.match?(/[+-]\d{2}:\d{2}$/))+ rescue ArgumentError, TypeError+ false+ end++ def error_message+ I18n.t("site_settings.errors.invalid_datetime")+ end+enddiff --git a/spec/lib/schema_settings_object_validator_spec.rb b/spec/lib/schema_settings_object_validator_spec.rbindex acbd8d62333..8c65b2fc111 100644--- a/spec/lib/schema_settings_object_validator_spec.rb+++ b/spec/lib/schema_settings_object_validator_spec.rb@@ -1300,5 +1300,115 @@ RSpec.describe SchemaSettingsObjectValidator doexpect(queries.length).to eq(1)endend++ context "for datetime properties" do+ let(:schema) { { name: "section", properties: { datetime_property: { type: "datetime" } } } }++ it "should not return any error messages when the value of the property is a valid UTC datetime" do+ expect(+ described_class.new(+ schema: schema,+ object: {+ datetime_property: "2024-12-29T15:30:00Z",+ },+ ).validate,+ ).to eq({})++ expect(+ described_class.new(+ schema: schema,+ object: {+ datetime_property: "2024-12-29T15:30:00.000Z",+ },+ ).validate,+ ).to eq({})+ end++ it "should not return any error messages when the value is an ISO 8601 datetime with timezone offset" do+ expect(+ described_class.new(+ schema: schema,+ object: {+ datetime_property: "2024-12-29T15:30:00+05:30",+ },+ ).validate,+ ).to eq({})+ end++ it "should not return any error messages when the value is not present and it's not required in the schema" do+ expect(described_class.new(schema: schema, object: {}).validate).to eq({})+ end++ it "should not return any error messages when the value is an empty string and it's not required" do+ expect(+ described_class.new(schema: schema, object: { datetime_property: "" }).validate,+ ).to eq({})+ end++ it "should return the right hash of error messages when value of property is not present and it's required" do+ schema = {+ name: "section",+ properties: {+ datetime_property: {+ type: "datetime",+ required: true,+ },+ },+ }+ errors = described_class.new(schema: schema, object: {}).validate++ expect(errors.keys).to eq(["/datetime_property"])+ expect(errors["/datetime_property"].full_messages).to contain_exactly("must be present")+ end++ it "should return the right hash of error messages when value of property is not a valid datetime" do+ errors =+ described_class.new(+ schema: schema,+ object: {+ datetime_property: "not a datetime",+ },+ ).validate++ expect(errors.keys).to eq(["/datetime_property"])+ expect(errors["/datetime_property"].full_messages).to contain_exactly(+ "must be a valid datetime",+ )+ end++ it "should return the right hash of error messages when value is a date-only string" do+ errors =+ described_class.new(schema: schema, object: { datetime_property: "2024-12-29" }).validate++ expect(errors.keys).to eq(["/datetime_property"])+ expect(errors["/datetime_property"].full_messages).to contain_exactly(+ "must be a valid datetime",+ )+ end++ it "should return the right hash of error messages when value is datetime without timezone" do+ errors =+ described_class.new(+ schema: schema,+ object: {+ datetime_property: "2024-12-29T15:30:00",+ },+ ).validate++ expect(errors.keys).to eq(["/datetime_property"])+ expect(errors["/datetime_property"].full_messages).to contain_exactly(+ "must be a valid datetime",+ )+ end++ it "should return the right hash of error messages when value of property is not a string" do+ errors = described_class.new(schema: schema, object: { datetime_property: 123 }).validate++ expect(errors.keys).to eq(["/datetime_property"])+ expect(errors["/datetime_property"].full_messages).to contain_exactly(+ "must be a valid datetime",+ )+ end+ endendenddiff --git a/spec/lib/site_setting_extension_spec.rb b/spec/lib/site_setting_extension_spec.rbindex e34c052f30b..37ee134d7ff 100644--- a/spec/lib/site_setting_extension_spec.rb+++ b/spec/lib/site_setting_extension_spec.rb@@ -558,6 +558,58 @@ RSpec.describe SiteSettingExtension doendend+ describe "datetime setting" do+ before do+ settings.setting(:datetime_setting, "2024-01-01T00:00:00Z", type: "datetime")+ settings.refresh!+ end++ after :each do+ settings.remove_override!(:datetime_setting)+ end++ it "stores valid datetime values" do+ settings.datetime_setting = "2024-12-29T15:30:00Z"+ expect(settings.datetime_setting).to eq("2024-12-29T15:30:00Z")+ end++ it "stores valid datetime values with timezone offset" do+ settings.datetime_setting = "2024-12-29T15:30:00+05:30"+ expect(settings.datetime_setting).to eq("2024-12-29T15:30:00+05:30")+ end++ it "stores valid datetime values with milliseconds" do+ settings.datetime_setting = "2024-12-29T15:30:00.123Z"+ expect(settings.datetime_setting).to eq("2024-12-29T15:30:00.123Z")+ end++ it "rejects date-only strings" do+ expect { settings.datetime_setting = "2024-12-29" }.to raise_error(+ Discourse::InvalidParameters,+ )+ end++ it "rejects datetime without timezone" do+ expect { settings.datetime_setting = "2024-12-29T15:30:00" }.to raise_error(+ Discourse::InvalidParameters,+ )+ end++ it "rejects invalid datetime strings" do+ expect { settings.datetime_setting = "not a datetime" }.to raise_error(+ Discourse::InvalidParameters,+ )+ expect { settings.datetime_setting = "2024-13-01T15:30:00Z" }.to raise_error(+ Discourse::InvalidParameters,+ )+ end++ it "allows blank values" do+ settings.datetime_setting = ""+ expect(settings.datetime_setting).to eq("")+ end+ end+describe "set for an invalid setting name" doit "raises an error" dosettings.setting(:test_setting, 77)diff --git a/spec/lib/site_settings/type_supervisor_spec.rb b/spec/lib/site_settings/type_supervisor_spec.rbindex d6b2c9717e7..0162301ca6a 100644--- a/spec/lib/site_settings/type_supervisor_spec.rb+++ b/spec/lib/site_settings/type_supervisor_spec.rb@@ -99,6 +99,9 @@ RSpec.describe SiteSettings::TypeSupervisor doit "'file_size_restriction' should be at the right position" doexpect(SiteSettings::TypeSupervisor.types[:file_size_restriction]).to eq(27)end+ it "'datetime' should be at the right position" do+ expect(SiteSettings::TypeSupervisor.types[:datetime]).to eq(31)+ endendenddiff --git a/spec/lib/validators/datetime_setting_validator_spec.rb b/spec/lib/validators/datetime_setting_validator_spec.rbnew file mode 100644index 00000000000..b91af0e0ee7--- /dev/null+++ b/spec/lib/validators/datetime_setting_validator_spec.rb@@ -0,0 +1,24 @@+# frozen_string_literal: true++RSpec.describe DatetimeSettingValidator do+ describe "#valid_value?" do+ subject(:validator) { described_class.new }++ it "returns true for blank values" do+ expect(validator.valid_value?("")).to eq(true)+ expect(validator.valid_value?(nil)).to eq(true)+ end++ it "returns true for valid ISO 8601 datetime with Z suffix" do+ expect(validator.valid_value?("2024-12-29T15:30:00Z")).to eq(true)+ end++ it "returns true for valid ISO 8601 datetime with timezone offset" do+ expect(validator.valid_value?("2024-12-29T15:30:00+05:30")).to eq(true)+ end++ it "returns false for invalid datetime strings" do+ expect(validator.valid_value?("not a datetime")).to eq(false)+ end+ end+end