Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: adds user logged in trigger to workflows (#40633)

Joffrey JAFFEUXc5c00276b8dd
diff --git a/app/models/user.rb b/app/models/user.rb
index 35d5601dd59..3dca2d1590a 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -1205,12 +1205,13 @@ class User < ActiveRecord::Base
return if !User.should_update_last_seen?(id, now)
end
+ previous_seen_at = last_seen_at
update_previous_visit(now)
# using update_column to avoid the AR transaction
update_column(:last_seen_at, now)
update_column(:first_seen_at, now) unless first_seen_at
- DiscourseEvent.trigger(:user_seen, self)
+ DiscourseEvent.trigger(:user_seen, self, previous_seen_at)
end
def self.gravatar_template(email)
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/user-seen-trigger-options.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/user-seen-trigger-options.gjs
new file mode 100644
index 00000000000..4ac5ff2fdf5
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/user-seen-trigger-options.gjs
@@ -0,0 +1,106 @@
+import Component from "@glimmer/component";
+import { action } from "@ember/object";
+import { i18n } from "discourse-i18n";
+
+const DEFAULT_AMOUNT = 30;
+const DEFAULT_UNIT = "days";
+const UNIT_OPTIONS = ["hours", "days", "weeks", "months"].map((unit) => ({
+ value: unit,
+ label: i18n(`discourse_workflows.user_seen.not_seen_for_unit_${unit}`),
+}));
+
+function isBlank(value) {
+ return value === undefined || value === null || value === "";
+}
+
+export default class UserSeenTriggerOptions extends Component {
+ unitOptions = UNIT_OPTIONS;
+
+ get notSeenForMoreThanEnabled() {
+ return this.args.configuration?.trigger_on_not_seen_for_more_than === true;
+ }
+
+ @action
+ handleNotSeenForMoreThanSet(value, { set }) {
+ set("trigger_on_not_seen_for_more_than", value);
+
+ if (!value) {
+ return;
+ }
+
+ if (isBlank(this.args.formApi?.get("not_seen_for_amount"))) {
+ set("not_seen_for_amount", DEFAULT_AMOUNT);
+ }
+
+ if (isBlank(this.args.formApi?.get("not_seen_for_unit"))) {
+ set("not_seen_for_unit", DEFAULT_UNIT);
+ }
+ }
+
+ <template>
+ <@form.Field
+ @name="trigger_on_first_seen"
+ @title={{i18n "discourse_workflows.user_seen.trigger_on_first_seen"}}
+ @format="full"
+ @type="checkbox"
+ as |field|
+ >
+ <field.Control>
+ {{i18n
+ "discourse_workflows.user_seen.trigger_on_first_seen_description"
+ }}
+ </field.Control>
+ </@form.Field>
+
+ <@form.Field
+ @name="trigger_on_not_seen_for_more_than"
+ @title={{i18n
+ "discourse_workflows.user_seen.trigger_on_not_seen_for_more_than"
+ }}
+ @format="full"
+ @type="checkbox"
+ @onSet={{this.handleNotSeenForMoreThanSet}}
+ as |field|
+ >
+ <field.Control>
+ {{i18n
+ "discourse_workflows.user_seen.trigger_on_not_seen_for_more_than_description"
+ }}
+ </field.Control>
+ </@form.Field>
+
+ {{#if this.notSeenForMoreThanEnabled}}
+ <@form.Container class="workflows-user-seen-duration">
+ <@form.Field
+ @name="not_seen_for_amount"
+ @title={{i18n "discourse_workflows.user_seen.not_seen_for_amount"}}
+ @showTitle={{false}}
+ @type="input-number"
+ @validation="required|integer|between:1,9007199254740991"
+ class="workflows-user-seen-duration__amount"
+ as |field|
+ >
+ <field.Control />
+ </@form.Field>
+
+ <@form.Field
+ @name="not_seen_for_unit"
+ @title={{i18n "discourse_workflows.user_seen.not_seen_for_unit"}}
+ @showTitle={{false}}
+ @type="select"
+ @validation="required"
+ class="workflows-user-seen-duration__unit"
+ as |field|
+ >
+ <field.Control @includeNone={{false}} as |select|>
+ {{#each this.unitOptions as |option|}}
+ <select.Option @value={{option.value}}>
+ {{option.label}}
+ </select.Option>
+ {{/each}}
+ </field.Control>
+ </@form.Field>
+ </@form.Container>
+ {{/if}}
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/field-control-registry.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/field-control-registry.js
index 93eeae9daf2..d06005db618 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/field-control-registry.js
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/field-control-registry.js
@@ -22,6 +22,7 @@ import TagsControl from "../../components/workflows/configurators/tags-control";
import UrlPreview from "../../components/workflows/configurators/url-preview";
import UserControl from "../../components/workflows/configurators/user-control";
import UserOrGroupControl from "../../components/workflows/configurators/user-or-group-control";
+import UserSeenTriggerOptions from "../../components/workflows/configurators/user-seen-trigger-options";
const FIELD_CONTROL_REGISTRY = {
notice: { kind: "standalone", renderer: NoticeControl },
@@ -34,6 +35,10 @@ const FIELD_CONTROL_REGISTRY = {
},
data_table_columns: { kind: "standalone", renderer: DataTableColumns },
query_params: { kind: "standalone", renderer: QueryParams },
+ user_seen_trigger_options: {
+ kind: "standalone",
+ renderer: UserSeenTriggerOptions,
+ },
code: { kind: "field", type: "code", renderer: CodeControl },
combo_box: { kind: "field", type: "custom", renderer: ComboBox },
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/configurator/configurator.scss b/plugins/discourse-workflows/assets/stylesheets/common/configurator/configurator.scss
index fbc7a4d0642..5e46a34a0d6 100644
--- a/plugins/discourse-workflows/assets/stylesheets/common/configurator/configurator.scss
+++ b/plugins/discourse-workflows/assets/stylesheets/common/configurator/configurator.scss
@@ -277,3 +277,26 @@
min-width: 0;
}
}
+
+.workflows-user-seen-duration {
+ margin-inline-start: calc(var(--space-4) + var(--space-2));
+
+ > .form-kit__container-content {
+ display: grid;
+ grid-template-columns: minmax(4.5rem, 5.5rem) minmax(7rem, 8.5rem);
+ align-items: center;
+ gap: var(--space-2);
+ width: fit-content;
+ }
+
+ &__amount,
+ &__unit {
+ margin: 0;
+ min-width: 0;
+
+ > .form-kit__container-content {
+ width: 100%;
+ min-width: 0;
+ }
+ }
+}
diff --git a/plugins/discourse-workflows/config/locales/client.en.yml b/plugins/discourse-workflows/config/locales/client.en.yml
index 8108904cebe..feb89e20203 100644
--- a/plugins/discourse-workflows/config/locales/client.en.yml
+++ b/plugins/discourse-workflows/config/locales/client.en.yml
@@ -218,6 +218,7 @@ en:
"trigger:reviewable_approved": "Approved reviewable"
"trigger:badge_granted": "Badge granted"
"trigger:user_search": "User search"
+ "trigger:user_seen": "User seen"
"trigger:webhook": "Webhook"
"trigger:workflow_call": "Workflow call"
"trigger:manual": "Manual trigger"
@@ -265,6 +266,7 @@ en:
"trigger:reviewable_approved": "Fires when a reviewable is approved"
"trigger:badge_granted": "Fires when a user is granted a badge"
"trigger:user_search": "Fires when a user searches the site"
+ "trigger:user_seen": "Fires when a user is seen"
"trigger:webhook": "Fires when an external service sends a webhook request"
"trigger:workflow_call": "Fires when another workflow calls this workflow"
"trigger:manual": "Fires when triggered manually by an admin"
@@ -717,6 +719,20 @@ en:
badge_id: "Badge"
badge_id_description: "Only trigger when this badge is granted. Leave blank for any badge."
badge_id_placeholder: "Any badge"
+ user_seen:
+ group_ids: "Groups"
+ group_ids_description: "Only trigger for users in at least one of these groups"
+ group_ids_placeholder: "All groups"
+ trigger_on_first_seen: "First seen"
+ trigger_on_first_seen_description: "The user has never been seen before."
+ trigger_on_not_seen_for_more_than: "Returning after inactivity"
+ trigger_on_not_seen_for_more_than_description: "Only applies to users with a previous seen date."
+ not_seen_for_amount: "Duration"
+ not_seen_for_unit: "Unit"
+ not_seen_for_unit_hours: "Hours"
+ not_seen_for_unit_days: "Days"
+ not_seen_for_unit_weeks: "Weeks"
+ not_seen_for_unit_months: "Months"
schedule:
rule: "Trigger rules"
add_rule: "Add rule"
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/event_listener.rb b/plugins/discourse-workflows/lib/discourse_workflows/event_listener.rb
index 77bb9c9c854..d703ce0223d 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/event_listener.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/event_listener.rb
@@ -10,6 +10,7 @@ module DiscourseWorkflows
return unless trigger.valid?
trigger_data = nil
+ user_id = trigger.user_id if trigger.respond_to?(:user_id)
WorkflowDependency
.cached_published_triggers(trigger_class.identifier)
@@ -22,6 +23,7 @@ module DiscourseWorkflows
DiscourseWorkflows::TriggerDispatcher.enqueue(
published_trigger,
trigger_data: (trigger_data ||= trigger.output),
+ user_id: user_id,
)
rescue => e
Rails.logger.error(
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/user_seen/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/user_seen/v1.rb
new file mode 100644
index 00000000000..77f8fc05209
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/user_seen/v1.rb
@@ -0,0 +1,181 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module UserSeen
+ class V1 < NodeType
+ NOT_SEEN_UNITS = %w[hours days weeks months].freeze
+
+ description(
+ name: "trigger:user_seen",
+ version: "1.0",
+ defaults: {
+ icon: "user-check",
+ color: "green",
+ },
+ group: "discourse_triggers",
+ events: [:user_seen],
+ output_contracts: [{ schema: Schema::USER_SEEN_SCHEMA }],
+ properties: {
+ trigger_conditions: {
+ type: :custom,
+ ui: {
+ control: :user_seen_trigger_options,
+ },
+ },
+ group_ids: {
+ type: :multi_options,
+ required: false,
+ default: [],
+ type_options: {
+ load_options_method: "groups",
+ },
+ control_options: {
+ value_property: "id",
+ name_property: "name",
+ filterable: true,
+ },
+ },
+ trigger_on_first_seen: {
+ type: :boolean,
+ required: false,
+ default: true,
+ ui: {
+ hidden: true,
+ },
+ },
+ trigger_on_not_seen_for_more_than: {
+ type: :boolean,
+ required: false,
+ default: false,
+ ui: {
+ hidden: true,
+ },
+ },
+ not_seen_for_amount: {
+ type: :integer,
+ required: true,
+ default: 30,
+ min: 1,
+ ui: {
+ hidden: true,
+ },
+ },
+ not_seen_for_unit: {
+ type: :options,
+ required: true,
+ default: "days",
+ options: NOT_SEEN_UNITS,
+ ui: {
+ hidden: true,
+ },
+ },
+ },
+ capabilities: {
+ provides_current_user: true,
+ },
+ )
+
+ def self.load_options_context(context)
+ case context.method_name
+ when "groups"
+ ::Group
+ .order(:name)
+ .pluck(:id, :name)
+ .select { |_, name| context.matches_filter?(name) }
+ .map { |id, name| { id:, name: } }
+ end
+ end
+
+ def initialize(user, previous_seen_at = nil)
+ super(parameters: {})
+ @user = user
+ @previous_seen_at = previous_seen_at
+ end
+
+ def valid?
+ @user.present?
+ end
+
+ def user_id
+ @user.id
+ end
+
+ def output
+ {
+ user: user_data(@user),
+ seen: {
+ first_seen: first_seen?,
+ current_seen_at: current_seen_at&.iso8601,
+ previous_seen_at: previous_seen_at&.iso8601,
+ seconds_since_previous_seen: seconds_since_previous_seen,
+ },
+ }
+ end
+
+ def matches?(trigger_ctx)
+ matches_groups?(trigger_ctx.get_node_parameter("group_ids", [])) &&
+ (matches_first_seen?(trigger_ctx) || matches_not_seen_for_more_than?(trigger_ctx))
+ end
+
+ private
+
+ def matches_first_seen?(trigger_ctx)
+ trigger_ctx.get_node_parameter("trigger_on_first_seen", true) && first_seen?
+ end
+
+ def matches_not_seen_for_more_than?(trigger_ctx)
+ trigger_ctx.get_node_parameter("trigger_on_not_seen_for_more_than", false) &&
+ not_seen_for_more_than?(trigger_ctx)
+ end
+
+ def matches_groups?(group_ids)
+ raw_group_ids = Array.wrap(group_ids).reject(&:blank?)
+ return true if raw_group_ids.empty?
+
+ group_ids = normalize_group_ids(raw_group_ids)
+ group_ids.present? && !!@user&.in_any_groups?(group_ids)
+ end
+
+ def normalize_group_ids(group_ids)
+ group_ids.filter_map do |group_id|
+ value = group_id.to_s
+ value.to_i if value.match?(/\A\d+\z/)
+ end
+ end
+
+ def first_seen?
+ previous_seen_at.blank?
+ end
+
+ def current_seen_at
+ @user.last_seen_at
+ end
+
+ def previous_seen_at
+ @previous_seen_at
+ end
+
+ def seconds_since_previous_seen
+ return nil if previous_seen_at.blank? || current_seen_at.blank?
+
+ (current_seen_at - previous_seen_at).to_i
+ end
+
+ def not_seen_for_more_than?(trigger_ctx)
+ return false if previous_seen_at.blank?
+
+ amount = trigger_ctx.get_node_parameter("not_seen_for_amount", 30).to_i
+ unit = trigger_ctx.get_node_parameter("not_seen_for_unit", "days").presence || "days"
+
+ amount.positive? && NOT_SEEN_UNITS.include?(unit) &&
+ previous_seen_at <= amount.public_send(unit).ago
+ end
+
+ def user_data(user)
+ serialize_record(user, BasicUserSerializer)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/property_schema_validator.rb b/plugins/discourse-workflows/lib/discourse_workflows/property_schema_validator.rb
index cf6e5b3eaf6..5ac61d2de6e 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/property_schema_validator.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/property_schema_validator.rb
@@ -113,6 +113,7 @@ module DiscourseWorkflows
textarea
url_preview
user
+ user_seen_trigger_options
user_or_group
].freeze
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/schema.rb b/plugins/discourse-workflows/lib/discourse_workflows/schema.rb
index 5783b77fa5e..4f111fb1264 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/schema.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/schema.rb
@@ -221,6 +221,32 @@ module DiscourseWorkflows
USER_ADDED_TO_GROUP_SCHEMA = group_membership_event("added")
USER_REMOVED_FROM_GROUP_SCHEMA = group_membership_event("removed")
+ USER_SEEN_SCHEMA =
+ document(
+ BASIC_USER_SCHEMA.fetch("properties").merge(
+ "seen" => {
+ "type" => "object",
+ "description" => "User seen event details",
+ "properties" => {
+ "first_seen" => {
+ "type" => "boolean",
+ },
+ "current_seen_at" => {
+ "type" => %w[string null],
+ "format" => "date-time",
+ },
+ "previous_seen_at" => {
+ "type" => %w[string null],
+ "format" => "date-time",
+ },
+ "seconds_since_previous_seen" => {
+ "type" => %w[integer null],
+ },
+ },
+ },
+ ),
+ )
+
BADGE_PROPERTIES = JSON.parse(<<~JSON).freeze
{
"id": { "type": "integer" },
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/event_listener_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/event_listener_spec.rb
index ee2741b9a08..e392d366bc3 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/event_listener_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/event_listener_spec.rb
@@ -245,6 +245,105 @@ RSpec.describe DiscourseWorkflows::EventListener do
)
end
+ it "only enqueues user seen workflows matching the trigger setting" do
+ seen_at = Time.zone.now
+ user.update_columns(first_seen_at: seen_at, last_seen_at: seen_at)
+
+ create_published_workflow("matching-trigger", "trigger:user_seen")
+ create_published_workflow(
+ "returning-user-trigger",
+ "trigger:user_seen",
+ configuration: {
+ "trigger_on_first_seen" => false,
+ "trigger_on_not_seen_for_more_than" => true,
+ "not_seen_for_amount" => 1,
+ "not_seen_for_unit" => "days",
+ },
+ )
+ create_published_workflow(
+ "combined-trigger",
+ "trigger:user_seen",
+ configuration: {
+ "trigger_on_first_seen" => true,
+ "trigger_on_not_seen_for_more_than" => true,
+ "not_seen_for_amount" => 1,
+ "not_seen_for_unit" => "days",
+ },
+ )
+
+ described_class.handle(DiscourseWorkflows::Nodes::UserSeen::V1, user, nil)
+
+ expect(enqueued_trigger_node_ids).to contain_exactly("matching-trigger", "combined-trigger")
+ expect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last["args"].first["user_id"]).to eq(
+ user.id,
+ )
+ end
+
+ it "enqueues user seen workflows for returning users" do
+ previous_seen_at = 2.days.ago
+ user.update_columns(first_seen_at: 1.month.ago, last_seen_at: Time.zone.now)
+
+ create_published_workflow("new-user-trigger", "trigger:user_seen")
+ create_published_workflow(
+ "returning-user-trigger",
+ "trigger:user_seen",
+ configuration: {
+ "trigger_on_first_seen" => false,
+ "trigger_on_not_seen_for_more_than" => true,
+ "not_seen_for_amount" => 1,
+ "not_seen_for_unit" => "days",
+ },
+ )
+ create_published_workflow(
+ "combined-trigger",
+ "trigger:user_seen",
+ configuration: {
+ "trigger_on_first_seen" => true,
+ "trigger_on_not_seen_for_more_than" => true,
+ "not_seen_for_amount" => 1,
+ "not_seen_for_unit" => "days",
+ },
+ )
+
+ described_class.handle(DiscourseWorkflows::Nodes::UserSeen::V1, user, previous_seen_at)
+
+ expect(enqueued_trigger_node_ids).to contain_exactly(
+ "returning-user-trigger",
+ "combined-trigger",
+ )
+ end
+
+ it "only enqueues user seen workflows matching the selected groups" do
+ group = Fabricate(:group)
+ other_group = Fabricate(:group)
+ seen_at = Time.zone.now
+ user.update_columns(first_seen_at: seen_at, last_seen_at: seen_at)
+ group.add(user)
+
+ create_published_workflow("all-groups-trigger", "trigger:user_seen")
+ create_published_workflow(
+ "matching-group-trigger",
+ "trigger:user_seen",
+ configuration: {
+ "group_ids" => [group.id.to_s],
+ },
+ )
+ create_published_workflow(
+ "group-mismatch-trigger",
+ "trigger:user_seen",
+ configuration: {
+ "group_ids" => [other_group.id.to_s],
+ },
+ )
+
+ described_class.handle(DiscourseWorkflows::Nodes::UserSeen::V1, user, nil)
+
+ expect(enqueued_trigger_node_ids).to contain_exactly(
+ "all-groups-trigger",
+ "matching-group-trigger",
+ )
+ end
+
it "does not enqueue post edited workflows for replies by default" do
create_post(topic: topic)
create_published_workflow("first-post-only", "trigger:post_edited")
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/user_seen_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/user_seen_spec.rb
new file mode 100644
index 00000000000..fabdb77d79e
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/user_seen_spec.rb
@@ -0,0 +1,206 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::UserSeen::V1 do
+ fab!(:user)
+ fab!(:group) { Fabricate(:group, name: "workflow_seen_group") }
+ fab!(:other_group) { Fabricate(:group, name: "workflow_other_grp") }
+
+ describe ".load_options_context" do
+ def load_options(filter: nil)
+ context =
+ DiscourseWorkflows::LoadOptionsContext.new(
+ method_name: "groups",
+ filter: filter,
+ node_class: described_class,
+ )
+
+ described_class.load_options_context(context)
+ end
+
+ it "returns groups for the chooser" do
+ expect(load_options).to include(
+ { id: group.id, name: group.name },
+ { id: other_group.id, name: other_group.name },
+ )
+ end
+
+ it "filters groups by the filter term" do
+ expect(load_options(filter: group.name)).to contain_exactly(
+ { id: group.id, name: group.name },
+ )
+ end
+ end
+
+ describe "#valid?" do
+ it "returns true when user is present" do
+ trigger = described_class.new(user)
+ expect(trigger).to be_valid
+ end
+
+ it "returns false when user is nil" do
+ trigger = described_class.new(nil)
+ expect(trigger).not_to be_valid
+ end
+ end
+
+ describe "#output" do
+ it "returns user data and first seen state" do
+ seen_at = Time.zone.now
+ user.update_columns(first_seen_at: seen_at, last_seen_at: seen_at)
+
+ trigger = described_class.new(user)
+ output = trigger.output
+
+ expect(output[:user][:id]).to eq(user.id)
+ expect(output[:user][:username]).to eq(user.username)
+ expect(output[:seen][:first_seen]).to eq(true)
+ expect(output[:seen][:current_seen_at]).to eq(seen_at.iso8601)
+ expect(output[:seen][:previous_seen_at]).to eq(nil)
+ expect(output[:seen][:seconds_since_previous_seen]).to eq(nil)
+ expect(output).to match_node_output_schema(described_class)
+ end
+
+ it "returns previous seen data" do
+ current_seen_at = Time.zone.now
+ previous_seen_at = current_seen_at - 2.days
+ user.update_columns(first_seen_at: 1.month.ago, last_seen_at: current_seen_at)
+
+ output = described_class.new(user, previous_seen_at).output
+
+ expect(output[:seen][:first_seen]).to eq(false)
+ expect(output[:seen][:current_seen_at]).to eq(current_seen_at.iso8601)
+ expect(output[:seen][:previous_seen_at]).to eq(previous_seen_at.iso8601)
+ expect(output[:seen][:seconds_since_previous_seen]).to eq(2.days.to_i)
+ expect(output).to match_node_output_schema(described_class)
+ end
+ end
+
+ describe "#user_id" do
+ it "returns the seen user ID" do
+ expect(described_class.new(user).user_id).to eq(user.id)
+ end
+ end
+
+ describe "#matches?" do
+ it "matches first seen events by default" do
+ seen_at = Time.zone.now
+ user.update_columns(first_seen_at: seen_at, last_seen_at: seen_at)
+
+ expect(described_class.new(user).matches?(trigger_context({}))).to eq(true)
+ end
+
+ it "does not match later seen events by default" do
+ user.update_columns(first_seen_at: 2.days.ago, last_seen_at: Time.zone.now)
+
+ expect(described_class.new(user, 2.hours.ago).matches?(trigger_context({}))).to eq(false)
+ end
+
+ it "matches only users in the selected groups" do
+ seen_at = Time.zone.now
+ user.update_columns(first_seen_at: seen_at, last_seen_at: seen_at)
+ group.add(user)
+
+ expect(
+ described_class.new(user).matches?(trigger_context("group_ids" => [group.id.to_s])),
+ ).to eq(true)
+ expect(
+ described_class.new(user).matches?(trigger_context("group_ids" => [other_group.id.to_s])),
+ ).to eq(false)
+ end
+
+ it "does not match malformed group filters" do
+ seen_at = Time.zone.now
+ user.update_columns(first_seen_at: seen_at, last_seen_at: seen_at)
+
+ expect(described_class.new(user).matches?(trigger_context("group_ids" => ["bogus"]))).to eq(
+ false,
+ )
+ end
+
+ it "does not match first seen events when first seen is disabled" do
+ seen_at = Time.zone.now
+ user.update_columns(first_seen_at: seen_at, last_seen_at: seen_at)
+
+ expect(
+ described_class.new(user).matches?(trigger_context("trigger_on_first_seen" => false)),
+ ).to eq(false)
+ end
+
+ it "matches returning users who have not been seen for more than the configured time" do
+ user.update_columns(first_seen_at: 1.month.ago, last_seen_at: Time.zone.now)
+
+ expect(
+ described_class.new(user, 2.days.ago).matches?(
+ trigger_context(
+ "trigger_on_not_seen_for_more_than" => true,
+ "not_seen_for_amount" => 1,
+ "not_seen_for_unit" => "days",
+ ),
+ ),
+ ).to eq(true)
+ end
+
+ it "does not match returning users seen within the configured time" do
+ user.update_columns(first_seen_at: 1.month.ago, last_seen_at: Time.zone.now)
+
+ expect(
+ described_class.new(user, 2.hours.ago).matches?(
+ trigger_context(
+ "trigger_on_not_seen_for_more_than" => true,
+ "not_seen_for_amount" => 1,
+ "not_seen_for_unit" => "days",
+ ),
+ ),
+ ).to eq(false)
+ end
+
+ it "does not match first seen events with only the not seen threshold enabled" do
+ seen_at = Time.zone.now
+ user.update_columns(first_seen_at: seen_at, last_seen_at: seen_at)
+
+ expect(
+ described_class.new(user).matches?(
+ trigger_context(
+ "trigger_on_first_seen" => false,
+ "trigger_on_not_seen_for_more_than" => true,
+ "not_seen_for_amount" => 1,
+ "not_seen_for_unit" => "days",
+ ),
+ ),
+ ).to eq(false)
+ end
+
+ it "matches when either enabled condition matches" do
+ user.update_columns(first_seen_at: 1.month.ago, last_seen_at: Time.zone.now)
+
+ expect(
+ described_class.new(user, 2.days.ago).matches?(
+ trigger_context(
+ "trigger_on_first_seen" => true,
+ "trigger_on_not_seen_for_more_than" => true,
+ "not_seen_for_amount" => 1,
+ "not_seen_for_unit" => "days",
+ ),
+ ),
+ ).to eq(true)
+ end
+
+ it "does not match when no conditions are enabled" do
+ seen_at = Time.zone.now
+ user.update_columns(first_seen_at: seen_at, last_seen_at: seen_at)
+
+ expect(
+ described_class.new(user).matches?(
+ trigger_context(
+ "trigger_on_first_seen" => false,
+ "trigger_on_not_seen_for_more_than" => false,
+ ),
+ ),
+ ).to eq(false)
+ end
+ end
+
+ def trigger_context(parameters)
+ DiscourseWorkflows::TriggerNodeContext.new({ "parameters" => parameters })
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/property_schema_validator_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/property_schema_validator_spec.rb
index c21b93cbcc7..1756e544bab 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/property_schema_validator_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/property_schema_validator_spec.rb
@@ -87,6 +87,19 @@ RSpec.describe DiscourseWorkflows::PropertySchemaValidator do
expect(validate(schema)).to eq([])
end
+ it "accepts user seen trigger option controls" do
+ schema = {
+ trigger_conditions: {
+ type: :custom,
+ ui: {
+ control: :user_seen_trigger_options,
+ },
+ },
+ }
+
+ expect(validate(schema)).to eq([])
+ end
+
it "flags unknown ui.control values" do
errors = validate(title: { type: :string, ui: { control: :neon } })
expect(errors.first).to include("title.ui.control")
diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/property-engine-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/property-engine-test.gjs
index 010832484df..c9c2a66478b 100644
--- a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/property-engine-test.gjs
+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/property-engine-test.gjs
@@ -213,6 +213,154 @@ module("Integration | Component | workflows property engine", function (hooks) {
assert.false(this.formApi.get("include_subcategories"));
});
+ test("renders user seen trigger options as a compact condition group", async function (assert) {
+ this.setProperties({
+ configuration: {
+ group_ids: [],
+ trigger_on_first_seen: true,
+ trigger_on_not_seen_for_more_than: false,
+ not_seen_for_amount: 30,
+ not_seen_for_unit: "days",
+ },
+ formApi: null,
+ nodeType: "trigger:user_seen",
+ nodeTypes: [
+ {
+ identifier: "trigger:user_seen",
+ name: "trigger:user_seen",
+ version: "1.0",
+ metadata: {
+ groups: [
+ { id: 1, name: "support" },
+ { id: 2, name: "moderators" },
+ ],
+ },
+ },
+ ],
+ schema: {
+ trigger_conditions: {
+ type: "custom",
+ ui: {
+ control: "user_seen_trigger_options",
+ },
+ },
+ group_ids: {
+ type: "multi_options",
+ default: [],
+ type_options: {
+ load_options_method: "groups",
+ },
+ control_options: {
+ filterable: true,
+ name_property: "name",
+ value_property: "id",
+ },
+ },
+ trigger_on_first_seen: {
+ type: "boolean",
+ default: true,
+ ui: {
+ hidden: true,
+ },
+ },
+ trigger_on_not_seen_for_more_than: {
+ type: "boolean",
+ default: false,
+ ui: {
+ hidden: true,
+ },
+ },
+ not_seen_for_amount: {
+ type: "integer",
+ default: 30,
+ min: 1,
+ ui: {
+ hidden: true,
+ },
+ },
+ not_seen_for_unit: {
+ type: "options",
+ default: "days",
+ options: ["hours", "days", "weeks", "months"],
+ ui: {
+ hidden: true,
+ },
+ },
+ },
+ registerApi: (api) => {
+ this.set("formApi", api);
+ },
+ });
+
+ await render(
+ <template>
+ <Form
+ @data={{this.configuration}}
+ @onRegisterApi={{this.registerApi}}
+ as |form transientData|
+ >
+ <PropertyEngineConfigurator
+ @form={{form}}
+ @formApi={{this.formApi}}
+ @configuration={{transientData}}
+ @nodeType={{this.nodeType}}
+ @nodeTypes={{this.nodeTypes}}
+ @schema={{this.schema}}
+ @session={{this.session}}
+ />
+ </Form>
+ </template>
+ );
+
+ await waitFor("input[name='trigger_on_first_seen']:checked");
+
+ assert.dom(".form-kit__control-checkbox-description").exists({ count: 2 });
+ assert.deepEqual(
+ findAll(".form-kit__control-checkbox-description").map((description) =>
+ description.textContent.trim()
+ ),
+ [
+ "The user has never been seen before.",
+ "Only applies to users with a previous seen date.",
+ ],
+ "checkbox descriptions render through FormKit"
+ );
+ assert.dom(".multi-select").exists("the group limiter field renders");
+ assert.dom("input[type='checkbox']").exists({ count: 2 });
+ assert.dom("input[name='trigger_on_first_seen']").isChecked();
+ assert
+ .dom("input[name='trigger_on_not_seen_for_more_than']")
+ .isNotChecked();
+ assert.dom("input[name='not_seen_for_amount']").doesNotExist();
+ assert.dom("select[name='not_seen_for_unit']").doesNotExist();
+
+ const groupSelector = selectKit(".multi-select");
+ await groupSelector.expand();
+ await groupSelector.selectRowByValue("2");
+
+ assert.deepEqual(
+ this.formApi.get("group_ids").map(String),
+ ["2"],
+ "selected group IDs are saved"
+ );
+
+ await click("input[name='trigger_on_not_seen_for_more_than']");
+ await waitFor("input[name='not_seen_for_amount']");
+
+ assert.true(this.formApi.get("trigger_on_not_seen_for_more_than"));
+ assert.strictEqual(this.formApi.get("not_seen_for_amount"), 30);
+ assert.strictEqual(this.formApi.get("not_seen_for_unit"), "days");
+ assert.dom(".form-kit__container.workflows-user-seen-duration").exists();
+ assert.dom("input[name='not_seen_for_amount']").hasValue("30");
+ assert.dom("select[name='not_seen_for_unit']").hasValue("days");
+
+ await fillIn("input[name='not_seen_for_amount']", "45");
+ await select("select[name='not_seen_for_unit']", "weeks");
+
+ assert.strictEqual(String(this.formApi.get("not_seen_for_amount")), "45");
+ assert.strictEqual(this.formApi.get("not_seen_for_unit"), "weeks");
+ });
+
test("can clear optional category controls", async function (assert) {
this.setProperties({
configuration: {
diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb
index 6a2eedf6c9d..8a61824c83c 100644
--- a/spec/models/user_spec.rb
+++ b/spec/models/user_spec.rb
@@ -1478,6 +1478,17 @@ RSpec.describe User do
user.update_last_seen!(second_visit_date)
expect(user.reload.first_seen_at).to eq_time(first_visit_date)
end
+
+ it "triggers user_seen with the previous seen timestamp" do
+ user.update_last_seen!(first_visit_date)
+
+ events =
+ DiscourseEvent.track_events(:user_seen) do
+ user.update_last_seen!(second_visit_date, force: true)
+ end
+
+ expect(events.first[:params]).to eq([user, first_visit_date])
+ end
end
describe "update_timezone_if_missing" do