A platform for community discussion. Free, open, simple.
FEATURE: Event reminder preferences and calendar prompt (#43621)
Martin Brennan7d2f730d36a4
diff --git a/app/assets/stylesheets/color_definitions.scss b/app/assets/stylesheets/color_definitions.scssindex 9d8519f2984..dd2e86640ff 100644--- a/app/assets/stylesheets/color_definitions.scss+++ b/app/assets/stylesheets/color_definitions.scss@@ -78,6 +78,7 @@--danger-low-mid: #{$danger-low-mid};--danger-medium: #{$danger-medium};--danger-hover: #{$danger-hover};+ --success-very-low: #{$success-very-low};--success-low: #{$success-low};--success-medium: #{$success-medium};--success-hover: #{$success-hover};diff --git a/app/assets/stylesheets/common/foundation/color_transformations.scss b/app/assets/stylesheets/common/foundation/color_transformations.scssindex 2f02891fea9..7acd232db37 100644--- a/app/assets/stylesheets/common/foundation/color_transformations.scss+++ b/app/assets/stylesheets/common/foundation/color_transformations.scss@@ -94,6 +94,7 @@ $danger-medium: dark-light-diff($danger, $secondary, 30%, -35%) !default;$danger-hover: dark-light-diff($danger, $secondary, -20%, -20%) !default;// success+$success-very-low: dark-light-diff($success, $secondary, 90%, -70%) !default;$success-low: dark-light-diff($success, $secondary, 80%, -60%) !default;$success-medium: dark-light-diff($success, $secondary, 50%, -40%) !default;$success-hover: dark-light-diff($success, $secondary, -20%, -20%) !default;diff --git a/app/controllers/calendar_subscriptions_controller.rb b/app/controllers/calendar_subscriptions_controller.rbindex d0c7d1e7258..5569456bf6a 100644--- a/app/controllers/calendar_subscriptions_controller.rb+++ b/app/controllers/calendar_subscriptions_controller.rb@@ -8,7 +8,15 @@ class CalendarSubscriptionsController < ApplicationControllerbefore_action :rate_limit_create, only: :createdef show- render json: { has_subscription: find_calendar_api_key.present?, feeds: feed_names }+ key = find_calendar_api_key+ scopes = key ? key.scopes.map(&:name) : []+ generated_feeds =+ plugin_feeds.select { |feed| scopes.include?(feed[:scope].to_s) }.map { |feed| feed[:name] }+ render json: {+ has_subscription: key.present?,+ feeds: feed_names,+ generated_feeds: generated_feeds,+ }enddef creatediff --git a/app/models/user_option.rb b/app/models/user_option.rbindex 567efbf2bab..e7b20fbd124 100644--- a/app/models/user_option.rb+++ b/app/models/user_option.rb@@ -328,6 +328,7 @@ end# enable_quoting :boolean default(TRUE), not null# enable_smart_lists :boolean default(TRUE), not null# enable_upcoming_change_available_notifications :boolean default(TRUE), not null+# event_reminder_preference :integer default("personal_message"), not null# external_links_in_new_tab :boolean default(FALSE), not null# hide_presence :boolean default(FALSE), not null# hide_profile :boolean default(FALSE), not nulldiff --git a/db/structure.sql b/db/structure.sqlindex 685e3e5ad1f..8167387f770 100644--- a/db/structure.sql+++ b/db/structure.sql@@ -12732,7 +12732,8 @@ CREATE TABLE public.user_options (chat_channel_list_sort_starred integer DEFAULT 0 NOT NULL,chat_channel_list_sort_dms integer DEFAULT 2 NOT NULL,chat_channel_list_filter_starred integer DEFAULT 0 NOT NULL,- chat_channel_list_filter_dms integer DEFAULT 0 NOT NULL+ chat_channel_list_filter_dms integer DEFAULT 0 NOT NULL,+ event_reminder_preference integer DEFAULT 0 NOT NULL);@@ -25388,6 +25389,7 @@ INSERT INTO "schema_migrations" (version) VALUES('20260914172801'),('20260914172757'),('20260914140746'),+('20260914032737'),('20260910110851'),('20260910033302'),('20260910030427'),diff --git a/frontend/discourse/app/templates/preferences/calendar-subscriptions.gjs b/frontend/discourse/app/templates/preferences/calendar-subscriptions.gjsindex d4a94c51837..e493d04569f 100644--- a/frontend/discourse/app/templates/preferences/calendar-subscriptions.gjs+++ b/frontend/discourse/app/templates/preferences/calendar-subscriptions.gjs@@ -76,6 +76,10 @@ export default class CalendarSubscriptions extends Component {}<template>+ <PluginOutlet+ @name="calendar-preferences"+ @outletArgs={{lazyHash [email protected]}}+ /><div class="calendar-subscriptions"><p class="calendar-subscriptions__description">{{i18n "user.calendar_subscriptions.description"}}diff --git a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/calendar-prompt.gjs b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/calendar-prompt.gjsnew file mode 100644index 00000000000..2ad3e6b878c--- /dev/null+++ b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/calendar-prompt.gjs@@ -0,0 +1,93 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { action } from "@ember/object";+import { service } from "@ember/service";+import { trustHTML } from "@ember/template";+import { escapeExpression } from "discourse/lib/utilities";+import DButton from "discourse/ui-kit/d-button";+import dIcon from "discourse/ui-kit/helpers/d-icon";+import { i18n } from "discourse-i18n";+import addEventToCalendar from "../../lib/add-event-to-calendar";++export default class CalendarPrompt extends Component {+ @service currentUser;+ @service router;+ @service siteSettings;++ @tracked dismissed = false;++ get subscribedMessage() {+ const calendarUrl = this.router.urlFor(+ "preferences.calendar-subscriptions",+ this.currentUser.username+ );++ return trustHTML(+ i18n("discourse_events.calendar_prompt.subscribed", {+ calendarUrl: escapeExpression(calendarUrl),+ })+ );+ }++ get subscriptionLabel() {+ return this.siteSettings.enable_improved_event_reminders+ ? "discourse_events.calendar_prompt.subscribe_with_preferences"+ : "discourse_events.calendar_prompt.subscribe";+ }++ @action+ dismiss() {+ this.dismissed = true;+ }++ @action+ add() {+ addEventToCalendar(this.args.event);+ this.dismiss();+ }++ @action+ preferences() {+ this.router.transitionTo(+ "preferences.calendar-subscriptions",+ this.currentUser.username+ );+ }++ <template>+ {{#unless this.dismissed}}+ <section class="event-calendar-prompt">+ <div class="event-calendar-prompt__heading">+ {{dIcon "far-calendar-plus" class="event-calendar-prompt__icon"}}+ <p role="status">+ {{#if @hasSubscription}}+ {{this.subscribedMessage}}+ {{else}}+ {{i18n "discourse_events.calendar_prompt.title"}}+ {{/if}}+ </p>+ <DButton+ class="btn-transparent event-calendar-prompt__dismiss"+ @action={{this.dismiss}}+ @ariaLabel="discourse_events.calendar_prompt.dismiss"+ @icon="xmark"+ />+ </div>+ {{#unless @hasSubscription}}+ <div class="event-calendar-prompt__actions">+ <DButton+ class="btn-primary"+ @action={{this.add}}+ @label="discourse_post_event.add_to_calendar"+ />+ <DButton+ class="btn-link event-calendar-prompt__settings"+ @action={{this.preferences}}+ @label={{this.subscriptionLabel}}+ />+ </div>+ {{/unless}}+ </section>+ {{/unless}}+ </template>+}diff --git a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/more-menu.gjs b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/more-menu.gjsindex 47849240fdc..4bf7e71ac7e 100644--- a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/more-menu.gjs+++ b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/more-menu.gjs@@ -5,7 +5,6 @@ import EmberObject, { action } from "@ember/object";import { service } from "@ember/service";import DMenu from "discourse/float-kit/components/d-menu";import { popupAjaxError } from "discourse/lib/ajax-error";-import { downloadCalendar } from "discourse/lib/download-calendar";import { exportEntity } from "discourse/lib/export-csv";import { cook } from "discourse/lib/text";import { applyValueTransformer } from "discourse/lib/transformer";@@ -13,6 +12,7 @@ import DButton from "discourse/ui-kit/d-button";import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";import { i18n } from "discourse-i18n";+import addEventToCalendar from "../../lib/add-event-to-calendar";import {buildParams,removeEvent,@@ -76,24 +76,7 @@ export default class DiscoursePostEventMoreMenu extends Component {addToCalendar() {this.menuApi.close();- const event = this.args.event;-- downloadCalendar(- event.name || event.post.topic.title,- [- {- startsAt: event.startsAt,- endsAt: event.endsAt,- timezone: event.timezone,- allDay: event.allDay,- },- ],- {- rrule: event.rrule,- location: event.location,- details: event.description,- }- );+ addEventToCalendar(this.args.event);}@actiondiff --git a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/status.gjs b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/status.gjsindex 4b3380ebbb6..16db6dfc812 100644--- a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/status.gjs+++ b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/status.gjs@@ -1,10 +1,12 @@import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";import { concat, fn } from "@ember/helper";import { action } from "@ember/object";import { service } from "@ember/service";import PluginOutlet from "discourse/components/plugin-outlet";import DMenu from "discourse/float-kit/components/d-menu";import lazyHash from "discourse/helpers/lazy-hash";+import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";import { deferAnonymousAction } from "discourse/lib/anonymous-action";import DButton from "discourse/ui-kit/d-button";@@ -12,6 +14,7 @@ import DComboButton from "discourse/ui-kit/d-combo-button";import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";import { i18n } from "discourse-i18n";+import CalendarPrompt from "./calendar-prompt";const statusButtonClass = (selected) =>selected ? "btn-primary" : "btn-default";@@ -65,6 +68,8 @@ export default class DiscoursePostEventStatus extends Component {@service site;@service siteSettings;+ @tracked calendarPrompt = null;+goingMenu = null;get eventButtons() {@@ -136,6 +141,7 @@ export default class DiscoursePostEventStatus extends Component {async leaveEvent() {try {const invitee = this.args.event.watchingInvitee;+ this.calendarPrompt = null;await this.discoursePostEventApi.leaveEvent(this.args.event, invitee);@@ -151,13 +157,13 @@ export default class DiscoursePostEventStatus extends Component {@actionasync goingThisEvent() {this.goingMenu?.close();- await this._setAttendance({ status: "going", recurring: false });+ await this.#setAttendance({ status: "going", recurring: false });}@actionasync goingAllFollowing() {this.goingMenu?.close();- await this._setAttendance({ status: "going", recurring: true });+ await this.#setAttendance({ status: "going", recurring: true });}@action@@ -171,21 +177,38 @@ export default class DiscoursePostEventStatus extends Component {const watching = this.args.event.watchingInvitee;if (!watching) {- await this._setAttendance({ status });+ await this.#setAttendance({ status });return;}if (status === watching.status) {await (this.canLeave? this.leaveEvent()- : this._setAttendance({ status: null }));+ : this.#setAttendance({ status: null }));return;}- await this._setAttendance({ status });+ await this.#setAttendance({ status });+ }++ #changingToPositiveRSVP(previousStatus) {+ return (+ ["going", "interested"].includes(+ this.args.event.watchingInvitee?.status+ ) && !["going", "interested"].includes(previousStatus)+ );+ }++ async #hasCalendarSubscription() {+ const result = await ajax("/calendar-subscriptions.json");+ return (+ result.generated_feeds?.includes("my_events") ||+ result.generated_feeds?.includes("all_events") ||+ false+ );}- async _setAttendance(payload) {+ async #setAttendance(payload) {if (!this.currentUser) {if (!payload.status) {return;@@ -197,9 +220,12 @@ export default class DiscoursePostEventStatus extends Component {});}+ const event = this.args.event;+ const previousStatus = event.watchingInvitee?.status;+ let rsvpSuccess = false;try {- const event = this.args.event;const data = { status: payload.status, postId: event.id };+ this.calendarPrompt = null;if (event.watchingInvitee) {await this.discoursePostEventApi.updateEventAttendance(event, payload);@@ -208,8 +234,26 @@ export default class DiscoursePostEventStatus extends Component {await this.discoursePostEventApi.joinEvent(event, payload);this.appEvents.trigger("calendar:create-invitee-status", data);}- } catch (e) {- popupAjaxError(e);++ rsvpSuccess = true;+ } catch (err) {+ popupAjaxError(err);+ }++ if (rsvpSuccess) {+ if (this.#changingToPositiveRSVP(previousStatus)) {+ try {+ const hasSubscription = await this.#hasCalendarSubscription();+ if (+ !this.isDestroying &&+ this.args.event.watchingInvitee?.status === payload.status+ ) {+ this.calendarPrompt = { hasSubscription };+ }+ } catch {+ // Don't worry about showing the prompt if the subscription check fails, it's nonessential.+ }+ }}}@@ -349,5 +393,11 @@ export default class DiscoursePostEventStatus extends Component {{{/if}}</PluginOutlet></section>+ {{#if this.calendarPrompt}}+ <CalendarPrompt+ @event={{@event}}+ @hasSubscription={{this.calendarPrompt.hasSubscription}}+ />+ {{/if}}</template>}diff --git a/plugins/discourse-events/assets/javascripts/discourse/connectors/calendar-preferences/discourse-events-preferences.gjs b/plugins/discourse-events/assets/javascripts/discourse/connectors/calendar-preferences/discourse-events-preferences.gjsnew file mode 100644index 00000000000..d82e09ed525--- /dev/null+++ b/plugins/discourse-events/assets/javascripts/discourse/connectors/calendar-preferences/discourse-events-preferences.gjs@@ -0,0 +1,67 @@+import Component from "@glimmer/component";+import { concat } from "@ember/helper";+import { action } from "@ember/object";+import { service } from "@ember/service";+import Form from "discourse/components/form";+import { i18n } from "discourse-i18n";++export default class DiscourseEventsPreferences extends Component {+ @service siteSettings;++ @service toasts;++ preferences = ["none", "notification", "personal_message"];++ get data() {+ return {+ event_reminder_preference:+ this.args.outletArgs.model.user_option.event_reminder_preference,+ };+ }++ @action+ async save(data) {+ const user = this.args.outletArgs.model;+ user.set(+ "user_option.event_reminder_preference",+ data.event_reminder_preference+ );+ await user.save(["event_reminder_preference"]);+ this.toasts.success({ data: { message: i18n("saved") } });+ }++ <template>+ {{#if+ (and+ this.siteSettings.discourse_post_event_enabled+ this.siteSettings.enable_improved_event_reminders+ )+ }}+ <section class="event-reminder-preferences">+ <h3>{{i18n "discourse_events.preferences.reminders.title"}}</h3>+ <p>{{i18n "discourse_events.preferences.reminders.description"}}</p>+ <Form @data={{this.data}} @onSubmit={{this.save}} as |form|>+ <form.Field+ @format="large"+ @name="event_reminder_preference"+ @title={{i18n "discourse_events.preferences.reminders.preference"}}+ @type="select"+ as |field|+ >+ <field.Control @includeNone={{false}} as |select|>+ {{#each this.preferences as |preference|}}+ <select.Option @value={{preference}}>{{i18n+ (concat+ "discourse_events.preferences.reminders.preferences."+ preference+ )+ }}</select.Option>+ {{/each}}+ </field.Control>+ </form.Field>+ <form.Submit @label="submit" />+ </Form>+ </section>+ {{/if}}+ </template>+}diff --git a/plugins/discourse-events/assets/javascripts/discourse/initializers/event-user-options.js b/plugins/discourse-events/assets/javascripts/discourse/initializers/event-user-options.jsnew file mode 100644index 00000000000..6c555da0eae--- /dev/null+++ b/plugins/discourse-events/assets/javascripts/discourse/initializers/event-user-options.js@@ -0,0 +1,11 @@+import { withPluginApi } from "discourse/lib/plugin-api";++export default {+ name: "event-user-options",++ initialize() {+ withPluginApi((api) => {+ api.addSaveableUserOption("event_reminder_preference");+ });+ },+};diff --git a/plugins/discourse-events/assets/javascripts/discourse/lib/add-event-to-calendar.js b/plugins/discourse-events/assets/javascripts/discourse/lib/add-event-to-calendar.jsnew file mode 100644index 00000000000..798daa41f2c--- /dev/null+++ b/plugins/discourse-events/assets/javascripts/discourse/lib/add-event-to-calendar.js@@ -0,0 +1,24 @@+import { downloadCalendar } from "discourse/lib/download-calendar";++export default function addEventToCalendar(event) {+ downloadCalendar(+ event.name || event.post.topic.title,+ [+ {+ startsAt: event.startsAt,+ endsAt: event.endsAt,+ timezone: event.timezone,+ allDay: event.allDay,+ },+ ],+ {+ rrule:+ event.watchingInvitee?.status === "going" &&+ !event.watchingInvitee.recurring+ ? null+ : event.rrule,+ location: event.location,+ details: event.description,+ }+ );+}diff --git a/plugins/discourse-events/assets/stylesheets/common/event-calendar-prompt.scss b/plugins/discourse-events/assets/stylesheets/common/event-calendar-prompt.scssnew file mode 100644index 00000000000..9e1adbaf4ed--- /dev/null+++ b/plugins/discourse-events/assets/stylesheets/common/event-calendar-prompt.scss@@ -0,0 +1,44 @@+@use "sass:color";++.event-calendar-prompt {+ border-top: 1px solid var(--primary-low);+ padding: 1em;+ background: var(--success-very-low);++ &__heading {+ display: grid;+ grid-template-columns: 1em minmax(0, 1fr) auto;+ align-items: center;+ gap: 0.75em;+ }++ &__heading p {+ margin: 0;+ }++ &__icon {+ color: var(--success);+ }++ &__dismiss {+ padding: 0.25em;+ color: var(--primary-high);+ }++ &__actions {+ display: flex;+ align-items: center;+ flex-wrap: wrap;+ gap: 0.75em 1em;+ margin-top: 0.75em;+ }++ &__settings {+ text-decoration: underline;+ text-underline-offset: 0.15em;+ }+}++.event-reminder-preferences {+ margin-bottom: 2em;+}diff --git a/plugins/discourse-events/config/locales/client.en.yml b/plugins/discourse-events/config/locales/client.en.ymlindex 3786081c4df..e11f85a38da 100644--- a/plugins/discourse-events/config/locales/client.en.yml+++ b/plugins/discourse-events/config/locales/client.en.yml@@ -39,11 +39,25 @@ en:rsvp_to_event: "RSVP to the event to start chatting"rsvp_to_event_with_link: "RSVP to <a href='%{url}'>the event</a> to start chatting"rsvp_body: "Connect with other attendees before, during, and after the event."+ calendar_prompt:+ title: "Add this event to your calendar?"+ subscribed: 'This event will be added to your <a href="%{calendarUrl}">subscribed calendar</a>.'+ dismiss: "Dismiss calendar prompt"+ subscribe: "Subscribe to your events"+ subscribe_with_preferences: "Subscribe to events or change notification preferences"preferences:+ reminders:+ title: "Event reminders"+ description: "For events you're Going to or Interested in. The organizer chooses when reminders are sent."+ preference: "Send event reminders via"+ preferences:+ personal_message: "Send a personal message"+ notification: "Notification"+ none: "None"all_events: "Discourse Events - All events"all_events_description: "All forum events"my_events: "Discourse Events - My events"- my_events_description: "Events you are going to or interested in"+ my_events_description: "Events you are Going to or Interested in"on_holiday: "On Holiday"disable_holiday: "Disable"enable_holiday: "Enable"diff --git a/plugins/discourse-events/config/locales/server.en.yml b/plugins/discourse-events/config/locales/server.en.ymlindex b56a5e51a41..9dcdb717133 100644--- a/plugins/discourse-events/config/locales/server.en.yml+++ b/plugins/discourse-events/config/locales/server.en.yml@@ -38,6 +38,25 @@ en:```text%{logs}```+ discourse_post_event_reminder:+ title: "Event reminder"+ subject_template: ":date: %{subject}"+ text_body_template: |+ **%{date_range} (%{timezone})**++ %{description}++ %{location_section}++ #### Guests++ %{guests}++ %{additional_guests}++ %{join_event}++ [Go to event topic](%{event_url})site_settings:map_events_to_color: "Assign a color to each tag or category."@@ -73,6 +92,7 @@ en:sidebar_show_upcoming_events: "Show upcoming events link in the sidebar under 'More'."calendar_first_day_of_week: "Set the first day of the week for calendar display. Options are Saturday, Sunday, or Monday."enable_events_category_type_setup: "Enables the Events category type option during category creation setup."+ enable_improved_event_reminders: "Lets members choose whether event reminders are sent as personal messages, notifications, or not at all."livestream_allowed_hosts: "Hosts that can be used as an event livestream."livestream_allowed_hosts_invalid: "These entries are not hosts: %{hosts}. Enter the host on its own (for example zoom.us), which allows every URL on it and its subdomains."livestream_zoom_enabled: "Enable Zoom video embedding for livestream topics."@@ -82,6 +102,24 @@ en:livestream_enable_modal_chat_on_mobile: "Show livestream chat in a modal on mobile."discourse_events:+ reminder:+ subjects:+ before: "%{title} is about to start"+ ongoing: "%{title} is ongoing"+ after: "%{title} has ended"+ location: |-+ #### Location++ %{location}+ guest: "- %{name}"+ guest_with_role: "- %{name} (*%{role}*)"+ roles:+ organizer: "Organizer"+ host: "Host"+ additional_guests:+ one: " and %{count} other"+ other: " and %{count} others"+ join_event: "[Join event](%{url})"category_type:default_calendar_view:label: "Default calendar view"diff --git a/plugins/discourse-events/config/settings.yml b/plugins/discourse-events/config/settings.ymlindex 2827f907297..7222e780c15 100644--- a/plugins/discourse-events/config/settings.yml+++ b/plugins/discourse-events/config/settings.yml@@ -142,6 +142,14 @@ discourse_events:impact: "feature,staff"learn_more_url: "https://meta.discourse.org/t/-/401309"requires_plugin_enabled: false+ enable_improved_event_reminders:+ default: false+ hidden: true+ client: true+ upcoming_change:+ status: "experimental"+ impact: "feature,all_members"+ learn_more_url: "https://meta.discourse.org/t/-/412427"livestream_allowed_hosts:type: host_listdefault: "youtube.com|youtu.be|twitch.tv|zoom.us|kick.com|tiktok.com|instagram.com|facebook.com"diff --git a/plugins/discourse-events/db/migrate/20260914032737_add_event_reminder_preference_to_user_options.rb b/plugins/discourse-events/db/migrate/20260914032737_add_event_reminder_preference_to_user_options.rbnew file mode 100644index 00000000000..b14a09f1a5c--- /dev/null+++ b/plugins/discourse-events/db/migrate/20260914032737_add_event_reminder_preference_to_user_options.rb@@ -0,0 +1,7 @@+# frozen_string_literal: true++class AddEventReminderPreferenceToUserOptions < ActiveRecord::Migration[8.0]+ def change+ add_column :user_options, :event_reminder_preference, :integer, default: 0, null: false+ end+enddiff --git a/plugins/discourse-events/jobs/regular/discourse_post_event/send_reminder.rb b/plugins/discourse-events/jobs/regular/discourse_post_event/send_reminder.rbindex 25eaa39c9d9..74c643fedf7 100644--- a/plugins/discourse-events/jobs/regular/discourse_post_event/send_reminder.rb+++ b/plugins/discourse-events/jobs/regular/discourse_post_event/send_reminder.rb@@ -4,24 +4,46 @@ module Jobsclass DiscoursePostEventSendReminder < ::Jobs::Basesidekiq_options retry: false+ MAX_GUESTS = 5+def execute(args)- raise Discourse::InvalidParameters.new(:event_id) if args[:event_id].blank?- raise Discourse::InvalidParameters.new(:reminder) if args[:reminder].blank?+ return unless SiteSetting.discourse_post_event_enabled+ return if args[:event_id].blank? || args[:reminder].blank?event =- DiscourseEvents::Events::Event.includes(post: [:topic], invitees: [:user]).find(- args[:event_id],- )+ DiscourseEvents::Events::Event.includes(+ { post: %i[topic user] },+ { event_hosts: :user },+ { invitees: :user },+ ).find(args[:event_id])++ return if event.post.blank?+ return if event.closed || event.deleted_at- return unless event.post+ event_date =+ if args[:event_date_id]+ event.event_dates.find_by(id: args[:event_date_id])+ else+ event.current_event_date+ end++ return if event_date.blank? || event.starts_at.nil?+ return if args[:event_date_id] && event_date.starts_at != event.starts_atinvitees =- event.invitees.where(- status: [- DiscourseEvents::Events::Invitee.statuses[:going],- DiscourseEvents::Events::Invitee.statuses[:interested],- ],- )+ event+ .invitees+ .where(status: DiscourseEvents::Events::Invitee.statuses.values_at(:going, :interested))+ .includes(user: :user_option)++ prefix = reminder_prefix(event)++ invitees.find_each do |invitee|+ next unless reminder_preference(invitee.user) == "personal_message"+ next unless eligible_recipient?(invitee.user, event)++ send_personal_message(invitee.user, event, event_date, prefix)+ endalready_notified_users =Notification.where(@@ -31,23 +53,7 @@ module Jobspost_number: 1,)- return if event.starts_at.nil?-- # Convert both times to UTC for proper comparison- current_time = Time.current- event_start_time =- (- if event.starts_at.is_a?(ActiveSupport::TimeWithZone)- event.starts_at- else- event.starts_at.in_time_zone(event.timezone || "UTC")- end- )-- event_started = current_time > event_start_time-- # we remove users who have been visiting the topic since event started- if event_started+ if event_started?(event)invitees =invitees.where.not(user_id:@@ -55,7 +61,7 @@ module Jobs.where("topic_users.topic_id = ? AND topic_users.last_visited_at >= ? AND topic_users.last_read_post_number >= ?",event.post.topic_id,- event_start_time,+ event_start_time(event),1,).pluck(:user_id)@@ -65,29 +71,16 @@ module Jobsinvitees = invitees.where.not(user_id: already_notified_users.pluck(:user_id))end- event_end_time =- (- if event.ends_at.is_a?(ActiveSupport::TimeWithZone)- event.ends_at- else- event.ends_at&.in_time_zone(event.timezone || "UTC")- end- )- event_ended = event_end_time && current_time > event_end_time- prefix = "before"- if event_ended- prefix = "after"- elsif event_started && !event_ended- prefix = "ongoing"- end-invitees.find_each do |invitee|+ next unless reminder_preference(invitee.user) == "notification"+ next unless invitee.user.guardian.can_see?(event.post)+attrs = {notification_type: Notification.types[:event_reminder] || Notification.types[:custom],topic_id: event.post.topic_id,post_number: event.post.post_number,data: {- topic_title: event.name || event.post.topic.title,+ topic_title: event_title(event),display_username: invitee.user.username,message: "discourse_post_event.notifications.#{prefix}_event_reminder",}.to_json,@@ -103,11 +96,202 @@ module Jobsexcerpt:I18n.t("discourse_post_event.notifications.#{prefix}_event_reminder",- title: event.name || event.post.topic.title,+ title: event_title(event),locale: invitee.user.effective_locale,),)endend++ private++ def reminder_preference(user)+ return "notification" unless user.upcoming_change_enabled?(:enable_improved_event_reminders)++ user.user_option.event_reminder_preference+ end++ def eligible_recipient?(user, event)+ user.active? && user.human? && !user.staged? && user.guardian.can_see?(event.post)+ end++ def send_personal_message(user, event, event_date, prefix)+ I18n.with_locale(user.effective_locale) do+ SystemMessage.create_from_system_user(+ user,+ :discourse_post_event_reminder,+ personal_message_params(user, event, event_date, prefix),+ )+ end+ end++ def personal_message_params(user, event, event_date, prefix)+ timezone = user.user_option.timezone.presence || event.timezone.presence || "UTC"+ {+ subject: I18n.t("discourse_events.reminder.subjects.#{prefix}", title: event_title(event)),+ event_name: escape_markdown(event_title(event)),+ date_range: date_range(event, event_date, timezone),+ timezone: timezone,+ description: event.description.to_s,+ location_section: location_section(event),+ guests: guest_list(event),+ additional_guests: additional_guests(event),+ join_event: join_event(event),+ event_url: event.post.full_url,+ }+ end++ def date_range(event, event_date, timezone)+ format = event.all_day? ? :date_only : :long+ starts_at = I18n.l(event_date.starts_at.in_time_zone(timezone), format: format)+ return starts_at if event_date.ends_at.blank?++ ends_at = I18n.l(event_date.ends_at.in_time_zone(timezone), format: format)+ "#{starts_at} - #{ends_at}"+ end++ def location_section(event)+ return "" if event.location.blank? || location_url(event).present?++ I18n.t("discourse_events.reminder.location", location: event.location)+ end++ def join_event(event)+ url = join_url(event)+ return "" if url.blank?++ I18n.t("discourse_events.reminder.join_event", url: url)+ end++ def join_url(event)+ if event.livestream? && event.livestream_url.present?+ return "#{event.post.topic.url}/zoom" if event.is_zoom_livestream?++ return event.post.full_url+ end++ return location_url(event) if event.location.present?++ normalize_url(event.url)+ end++ def location_url(event)+ location = event.location.to_s.strip+ return if location.blank?+ return normalize_url(location) if DiscourseEvents::Events::Parser.linkable_url?(location)++ fragment =+ Nokogiri::HTML5.fragment(+ DiscourseEvents::Events::Parser.cook_location(location, post: event.post),+ )+ anchor = fragment.at_css("a[href]")+ return if anchor.blank? || fragment.text.strip != anchor.text.strip++ anchor["href"]+ end++ def normalize_url(url)+ url = url.to_s.strip+ return if url.blank?+ return url if DiscourseEvents::Events::Parser.linkable_url?(url)++ "https://#{url}"+ end++ def guest_list(event)+ guest_rows(event).first(MAX_GUESTS).map { |guest| guest[:line] }.join("\n")+ end++ def additional_guests(event)+ guests = guest_rows(event)+ visible_user_ids = guests.first(MAX_GUESTS).pluck(:user_id)+ count = going_invitees(event).count { |invitee| visible_user_ids.exclude?(invitee.user_id) }+ return "" if count.zero?++ I18n.t("discourse_events.reminder.additional_guests", count: count)+ end++ def guest_rows(event)+ rows = []+ seen_user_ids = Set.new+ add_guest(rows, seen_user_ids, event.post.user, :organizer)+ event.event_hosts.each { |event_host| add_guest(rows, seen_user_ids, event_host.user, :host) }+ going_invitees(event).each { |invitee| add_guest(rows, seen_user_ids, invitee.user) }+ interested_invitees(event).each { |invitee| add_guest(rows, seen_user_ids, invitee.user) }+ rows+ end++ def add_guest(rows, seen_user_ids, user, role = nil)+ return if user.blank? || seen_user_ids.include?(user.id)++ seen_user_ids << user.id+ name = escape_markdown(display_name(user))+ line =+ if role+ I18n.t(+ "discourse_events.reminder.guest_with_role",+ name: name,+ role: I18n.t("discourse_events.reminder.roles.#{role}"),+ )+ else+ I18n.t("discourse_events.reminder.guest", name: name)+ end+ rows << { user_id: user.id, line: line }+ end++ def going_invitees(event)+ event.invitees.select(&:going?).sort_by { |invitee| [invitee.created_at, invitee.id] }+ end++ def interested_invitees(event)+ event+ .invitees+ .select do |invitee|+ invitee.status == DiscourseEvents::Events::Invitee.statuses[:interested]+ end+ .sort_by { |invitee| [invitee.created_at, invitee.id] }+ end++ def display_name(user)+ return user.username if SiteSetting.prioritize_username_in_ux? || !SiteSetting.enable_names?++ user.name.presence || user.username+ end++ def escape_markdown(text)+ text.to_s.gsub(/([\\`*_{}\[\]()#+.!>|~-])/, '\\\\\1')+ end++ def reminder_prefix(event)+ return "after" if event_ended?(event)+ return "ongoing" if event_started?(event)++ "before"+ end++ def event_started?(event)+ Time.current > event_start_time(event)+ end++ def event_ended?(event)+ event_end_time(event).present? && Time.current > event_end_time(event)+ end++ def event_start_time(event)+ return event.starts_at if event.starts_at.is_a?(ActiveSupport::TimeWithZone)++ event.starts_at.in_time_zone(event.timezone || "UTC")+ end++ def event_end_time(event)+ return if event.ends_at.blank?+ return event.ends_at if event.ends_at.is_a?(ActiveSupport::TimeWithZone)++ event.ends_at.in_time_zone(event.timezone || "UTC")+ end++ def event_title(event)+ event.name.presence || event.post.topic.title+ endendenddiff --git a/plugins/discourse-events/jobs/scheduled/monitor_event_dates.rb b/plugins/discourse-events/jobs/scheduled/monitor_event_dates.rbindex aaa6412cedc..0aef2206706 100644--- a/plugins/discourse-events/jobs/scheduled/monitor_event_dates.rb+++ b/plugins/discourse-events/jobs/scheduled/monitor_event_dates.rb@@ -21,6 +21,7 @@ module Jobs::Jobs.enqueue(:discourse_post_event_send_reminder,event_id: event_date.event.id,+ event_date_id: event_date.id,reminder: reminder[:description],)event_date.update!(reminder_counter: event_date.reminder_counter + 1)diff --git a/plugins/discourse-events/lib/discourse_events/user_option_extension.rb b/plugins/discourse-events/lib/discourse_events/user_option_extension.rbnew file mode 100644index 00000000000..9d6344831c0--- /dev/null+++ b/plugins/discourse-events/lib/discourse_events/user_option_extension.rb@@ -0,0 +1,17 @@+# frozen_string_literal: true++module DiscourseEvents+ module UserOptionExtension+ def self.prepended(base)+ unless base.method_defined?(:event_reminder_preference_personal_message?)+ # Allow model annotation after the column's migration is rolled back.+ base.attribute :event_reminder_preference, :integer+ base.enum :event_reminder_preference,+ { personal_message: 0, none: 1, notification: 2 },+ prefix: true,+ scopes: false,+ validate: true+ end+ end+ end+enddiff --git a/plugins/discourse-events/plugin.rb b/plugins/discourse-events/plugin.rbindex 4a0025aff24..759f010ebc7 100644--- a/plugins/discourse-events/plugin.rb+++ b/plugins/discourse-events/plugin.rb@@ -18,6 +18,7 @@ require_relative "lib/discourse_events/configuration/upcoming_events_default_vieenabled_site_setting :discourse_events_enabledregister_svg_icon "calendar-days"+register_asset "stylesheets/common/event-calendar-prompt.scss"register_asset "stylesheets/common/full-calendar-ext.scss"register_asset "stylesheets/common/discourse-calendar.scss"register_asset "stylesheets/common/discourse-calendar-holidays.scss"@@ -232,6 +233,10 @@ Dir.each { |f| require(f) }after_initialize do+ UserOption.prepend DiscourseEvents::UserOptionExtension+ UserUpdater::OPTION_ATTR.push(:event_reminder_preference)+ add_to_serializer(:user_option, :event_reminder_preference) { object.event_reminder_preference }+if respond_to?(:register_discourse_workflows_node)register_discourse_workflows_node do[diff --git a/plugins/discourse-events/public/images/upcoming_changes/enable_improved_event_reminders.png b/plugins/discourse-events/public/images/upcoming_changes/enable_improved_event_reminders.pngnew file mode 100644index 00000000000..70ca05f2bd7Binary files /dev/null and b/plugins/discourse-events/public/images/upcoming_changes/enable_improved_event_reminders.png differdiff --git a/plugins/discourse-events/spec/jobs/regular/discourse_post_event/send_reminder_spec.rb b/plugins/discourse-events/spec/jobs/regular/discourse_post_event/send_reminder_spec.rbindex 17b51b9c04c..984c1c187f5 100644--- a/plugins/discourse-events/spec/jobs/regular/discourse_post_event/send_reminder_spec.rb+++ b/plugins/discourse-events/spec/jobs/regular/discourse_post_event/send_reminder_spec.rb@@ -55,14 +55,11 @@ describe Jobs::DiscoursePostEventSendReminder dodescribe "#execute" docontext "with invalid params" do- it "raises an invalid parameters errors" do- expect { Jobs::DiscoursePostEventSendReminder.new.execute(event_id: 1) }.to raise_error(- Discourse::InvalidParameters,- )-- expect { Jobs::DiscoursePostEventSendReminder.new.execute(reminder: "foo") }.to raise_error(- Discourse::InvalidParameters,- )+ it "skips incomplete jobs without notifying or emailing anyone" do+ expect {+ described_class.new.execute(event_id: 1)+ described_class.new.execute(reminder: "foo")+ }.not_to change { [Notification.count, ActionMailer::Base.deliveries.size] }endend@@ -278,6 +275,152 @@ describe Jobs::DiscoursePostEventSendReminder doendend+ context "with improved event reminders" do+ fab!(:recipient) { Fabricate(:user, name: "Recipient Name") }+ fab!(:organizer) { Fabricate(:user, name: "Organizer Name") }+ fab!(:host) { Fabricate(:user, name: "Host Name") }+ fab!(:event_post) { Fabricate(:post, user: organizer) }+ fab!(:event) do+ Fabricate(+ :event,+ post: event_post,+ name: "Community breakfast",+ description: "Breakfast before the conference.",+ location: "Riverside Café",+ original_starts_at: 3.hours.from_now,+ original_ends_at: 4.hours.from_now,+ timezone: "Australia/Brisbane",+ reminders: "notification.5.minutes",+ )+ end++ before do+ SiteSetting.enable_improved_event_reminders = true+ event.update!(host_user_ids: [host.id])+ DiscourseEvents::Events::Invitee.create_attendance!(recipient.id, event.id, :going)+ end++ def reminder_message_for(user)+ topic =+ Topic+ .private_messages+ .joins(:topic_allowed_users)+ .where(topic_allowed_users: { user_id: user.id })+ .order(id: :desc)+ .first+ topic&.first_post+ end++ it "sends a personal message by default using the normal PM delivery path" do+ expect { described_class.new.execute(event_id: event.id, reminder: reminders) }.to change {+ Topic.private_messages.count+ }.by(1)++ message = reminder_message_for(recipient)+ expect(message.topic.title).to eq(":date: Community breakfast is about to start")+ expect(message.raw).to include(+ "Breakfast before the conference.",+ "#### Location",+ "Riverside Café",+ "#### Guests",+ event_post.full_url,+ )+ expect(message.topic.subtype).to eq(TopicSubtype.system_message)+ end++ it "uses usernames for guests when usernames are prioritized" do+ SiteSetting.prioritize_username_in_ux = true++ described_class.new.execute(event_id: event.id, reminder: reminders)++ raw = reminder_message_for(recipient).raw+ expect(raw).to include(+ "- #{organizer.username} (*Organizer*)",+ "- #{host.username} (*Host*)",+ "- #{recipient.username}",+ )+ expect(raw).not_to include(organizer.name, host.name, recipient.name)+ end++ it "orders guests by role and RSVP status and summarizes additional Going attendees" do+ SiteSetting.prioritize_username_in_ux = false+ regular_going_users = Fabricate.times(5, :user)+ interested_user = Fabricate(:user, name: "Interested Guest")+ regular_going_users.each do |user|+ user.user_option.update!(event_reminder_preference: "none")+ DiscourseEvents::Events::Invitee.create_attendance!(user.id, event.id, :going)+ end+ interested_user.user_option.update!(event_reminder_preference: "none")+ DiscourseEvents::Events::Invitee.create_attendance!(+ interested_user.id,+ event.id,+ :interested,+ )++ described_class.new.execute(event_id: event.id, reminder: reminders)++ raw = reminder_message_for(recipient).raw+ guest_lines = raw.lines.grep(/^-/).map(&:strip)+ expect(guest_lines.first(3)).to eq(+ ["- #{organizer.name} (*Organizer*)", "- #{host.name} (*Host*)", "- #{recipient.name}"],+ )+ expect(guest_lines.length).to eq(5)+ expect(raw).to include("and 3 others")+ expect(raw).not_to include(interested_user.name)+ end++ it "sends only the selected delivery type" do+ recipient.user_option.update!(event_reminder_preference: "notification")++ expect { described_class.new.execute(event_id: event.id, reminder: reminders) }.to change {+ recipient+ .notifications+ .where(notification_type: Notification.types[:event_reminder])+ .count+ }.by(1).and not_change { Topic.private_messages.count }++ recipient.notifications.delete_all+ recipient.user_option.update!(event_reminder_preference: "none")+ expect {+ described_class.new.execute(event_id: event.id, reminder: reminders)+ }.to not_change { recipient.notifications.count }.and not_change {+ Topic.private_messages.count+ }+ end++ it "links Zoom livestreams to the topic Zoom route" do+ SiteSetting.livestream_zoom_enabled = true+ event.update_columns(location: "https://zoom.us/j/123456789", livestream: true)++ described_class.new.execute(event_id: event.id, reminder: reminders)++ raw = reminder_message_for(recipient).raw+ expect(raw).to include("[Join event](#{event.post.topic.url}/zoom)")+ expect(raw).not_to include("#### Location")+ end++ it "links virtual events directly to their URL location" do+ event.update!(location: "[Video call](https://meet.example.com/room)")++ described_class.new.execute(event_id: event.id, reminder: reminders)++ raw = reminder_message_for(recipient).raw+ expect(raw).to include("[Join event](https://meet.example.com/room)")+ expect(raw).not_to include("#### Location")+ end++ it "keeps legacy notifications while the upcoming change is disabled" do+ SiteSetting.enable_improved_event_reminders = false++ expect { described_class.new.execute(event_id: event.id, reminder: reminders) }.to change {+ recipient+ .notifications+ .where(notification_type: Notification.types[:event_reminder])+ .count+ }.by(1).and not_change { Topic.private_messages.count }+ end+ end+context "with recurring event" dolet!(:recurring_event) doFabricate(diff --git a/plugins/discourse-events/spec/requests/calendar_subscriptions_spec.rb b/plugins/discourse-events/spec/requests/calendar_subscriptions_spec.rbindex 683b93a8f63..6985bd3ca8a 100644--- a/plugins/discourse-events/spec/requests/calendar_subscriptions_spec.rb+++ b/plugins/discourse-events/spec/requests/calendar_subscriptions_spec.rb@@ -43,4 +43,19 @@ describe "Calendar subscription feeds" doexpect(response.parsed_body["feeds"]).to contain_exactly("bookmarks", "all_events", "my_events")end++ it "distinguishes generated events URLs from a bookmarks-only key and revocation" do+ sign_in(user)+ get "/calendar-subscriptions.json"+ expect(response.parsed_body["generated_feeds"]).to eq([])+ post "/calendar-subscriptions.json"+ get "/calendar-subscriptions.json"+ expect(response.parsed_body["generated_feeds"]).to contain_exactly("all_events", "my_events")+ user.user_api_keys.last.scopes.where(name: "discourse-calendar:events_calendar").destroy_all+ get "/calendar-subscriptions.json"+ expect(response.parsed_body["generated_feeds"]).to eq([])+ delete "/calendar-subscriptions.json"+ get "/calendar-subscriptions.json"+ expect(response.parsed_body["has_subscription"]).to eq(false)+ endenddiff --git a/plugins/discourse-events/spec/requests/event_reminder_user_option_spec.rb b/plugins/discourse-events/spec/requests/event_reminder_user_option_spec.rbnew file mode 100644index 00000000000..f15059f27c5--- /dev/null+++ b/plugins/discourse-events/spec/requests/event_reminder_user_option_spec.rb@@ -0,0 +1,45 @@+# frozen_string_literal: true++RSpec.describe UsersController do+ fab!(:user)++ before do+ SiteSetting.discourse_events_enabled = true+ SiteSetting.discourse_post_event_enabled = true+ end++ describe "event reminder preferences" do+ it "serializes the default and saves each channel through user preferences" do+ sign_in(user)+ get "/u/#{user.username}.json"+ expect(response.parsed_body.dig("user", "user_option", "event_reminder_preference")).to eq(+ "personal_message",+ )++ %w[personal_message none notification].each do |channel|+ put "/u/#{user.username}.json", params: { event_reminder_preference: channel }+ expect(response.status).to eq(200)+ expect(user.user_option.reload.event_reminder_preference).to eq(channel)+ end+ end++ it "rejects invalid channels without changing the option" do+ sign_in(user)+ put "/u/#{user.username}.json", params: { event_reminder_preference: "email" }+ expect(response.status).to eq(422)+ expect(user.user_option.reload.event_reminder_preference).to eq("personal_message")+ end++ it "requires login" do+ put "/u/#{user.username}.json", params: { event_reminder_preference: "none" }+ expect(response.status).to eq(403)+ end++ it "prevents editing another user's option" do+ sign_in(Fabricate(:user))+ put "/u/#{user.username}.json", params: { event_reminder_preference: "none" }+ expect(response.status).to eq(403)+ expect(user.user_option.reload.event_reminder_preference).to eq("personal_message")+ end+ end+enddiff --git a/plugins/discourse-events/spec/system/page_objects/discourse_events/post_event.rb b/plugins/discourse-events/spec/system/page_objects/discourse_events/post_event.rbindex 1a8317ac549..37839e2ec94 100644--- a/plugins/discourse-events/spec/system/page_objects/discourse_events/post_event.rb+++ b/plugins/discourse-events/spec/system/page_objects/discourse_events/post_event.rb@@ -25,6 +25,26 @@ module PageObjectsselfend+ def has_calendar_prompt?+ has_css?(+ ".event-calendar-prompt",+ text: I18n.t("js.discourse_events.calendar_prompt.title"),+ ) &&+ has_css?(+ ".event-calendar-prompt__actions button",+ text: I18n.t("js.discourse_post_event.add_to_calendar"),+ )+ end++ def has_no_calendar_prompt?+ has_no_css?(".event-calendar-prompt")+ end++ def dismiss_calendar_prompt+ find(".event-calendar-prompt__dismiss").click+ self+ end+def not_goinglocator(".not-going-button").clickselfdiff --git a/plugins/discourse-events/spec/system/rsvp_calendar_prompt_spec.rb b/plugins/discourse-events/spec/system/rsvp_calendar_prompt_spec.rbnew file mode 100644index 00000000000..2c19374bba4--- /dev/null+++ b/plugins/discourse-events/spec/system/rsvp_calendar_prompt_spec.rb@@ -0,0 +1,43 @@+# frozen_string_literal: true++RSpec.describe "RSVP calendar prompt" do+ fab!(:admin)+ fab!(:user)++ let(:post_event_page) { PageObjects::Pages::DiscourseEvents::PostEvent.new }++ before do+ SiteSetting.discourse_events_enabled = true+ SiteSetting.discourse_post_event_enabled = true+ SiteSetting.event_participation_buttons = "going|interested|not going"+ sign_in(user)+ end++ it "offers to add the event to a calendar after Going, including when rejoining",+ time: Time.zone.parse("2026-09-14 12:00:00") do+ post =+ PostCreator.create!(+ admin,+ title: "Conference day breakfast",+ raw:+ "[event start=\"#{2.hours.from_now.iso8601}\" end=\"#{3.hours.from_now.iso8601}\" status=\"public\"]\n[/event]",+ )++ visit(post.topic.url)+ expect(post_event_page).to have_going_button+ expect(post_event_page).to have_no_calendar_prompt++ post_event_page.going+ expect(post_event_page).to have_pressed_status(:going)+ expect(post_event_page).to have_calendar_prompt++ post_event_page.dismiss_calendar_prompt+ expect(post_event_page).to have_no_calendar_prompt+ post_event_page.going+ expect(post_event_page).to have_no_selected_status(:going)++ post_event_page.going+ expect(post_event_page).to have_pressed_status(:going)+ expect(post_event_page).to have_calendar_prompt+ end+enddiff --git a/plugins/discourse-events/test/javascripts/acceptance/event-reminder-preferences-test.js b/plugins/discourse-events/test/javascripts/acceptance/event-reminder-preferences-test.jsnew file mode 100644index 00000000000..e8a5f755c1a--- /dev/null+++ b/plugins/discourse-events/test/javascripts/acceptance/event-reminder-preferences-test.js@@ -0,0 +1,47 @@+import { visit } from "@ember/test-helpers";+import { test } from "qunit";+import { cloneJSON } from "discourse/lib/object";+import userFixtures from "discourse/tests/fixtures/user-fixtures";+import form from "discourse/tests/helpers/form-kit-helper";+import { acceptance } from "discourse/tests/helpers/qunit-helpers";++acceptance("Event reminder preferences", function (needs) {+ needs.user();+ needs.settings({+ discourse_post_event_enabled: true,+ enable_improved_event_reminders: true,+ });++ let savedData;+ needs.pretender((server, helper) => {+ server.get("/u/eviltrout.json", () => {+ const profile = cloneJSON(userFixtures["/u/eviltrout.json"]);+ profile.user.can_edit = true;+ profile.user.user_option.event_reminder_preference = "personal_message";+ return helper.response(profile);+ });+ server.get("/calendar-subscriptions.json", () =>+ helper.response({ has_subscription: false })+ );+ server.put("/u/eviltrout.json", (request) => {+ savedData = helper.parsePostData(request.requestBody);+ return helper.response({ user: {} });+ });+ });++ test("saves the user option from the Calendar tab", async function (assert) {+ await visit("/u/eviltrout/preferences/calendar-subscriptions");+ assert+ .dom(".event-reminder-preferences select")+ .hasValue("personal_message");+ await form(".event-reminder-preferences form")+ .field("event_reminder_preference")+ .select("notification");+ await form(".event-reminder-preferences form").submit();+ assert.strictEqual(+ savedData.event_reminder_preference,+ "notification",+ "uses the user preferences endpoint"+ );+ });+});diff --git a/plugins/discourse-events/test/javascripts/integration/components/discourse-events-preferences-test.gjs b/plugins/discourse-events/test/javascripts/integration/components/discourse-events-preferences-test.gjsnew file mode 100644index 00000000000..042f952a86c--- /dev/null+++ b/plugins/discourse-events/test/javascripts/integration/components/discourse-events-preferences-test.gjs@@ -0,0 +1,80 @@+import { hash } from "@ember/helper";+import { render } from "@ember/test-helpers";+import { module, test } from "qunit";+import User, { addSaveableUserOptionField } from "discourse/models/user";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import form from "discourse/tests/helpers/form-kit-helper";+import DiscourseEventsPreferences from "../../discourse/connectors/calendar-preferences/discourse-events-preferences";++module(+ "Integration | Component | DiscourseEventsPreferences",+ function (hooks) {+ setupRenderingTest(hooks);++ test("loads and saves the native delivery selector", async function (assert) {+ this.siteSettings.discourse_post_event_enabled = true;+ this.siteSettings.enable_improved_event_reminders = true;+ addSaveableUserOptionField("event_reminder_preference");+ this.user = User.create({+ username: "sam",+ user_option: { event_reminder_preference: "personal_message" },+ });+ let saved;+ pretender.put("/u/sam.json", (request) => {+ saved = new URLSearchParams(request.requestBody).get(+ "event_reminder_preference"+ );+ return response({ user: { username: "sam" } });+ });+ await render(+ <template>+ <DiscourseEventsPreferences @outletArgs={{hash model=this.user}} />+ </template>+ );+ assert+ .dom("select.d-native-select")+ .hasValue(+ "personal_message",+ "uses the current channel in a native select"+ );+ await form().field("event_reminder_preference").select("notification");+ await form().submit();+ assert.strictEqual(+ saved,+ "notification",+ "saves the selected preference"+ );+ const toasts = this.owner.lookup("service:toasts").activeToasts;+ assert.strictEqual(toasts.length, 1, "shows a confirmation toast");+ assert.strictEqual(+ toasts[0].options.data.message,+ "Saved!",+ "confirms the save"+ );+ assert.strictEqual(+ toasts[0].options.data.theme,+ "success",+ "uses a success toast"+ );+ });++ test("does not show preferences when events are disabled", async function (assert) {+ this.siteSettings.discourse_post_event_enabled = false;+ this.siteSettings.enable_improved_event_reminders = true;+ await render(<template><DiscourseEventsPreferences /></template>);+ assert+ .dom(".event-reminder-preferences")+ .doesNotExist("does not offer disabled settings");+ });++ test("does not show preferences before the upcoming change is enabled", async function (assert) {+ this.siteSettings.discourse_post_event_enabled = true;+ this.siteSettings.enable_improved_event_reminders = false;+ await render(<template><DiscourseEventsPreferences /></template>);+ assert+ .dom(".event-reminder-preferences")+ .doesNotExist("does not expose the upcoming preference");+ });+ }+);diff --git a/plugins/discourse-events/test/javascripts/integration/components/event-calendar-prompt-test.gjs b/plugins/discourse-events/test/javascripts/integration/components/event-calendar-prompt-test.gjsnew file mode 100644index 00000000000..223c2f8764d--- /dev/null+++ b/plugins/discourse-events/test/javascripts/integration/components/event-calendar-prompt-test.gjs@@ -0,0 +1,147 @@+import { click, render } from "@ember/test-helpers";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import Status from "../../discourse/components/discourse-post-event/status";+import Event from "../../discourse/models/discourse-post-event-event";++module("Integration | Component | EventCalendarPrompt", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.siteSettings.event_participation_buttons =+ "going|interested|not going";+ this.siteSettings.enable_improved_event_reminders = true;+ this.event = Event.create({+ id: 99,+ status: "public",+ sample_invitees: [],+ stats: {},+ creator: { id: 2 },+ });+ pretender.post("/discourse-post-event/events/99/invitees", (request) => {+ const params = new URLSearchParams(request.requestBody);+ return response({+ invitee: {+ id: 5,+ status: params.get("invitee[status]"),+ user: { id: this.currentUser.id },+ recurring: false,+ meta: {+ event_stats: { going: 1, interested: 0 },+ event_should_display_invitees: true,+ },+ },+ });+ });+ pretender.put("/discourse-post-event/events/99/invitees/5", (request) => {+ const params = new URLSearchParams(request.requestBody);+ return response({+ invitee: {+ id: 5,+ status: params.get("invitee[status]"),+ user: { id: this.currentUser.id },+ recurring: false,+ meta: {+ event_stats: { going: 1, interested: 0 },+ event_should_display_invitees: true,+ },+ },+ });+ });+ pretender.delete("/discourse-post-event/events/99/invitees/5", () => [+ 204,+ {},+ "",+ ]);+ pretender.get("/calendar-subscriptions.json", () =>+ response({ has_subscription: false, generated_feeds: [] })+ );+ });++ test("does not mention notification preferences when improved reminders are disabled", async function (assert) {+ this.siteSettings.enable_improved_event_reminders = false;++ await render(<template><Status @event={{this.event}} /></template>);+ await click(".going-button");++ assert+ .dom(".event-calendar-prompt")+ .exists("still prompts after a successful Going RSVP");+ assert+ .dom(".event-calendar-prompt__settings")+ .hasText("Subscribe to your events");+ });++ test("appears again after leaving and rejoining, even after dismissal", async function (assert) {+ await render(<template><Status @event={{this.event}} /></template>);+ assert+ .dom(".event-calendar-prompt")+ .doesNotExist("does not prompt on initial load");+ await click(".going-button");+ assert+ .dom(".event-calendar-prompt")+ .includesText(+ "Add this event to your calendar?",+ "prompts after a successful Going RSVP"+ );+ assert+ .dom(".event-calendar-prompt__settings")+ .hasText(+ "Subscribe to events or change notification preferences",+ "links to calendar subscription and reminder settings"+ );+ await click(".event-calendar-prompt__heading button");+ assert.dom(".event-calendar-prompt").doesNotExist("dismisses the prompt");+ await click(".interested-button");+ assert+ .dom(".event-calendar-prompt")+ .doesNotExist("does not nag again for Interested");+ await click(".not-going-button");+ await click(".interested-button");+ assert+ .dom(".event-calendar-prompt")+ .exists("prompts again when becoming Interested");+ await click(".going-button");+ await click(".going-button");+ assert.dom(".event-calendar-prompt").doesNotExist("hides when leaving");+ await click(".going-button");+ assert+ .dom(".event-calendar-prompt")+ .exists("prompts again when rejoining as Going");+ });++ test("offers contextual guidance when events subscription URLs exist", async function (assert) {+ pretender.get("/calendar-subscriptions.json", () =>+ response({ has_subscription: true, generated_feeds: ["my_events"] })+ );+ await render(<template><Status @event={{this.event}} /></template>);+ await click(".interested-button");+ assert+ .dom(".event-calendar-prompt")+ .includesText(+ "This event will be added to your subscribed calendar.",+ "acknowledges the generated events subscription"+ );+ assert+ .dom(".event-calendar-prompt__actions")+ .doesNotExist("does not offer an individual calendar download");+ assert+ .dom(".event-calendar-prompt a")+ .hasText("subscribed calendar", "links the calendar description");+ await click(".not-going-button");+ assert.dom(".event-calendar-prompt").doesNotExist("hides when not going");+ });++ test("ignores subscription lookup failures after a successful RSVP", async function (assert) {+ pretender.get("/calendar-subscriptions.json", () => response(500, {}));+ await render(<template><Status @event={{this.event}} /></template>);+ await click(".going-button");+ assert+ .dom(".going-button")+ .hasAttribute("aria-pressed", "true", "keeps the successful RSVP");+ assert+ .dom(".event-calendar-prompt")+ .doesNotExist("does not infer subscription state on error");+ });+});