Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Add rule groups, search and filters to the rules page (#4466)

GFRf3d4e21f2631
diff --git a/app/controllers/rule_groups_controller.rb b/app/controllers/rule_groups_controller.rb
new file mode 100644
index 0000000000..74985e8a00
--- /dev/null
+++ b/app/controllers/rule_groups_controller.rb
@@ -0,0 +1,70 @@
+class RuleGroupsController < ApplicationController
+ before_action :require_non_guest!
+ before_action :set_rule_group, only: %i[edit update destroy reorder activation]
+
+ def new
+ @rule_group = Current.family.rule_groups.new
+ end
+
+ def create
+ @rule_group = Current.family.rule_groups.new(rule_group_params)
+
+ if @rule_group.save
+ redirect_to rules_path, notice: t(".success")
+ else
+ redirect_with_errors
+ end
+ end
+
+ def edit
+ end
+
+ def update
+ if @rule_group.update(rule_group_params)
+ redirect_to rules_path, notice: t(".success")
+ else
+ redirect_with_errors
+ end
+ end
+
+ # The rules stay where they are, now without a group (see RuleGroup).
+ def destroy
+ @rule_group.destroy!
+ redirect_to rules_path, notice: t(".success")
+ end
+
+ def reorder
+ Rule::Layout.new(Current.family).reorder_group!(@rule_group, params.require(:rule_ids))
+ head :no_content
+ rescue ArgumentError
+ head :unprocessable_entity
+ end
+
+ # Switches every rule of the group on or off. Not a state of the group: each
+ # rule keeps its own switch.
+ def activation
+ active = ActiveModel::Type::Boolean.new.cast(params.require(:active))
+ unchanged = @rule_group.switch_rules(active)
+
+ if unchanged.any?
+ redirect_to rules_path, alert: t(".partially_switched", count: unchanged.size)
+ else
+ redirect_to rules_path, notice: t(active ? ".activated" : ".deactivated", name: @rule_group.name)
+ end
+ end
+
+ private
+ # The form targets the whole page (_top), so a re-rendered form would
+ # replace the rules page with a page holding only the dialog.
+ def redirect_with_errors
+ redirect_to rules_path, alert: @rule_group.errors.full_messages.to_sentence
+ end
+
+ def set_rule_group
+ @rule_group = Current.family.rule_groups.find(params[:id])
+ end
+
+ def rule_group_params
+ params.require(:rule_group).permit(:name)
+ end
+end
diff --git a/app/controllers/rules_controller.rb b/app/controllers/rules_controller.rb
index 95811f67ef..48e2532d25 100644
--- a/app/controllers/rules_controller.rb
+++ b/app/controllers/rules_controller.rb
@@ -7,6 +7,8 @@ class RulesController < ApplicationController
def index
@rules = Current.family.rules.includes(:actions, conditions: :sub_conditions).ordered.to_a
Rule.share_option_lists(@rules)
+ @layout = Rule::Layout.new(Current.family, rules: @rules)
+ @list_filter = Rule::ListFilter.new(@rules)
# Fetch recent rule runs with pagination
recent_runs_scope = RuleRun
@@ -45,7 +47,7 @@ class RulesController < ApplicationController
def create
@rule = Current.family.rules.build(rule_params)
- if @rule.save
+ if save_rule
redirect_to confirm_rule_path(@rule, reload_on_close: true)
else
render_invalid_rule :new
@@ -77,7 +79,9 @@ class RulesController < ApplicationController
end
def update
- if @rule.update(rule_params)
+ @rule.assign_attributes(rule_params)
+
+ if save_rule
flash_message = if @rule.notification_baseline_timed_out?
{ alert: t("rules.notification_baseline_timed_out") }
else
@@ -98,15 +102,21 @@ class RulesController < ApplicationController
redirect_to rules_path, notice: t(".success")
end
+ # Orders the top-level items: groups and rules without a group. The rules
+ # inside a group are ordered by RuleGroupsController#reorder.
def reorder
- Rule.update_positions!(Current.family, params.require(:rule_ids))
+ Rule::Layout.new(Current.family).reorder!(params.require(:items))
head :no_content
rescue ArgumentError
head :unprocessable_entity
end
+ # Groups go too: without their rules they would be empty folders.
def destroy_all
- Current.family.rules.destroy_all
+ Rule.transaction do
+ Current.family.rules.destroy_all
+ Current.family.rule_groups.destroy_all
+ end
redirect_to rules_path, notice: t(".success")
end
@@ -134,6 +144,16 @@ class RulesController < ApplicationController
end
private
+ # A group typed into the form may be created by another request at the
+ # same moment; the save then rolls back, and saving again finds it.
+ def save_rule
+ @rule.save
+ rescue ActiveRecord::RecordNotUnique
+ raise unless @rule.rule_group&.new_record?
+
+ @rule.save
+ end
+
def render_invalid_rule(template)
# A native select cannot preserve an invalid option on resubmission. An
# action marked for destruction is not validated, but is still rendered.
@@ -227,6 +247,7 @@ class RulesController < ApplicationController
def rule_params
params.require(:rule).permit(
:resource_type, :effective_date, :active, :name, :stop_processing,
+ :rule_group_id, :new_rule_group_name,
conditions_attributes: [
:id, :condition_type, :operator, :value, :_destroy,
sub_conditions_attributes: [ :id, :condition_type, :operator, :value, :_destroy ]
diff --git a/app/helpers/rules_helper.rb b/app/helpers/rules_helper.rb
new file mode 100644
index 0000000000..c45996239a
--- /dev/null
+++ b/app/helpers/rules_helper.rb
@@ -0,0 +1,27 @@
+module RulesHelper
+ FILTER_ICONS = { status: "toggle-right", action_type: "zap", condition_type: "filter", account: "layers", group: "folder" }.freeze
+
+ # The tabs of the rules filter popover, each as { name:, label:, icon:, items:, selected: }.
+ # Each name is also the URL parameter that keeps the filter on a reload.
+ # Filters with nothing to choose from are left out, and a value from the
+ # URL that is not offered selects "all".
+ def rule_filters(list_filter, groups)
+ filters = {
+ status: [ [ t("rules.filters.status.active"), "active" ], [ t("rules.filters.status.inactive"), "inactive" ] ],
+ action_type: list_filter.action_type_options,
+ condition_type: list_filter.condition_type_options,
+ account: list_filter.account_options,
+ group: groups.any? ? [ [ t("rules.filters.group.none"), "none" ] ] + groups.map { |group| [ group.name, group.id ] } : []
+ }
+
+ filters.filter_map do |name, options|
+ next if options.empty?
+
+ items = [ { label: t("rules.filters.#{name}.all"), value: "" } ] + options.map { |label, value| { label: label, value: value.to_s } }
+ selected = params[name].to_s
+ selected = "" unless items.any? { |item| item[:value] == selected }
+
+ { name: name, label: t("rules.filters.#{name}.label"), icon: FILTER_ICONS.fetch(name), items: items, selected: selected }
+ end
+ end
+end
diff --git a/app/javascript/controllers/rules_filter_controller.js b/app/javascript/controllers/rules_filter_controller.js
new file mode 100644
index 0000000000..9b98351c13
--- /dev/null
+++ b/app/javascript/controllers/rules_filter_controller.js
@@ -0,0 +1,280 @@
+import { Controller } from "@hotwired/stimulus";
+import replaceUrl from "utils/replace_url";
+
+// Searches and filters the rules list in the browser, and folds rule groups.
+// Each rule row carries its search text and filter values as data-rule-*
+// attributes. While a search or filter is active, groups with matches are
+// shown open and dragging is off: with rules hidden, a drop could land
+// somewhere the user cannot see.
+export default class extends Controller {
+ static targets = [
+ "input",
+ "option",
+ "filterButton",
+ "badges",
+ "badge",
+ "rule",
+ "group",
+ "disclosure",
+ "ruleToggle",
+ "handle",
+ "dragHint",
+ "empty",
+ "reset",
+ ];
+
+ // The server renders the fields from the URL, so a reload keeps them.
+ connect() {
+ this.filter();
+ }
+
+ disconnect() {
+ clearTimeout(this.urlSyncTimer);
+ }
+
+ filter() {
+ const rawQuery = this.inputTarget.value.trim();
+ const query = this.#normalize(rawQuery);
+ const filters = this.#selectedFilters();
+ const filtering =
+ rawQuery.length > 0 || Object.values(filters).some((value) => value);
+ let visibleCount = 0;
+
+ this.ruleTargets.forEach((rule) => {
+ const show = !filtering || this.#matches(rule, rawQuery, query, filters);
+ rule.classList.toggle("hidden", !show);
+ if (show) visibleCount++;
+ });
+
+ this.ruleToggleTargets.forEach((toggle) => {
+ const rule = this.#ruleOf(toggle);
+ this.#setRuleOpen(rule, filtering || !this.#isCollapsed(rule));
+ });
+
+ this.groupTargets.forEach((group) => {
+ const hasMatch = this.ruleTargets.some(
+ (rule) => group.contains(rule) && !rule.classList.contains("hidden"),
+ );
+ group.classList.toggle("hidden", filtering && !hasMatch);
+ this.#setGroupOpen(group, filtering || !this.#isCollapsed(group));
+ });
+
+ this.filtering = filtering;
+ this.emptyTarget.classList.toggle("hidden", !filtering || visibleCount > 0);
+ this.dragHintTarget.classList.toggle("hidden", !filtering);
+ this.resetTarget.classList.toggle("hidden", !filtering);
+ this.#updateBadges();
+ this.#setDraggable(!filtering);
+ this.#scheduleUrlSync();
+ }
+
+ // Folding is remembered per device. While filtering, groups are shown open
+ // for their matches, so a toggle then only changes the view. Opening a
+ // group from this script fires the event too; outside a filter it then
+ // stores the state it was set from.
+ groupToggled(event) {
+ if (this.filtering) return;
+
+ const details = event.currentTarget;
+ const group = this.groupTargets.find((target) => target.contains(details));
+ if (group) this.#storeCollapsed(group, !details.open);
+ }
+
+ #matches(rule, rawQuery, query, filters) {
+ // A query that normalizes to nothing (e.g. a lone combining mark) matches
+ // no rule rather than every rule.
+ if (rawQuery.length > 0) {
+ if (query.length === 0) return false;
+ if (!this.#normalize(rule.dataset.ruleSearch || "").includes(query)) {
+ return false;
+ }
+ }
+
+ if (
+ filters.status &&
+ rule.dataset.ruleActive !== String(filters.status === "active")
+ ) {
+ return false;
+ }
+
+ return (
+ this.#listIncludes(rule.dataset.ruleActions, filters.action_type) &&
+ this.#listIncludes(rule.dataset.ruleConditions, filters.condition_type) &&
+ this.#listIncludes(rule.dataset.ruleAccounts, filters.account) &&
+ (!filters.group || rule.dataset.ruleGroup === filters.group)
+ );
+ }
+
+ #listIncludes(list, value) {
+ if (!value) return true;
+ return (list || "").split(" ").includes(value);
+ }
+
+ // Each filter is a radio group whose "all" option has an empty value.
+ #selectedFilters() {
+ return Object.fromEntries(
+ this.#checkedOptions().map((option) => [
+ option.dataset.filterParam,
+ option.value,
+ ]),
+ );
+ }
+
+ #checkedOptions() {
+ return this.optionTargets.filter((option) => option.checked);
+ }
+
+ // The badge of a filter names its chosen option; "all" hides it.
+ #updateBadges() {
+ const chosen = Object.fromEntries(
+ this.#checkedOptions()
+ .filter((option) => option.value)
+ .map((option) => [option.dataset.filterParam, option]),
+ );
+
+ this.badgeTargets.forEach((badge) => {
+ const option = chosen[badge.dataset.filterParam];
+ badge.classList.toggle("hidden", !option);
+ badge.querySelector("[data-badge-value]").textContent = option
+ ? option.dataset.filterLabel
+ : "";
+ });
+ this.badgesTarget.classList.toggle(
+ "hidden",
+ Object.keys(chosen).length === 0,
+ );
+ }
+
+ // The badge's remove button picks the filter's "all" option again. Its
+ // badge then hides, so focus moves to the filter button instead of being
+ // lost.
+ clearFilter(event) {
+ const all = this.optionTargets.find(
+ (option) =>
+ option.dataset.filterParam === event.params.name && !option.value,
+ );
+ if (all) all.checked = true;
+ this.filter();
+ this.focusFilterButton();
+ }
+
+ // After the popover closes, focus returns to the button that opened it.
+ focusFilterButton() {
+ this.filterButtonTarget.focus();
+ }
+
+ // Enter on a radio would submit the search form and reload the page.
+ ignoreEnter(event) {
+ event.preventDefault();
+ }
+
+ // A rule outside a group folds to its title line; remembered like a group.
+ toggleRule(event) {
+ const rule = this.#ruleOf(event.currentTarget);
+ const open = event.currentTarget.getAttribute("aria-expanded") !== "true";
+ if (!this.filtering) this.#storeCollapsed(rule, !open);
+ this.#setRuleOpen(rule, open);
+ }
+
+ #ruleOf(element) {
+ return this.ruleTargets.find((rule) => rule.contains(element));
+ }
+
+ #setRuleOpen(rule, open) {
+ if (!rule) return;
+
+ const toggle = this.ruleToggleTargets.find((target) =>
+ rule.contains(target),
+ );
+ toggle?.setAttribute("aria-expanded", String(open));
+ toggle?.classList.toggle("-rotate-90", !open);
+ rule.querySelectorAll("[data-rule-details]").forEach((details) => {
+ details.classList.toggle("hidden", !open);
+ });
+ }
+
+ #setGroupOpen(group, open) {
+ const details = this.disclosureTargets.find((target) =>
+ group.contains(target),
+ );
+ if (details) details.open = open;
+ }
+
+ #setDraggable(enabled) {
+ this.element.querySelectorAll("[draggable]").forEach((item) => {
+ item.setAttribute("draggable", String(enabled));
+ });
+ this.handleTargets.forEach((handle) => {
+ handle.classList.toggle("invisible", !enabled);
+ handle.disabled = !enabled;
+ });
+ }
+
+ // Groups and rules outside a group are folded by id.
+ #storageKey(element) {
+ return element.dataset.groupId
+ ? `rule-group-collapsed:${element.dataset.groupId}`
+ : `rule-collapsed:${element.dataset.ruleId}`;
+ }
+
+ // Storage can be unavailable (private mode, blocked site data); everything
+ // then simply starts open.
+ #isCollapsed(element) {
+ try {
+ return localStorage.getItem(this.#storageKey(element)) === "true";
+ } catch {
+ return false;
+ }
+ }
+
+ #storeCollapsed(element, collapsed) {
+ try {
+ if (collapsed) {
+ localStorage.setItem(this.#storageKey(element), "true");
+ } else {
+ localStorage.removeItem(this.#storageKey(element));
+ }
+ } catch {
+ // Not remembered; the fold still applies to this page.
+ }
+ }
+
+ // Case- and diacritic-insensitive, as in list_filter_controller.
+ #normalize(value) {
+ return value
+ .normalize("NFD")
+ .replace(/\p{Mark}/gu, "")
+ .toLowerCase();
+ }
+
+ // Debounced so a typing burst updates the URL once.
+ #scheduleUrlSync() {
+ clearTimeout(this.urlSyncTimer);
+ this.urlSyncTimer = setTimeout(() => this.#syncUrl(), 200);
+ }
+
+ #syncUrl() {
+ const params = new URLSearchParams(window.location.search);
+
+ const values = {
+ ...this.#selectedFilters(),
+ q: this.inputTarget.value.trim(),
+ };
+
+ Object.entries(values).forEach(([param, value]) => {
+ if (value) {
+ params.set(param, value);
+ } else {
+ params.delete(param);
+ }
+ });
+
+ const query = params.toString();
+ const url = query
+ ? `${window.location.pathname}?${query}`
+ : window.location.pathname;
+ if (url !== `${window.location.pathname}${window.location.search}`) {
+ replaceUrl(url);
+ }
+ }
+}
diff --git a/app/javascript/controllers/sortable_list_controller.js b/app/javascript/controllers/sortable_list_controller.js
index e24dfbd6f5..3e76bc802c 100644
--- a/app/javascript/controllers/sortable_list_controller.js
+++ b/app/javascript/controllers/sortable_list_controller.js
@@ -5,6 +5,12 @@ import { Controller } from "@hotwired/stimulus";
// data-sortable-list-target="item" and data-sortable-list-id. On every change
// the ids are sent as JSON to urlValue, nested under paramValue
// ("a.b" sends { a: { b: [...] } }).
+//
+// A list can hold another list (rule groups inside the rules list). The inner
+// one uses this controller as "sortable-sublist": Stimulus does not pass a
+// controller events from inside a nested controller of the same name, and
+// the outer list needs the dragover and drop events over the inner one to
+// move a whole group. Each list handles only drags of its own items.
export default class extends Controller {
static targets = ["item"];
@@ -53,6 +59,9 @@ export default class extends Controller {
// A drag starting inside a row that is not draggable itself (an image,
// selected text) is not a reorder.
if (!event.currentTarget.draggable) return;
+ // A drag that started on an item of a nested list bubbles up to this
+ // list's item around it; the nested list handles it.
+ if (!this.ownsItem(event.target, event.currentTarget)) return;
// If a touch interaction is in progress, cancel native drag —
// use touch events with hold delay instead.
@@ -110,9 +119,7 @@ export default class extends Controller {
touchStart(event) {
// Find the parent item element from the handle
- const section = event.currentTarget.closest(
- "[data-sortable-list-target='item']",
- );
+ const section = event.currentTarget.closest(this.itemSelector);
if (!section) return;
// Another controller may switch dragging off for a while, e.g. the
@@ -243,9 +250,7 @@ export default class extends Controller {
// Bound either on the item itself or on a handle inside it. Focus returns
// to the bound element after each move.
handleKeyDown(event) {
- const currentSection = event.currentTarget.closest(
- "[data-sortable-list-target='item']",
- );
+ const currentSection = event.currentTarget.closest(this.itemSelector);
if (!currentSection) return;
// Keys pressed on a control inside the item (a header button, a widget's
// own inputs) belong to that control, not to the reorder grab.
@@ -345,6 +350,19 @@ export default class extends Controller {
}
}
+ get itemSelector() {
+ return `[data-${this.identifier}-target='item']`;
+ }
+
+ // Whether the drag started on `item` itself rather than on a draggable item
+ // of a list nested in it. A text drag starts on a text node, so look from
+ // its parent element.
+ ownsItem(target, item) {
+ const element =
+ target.nodeType === Node.ELEMENT_NODE ? target : target.parentElement;
+ return element?.closest("[draggable='true']") === item;
+ }
+
// ===== Drop Position =====
// Measures the items before touching any classes, so a drag event does
// not force an extra layout pass.
diff --git a/app/javascript/controllers/sortable_sublist_controller.js b/app/javascript/controllers/sortable_sublist_controller.js
new file mode 100644
index 0000000000..03c8a74603
--- /dev/null
+++ b/app/javascript/controllers/sortable_sublist_controller.js
@@ -0,0 +1,3 @@
+// The sortable list under a second name, for a list inside another sortable
+// list (see sortable_list_controller.js).
+export { default } from "controllers/sortable_list_controller";
diff --git a/app/models/demo/generator.rb b/app/models/demo/generator.rb
index 41c70fed3e..ed1ac74a1d 100644
--- a/app/models/demo/generator.rb
+++ b/app/models/demo/generator.rb
@@ -91,6 +91,7 @@ class Demo::Generator
create_realistic_accounts!(family)
create_realistic_transactions!(family)
generate_budget_auto_fill!(family)
+ create_sample_rules!(family)
puts "🎯 Seeding goals..."
generate_goals!(family)
@@ -122,6 +123,9 @@ class Demo::Generator
# Auto-fill current-month budget based on recent spending averages
generate_budget_auto_fill!(family)
+ puts "📏 Creating sample rules..."
+ create_sample_rules!(family)
+
puts "🎯 Seeding goals..."
generate_goals!(family)
@@ -289,6 +293,32 @@ class Demo::Generator
@interest_cat = family.categories.create!(name: "Loan Interest", color: "#475569")
end
+ # Example rules, two groups and one rule without a group, so the rules page
+ # shows how rules are grouped. All are off, so the demo transactions stay as
+ # generated until someone switches the rules on or applies them.
+ def create_sample_rules!(family)
+ sample_rules = [
+ [ "Subscriptions", [ [ "Netflix", @entertainment_cat ], [ "Spotify", @entertainment_cat ] ] ],
+ [ "Groceries", [ [ "Whole Foods", @groceries_cat ], [ "Trader Joe's", @groceries_cat ] ] ],
+ [ nil, [ [ "Local Coffee", @coffee_cat ] ] ]
+ ]
+
+ sample_rules.each do |group_name, rules|
+ group = family.rule_groups.find_or_create_named!(group_name) if group_name
+
+ rules.each do |name_contains, category|
+ family.rules.create!(
+ name: "#{name_contains} → #{category.name}",
+ resource_type: "transaction",
+ active: false,
+ rule_group: group,
+ conditions_attributes: [ { condition_type: "transaction_name", operator: "like", value: name_contains } ],
+ actions_attributes: [ { action_type: "set_transaction_category", value: category.id } ]
+ )
+ end
+ end
+ end
+
def create_realistic_accounts!(family)
# Checking accounts (USD)
@chase_checking = family.accounts.create!(accountable: Depository.new(subtype: "checking"), name: "Chase Premier Checking", balance: 0, currency: "USD")
diff --git a/app/models/family.rb b/app/models/family.rb
index f20798c06b..b2fe1f6026 100644
--- a/app/models/family.rb
+++ b/app/models/family.rb
@@ -59,6 +59,7 @@ class Family < ApplicationRecord
has_many :entries, through: :accounts
has_many :transactions, through: :accounts
has_many :rules, dependent: :destroy
+ has_many :rule_groups, dependent: :destroy
has_many :trades, through: :accounts
has_many :holdings, through: :accounts
@@ -572,11 +573,13 @@ class Family < ApplicationRecord
end
# A rule with no conditions at the top of the order, the others moving
- # down one.
+ # down one. Rule groups share the rules' positions (see Rule::Layout), so
+ # they move too.
def add_classifier_rule!(action_type, active: true)
Rule.transaction do
Rule.lock_positions!(self)
rules.update_all("position = position + 1")
+ rule_groups.update_all("position = position + 1")
rules.create!(name: self.class.classifier_rule_name(action_type), resource_type: "transaction", active: active, position: 1,
actions_attributes: [ { action_type: action_type } ])
end
diff --git a/app/models/family/data_exporter.rb b/app/models/family/data_exporter.rb
index 32c4dbbd41..888c395bae 100644
--- a/app/models/family/data_exporter.rb
+++ b/app/models/family/data_exporter.rb
@@ -161,18 +161,19 @@ class Family::DataExporter
def generate_rules_csv
CSV.generate do |csv|
- csv << [ "name", "resource_type", "active", "effective_date", "conditions", "actions" ]
+ csv << [ "name", "resource_type", "active", "effective_date", "conditions", "actions", "group" ]
# Only export rules belonging to this family, in run order so an
# import recreates them in the same order
- @family.rules.includes(conditions: :sub_conditions, actions: []).ordered.each do |rule|
+ @family.rules.includes(:rule_group, conditions: :sub_conditions, actions: []).ordered.each do |rule|
csv << [
rule.name,
rule.resource_type,
rule.active,
rule.effective_date&.iso8601,
serialize_conditions_for_csv(rule.conditions),
- serialize_actions_for_csv(rule.actions)
+ serialize_actions_for_csv(rule.actions),
+ rule.rule_group&.name
]
end
end
@@ -541,7 +542,7 @@ class Family::DataExporter
end
# Export rules with versioned schema, in run order
- @family.rules.includes(conditions: :sub_conditions, actions: []).ordered.each do |rule|
+ @family.rules.includes(:rule_group, conditions: :sub_conditions, actions: []).ordered.each do |rule|
lines << {
type: "Rule",
version: 1,
@@ -757,6 +758,7 @@ class Family::DataExporter
effective_date: rule.effective_date&.iso8601,
position: rule.position,
stop_processing: rule.stop_processing,
+ group: rule.rule_group&.name,
conditions: rule.conditions.where(parent_id: nil).map { |condition| serialize_condition(condition) },
actions: rule.actions.map { |action| serialize_action(action) }
}
diff --git a/app/models/family/data_importer.rb b/app/models/family/data_importer.rb
index 4494b73763..3bb4dc4673 100644
--- a/app/models/family/data_importer.rb
+++ b/app/models/family/data_importer.rb
@@ -1388,6 +1388,8 @@ class Family::DataImporter
[ position || Float::INFINITY, index ]
end.map(&:first)
with_stored_email_action = Rule.ids_with_stored_email_notification_action(@family.rules)
+ # The last rule each group lost in this import, keyed by group id.
+ left_group_last = {}
records.each do |record|
data = record["data"]
@@ -1406,6 +1408,9 @@ class Family::DataImporter
effective_date: data["effective_date"].present? ? Date.parse(data["effective_date"].to_s) : nil,
stop_processing: data["stop_processing"] || false
)
+ # Exports from before rule groups have no group key; an existing rule
+ # then keeps its group.
+ rule.rule_group = find_or_create_rule_group(data["group"]) if data.key?("group")
# An email action replacing the rule's own keeps the baseline it recorded
# (see Rule::Action#keep_notification_baseline), as stored before this
@@ -1427,12 +1432,46 @@ class Family::DataImporter
build_rule_action(rule, action_data).keep_notification_baseline = had_email_action
end
+ left_group_id = rule.rule_group_id_was if rule.will_save_change_to_rule_group_id? && rule.rule_group.nil?
+
rule.save!
+ if left_group_id
+ # Each rule leaving a group lands right below it (Rule#place_in_rule_group),
+ # so one that left the same group earlier in this import would end up
+ # after it. Keep the exported run order instead.
+ previous = left_group_last[left_group_id] || session_rule_left_earlier(rule)
+ Rule::Layout.new(@family).place_after_rule!(rule, previous) if previous
+ left_group_last[left_group_id] = rule
+ end
map_source!(:rules, old_id, rule)
increment_summary("Rule", created ? :created : :updated)
end
end
+ # Session imports arrive in chunks, each through a fresh importer, so a rule
+ # that left the same group in an earlier chunk is not in the importer's own
+ # map. Rules this session has already imported come earlier in the run
+ # order, and those that left the group now sit right below this one: the
+ # last of that run is where this rule belongs.
+ def session_rule_left_earlier(rule)
+ return unless @import_session
+
+ session_rule_ids = @import_session.source_mappings.where(source_type: "Rule").pluck(:target_id).to_set
+ items = Rule::Layout.new(@family).items
+ index = items.index { |item| !item.group? && item.rule.id == rule.id }
+ return unless index
+
+ items.drop(index + 1).take_while { |item| !item.group? && session_rule_ids.include?(item.rule.id) }.last&.rule
+ end
+
+ def find_or_create_rule_group(name)
+ validate_rule_text!(name, field: "group")
+ name = name.to_s.strip
+ return if name.empty?
+
+ @family.rule_groups.find_or_create_named!(name)
+ end
+
def build_rule_condition(rule, condition_data, parent: nil)
value = resolve_rule_condition_value(condition_data)
diff --git a/app/models/family/financial_data_reset.rb b/app/models/family/financial_data_reset.rb
index 3fdda3402c..7702359c34 100644
--- a/app/models/family/financial_data_reset.rb
+++ b/app/models/family/financial_data_reset.rb
@@ -24,6 +24,7 @@ class Family::FinancialDataReset
balances
recurring_transactions
rules
+ rule_groups
rule_actions
rule_conditions
rule_runs
@@ -158,6 +159,7 @@ class Family::FinancialDataReset
scope(:account_providers).destroy_all
scope(:recurring_transactions).destroy_all
scope(:rules).destroy_all
+ scope(:rule_groups).destroy_all
scope(:budgets).destroy_all
scope(:categories).destroy_all
scope(:tags).destroy_all
@@ -286,6 +288,7 @@ class Family::FinancialDataReset
balances: Balance.where(account_id: account_ids),
recurring_transactions: RecurringTransaction.where(family_id: family.id),
rules: rule_scope,
+ rule_groups: RuleGroup.where(family_id: family.id),
rule_actions: Rule::Action.where(rule_id: rule_ids),
rule_conditions: Rule::Condition.where(rule_id: rule_ids),
rule_runs: RuleRun.where(rule_id: rule_ids),
diff --git a/app/models/rule.rb b/app/models/rule.rb
index bf54956eeb..3486faa0b3 100644
--- a/app/models/rule.rb
+++ b/app/models/rule.rb
@@ -6,6 +6,7 @@ class Rule < ApplicationRecord
SUPPORTED_RESOURCE_TYPES = %w[transaction].freeze
belongs_to :family
+ belongs_to :rule_group, optional: true
has_many :conditions, dependent: :destroy
has_many :actions, dependent: :destroy
has_many :rule_runs, dependent: :destroy
@@ -13,7 +14,12 @@ class Rule < ApplicationRecord
accepts_nested_attributes_for :conditions, allow_destroy: true
accepts_nested_attributes_for :actions, allow_destroy: true
+ # A name typed into the form's "new group" field. The rule joins that group,
+ # which is created unless the family already has one with that name.
+ attribute :new_rule_group_name, :string
+
before_validation :normalize_name
+ before_validation :assign_new_rule_group
before_create :assign_next_position
# Rules run top to bottom. created_at breaks ties, e.g. for rules created at
@@ -27,6 +33,8 @@ class Rule < ApplicationRecord
validates :name, length: { minimum: 1 }, allow_nil: true, if: -> { name.to_s.valid_encoding? }
validates_with DatabaseTextValidator, attributes: %i[name resource_type]
validate :no_nested_compound_conditions
+ validate :rule_group_of_same_family
+ validate :new_rule_group_valid
# Every rule must have at least 1 action
validate :min_actions
@@ -63,6 +71,15 @@ class Rule < ApplicationRecord
before_update :note_match_criteria_change
after_update :seed_notification_baseline, if: :notification_baseline_out_of_date?
+ # Joining a group puts the rule at the end of that group; leaving one keeps
+ # it right below the group. Either way the rules still run in the order the
+ # list shows (see Rule::Layout).
+ # The family's position lock is taken before the rule's row is written, in
+ # the order every other position writer takes them, so a concurrent reorder
+ # cannot deadlock against this save.
+ before_save -> { Rule.lock_positions!(family) }, if: :will_save_change_to_rule_group_id?
+ after_save :place_in_rule_group, if: :saved_change_to_rule_group_id?
+
# Set when this save's after_update took the baseline, or tried to and timed
# out. Rule::Action's commit callback for an email action added in the same
# save then skips its own, which would run the query again and, on a timeout,
@@ -148,34 +165,24 @@ class Rule < ApplicationRecord
matching_scope.pluck(:id)
end
- # Holds the family's rule positions until the transaction ends. with_connection
- # is the transaction's own connection and isn't leased to the thread for good.
+ # Serializes position changes per family with a transaction-scoped advisory
+ # lock. Without it, two rules created at the same time both read the same
+ # MAX(position) and share a position, so their run order would silently fall
+ # back to the created_at/id tie-break. The lock is held until the transaction
+ # ends. with_connection is the transaction's own connection and isn't leased
+ # to the thread for good.
def self.lock_positions!(family)
with_connection do |connection|
connection.execute(sanitize_sql_array([ "SELECT pg_advisory_xact_lock(?, hashtext(?))", POSITION_LOCK_NAMESPACE, family.id.to_s ]))
end
end
- # Sets the run order of all rules of a family. ordered_ids must list every
- # rule of the family exactly once, so a stale page (a rule added or deleted
- # meanwhile) cannot leave rules with clashing or missing positions.
- def self.update_positions!(family, ordered_ids)
- ordered_ids = Array(ordered_ids).map(&:to_s)
- family_rule_ids = family.rules.pluck(:id)
-
- unless ordered_ids.size == family_rule_ids.size && ordered_ids.sort == family_rule_ids.sort
- raise ArgumentError, "ordered_ids must list every rule of the family exactly once"
- end
-
- return if ordered_ids.empty?
-
- encoder = PG::TextEncoder::Array.new
- sql = sanitize_sql_array([ <<~SQL.squish, encoder.encode(ordered_ids), encoder.encode((1..ordered_ids.size).to_a), family.id ])
- UPDATE rules SET position = new_positions.position
- FROM unnest(?::uuid[], ?::integer[]) AS new_positions(id, position)
- WHERE rules.id = new_positions.id AND rules.family_id = ?
- SQL
- with_connection { |connection| connection.update(sql, "Rule Update Positions") }
+ # The position after every rule and rule group of the family, which share one
+ # sequence (see Rule::Layout). Takes the lock, so call it inside the
+ # transaction that writes the position.
+ def self.next_position_for(family)
+ lock_positions!(family)
+ [ family.rules.maximum(:position).to_i, family.rule_groups.maximum(:position).to_i ].max + 1
end
# Excludes transaction ids with one array parameter. where.not(id: ids) sends
@@ -358,16 +365,52 @@ class Rule < ApplicationRecord
end
private
- # Serialized per family with a transaction-scoped advisory lock: without
- # it, two rules created at the same time both read the same MAX(position)
- # and share a position, so their run order would silently fall back to
- # the created_at/id tie-break. before_create runs inside the save
- # transaction, so the lock is held until the new row is committed.
+ # before_create runs inside the save transaction, so the lock taken by
+ # next_position_for is held until the new row is committed.
def assign_next_position
return if position.to_i.positive?
- self.class.lock_positions!(family)
- self.position = family.rules.maximum(:position).to_i + 1
+ self.position = Rule.next_position_for(family)
+ end
+
+ def assign_new_rule_group
+ name = new_rule_group_name.to_s
+ return if family.nil?
+
+ # A name the database will not store is left to RuleGroup's validation.
+ unless DatabaseTextValidator.acceptable?(name)
+ self.rule_group = family.rule_groups.build(name: name)
+ return
+ end
+
+ name = name.strip
+ return if name.empty?
+
+ self.rule_group = family.rule_groups.find_or_initialize_by(name: name)
+ end
+
+ # An id that names no group would otherwise fail on the foreign key.
+ def rule_group_of_same_family
+ if rule_group.nil?
+ errors.add(:rule_group, :invalid) if rule_group_id.present?
+ elsif rule_group.family_id != family_id
+ errors.add(:rule_group, :invalid)
+ end
+ end
+
+ # A group built from the form's name is saved with the rule; its errors are
+ # shown on the name field instead of being dropped.
+ def new_rule_group_valid
+ return unless rule_group&.new_record? && rule_group.invalid?
+
+ rule_group.errors.each do |error|
+ errors.add(:new_rule_group_name, error.message)
+ end
+ end
+
+ def place_in_rule_group
+ group = rule_group || RuleGroup.find_by(id: rule_group_id_before_last_save)
+ Rule::Layout.new(family).place_after_group!(self, group) if group
end
def min_actions
diff --git a/app/models/rule/layout.rb b/app/models/rule/layout.rb
new file mode 100644
index 0000000000..706e7a0baf
--- /dev/null
+++ b/app/models/rule/layout.rb
@@ -0,0 +1,143 @@
+# The rules page as a list of top-level items: rules without a group and rule
+# groups, in any mix. A group holds its rules as one block, so the list still
+# reads as the order the rules run in.
+#
+# Rules and groups share one position sequence. A group's position marks its
+# place among the top-level items, and its rules follow it directly, so
+# Rule.ordered (by position) is the same order the page shows. Every change
+# that moves a rule into or out of a group places it to keep it that way.
+class Rule::Layout
+ Item = Data.define(:rule, :group, :rules) do
+ def group? = group.present?
+
+ def key = group? ? "group:#{group.id}" : "rule:#{rule.id}"
+ end
+
+ def initialize(family, rules: family.rules.ordered)
+ @family = family
+ @rules = rules
+ end
+
+ def items
+ @items ||= begin
+ rules_by_group = rules.to_a.group_by(&:rule_group_id)
+ groups = family.rule_groups.order(:position, :created_at, :id).to_a
+
+ group_items = groups.map { |group| [ group.position, 0, Item.new(rule: nil, group: group, rules: rules_by_group.fetch(group.id, [])) ] }
+ rule_items = rules_by_group.fetch(nil, []).map { |rule| [ rule.position, 1, Item.new(rule: rule, group: nil, rules: []) ] }
+
+ # A group sorts before a rule on the same position, so a rule that just
+ # left a group stays below it.
+ (group_items + rule_items).each_with_index.sort_by { |(position, kind, _), index| [ position, kind, index ] }.map { |(_, _, item), _| item }
+ end
+ end
+
+ def groups
+ items.select(&:group?).map(&:group)
+ end
+
+ # Moves a rule to right after the group's last other rule: the end of the
+ # group it joined, or right below the group it left. The items after that
+ # spot shift down by one, with one statement per table.
+ def place_after_group!(rule, group)
+ with_lock do
+ anchor = [
+ family.rule_groups.where(id: group.id).pick(:position).to_i,
+ family.rules.where(rule_group_id: group.id).where.not(id: rule.id).maximum(:position).to_i
+ ].max
+
+ place_after_position!(rule, anchor)
+ end
+ end
+
+ # Moves a rule without a group to right after another one, shifting the items
+ # after it down by one.
+ def place_after_rule!(rule, anchor_rule)
+ with_lock do
+ place_after_position!(rule, family.rules.where(id: anchor_rule.id).pick(:position).to_i)
+ end
+ end
+
+ # Sets the order of the top-level items. keys lists every group and every
+ # rule without a group exactly once (Item#key), so a stale page cannot drop
+ # an item or put a rule outside its group.
+ def reorder!(keys)
+ keys = Array(keys).map(&:to_s)
+
+ with_lock do
+ current = Rule::Layout.new(family).items
+ unless keys.size == current.size && keys.sort == current.map(&:key).sort
+ raise ArgumentError, "keys must list every top-level item exactly once"
+ end
+
+ by_key = current.index_by(&:key)
+ write_positions!(keys.map { |key| by_key.fetch(key) })
+ end
+ end
+
+ # Sets the order of the rules inside a group. rule_ids lists every rule of
+ # the group exactly once. The group keeps its place in the list.
+ def reorder_group!(group, rule_ids)
+ rule_ids = Array(rule_ids).map(&:to_s)
+
+ with_lock do
+ group_rules = family.rules.where(rule_group_id: group.id).ordered.to_a
+ unless rule_ids.size == group_rules.size && rule_ids.sort == group_rules.map(&:id).sort
+ raise ArgumentError, "rule_ids must list every rule of the group exactly once"
+ end
+
+ update_rule_positions!(rule_ids.zip(group_rules.map(&:position)))
+ end
+ end
+
+ private
+ attr_reader :family, :rules
+
+ def with_lock(&block)
+ Rule.transaction do
+ Rule.lock_positions!(family)
+ block.call
+ end
+ end
+
+ def place_after_position!(rule, anchor)
+ family.rules.where.not(id: rule.id).where("position > ?", anchor).update_all("position = position + 1")
+ family.rule_groups.where("position > ?", anchor).update_all("position = position + 1")
+ rule.update_column(:position, anchor + 1)
+ end
+
+ def write_positions!(items)
+ rule_positions = []
+ group_positions = []
+ position = 0
+
+ items.each do |item|
+ if item.group?
+ group_positions << [ item.group.id, position += 1 ]
+ item.rules.each { |rule| rule_positions << [ rule.id, position += 1 ] }
+ else
+ rule_positions << [ item.rule.id, position += 1 ]
+ end
+ end
+
+ update_rule_positions!(rule_positions)
+ update_positions!(RuleGroup, group_positions)
+ end
+
+ def update_rule_positions!(pairs)
+ update_positions!(Rule, pairs)
+ end
+
+ def update_positions!(model, pairs)
+ return if pairs.empty?
+
+ encoder = PG::TextEncoder::Array.new
+ table = model.quoted_table_name
+ sql = model.sanitize_sql_array([ <<~SQL.squish, encoder.encode(pairs.map(&:first)), encoder.encode(pairs.map(&:last)), family.id ])
+ UPDATE #{table} SET position = new_positions.position
+ FROM unnest(?::uuid[], ?::integer[]) AS new_positions(id, position)
+ WHERE #{table}.id = new_positions.id AND #{table}.family_id = ?
+ SQL
+ model.with_connection { |connection| connection.update(sql, "#{model.name} Update Positions") }
+ end
+end
diff --git a/app/models/rule/list_filter.rb b/app/models/rule/list_filter.rb
new file mode 100644
index 0000000000..d5d444af26
--- /dev/null
+++ b/app/models/rule/list_filter.rb
@@ -0,0 +1,114 @@
+# What the rules page needs to search and filter its list in the browser: a
+# search text per rule and the values of each filter. Option lists are read
+# once per condition or action type, not once per rule, so the page stays at
+# a fixed number of queries however many rules there are.
+class Rule::ListFilter
+ def initialize(rules)
+ @rules = rules.to_a
+ @condition_options = {}
+ @action_options = {}
+ end
+
+ # The rule's name with the labels and values of its conditions and actions,
+ # e.g. "Groceries Merchant Rewe Set category Food".
+ def search_text(rule)
+ parts = [ rule.name ]
+
+ leaf_conditions(rule).each do |condition|
+ parts << condition.filter.label << condition_value(condition)
+ end
+
+ rule.actions.each do |action|
+ parts << action.executor.label << action_value(action)
+ end
+
+ parts.compact_blank.join(" ")
+ end
+
+ def action_types(rule)
+ rule.actions.map(&:action_type).uniq
+ end
+
+ def condition_types(rule)
+ leaf_conditions(rule).map(&:condition_type).uniq
+ end
+
+ # Only accounts the user can see, so the page holds no ids of others.
+ def account_ids(rule)
+ condition_account_ids(rule) & account_options.map { |_name, id| id.to_s }
+ end
+
+ # [label, key] pairs for the types the family's rules use.
+ def action_type_options
+ type_options(rules.flat_map(&:actions)) { |action| [ action.executor.label, action.action_type ] }
+ end
+
+ def condition_type_options
+ type_options(rules.flat_map { |rule| leaf_conditions(rule) }) { |condition| [ condition.filter.label, condition.condition_type ] }
+ end
+
+ # [name, id] pairs for the accounts the rules' conditions name. Accounts the
+ # user cannot see are left out, as they are in the rule form.
+ def account_options
+ @account_options ||= begin
+ ids = rules.flat_map { |rule| condition_account_ids(rule) }.to_set
+ condition = rules.lazy.flat_map { |rule| leaf_conditions(rule) }.find { |c| c.condition_type == "transaction_account" }
+ condition ? Array(condition_options_for(condition)).select { |_name, id| ids.include?(id.to_s) } : []
+ end
+ end
+
+ private
+ attr_reader :rules
+
+ def condition_account_ids(rule)
+ leaf_conditions(rule).select { |condition| condition.condition_type == "transaction_account" }.map(&:value).compact_blank.uniq
+ end
+
+ # Conditions inside a condition group count like those at the top.
+ def leaf_conditions(rule)
+ rule.conditions.flat_map { |condition| condition.compound? ? condition.sub_conditions.to_a : [ condition ] }
+ end
+
+ def type_options(records)
+ records.map { |record| yield(record) }.uniq(&:last).sort_by { |label, _key| label.to_s.downcase }
+ end
+
+ def condition_value(condition)
+ return if condition.value.blank?
+
+ options = condition_options_for(condition)
+ return condition.value unless options
+
+ options.find { |_label, id| id.to_s == condition.value.to_s }&.first
+ end
+
+ def action_value(action)
+ return if action.value.blank?
+
+ # Structured values (e.g. a split's JSON) have their own summary.
+ custom_display = action.executor.value_display(action.value)
+ return custom_display if custom_display
+
+ # A free-text action (e.g. set the name) has no options: its value is
+ # the text itself.
+ options = action_options_for(action)
+ return action.value if options.nil?
+ return if options.empty?
+
+ values = action.executor.type == "multi_select" ? action.value.to_s.split(",") : [ action.value.to_s ]
+ labels_by_id = options.to_h { |label, id| [ id.to_s, label ] }
+ values.filter_map { |value| labels_by_id[value] }.join(" ")
+ end
+
+ def condition_options_for(condition)
+ @condition_options.fetch(condition.condition_type) do
+ @condition_options[condition.condition_type] = condition.options
+ end
+ end
+
+ def action_options_for(action)
+ @action_options.fetch(action.action_type) do
+ @action_options[action.action_type] = action.options
+ end
+ end
+end
diff --git a/app/models/rule_group.rb b/app/models/rule_group.rb
new file mode 100644
index 0000000000..c5d332ffd8
--- /dev/null
+++ b/app/models/rule_group.rb
@@ -0,0 +1,46 @@
+# A folder for rules, so a long rule list stays readable. It only arranges the
+# list: rules still run as one list from top to bottom (see Rule::Layout), and
+# a group has no state of its own.
+class RuleGroup < ApplicationRecord
+ belongs_to :family
+ has_many :rules, dependent: :nullify
+
+ scope :alphabetically, -> { order(Arel.sql("LOWER(name)"), :id) }
+
+ before_validation :normalize_name
+ before_create :assign_next_position
+
+ validates :name, presence: true, length: { maximum: 100 }, if: -> { name.to_s.valid_encoding? }
+ validates :name, uniqueness: { scope: :family_id }, if: -> { DatabaseTextValidator.acceptable?(name) }
+ validates_with DatabaseTextValidator, attributes: %i[name]
+
+ # The family's group with that name, created if missing. A group created at
+ # the same moment by another request is found instead of failing.
+ def self.find_or_create_named!(name)
+ find_by(name: name) || create_or_find_by!(name: name)
+ rescue ActiveRecord::RecordInvalid => error
+ # Committed between the lookup and the uniqueness validation.
+ raise unless error.record.errors.of_kind?(:name, :taken)
+
+ where(name: name).take!
+ end
+
+ # Switches every rule of the group on or off, one by one, so each rule runs
+ # its own callbacks (switching a rule on takes its email baseline). Returns
+ # the rules left as they were: invalid ones, and those kept off because that
+ # baseline timed out.
+ def switch_rules(active)
+ rules.ordered.to_a.reject do |rule|
+ rule.update(active: active) && !rule.notification_baseline_timed_out?
+ end
+ end
+
+ private
+ def assign_next_position
+ self.position = Rule.next_position_for(family)
+ end
+
+ def normalize_name
+ self.name = name.strip if name.is_a?(String) && name.valid_encoding? && !name.include?("\0")
+ end
+end
diff --git a/app/models/rule_import.rb b/app/models/rule_import.rb
index d264f22697..911f561f95 100644
--- a/app/models/rule_import.rb
+++ b/app/models/rule_import.rb
@@ -16,7 +16,7 @@ class RuleImport < Import
end
def column_keys
- %i[name resource_type active effective_date conditions actions]
+ %i[name resource_type active effective_date conditions actions rule_group]
end
def required_column_keys
@@ -33,7 +33,7 @@ class RuleImport < Import
def csv_template
csv_string = CSV.generate do |csv|
- csv << %w[name resource_type* active effective_date conditions* actions*]
+ csv << %w[name resource_type* active effective_date conditions* actions* group]
csv << [
"Categorize groceries",
@@ -41,7 +41,8 @@ class RuleImport < Import
"true",
"2024-01-01",
'[{"condition_type":"transaction_name","operator":"like","value":"grocery"}]',
- '[{"action_type":"set_transaction_category","value":"Groceries"}]'
+ '[{"action_type":"set_transaction_category","value":"Groceries"}]',
+ "Shopping"
]
csv << [
@@ -50,7 +51,8 @@ class RuleImport < Import
"true",
"",
'[{"condition_type":"transaction_name","operator":"like","value":"amazon"}]',
- '[{"action_type":"auto_categorize"}]'
+ '[{"action_type":"auto_categorize"}]',
+ ""
]
csv << [
@@ -59,7 +61,8 @@ class RuleImport < Import
"true",
"",
'[{"condition_type":"transaction_name","operator":"like","value":"rent"}]',
- '[{"action_type":"split_transaction","value":{"splits":[{"type":"percentage","name":"My share","share":"50","category":"Rent"},{"type":"percentage","name":"Partner share","share":"50","category":"Rent","tags":["Shared"]}]}}]'
+ '[{"action_type":"split_transaction","value":{"splits":[{"type":"percentage","name":"My share","share":"50","category":"Rent"},{"type":"percentage","name":"Partner share","share":"50","category":"Rent","tags":["Shared"]}]}}]',
+ ""
]
end
@@ -69,8 +72,9 @@ class RuleImport < Import
def generate_rows_from_csv
rows.destroy_all
+ header_size = header_row_size
csv_rows.each.with_index(1) do |row, index|
- normalized_row = normalize_rule_row(row)
+ normalized_row = normalize_rule_row(row, header_size: header_size)
rows.create!(
source_row_number: index,
@@ -80,6 +84,7 @@ class RuleImport < Import
effective_date: normalized_row[:effective_date].to_s.strip,
conditions: normalized_row[:conditions].to_s.strip,
actions: normalized_row[:actions].to_s.strip,
+ rule_group: normalized_row[:rule_group] && normalized_rule_text(normalized_row[:rule_group], attribute: :rule_group),
currency: default_currency
)
end
@@ -91,8 +96,17 @@ class RuleImport < Import
private
- def normalize_rule_row(row)
- fields = row.fields
+ # The optional group column is read by its header and left out of the
+ # positional fields, which re-assemble conditions and actions from
+ # everything after the fourth column.
+ def normalize_rule_row(row, header_size: row.headers.compact.size)
+ fields = row.fields.dup
+ headers = row.headers
+ group_index = headers.index { |header| header.to_s.strip.delete_suffix("*") == "group" }
+ # Counted from the end of the header row, so a row whose JSON was split
+ # into extra fields (CSV pads headers with nil for those) still gives up
+ # the right one.
+ group = fields.delete_at(group_index - header_size) if group_index
name, resource_type, active, effective_date = fields[0..3]
conditions, actions = extract_conditions_and_actions(fields[4..])
@@ -102,10 +116,19 @@ class RuleImport < Import
active: row["active"].presence || active,
effective_date: row["effective_date"].presence || effective_date,
conditions: conditions,
- actions: actions
+ actions: actions,
+ rule_group: group_index ? group.to_s : nil
}
end
+ # The number of cells in the header row, blank ones included. A row's
+ # headers cannot tell a blank header cell from the nil CSV pads in for a
+ # row with more fields than the header.
+ def header_row_size
+ header = CSV.parse_line((raw_file_str || "").strip, col_sep: col_sep, liberal_parsing: true)
+ header ? header.size : 0
+ end
+
def normalized_rule_text(value, attribute:)
text = value.to_s
reject_invalid_text!(text, label: Rule.human_attribute_name(attribute))
@@ -174,6 +197,8 @@ class RuleImport < Import
rule.active = row.active || false
rule.effective_date = parse_date(row.effective_date)
+ # A file without the group column leaves the rule's group as it is.
+ rule.rule_group = find_or_create_rule_group(row.rule_group) unless row.rule_group.nil?
# An email action replacing the rule's own keeps the baseline it recorded
# (see Rule::Action#keep_notification_baseline), as stored before this
@@ -199,6 +224,13 @@ class RuleImport < Import
rule.save!
end
+ def find_or_create_rule_group(name)
+ name = name.strip
+ return if name.empty?
+
+ family.rule_groups.find_or_create_named!(name)
+ end
+
def build_condition(rule, condition_data, parent: nil)
condition_type = condition_data["condition_type"]
operator = condition_data["operator"]
diff --git a/app/views/rule_groups/_form.html.erb b/app/views/rule_groups/_form.html.erb
new file mode 100644
index 0000000000..82b040f895
--- /dev/null
+++ b/app/views/rule_groups/_form.html.erb
@@ -0,0 +1,7 @@
+<%# locals: (rule_group:) %>
+<%= styled_form_with model: rule_group, class: "space-y-4", data: { turbo_frame: :_top } do |f| %>
+ <%= f.text_field :name, label: t("rule_groups.form.name_label"), placeholder: t("rule_groups.form.name_placeholder"), autofocus: true, required: true %>
+ <p class="text-xs text-secondary"><%= t("rule_groups.form.hint") %></p>
+
+ <%= f.submit %>
+<% end %>
diff --git a/app/views/rule_groups/edit.html.erb b/app/views/rule_groups/edit.html.erb
new file mode 100644
index 0000000000..3836834487
--- /dev/null
+++ b/app/views/rule_groups/edit.html.erb
@@ -0,0 +1,6 @@
+<%= render DS::Dialog.new do |dialog| %>
+ <% dialog.with_header(title: t(".title", name: @rule_group.name_was)) %>
+ <% dialog.with_body do %>
+ <%= render "rule_groups/form", rule_group: @rule_group %>
+ <% end %>
+<% end %>
diff --git a/app/views/rule_groups/new.html.erb b/app/views/rule_groups/new.html.erb
new file mode 100644
index 0000000000..965ea247c5
--- /dev/null
+++ b/app/views/rule_groups/new.html.erb
@@ -0,0 +1,6 @@
+<%= render DS::Dialog.new do |dialog| %>
+ <% dialog.with_header(title: t(".title")) %>
+ <% dialog.with_body do %>
+ <%= render "rule_groups/form", rule_group: @rule_group %>
+ <% end %>
+<% end %>
diff --git a/app/views/rules/_drag_handle.html.erb b/app/views/rules/_drag_handle.html.erb
new file mode 100644
index 0000000000..2f98d914dc
--- /dev/null
+++ b/app/views/rules/_drag_handle.html.erb
@@ -0,0 +1,13 @@
+<%# locals: (label:, list: "sortable-list") %>
+<%= render DS::Button.new(
+ variant: :icon,
+ icon: "grip-vertical",
+ size: :sm,
+ class: "ml-2 shrink-0 cursor-grab active:cursor-grabbing",
+ aria_label: label,
+ data: {
+ rules_filter_target: "handle",
+ action: %w[touchstart->touchStart touchmove->touchMove touchend->touchEnd touchcancel->touchCancel contextmenu->suppressContextMenu keydown->handleKeyDown]
+ .map { |binding| binding.sub("->", "->#{list}#") }.join(" ")
+ }
+) %>
diff --git a/app/views/rules/_filters.html.erb b/app/views/rules/_filters.html.erb
new file mode 100644
index 0000000000..198d6ac891
--- /dev/null
+++ b/app/views/rules/_filters.html.erb
@@ -0,0 +1,118 @@
+<%# locals: (list_filter:, groups:) %>
+<%# Filters in the browser (rules_filter_controller), laid out like the
+ transactions filter: a popover with one tab per filter and the active
+ filters as badges below the search. The form only submits when Enter is
+ pressed in the search, which reloads the same view. %>
+<% filters = rule_filters(list_filter, groups) %>
+<% active_filters = filters.select { |filter| filter[:selected].present? } %>
+<%= form_with url: rules_path, method: :get, class: "flex flex-col gap-2 mb-4", role: "search" do |form| %>
+ <div class="flex gap-2">
+ <div class="grow min-w-0">
+ <%= render DS::SearchInput.new(
+ name: "q",
+ value: params[:q],
+ aria_label: t("rules.filters.search_label"),
+ placeholder: t("rules.filters.search_placeholder"),
+ data: { rules_filter_target: "input", filter_param: "q", action: "input->rules-filter#filter" }
+ ) %>
+ </div>
+
+ <%= render DS::Popover.new(variant: "button", no_padding: true) do |popover| %>
+ <% popover.with_button(
+ id: "rule-filters-button",
+ type: "button",
+ text: t("rules.filters.button"),
+ variant: "outline",
+ icon: "list-filter",
+ data: { rules_filter_target: "filterButton" }
+ ) %>
+
+ <% popover.with_custom_content do %>
+ <%= render DS::Tabs.new(
+ variant: :unstyled,
+ active_tab: (active_filters.first || filters.first)[:name].to_s,
+ active_btn_classes: "bg-surface text-primary",
+ inactive_btn_classes: "text-secondary hover:bg-container-inset"
+ ) do |tabs| %>
+ <div id="rule-filters-menu" class="flex flex-col md:flex-row h-[50vh] md:h-80 w-full md:w-135 overflow-hidden">
+ <%= tabs.with_nav(classes: "shrink-0 flex w-full md:w-44 flex-row md:flex-col items-start p-3 text-sm font-medium text-secondary border-b md:border-b-0 md:border-r border-secondary overflow-x-auto md:overflow-x-visible md:overflow-y-auto") do |nav| %>
+ <% filters.each do |filter| %>
+ <%= nav.with_btn(id: filter[:name].to_s, label: filter[:label], classes: "w-full px-3 py-2 flex gap-2 items-center rounded-md whitespace-nowrap") do %>
+ <%= icon(filter[:icon]) %>
+ <%= tag.span(filter[:label], class: "text-sm font-medium") %>
+ <% end %>
+ <% end %>
+ <% end %>
+
+ <div class="flex flex-col grow overflow-y-auto">
+ <div class="grow p-3 border-b border-secondary overflow-y-auto">
+ <% filters.each do |filter| %>
+ <%= tabs.with_panel(tab_id: filter[:name].to_s) do %>
+ <fieldset class="p-2 space-y-3">
+ <legend class="sr-only"><%= filter[:label] %></legend>
+ <% filter[:items].each do |item| %>
+ <% id = "rule_filter_#{filter[:name]}_#{item[:value].presence || "all"}" %>
+ <div class="flex items-center gap-3">
+ <%# Enter on a radio would submit the form and reload the page. %>
+ <%= radio_button_tag filter[:name], item[:value], item[:value] == filter[:selected],
+ id: id,
+ data: {
+ rules_filter_target: "option",
+ filter_param: filter[:name],
+ filter_label: item[:label],
+ action: "change->rules-filter#filter keydown.enter->rules-filter#ignoreEnter"
+ } %>
+ <%= label_tag id, item[:label], class: "text-sm text-primary" %>
+ </div>
+ <% end %>
+ </fieldset>
+ <% end %>
+ <% end %>
+ </div>
+
+ <div class="flex justify-between items-center gap-2 bg-container p-3 shrink-0">
+ <div>
+ <%= render DS::Link.new(
+ text: t("rules.filters.reset"),
+ variant: "ghost",
+ href: rules_path,
+ class: "hidden",
+ data: { rules_filter_target: "reset" }
+ ) %>
+ </div>
+ <%= render DS::Button.new(
+ text: t("rules.filters.done"),
+ type: "button",
+ data: { action: "DS--popover#close rules-filter#focusFilterButton" }
+ ) %>
+ </div>
+ </div>
+ </div>
+ <% end %>
+ <% end %>
+ <% end %>
+ </div>
+
+ <%# Rendered from the URL, then kept in step by the controller. %>
+ <ul class="<%= class_names("flex items-center flex-wrap gap-2", "hidden" => active_filters.empty?) %>"
+ aria-label="<%= t("rules.filters.active_label") %>"
+ data-rules-filter-target="badges">
+ <% filters.each do |filter| %>
+ <% chosen = filter[:items].find { |item| item[:value] == filter[:selected] } if filter[:selected].present? %>
+ <%= tag.li class: ("hidden" unless chosen), data: { rules_filter_target: "badge", filter_param: filter[:name] } do %>
+ <div class="flex items-center gap-1 text-sm border border-secondary rounded-3xl py-1 pl-3 pr-1">
+ <span class="text-secondary"><%= filter[:label] %>:</span>
+ <span class="text-primary" data-badge-value><%= chosen&.dig(:label) %></span>
+ <%= render DS::Button.new(
+ variant: "icon",
+ icon: "x",
+ size: "sm",
+ type: "button",
+ aria_label: t("rules.filters.remove", filter: filter[:label]),
+ data: { action: "rules-filter#clearFilter", rules_filter_name_param: filter[:name] }
+ ) %>
+ </div>
+ <% end %>
+ <% end %>
+ </ul>
+<% end %>
diff --git a/app/views/rules/_form.html.erb b/app/views/rules/_form.html.erb
index 7a52e499d5..2b91642c02 100644
--- a/app/views/rules/_form.html.erb
+++ b/app/views/rules/_form.html.erb
@@ -19,6 +19,20 @@
</div>
</section>
+ <section class="space-y-4">
+ <div class="flex items-center gap-1 text-secondary">
+ <%= icon "folder", size: "sm" %>
+ <h3 class="text-sm font-medium text-primary"><%= t(".group_label") %></h3>
+ </div>
+ <div class="ml-6 grid grid-cols-1 sm:grid-cols-2 gap-2">
+ <%= f.select :rule_group_id,
+ rule.family.rule_groups.alphabetically.map { |group| [ group.name, group.id ] },
+ { include_blank: t(".no_group"), label: t(".group_select_label") } %>
+ <%= f.text_field :new_rule_group_name, label: t(".new_group_label"), placeholder: t(".new_group_placeholder") %>
+ </div>
+ <p class="ml-6 text-xs text-secondary"><%= t(".group_hint") %></p>
+ </section>
+
<section class="space-y-4">
<div class="flex items-center gap-1 text-secondary">
<h3 class="text-sm font-medium text-primary">IF</h3>
diff --git a/app/views/rules/_group.html.erb b/app/views/rules/_group.html.erb
new file mode 100644
index 0000000000..08c6310135
--- /dev/null
+++ b/app/views/rules/_group.html.erb
@@ -0,0 +1,68 @@
+<%# locals: (item:, list_filter:) %>
+<% group = item.group %>
+<% inactive_count = item.rules.count { |rule| !rule.active? } %>
+<div data-sortable-list-target="item"
+ data-sortable-list-id="<%= item.key %>"
+ draggable="true"
+ role="listitem"
+ aria-grabbed="false"
+ data-action="dragstart->sortable-list#dragStart dragend->sortable-list#dragEnd"
+ data-rules-filter-target="group"
+ data-group-id="<%= group.id %>">
+ <%# Opened by the page script (rules_filter_controller), which remembers
+ the fold per device. Buttons in the summary do not toggle it. %>
+ <%= render DS::Disclosure.new(
+ open: true,
+ summary_class: "list-none flex items-center gap-2 bg-surface pr-4 cursor-pointer focus-ring",
+ body_class: nil,
+ data: { rules_filter_target: "disclosure", action: "toggle->rules-filter#groupToggled" }
+ ) do |disclosure| %>
+ <% disclosure.with_summary_content do %>
+ <%= render "rules/drag_handle", label: t("rules.index.reorder_group", name: group.name) %>
+ <div class="flex items-center gap-2 grow min-w-0 py-3" data-rules-group-header>
+ <%= icon("chevron-right", size: "sm", class: "shrink-0 [details[open]>summary_&]:rotate-90 motion-safe:transition-transform motion-safe:duration-150") %>
+ <%= icon("folder", size: "sm", class: "shrink-0") %>
+ <span class="text-sm font-medium text-primary truncate"><%= group.name %></span>
+ <span class="text-xs text-secondary whitespace-nowrap">
+ <%= t("rules.group.rules_count", count: item.rules.size) %><% if inactive_count.positive? %> &middot; <%= t("rules.group.inactive_count", count: inactive_count) %><% end %>
+ </span>
+ </div>
+ <% unless Current.user&.guest? %>
+ <%= render DS::Menu.new do |menu| %>
+ <% if item.rules.any? %>
+ <% menu.with_item(variant: "button", text: t("rules.group.activate_all"), href: activation_rule_group_path(group, active: true), method: :patch, icon: "toggle-right") %>
+ <% menu.with_item(variant: "button", text: t("rules.group.deactivate_all"), href: activation_rule_group_path(group, active: false), method: :patch, icon: "toggle-left") %>
+ <% end %>
+ <% menu.with_item(variant: "link", text: t("rules.group.rename"), href: edit_rule_group_path(group), icon: "pencil", data: { turbo_frame: "modal" }) %>
+ <% menu.with_item(
+ variant: "button",
+ text: t("rules.group.delete"),
+ href: rule_group_path(group),
+ icon: "trash-2",
+ method: :delete,
+ confirm: CustomConfirm.new(
+ destructive: true,
+ title: t("rules.group.delete_confirm_title", name: group.name),
+ body: t("rules.group.delete_confirm_body"),
+ btn_text: t("rules.group.delete")
+ )) %>
+ <% end %>
+ <% end %>
+ <% end %>
+ <div id="<%= dom_id(group, :rules) %>"
+ class="flex flex-col divide-y divide-subdued border-t border-subdued pl-6"
+ data-controller="sortable-sublist"
+ data-sortable-sublist-url-value="<%= reorder_rule_group_path(group) %>"
+ data-sortable-sublist-param-value="rule_ids"
+ data-action="dragover->sortable-sublist#dragOver drop->sortable-sublist#drop"
+ role="list"
+ aria-label="<%= group.name %>">
+ <% if item.rules.empty? %>
+ <p class="px-4 py-3 text-sm text-secondary"><%= t("rules.group.empty") %></p>
+ <% end %>
+ <% item.rules.each do |rule| %>
+ <%= render "rules/list_rule", rule: rule, sortable_id: rule.id, list_filter: list_filter, list: "sortable-sublist" %>
+ <% end %>
+ </div>
+ <% end %>
+</div>
diff --git a/app/views/rules/_list_rule.html.erb b/app/views/rules/_list_rule.html.erb
new file mode 100644
index 0000000000..09f8cd4769
--- /dev/null
+++ b/app/views/rules/_list_rule.html.erb
@@ -0,0 +1,35 @@
+<%# locals: (rule:, sortable_id:, list_filter:, list: "sortable-list", foldable: false) %>
+<div class="flex items-center"
+ data-<%= list %>-target="item"
+ data-sortable-list-id="<%= sortable_id %>"
+ draggable="true"
+ role="listitem"
+ aria-grabbed="false"
+ data-action="dragstart-><%= list %>#dragStart dragend-><%= list %>#dragEnd"
+ data-rules-filter-target="rule"
+ data-rule-id="<%= rule.id %>"
+ data-rule-search="<%= list_filter.search_text(rule) %>"
+ data-rule-active="<%= rule.active? %>"
+ data-rule-actions="<%= list_filter.action_types(rule).join(" ") %>"
+ data-rule-conditions="<%= list_filter.condition_types(rule).join(" ") %>"
+ data-rule-accounts="<%= list_filter.account_ids(rule).join(" ") %>"
+ data-rule-group="<%= rule.rule_group_id || "none" %>">
+ <% rule_label = rule.name.presence || rule.primary_condition_title %>
+ <%= render "rules/drag_handle", list: list, label: t("rules.index.reorder_rule", name: rule_label) %>
+ <%# A rule outside a group folds to one line, like a group does. %>
+ <% if foldable %>
+ <%= render DS::Button.new(
+ variant: "icon",
+ size: "sm",
+ icon: "chevron-down",
+ title: t("rules.index.fold_rule", name: rule_label),
+ aria_label: t("rules.index.fold_rule", name: rule_label),
+ class: "shrink-0 motion-safe:transition-transform",
+ aria: { expanded: "true", controls: dom_id(rule, :details) },
+ data: { rules_filter_target: "ruleToggle", action: "rules-filter#toggleRule" }
+ ) %>
+ <% end %>
+ <div class="grow min-w-0">
+ <%= render "rules/rule", rule: rule %>
+ </div>
+</div>
diff --git a/app/views/rules/_rule.html.erb b/app/views/rules/_rule.html.erb
index 112d601641..8874834d07 100644
--- a/app/views/rules/_rule.html.erb
+++ b/app/views/rules/_rule.html.erb
@@ -15,7 +15,9 @@
<% if rule.conditions.any? %>
<% displayed_condition = rule.displayed_condition %>
<% additional_condition_count = rule.additional_displayable_conditions_count %>
- <div class="flex items-center gap-2 mt-1">
+ <%# Folding hides the details; a rule without a name keeps its
+ condition as its title. %>
+ <%= tag.div class: "flex items-center gap-2 mt-1", data: { rule_details: rule.name.present? || nil } do %>
<div class="flex items-center gap-1 text-secondary w-16 shrink-0">
<span class="font-mono text-xs">IF</span>
</div>
@@ -31,43 +33,45 @@
<%= t(".and_more_conditions", count: additional_condition_count) %>
<% end %>
</p>
- </div>
+ <% end %>
<% end %>
- <div class="flex items-center gap-2 mt-1">
- <div class="flex items-center gap-1 text-secondary w-16 shrink-0">
- <span class="font-mono text-xs"><%= t(".then") %></span>
- </div>
- <p class="flex min-w-0 items-center flex-wrap gap-x-1.5 gap-y-1 m-0">
- <span class="max-w-full truncate px-2 py-1 border border-secondary rounded-full">
- <% displayed_action = rule.displayed_action %>
- <% if displayed_action.nil? %>
- <%= t("rules.no_action") %>
- <% else %>
- <% if displayed_action.value && displayed_action.options %>
- <%= t(".action_label_to", label: displayed_action.executor.label, value: displayed_action.value_display) %>
+ <div id="<%= dom_id(rule, :details) %>" class="space-y-1.5" data-rule-details>
+ <div class="flex items-center gap-2 mt-1">
+ <div class="flex items-center gap-1 text-secondary w-16 shrink-0">
+ <span class="font-mono text-xs"><%= t(".then") %></span>
+ </div>
+ <p class="flex min-w-0 items-center flex-wrap gap-x-1.5 gap-y-1 m-0">
+ <span class="max-w-full truncate px-2 py-1 border border-secondary rounded-full">
+ <% displayed_action = rule.displayed_action %>
+ <% if displayed_action.nil? %>
+ <%= t("rules.no_action") %>
<% else %>
- <%= displayed_action.executor.label %>
+ <% if displayed_action.value && displayed_action.options %>
+ <%= t(".action_label_to", label: displayed_action.executor.label, value: displayed_action.value_display) %>
+ <% else %>
+ <%= displayed_action.executor.label %>
+ <% end %>
<% end %>
+ </span>
+ <% if rule.actions.size > 1 %>
+ <%= t(".and_more_actions", count: rule.actions.size - 1) %>
<% end %>
- </span>
- <% if rule.actions.size > 1 %>
- <%= t(".and_more_actions", count: rule.actions.size - 1) %>
- <% end %>
- </p>
- </div>
- <div class="flex items-center gap-2 mt-1">
- <div class="flex items-center gap-1 text-secondary w-16 shrink-0">
- <span class="font-mono text-xs">FOR</span>
+ </p>
+ </div>
+ <div class="flex items-center gap-2 mt-1">
+ <div class="flex items-center gap-1 text-secondary w-16 shrink-0">
+ <span class="font-mono text-xs">FOR</span>
+ </div>
+ <p class="flex min-w-0 items-center flex-wrap gap-x-1.5 gap-y-1 m-0">
+ <span class="max-w-full truncate px-2 py-1 border border-secondary rounded-full">
+ <% if rule.effective_date.nil? %>
+ <%= t(".all_past_and_future", resource: rule.resource_type.pluralize) %>
+ <% else %>
+ <%= t(".on_or_after", resource: rule.resource_type.pluralize, date: rule.effective_date.strftime("%b %-d, %Y")) %>
+ <% end %>
+ </span>
+ </p>
</div>
- <p class="flex min-w-0 items-center flex-wrap gap-x-1.5 gap-y-1 m-0">
- <span class="max-w-full truncate px-2 py-1 border border-secondary rounded-full">
- <% if rule.effective_date.nil? %>
- <%= t(".all_past_and_future", resource: rule.resource_type.pluralize) %>
- <% else %>
- <%= t(".on_or_after", resource: rule.resource_type.pluralize, date: rule.effective_date.strftime("%b %-d, %Y")) %>
- <% end %>
- </span>
- </p>
</div>
</div>
<div class="col-start-2 row-start-1 flex items-center gap-4 self-start sm:self-center <%= "sm:row-span-2" if has_title %>">
diff --git a/app/views/rules/index.html.erb b/app/views/rules/index.html.erb
index 09a15d84f6..b77dad1915 100644
--- a/app/views/rules/index.html.erb
+++ b/app/views/rules/index.html.erb
@@ -49,46 +49,51 @@
</div>
<% end %>
<div class="bg-container rounded-xl shadow-border-xs p-4">
- <% if @rules.any? %>
- <div class="bg-container-inset rounded-xl">
- <div class="flex justify-between px-4 py-2 text-xs uppercase">
- <div class="flex items-center gap-1.5 font-medium text-secondary">
- <p><%= t(".rules_heading") %></p>
- <span class="text-subdued">&middot;</span>
- <p><%= @rules.count %></p>
- </div>
- </div>
- <p class="px-4 pb-2 text-sm text-secondary"><%= t(".order_hint") %></p>
- <div class="p-1">
- <div class="flex flex-col bg-container rounded-lg shadow-border-xs divide-y divide-subdued"
- data-controller="sortable-list"
- data-sortable-list-url-value="<%= reorder_rules_path %>"
- data-sortable-list-param-value="rule_ids"
- data-action="dragover->sortable-list#dragOver drop->sortable-list#drop"
- role="list"
- aria-label="<%= t(".rules_heading") %>">
- <% @rules.each do |rule| %>
- <div class="flex items-center"
- data-sortable-list-target="item"
- data-sortable-list-id="<%= rule.id %>"
- draggable="true"
- role="listitem"
- aria-grabbed="false"
- data-action="dragstart->sortable-list#dragStart dragend->sortable-list#dragEnd">
- <%= render DS::Button.new(
- variant: :icon,
- icon: "grip-vertical",
- size: :sm,
- class: "ml-2 shrink-0 cursor-grab active:cursor-grabbing",
- aria_label: t(".reorder_rule", name: rule.name.presence || rule.primary_condition_title),
- data: { action: "touchstart->sortable-list#touchStart touchmove->sortable-list#touchMove touchend->sortable-list#touchEnd touchcancel->sortable-list#touchCancel contextmenu->sortable-list#suppressContextMenu keydown->sortable-list#handleKeyDown" }
- ) %>
- <div class="grow min-w-0">
- <%= render "rule", rule: rule %>
- </div>
- </div>
+ <% if @layout.items.any? %>
+ <%# A refresh (e.g. after a rule's switch saves) morphs the page back to
+ the server's open groups and unfiltered rows; filter() applies the
+ search, filters and stored folds again. %>
+ <div data-controller="rules-filter" data-action="turbo:morph@window->rules-filter#filter">
+ <%= render "rules/filters", list_filter: @list_filter, groups: @layout.groups %>
+
+ <div class="bg-container-inset rounded-xl">
+ <div class="flex justify-between items-center px-4 py-2">
+ <div class="flex items-center gap-1.5 text-xs uppercase font-medium text-secondary">
+ <p><%= t(".rules_heading") %></p>
+ <span class="text-subdued">&middot;</span>
+ <p><%= @rules.size %></p>
+ </div>
+ <% unless Current.user&.guest? %>
+ <%= render DS::Link.new(
+ text: t(".new_group"),
+ variant: "ghost",
+ size: "sm",
+ href: new_rule_group_path,
+ icon: "folder-plus",
+ frame: :modal
+ ) %>
<% end %>
</div>
+ <p class="px-4 pb-2 text-sm text-secondary"><%= t(".order_hint") %></p>
+ <p class="hidden px-4 pb-2 text-sm text-secondary" data-rules-filter-target="dragHint"><%= t(".filters.drag_disabled") %></p>
+ <div class="p-1">
+ <div class="flex flex-col bg-container rounded-lg shadow-border-xs divide-y divide-subdued"
+ data-controller="sortable-list"
+ data-sortable-list-url-value="<%= reorder_rules_path %>"
+ data-sortable-list-param-value="items"
+ data-action="dragover->sortable-list#dragOver drop->sortable-list#drop"
+ role="list"
+ aria-label="<%= t(".rules_heading") %>">
+ <% @layout.items.each do |item| %>
+ <% if item.group? %>
+ <%= render "rules/group", item: item, list_filter: @list_filter %>
+ <% else %>
+ <%= render "rules/list_rule", rule: item.rule, sortable_id: item.key, list_filter: @list_filter, foldable: true %>
+ <% end %>
+ <% end %>
+ </div>
+ <p class="hidden px-4 py-6 text-sm text-center text-secondary" data-rules-filter-target="empty"><%= t(".filters.no_matches") %></p>
+ </div>
</div>
</div>
<% else %>
diff --git a/config/locales/models/rule/de.yml b/config/locales/models/rule/de.yml
index 00d148bb78..494e04d52e 100644
--- a/config/locales/models/rule/de.yml
+++ b/config/locales/models/rule/de.yml
@@ -1,6 +1,10 @@
---
de:
activerecord:
+ attributes:
+ rule:
+ new_rule_group_name: Neue Gruppe
+ rule_group: Gruppe
errors:
models:
rule:
diff --git a/config/locales/models/rule/en.yml b/config/locales/models/rule/en.yml
index 30432251f6..dd2e36a0e8 100644
--- a/config/locales/models/rule/en.yml
+++ b/config/locales/models/rule/en.yml
@@ -1,6 +1,10 @@
---
en:
activerecord:
+ attributes:
+ rule:
+ new_rule_group_name: "New group"
+ rule_group: "Group"
errors:
models:
rule:
diff --git a/config/locales/models/rule_group/de.yml b/config/locales/models/rule_group/de.yml
new file mode 100644
index 0000000000..fd0b51c3e4
--- /dev/null
+++ b/config/locales/models/rule_group/de.yml
@@ -0,0 +1,10 @@
+---
+de:
+ activerecord:
+ models:
+ rule_group:
+ one: Gruppe
+ other: Gruppen
+ attributes:
+ rule_group:
+ name: Name
diff --git a/config/locales/models/rule_group/en.yml b/config/locales/models/rule_group/en.yml
new file mode 100644
index 0000000000..0e8bc04988
--- /dev/null
+++ b/config/locales/models/rule_group/en.yml
@@ -0,0 +1,10 @@
+---
+en:
+ activerecord:
+ models:
+ rule_group:
+ one: "Group"
+ other: "Groups"
+ attributes:
+ rule_group:
+ name: "Name"
diff --git a/config/locales/views/rule_groups/de.yml b/config/locales/views/rule_groups/de.yml
new file mode 100644
index 0000000000..4596326d36
--- /dev/null
+++ b/config/locales/views/rule_groups/de.yml
@@ -0,0 +1,23 @@
+---
+de:
+ rule_groups:
+ new:
+ title: Neue Regelgruppe
+ edit:
+ title: Gruppe „%{name}“ umbenennen
+ form:
+ name_label: Name
+ name_placeholder: z. B. Lebensmittel
+ hint: Gruppen ordnen nur die Regelliste. Die Regeln laufen weiter von oben nach unten.
+ create:
+ success: Gruppe angelegt
+ update:
+ success: Gruppe umbenannt
+ destroy:
+ success: Gruppe gelöscht. Ihre Regeln bleiben ohne Gruppe an ihrer Stelle.
+ activation:
+ activated: Alle Regeln in „%{name}“ sind eingeschaltet
+ deactivated: Alle Regeln in „%{name}“ sind ausgeschaltet
+ partially_switched:
+ one: 1 Regel konnte nicht umgeschaltet werden. Öffne sie, um den Grund zu sehen.
+ other: "%{count} Regeln konnten nicht umgeschaltet werden. Öffne sie, um den Grund zu sehen."
diff --git a/config/locales/views/rule_groups/en.yml b/config/locales/views/rule_groups/en.yml
new file mode 100644
index 0000000000..22b849b09e
--- /dev/null
+++ b/config/locales/views/rule_groups/en.yml
@@ -0,0 +1,23 @@
+---
+en:
+ rule_groups:
+ new:
+ title: New rule group
+ edit:
+ title: Rename group "%{name}"
+ form:
+ name_label: Name
+ name_placeholder: e.g. Groceries
+ hint: Groups only arrange the rules list. Rules still run from top to bottom.
+ create:
+ success: Group created
+ update:
+ success: Group renamed
+ destroy:
+ success: Group deleted. Its rules stay in place without a group.
+ activation:
+ activated: All rules in "%{name}" are on
+ deactivated: All rules in "%{name}" are off
+ partially_switched:
+ one: 1 rule could not be switched. Open it to see why.
+ other: "%{count} rules could not be switched. Open them to see why."
diff --git a/config/locales/views/rules/de.yml b/config/locales/views/rules/de.yml
index e42c5b1055..9089d6d151 100644
--- a/config/locales/views/rules/de.yml
+++ b/config/locales/views/rules/de.yml
@@ -95,6 +95,12 @@ de:
rule_name_placeholder: Gib dieser Regel einen Namen
starting_from: Ab dem
stop_processing_description: Weiter unten stehende Regeln ändern die Transaktionen nicht mehr, die diese Regel trifft.
+ group_label: Gruppe (optional)
+ group_select_label: Gruppe
+ no_group: Keine Gruppe
+ new_group_label: Oder neue Gruppe
+ new_group_placeholder: Name einer neuen Gruppe
+ group_hint: Gruppen ordnen nur die Liste. Eine Regel in einer Gruppe läuft dort, wo die Gruppe in der Liste steht.
stop_processing_label: Danach keine weiteren Regeln anwenden
then: DANN
index:
@@ -103,10 +109,56 @@ de:
new_rule: Neue Regel
no_rules_description: Mit Regeln bearbeitest du Transaktionen und andere Daten automatisch bei jedem Konto-Sync.
no_rules_title: Noch keine Regeln
- order_hint: Regeln laufen von oben nach unten. Setzt eine Regel ein Feld einer Transaktion, ändern weiter unten stehende Regeln dieses Feld nicht mehr. Tags ergänzt jede passende Regel. Ziehe Regeln, um die Reihenfolge zu ändern.
+ order_hint: Regeln laufen von oben nach unten, auch die Regeln in Gruppen. Setzt eine Regel ein Feld einer Transaktion, ändern weiter unten stehende Regeln dieses Feld nicht mehr. Tags ergänzt jede passende Regel. Ziehe Regeln und Gruppen, um die Reihenfolge zu ändern.
+ new_group: Neue Gruppe
+ reorder_group: "Gruppe %{name} verschieben. Mit Enter oder Leertaste greifen, dann mit den Pfeiltasten verschieben."
+ filters:
+ no_matches: Keine Regel passt zur Suche oder zu den Filtern.
+ drag_disabled: Während einer Suche oder eines Filters ist das Sortieren aus. Setze sie zurück, um die Reihenfolge zu ändern.
page_title: Regeln
+ fold_rule: "Regel %{name} ein- oder ausklappen"
reorder_rule: "Regel %{name} verschieben. Mit Enter oder Leertaste greifen, dann mit den Pfeiltasten verschieben."
rules_heading: Regeln
+ filters:
+ search_label: Regeln durchsuchen
+ search_placeholder: Name, Bedingungen und Aktionen durchsuchen
+ reset: Zurücksetzen
+ button: Filter
+ done: Fertig
+ active_label: Aktive Filter
+ remove: "Filter %{filter} entfernen"
+ status:
+ label: Status
+ all: Alle Status
+ active: Aktiv
+ inactive: Inaktiv
+ action_type:
+ label: Aktion
+ all: Alle Aktionen
+ condition_type:
+ label: Bedingung
+ all: Alle Bedingungen
+ account:
+ label: Konto
+ all: Alle Konten
+ group:
+ label: Gruppe
+ all: Alle Gruppen
+ none: Ohne Gruppe
+ group:
+ rules_count:
+ one: 1 Regel
+ other: "%{count} Regeln"
+ inactive_count:
+ one: 1 inaktiv
+ other: "%{count} inaktiv"
+ empty: Noch keine Regeln in dieser Gruppe. Wähle die Gruppe im Formular einer Regel.
+ activate_all: Alle Regeln einschalten
+ deactivate_all: Alle Regeln ausschalten
+ rename: Umbenennen
+ delete: Gruppe löschen
+ delete_confirm_title: Gruppe „%{name}“ löschen?
+ delete_confirm_body: Die Regeln bleiben an ihrer Stelle, nur ohne Gruppe. Keine Regel wird gelöscht.
rule:
action_label_to: "%{label} auf %{value}"
all_past_and_future: Alle bisherigen und künftigen %{resource}
diff --git a/config/locales/views/rules/en.yml b/config/locales/views/rules/en.yml
index 718506fd02..04ea084d49 100644
--- a/config/locales/views/rules/en.yml
+++ b/config/locales/views/rules/en.yml
@@ -15,6 +15,46 @@ en:
classifier_rules:
category_classifier: Category classifier
merchant_matcher: Merchant matcher
+ filters:
+ search_label: Search rules
+ search_placeholder: Search name, conditions and actions
+ reset: Reset
+ button: Filter
+ done: Done
+ active_label: Active filters
+ remove: "Remove filter %{filter}"
+ status:
+ label: Status
+ all: All statuses
+ active: Active
+ inactive: Inactive
+ action_type:
+ label: Action
+ all: All actions
+ condition_type:
+ label: Condition
+ all: All conditions
+ account:
+ label: Account
+ all: All accounts
+ group:
+ label: Group
+ all: All groups
+ none: No group
+ group:
+ rules_count:
+ one: 1 rule
+ other: "%{count} rules"
+ inactive_count:
+ one: 1 inactive
+ other: "%{count} inactive"
+ empty: No rules in this group yet. Choose the group in a rule's form.
+ activate_all: Turn on all rules
+ deactivate_all: Turn off all rules
+ rename: Rename
+ delete: Delete group
+ delete_confirm_title: Delete group "%{name}"?
+ delete_confirm_body: The rules stay where they are, without a group. No rule is deleted.
rule:
edit: Edit
re_apply_rule: Re-apply rule
@@ -42,13 +82,25 @@ en:
then: THEN
stop_processing_label: Stop processing further rules
stop_processing_description: Rules further down the list don't change transactions this rule matches.
+ group_label: Group (optional)
+ group_select_label: Group
+ no_group: No group
+ new_group_label: Or new group
+ new_group_placeholder: Name of a new group
+ group_hint: Groups only arrange the list. A rule in a group runs where the group stands in the list.
index:
page_title: Rules
delete_all_rules: Delete all rules
new_rule: New rule
ai_cost_warning: AI-enabled rule actions will cost money. Be sure to filter as narrowly as possible to avoid unnecessary costs.
rules_heading: Rules
- order_hint: Rules run from top to bottom. Once a rule sets a field on a transaction, rules further down don't change that field. Tags are added by every matching rule. Drag rules to change the order.
+ order_hint: Rules run from top to bottom, including the rules inside groups. Once a rule sets a field on a transaction, rules further down don't change that field. Tags are added by every matching rule. Drag rules and groups to change the order.
+ new_group: New group
+ reorder_group: "Move group %{name}. Press Enter or Space to grab it, then use the arrow keys to move it."
+ filters:
+ no_matches: No rules match the search or filters.
+ drag_disabled: Sorting is off while a search or filter is active. Reset them to change the order.
+ fold_rule: "Fold or unfold rule %{name}"
reorder_rule: "Move rule %{name}. Press Enter or Space to grab it, then use the arrow keys to move it."
no_rules_title: No rules yet
no_rules_description: Set up rules to perform actions to your transactions and other data on every account sync.
diff --git a/config/routes.rb b/config/routes.rb
index 51f65bb72b..5a5422cb81 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -703,6 +703,13 @@ Rails.application.routes.draw do
end
end
+ resources :rule_groups, only: %i[new create edit update destroy] do
+ member do
+ patch :reorder
+ patch :activation
+ end
+ end
+
resources :accounts, only: %i[index new show destroy], shallow: true do
member do
post :sync
diff --git a/db/migrate/20261021090000_create_rule_groups.rb b/db/migrate/20261021090000_create_rule_groups.rb
new file mode 100644
index 0000000000..b5788e94a7
--- /dev/null
+++ b/db/migrate/20261021090000_create_rule_groups.rb
@@ -0,0 +1,17 @@
+class CreateRuleGroups < ActiveRecord::Migration[8.1]
+ def change
+ create_table :rule_groups, id: :uuid do |t|
+ t.references :family, null: false, foreign_key: true, type: :uuid
+ t.string :name, null: false
+ t.integer :position, null: false, default: 0
+ t.timestamps
+ end
+
+ add_index :rule_groups, [ :family_id, :name ], unique: true
+
+ add_reference :rules, :rule_group, type: :uuid, foreign_key: { on_delete: :nullify }
+
+ # The group column of a rule CSV import
+ add_column :import_rows, :rule_group, :string
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 6692a18228..64f77314fc 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1308,6 +1308,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_31_120000) do
t.string "price"
t.string "qty"
t.string "resource_type"
+ t.string "rule_group"
t.integer "source_row_number", null: false
t.string "tags"
t.string "ticker"
@@ -2274,6 +2275,16 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_31_120000) do
t.index ["rule_id"], name: "index_rule_conditions_on_rule_id"
end
+ create_table "rule_groups", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.datetime "created_at", null: false
+ t.uuid "family_id", null: false
+ t.string "name", null: false
+ t.integer "position", default: 0, null: false
+ t.datetime "updated_at", null: false
+ t.index ["family_id", "name"], name: "index_rule_groups_on_family_id_and_name", unique: true
+ t.index ["family_id"], name: "index_rule_groups_on_family_id"
+ end
+
create_table "rule_runs", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
t.datetime "created_at", null: false
t.text "error_message"
@@ -2300,10 +2311,12 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_31_120000) do
t.string "name"
t.integer "position", default: 0, null: false
t.string "resource_type", null: false
+ t.uuid "rule_group_id"
t.boolean "stop_processing", default: false, null: false
t.datetime "updated_at", null: false
t.index ["family_id", "position"], name: "index_rules_on_family_id_and_position"
t.index ["family_id"], name: "index_rules_on_family_id"
+ t.index ["rule_group_id"], name: "index_rules_on_rule_group_id"
end
create_table "securities", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
@@ -3165,8 +3178,10 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_31_120000) do
add_foreign_key "rule_actions", "rules"
add_foreign_key "rule_conditions", "rule_conditions", column: "parent_id"
add_foreign_key "rule_conditions", "rules"
+ add_foreign_key "rule_groups", "families"
add_foreign_key "rule_runs", "rules"
add_foreign_key "rules", "families"
+ add_foreign_key "rules", "rule_groups", on_delete: :nullify
add_foreign_key "security_prices", "securities"
add_foreign_key "security_splits", "securities", on_delete: :cascade
add_foreign_key "sessions", "impersonation_sessions", column: "active_impersonator_session_id", on_delete: :nullify
diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml
index 3ba0091aae..ad18af7167 100644
--- a/docs/api/openapi.yaml
+++ b/docs/api/openapi.yaml
@@ -3769,6 +3769,7 @@ components:
- balances
- recurring_transactions
- rules
+ - rule_groups
- rule_actions
- rule_conditions
- rule_runs
@@ -3846,6 +3847,9 @@ components:
rules:
type: integer
minimum: 0
+ rule_groups:
+ type: integer
+ minimum: 0
rule_actions:
type: integer
minimum: 0
diff --git a/test/controllers/rule_groups_controller_test.rb b/test/controllers/rule_groups_controller_test.rb
new file mode 100644
index 0000000000..b27dc85e05
--- /dev/null
+++ b/test/controllers/rule_groups_controller_test.rb
@@ -0,0 +1,129 @@
+require "test_helper"
+
+class RuleGroupsControllerTest < ActionDispatch::IntegrationTest
+ setup do
+ @user = users(:family_admin)
+ sign_in @user
+ @family = @user.family
+ @group = @family.rule_groups.create!(name: "Food")
+ end
+
+ test "new" do
+ get new_rule_group_url
+ assert_response :success
+ end
+
+ test "creates a group at the end of the list" do
+ assert_difference "RuleGroup.count", 1 do
+ post rule_groups_url, params: { rule_group: { name: "Subscriptions" } }
+ end
+
+ assert_redirected_to rules_url
+ group = @family.rule_groups.find_by!(name: "Subscriptions")
+ assert_equal "group:#{group.id}", Rule::Layout.new(@family).items.last.key
+ end
+
+ test "rejects a duplicate name" do
+ assert_no_difference "RuleGroup.count" do
+ post rule_groups_url, params: { rule_group: { name: "Food" } }
+ end
+
+ assert_redirected_to rules_url
+ assert_match "already been taken", flash[:alert]
+ end
+
+ test "keeps the name when renaming to a taken one" do
+ other = @family.rule_groups.create!(name: "Housing")
+
+ patch rule_group_url(other), params: { rule_group: { name: "Food" } }
+
+ assert_redirected_to rules_url
+ assert_match "already been taken", flash[:alert]
+ assert_equal "Housing", other.reload.name
+ end
+
+ test "renames a group" do
+ patch rule_group_url(@group), params: { rule_group: { name: "Groceries" } }
+
+ assert_redirected_to rules_url
+ assert_equal "Groceries", @group.reload.name
+ end
+
+ test "deletes a group and keeps its rules" do
+ rule = create_rule(group: @group)
+
+ assert_difference "RuleGroup.count", -1 do
+ delete rule_group_url(@group)
+ end
+
+ assert_redirected_to rules_url
+ assert_nil rule.reload.rule_group_id
+ end
+
+ test "reorders the rules of a group" do
+ first = create_rule(group: @group)
+ second = create_rule(group: @group)
+
+ patch reorder_rule_group_url(@group), params: { rule_ids: [ second.id, first.id ] }, as: :json
+
+ assert_response :no_content
+ assert_equal [ second, first ], @family.rules.where(rule_group: @group).ordered.to_a
+ end
+
+ test "reorder rejects rules outside the group" do
+ first = create_rule(group: @group)
+ outside = create_rule
+
+ patch reorder_rule_group_url(@group), params: { rule_ids: [ first.id, outside.id ] }, as: :json
+
+ assert_response :unprocessable_entity
+ end
+
+ test "switches all rules of a group on and off" do
+ rule = create_rule(group: @group, active: false)
+
+ patch activation_rule_group_url(@group, active: true)
+ assert_redirected_to rules_url
+ assert rule.reload.active?
+
+ patch activation_rule_group_url(@group, active: false)
+ assert_not rule.reload.active?
+ end
+
+ test "groups of another family are not found" do
+ foreign = families(:empty).rule_groups.create!(name: "Foreign")
+
+ patch rule_group_url(foreign), params: { rule_group: { name: "Taken" } }
+ assert_response :not_found
+
+ patch activation_rule_group_url(foreign, active: true)
+ assert_response :not_found
+
+ get edit_rule_group_url(foreign)
+ assert_response :not_found
+
+ patch reorder_rule_group_url(foreign), params: { rule_ids: [] }, as: :json
+ assert_response :not_found
+
+ delete rule_group_url(foreign)
+ assert_response :not_found
+ assert_equal "Foreign", foreign.reload.name
+ end
+
+ test "guests cannot change groups" do
+ sign_in family_guest
+
+ assert_no_difference "RuleGroup.count" do
+ post rule_groups_url, params: { rule_group: { name: "Guest group" } }
+ end
+ patch activation_rule_group_url(@group, active: true)
+
+ assert_redirected_to accounts_url
+ end
+
+ private
+ def create_rule(group: nil, active: true)
+ @family.rules.create!(resource_type: "transaction", active: active, rule_group: group,
+ actions: [ Rule::Action.new(action_type: "exclude_transaction") ])
+ end
+end
diff --git a/test/controllers/rules_controller_test.rb b/test/controllers/rules_controller_test.rb
index 260f856d6e..fd18317c9f 100644
--- a/test/controllers/rules_controller_test.rb
+++ b/test/controllers/rules_controller_test.rb
@@ -310,13 +310,84 @@ class RulesControllerTest < ActionDispatch::IntegrationTest
family = @user.family
newest = family.rules.create!(resource_type: "transaction",
actions: [ Rule::Action.new(action_type: "exclude_transaction") ])
- ordered_ids = [ newest.id ] + (family.rules.ordered.pluck(:id) - [ newest.id ])
- Rule.update_positions!(family, ordered_ids)
+ ordered_keys = [ "rule:#{newest.id}" ] + (family.rules.ordered.pluck(:id) - [ newest.id ]).map { |id| "rule:#{id}" }
+ Rule::Layout.new(family).reorder!(ordered_keys)
get rules_url
assert_response :success
- assert_equal ordered_ids, css_select("[data-sortable-list-target='item']").map { |item| item["data-sortable-list-id"] }
+ assert_equal ordered_keys, css_select("[data-sortable-list-target='item']").map { |item| item["data-sortable-list-id"] }
+ end
+
+ test "index shows groups with their rules in run order" do
+ family = @user.family
+ group = family.rule_groups.create!(name: "Groceries")
+ grouped = family.rules.create!(resource_type: "transaction", name: "Grouped rule", rule_group: group,
+ actions: [ Rule::Action.new(action_type: "exclude_transaction") ])
+
+ get rules_url
+
+ assert_response :success
+ assert_select "[data-sortable-list-id='group:#{group.id}']" do
+ assert_select "[data-sortable-list-id='#{grouped.id}'][data-rule-group='#{group.id}']"
+ end
+ assert_select "input[type='radio'][name='group'][value='#{group.id}'][data-filter-label='Groceries']"
+ end
+
+ test "index keeps the filters of the URL and ignores values it does not offer" do
+ get rules_url(q: "rent", status: "inactive")
+
+ assert_response :success
+ assert_select "input[name='q'][value='rent']"
+ assert_select "input[type='radio'][name='status'][value='inactive'][checked]"
+ assert_select "label[for='rule_filter_status_inactive']", text: "Inactive"
+ assert_select "[data-rules-filter-target='badge'][data-filter-param='status']:not(.hidden) [data-badge-value]", text: "Inactive"
+
+ get rules_url(status: "bogus")
+
+ assert_select "input[type='radio'][name='status'][value=''][checked]"
+ assert_select "input[type='radio'][name='status'][checked]", count: 1
+ assert_select "[data-rules-filter-target='badges'].hidden"
+ end
+
+ test "index renders search and filter data for each rule" do
+ family = @user.family
+ category = family.categories.first
+ 3.times do |index|
+ family.rules.create!(resource_type: "transaction", name: "Rule #{index}",
+ conditions: [ Rule::Condition.new(condition_type: "transaction_category", operator: "=", value: category.id) ],
+ actions: [ Rule::Action.new(action_type: "set_transaction_category", value: category.id) ])
+ end
+
+ get rules_url
+
+ assert_response :success
+ assert_select "[data-rule-search*='#{category.name}']", minimum: 3
+ assert_select "input[type='radio'][name='action_type'][value='set_transaction_category'][data-filter-param='action_type']"
+ assert_select "[data-rules-filter-target='badge'][data-filter-param='action_type']"
+ end
+
+ test "index runs the same number of queries for more rules" do
+ family = @user.family
+ category = family.categories.first
+ add_rule = lambda do |index|
+ family.rules.create!(resource_type: "transaction", name: "Rule #{index}",
+ conditions: [ Rule::Condition.new(condition_type: "transaction_category", operator: "=", value: category.id) ],
+ actions: [ Rule::Action.new(action_type: "set_transaction_category", value: category.id), Rule::Action.new(action_type: "exclude_transaction") ])
+ end
+ count_queries = lambda do
+ count = 0
+ counter = ->(*, payload) { count += 1 unless payload[:name] == "SCHEMA" || payload[:sql].match?(/SAVEPOINT|BEGIN|COMMIT/) }
+ ActiveSupport::Notifications.subscribed(counter, "sql.active_record") { get rules_url }
+ count
+ end
+
+ add_rule.call(1)
+ get rules_url
+ few = count_queries.call
+ 3.times { |index| add_rule.call(index + 2) }
+
+ assert_equal few, count_queries.call
end
test "index runs the same number of queries however many rules it lists" do
@@ -347,7 +418,7 @@ class RulesControllerTest < ActionDispatch::IntegrationTest
actions: [ Rule::Action.new(action_type: "exclude_transaction") ])
ordered_ids = family.rules.ordered.pluck(:id).reverse
- patch reorder_rules_url, params: { rule_ids: ordered_ids }, as: :json
+ patch reorder_rules_url, params: { items: ordered_ids.map { |id| "rule:#{id}" } }, as: :json
assert_response :no_content
assert_equal ordered_ids, family.rules.ordered.pluck(:id)
@@ -360,13 +431,93 @@ class RulesControllerTest < ActionDispatch::IntegrationTest
actions: [ Rule::Action.new(action_type: "exclude_transaction") ])
before = family.rules.ordered.pluck(:id, :position)
- patch reorder_rules_url, params: { rule_ids: family.rules.pluck(:id) + [ other_rule.id ] }, as: :json
+ patch reorder_rules_url, params: { items: (family.rules.pluck(:id) + [ other_rule.id ]).map { |id| "rule:#{id}" } }, as: :json
assert_response :unprocessable_entity
assert_equal before, family.rules.ordered.pluck(:id, :position)
assert_equal 1, other_rule.reload.position
end
+ test "creates a rule in a new group" do
+ assert_difference [ "Rule.count", "RuleGroup.count" ], 1 do
+ post rules_url, params: { rule: {
+ resource_type: "transaction",
+ new_rule_group_name: " Subscriptions ",
+ conditions_attributes: { "0" => { condition_type: "transaction_name", operator: "like", value: "netflix" } },
+ actions_attributes: { "0" => { action_type: "exclude_transaction" } }
+ } }
+ end
+
+ assert_equal "Subscriptions", Rule.order(:created_at).last.rule_group.name
+ end
+
+ test "saves the rule again when its new group's insert hits the unique index" do
+ family = @user.family
+ conflicted = false
+ # Inserts the same group right before the rule's own insert of it, as a
+ # parallel request would. The rollback also removes this row, so the
+ # retry creates the group; with a committed row it finds it instead.
+ RuleGroup.any_instance.stubs(:assign_next_position).with do
+ unless conflicted
+ conflicted = true
+ RuleGroup.insert!({ family_id: family.id, name: "Bills", position: 0 })
+ end
+ true
+ end
+
+ assert_difference "Rule.count", 1 do
+ post rules_url, params: { rule: {
+ resource_type: "transaction",
+ new_rule_group_name: "Bills",
+ conditions_attributes: { "0" => { condition_type: "transaction_name", operator: "like", value: "power" } },
+ actions_attributes: { "0" => { action_type: "exclude_transaction" } }
+ } }
+ end
+
+ assert conflicted
+ assert_equal "Bills", Rule.order(:created_at).last.rule_group.name
+ end
+
+ test "shows the error of an invalid new group name" do
+ rule = rules(:one)
+
+ patch rule_url(rule), params: { rule: { new_rule_group_name: "x" * 101 } }
+
+ assert_response :unprocessable_entity
+ assert_nil rule.reload.rule_group_id
+ assert_match "New group", response.body
+ end
+
+ test "rejects a group id that does not exist" do
+ rule = rules(:one)
+
+ patch rule_url(rule), params: { rule: { rule_group_id: SecureRandom.uuid } }
+
+ assert_response :unprocessable_entity
+ assert_nil rule.reload.rule_group_id
+ end
+
+ test "deleting all rules deletes their groups too" do
+ family = @user.family
+ family.rule_groups.create!(name: "Bills")
+
+ delete destroy_all_rules_url
+
+ assert_redirected_to rules_url
+ assert_empty family.rules.reload
+ assert_empty family.rule_groups.reload
+ end
+
+ test "rejects a group of another family" do
+ rule = rules(:one)
+ foreign_group = families(:empty).rule_groups.create!(name: "Foreign")
+
+ patch rule_url(rule), params: { rule: { rule_group_id: foreign_group.id } }
+
+ assert_response :unprocessable_entity
+ assert_nil rule.reload.rule_group_id
+ end
+
test "can destroy conditions and actions while editing" do
rule = rules(:one)
diff --git a/test/models/demo/generator_test.rb b/test/models/demo/generator_test.rb
index 08857518ae..05d7583819 100644
--- a/test/models/demo/generator_test.rb
+++ b/test/models/demo/generator_test.rb
@@ -12,7 +12,7 @@ class Demo::GeneratorTest < ActiveSupport::TestCase
User.any_instance.stubs(:ai_available?).returns(false)
generator = Demo::Generator.new(seed: 42)
%i[create_realistic_categories! create_realistic_accounts! create_realistic_transactions!
- generate_budget_auto_fill! generate_goals! create_monitoring_api_key!].each do |step|
+ generate_budget_auto_fill! create_sample_rules! generate_goals! create_monitoring_api_key!].each do |step|
generator.stubs(step)
end
@@ -33,7 +33,7 @@ class Demo::GeneratorTest < ActiveSupport::TestCase
User.find_by!(email: "[email protected]").update!(email: "[email protected]")
generator = Demo::Generator.new(seed: 42)
%i[create_realistic_categories! create_realistic_accounts! create_realistic_transactions!
- generate_budget_auto_fill! generate_goals! create_monitoring_api_key!].each do |step|
+ generate_budget_auto_fill! create_sample_rules! generate_goals! create_monitoring_api_key!].each do |step|
generator.stubs(step)
end
@@ -125,6 +125,26 @@ class Demo::GeneratorTest < ActiveSupport::TestCase
assert_equal 1, ApiKey.where(display_key: ApiKey::DEMO_MONITORING_KEY).count
end
+ test "sample rules come in groups and are all switched off" do
+ generator = Demo::Generator.new(seed: 42)
+ generator.send(:create_realistic_categories!, @family)
+ existing_rule_ids = @family.rules.ids
+ generator.send(:create_sample_rules!, @family)
+
+ rules = @family.rules.where.not(id: existing_rule_ids).ordered.includes(:rule_group, :conditions, :actions).to_a
+ assert_equal 5, rules.size
+ assert rules.none?(&:active?), "sample rules must stay off until someone switches them on"
+ assert_equal [ "Groceries", "Subscriptions" ], @family.rule_groups.order(:name).pluck(:name)
+ assert rules.any? { |rule| rule.rule_group.nil? }, "the demo should also show a rule without a group"
+
+ netflix = rules.find { |rule| rule.conditions.first.value == "Netflix" }
+ assert_equal "Subscriptions", netflix.rule_group.name
+ assert_equal @family.categories.find_by!(name: "Entertainment").id, netflix.actions.first.value
+
+ # Each group's rules sit directly below it, in the order the page shows.
+ assert_equal @family.rules.ordered.to_a, Rule::Layout.new(@family).items.flat_map { |item| item.group? ? item.rules : [ item.rule ] }
+ end
+
# Regression for a `rake demo_data:default` crash: the goal-seeding matrix
# linked several active goals to the same account as a 100%-whole-account
# claim each, which violates GoalAccount#whole_account_link_must_be_exclusive
diff --git a/test/models/family/classifier_rules_test.rb b/test/models/family/classifier_rules_test.rb
index bb8b81361e..98415cbcf3 100644
--- a/test/models/family/classifier_rules_test.rb
+++ b/test/models/family/classifier_rules_test.rb
@@ -35,6 +35,22 @@ class Family::ClassifierRulesTest < ActiveSupport::TestCase
assert_operator mine.reload.position, :>, 2
end
+ test "an added rule moves rule groups down with the rules" do
+ loose = name_rule("Loose", "Starbucks", tags: [ @tag ])
+ group = @family.rule_groups.create!(name: "Groceries")
+ grouped = name_rule("Grouped", "Safeway", tags: [ @tag ])
+ grouped.update!(rule_group: group)
+ @family.classifier_rules("bayes_categorize").destroy_all
+
+ @family.add_classifier_rule!("bayes_categorize")
+
+ items = Rule::Layout.new(@family).items
+ assert_equal [ "Category classifier", "Merchant matcher", "Loose", "group:Groceries" ],
+ items.map { |item| item.group? ? "group:#{item.group.name}" : item.rule.name }
+ assert_equal [ grouped ], items.last.rules
+ assert_equal [ "Category classifier", "Merchant matcher", "Loose", "Grouped" ], @family.rules.ordered.map(&:name)
+ end
+
test "the switch is whether the rule is on" do
@family.set_classifier_rule_active!("bayes_categorize", false)
@@ -61,7 +77,7 @@ class Family::ClassifierRulesTest < ActiveSupport::TestCase
train_two_categories
held = uncategorized("Starbucks Coffee")
exception = name_rule("Hold for review", "Starbucks", tags: [ @tag ], stop_processing: true)
- Rule.update_positions!(@family, [ exception.id ] + (@family.rules.ordered.ids - [ exception.id ]))
+ Rule::Layout.new(@family).reorder!([ "rule:#{exception.id}" ] + (@family.rules.ordered.ids - [ exception.id ]).map { |id| "rule:#{id}" })
ApplyRulesJob.perform_now(@family)
diff --git a/test/models/family/data_exporter_test.rb b/test/models/family/data_exporter_test.rb
index 8ed9ea489b..4ca8e6bc63 100644
--- a/test/models/family/data_exporter_test.rb
+++ b/test/models/family/data_exporter_test.rb
@@ -200,7 +200,7 @@ class Family::DataExporterTest < ActiveSupport::TestCase
# Check rules.csv
rules_csv = zip.read("rules.csv")
- assert rules_csv.include?("name,resource_type,active,effective_date,conditions,actions")
+ assert rules_csv.include?("name,resource_type,active,effective_date,conditions,actions,group")
end
end
@@ -447,6 +447,19 @@ class Family::DataExporterTest < ActiveSupport::TestCase
end
end
+ test "exports the rule group name in CSV and NDJSON" do
+ @rule.update!(rule_group: @family.rule_groups.create!(name: "Food"))
+
+ Zip::File.open_buffer(@exporter.generate_export) do |zip|
+ rules_csv = CSV.parse(zip.read("rules.csv"), headers: true)
+ assert_equal "Food", rules_csv.find { |row| row["name"] == "Test Rule" }["group"]
+
+ rule_line = zip.read("all.ndjson").split("\n").map { |line| JSON.parse(line) }
+ .find { |line| line["type"] == "Rule" && line["data"]["name"] == "Test Rule" }
+ assert_equal "Food", rule_line["data"]["group"]
+ end
+ end
+
test "exports rule conditions with proper structure" do
zip_data = @exporter.generate_export
diff --git a/test/models/family/data_importer_test.rb b/test/models/family/data_importer_test.rb
index 1c36ec7611..e590dc5c80 100644
--- a/test/models/family/data_importer_test.rb
+++ b/test/models/family/data_importer_test.rb
@@ -2031,6 +2031,128 @@ class Family::DataImporterTest < ActiveSupport::TestCase
assert_not @family.rules.find_by(name: "Second").stop_processing
end
+ test "imports rule groups by name and keeps each group in one block" do
+ existing = @family.rule_groups.create!(name: "Food")
+ rule_record = ->(name, position, group) do
+ data = {
+ name: name,
+ resource_type: "transaction",
+ active: true,
+ position: position,
+ conditions: [ { condition_type: "transaction_name", operator: "like", value: name } ],
+ actions: [ { action_type: "exclude_transaction" } ]
+ }
+ data[:group] = group unless group == :absent
+ { type: "Rule", version: 1, data: data }
+ end
+ ndjson = build_ndjson([
+ rule_record.call("Loose", 1, nil),
+ rule_record.call("Groceries", 2, "Food"),
+ rule_record.call("Restaurants", 3, "Food"),
+ rule_record.call("Rent", 4, "Housing"),
+ rule_record.call("Old export", 5, :absent)
+ ])
+
+ Family::DataImporter.new(@family, ndjson).import!
+
+ rules = @family.rules.index_by(&:name)
+ assert_nil rules["Loose"].rule_group
+ assert_equal existing, rules["Groceries"].rule_group
+ assert_equal existing, rules["Restaurants"].rule_group
+ assert_equal "Housing", rules["Rent"].rule_group.name
+ assert_nil rules["Old export"].rule_group
+ # Rules joining a group that already exists run where that group stands.
+ assert_equal [ "Groceries", "Restaurants", "Loose", "Rent", "Old export" ], @family.rules.ordered.pluck(:name).last(5)
+ end
+
+ test "session rule reimport keeps the run order of rules leaving a group" do
+ group = @family.rule_groups.create!(name: "Food")
+ build_rule = ->(name) do
+ rule = @family.rules.build(name: name, resource_type: "transaction", active: true, rule_group: group)
+ rule.conditions.build(condition_type: "transaction_name", operator: "like", value: name)
+ rule.actions.build(action_type: "exclude_transaction")
+ rule.tap(&:save!)
+ end
+ first = build_rule.call("First")
+ second = build_rule.call("Second")
+ build_rule.call("Staying")
+
+ session = @family.import_sessions.create!(expected_chunks: 1)
+ { "rule-1" => first, "rule-2" => second }.each do |source_id, rule|
+ session.source_mappings.create!(family: @family, source_type: "Rule", source_id: source_id, target: rule)
+ end
+ rule_record = ->(id, name, position) do
+ {
+ type: "Rule",
+ version: 1,
+ data: {
+ id: id,
+ name: name,
+ resource_type: "transaction",
+ active: true,
+ position: position,
+ group: nil,
+ conditions: [ { condition_type: "transaction_name", operator: "like", value: name } ],
+ actions: [ { action_type: "exclude_transaction" } ]
+ }
+ }
+ end
+ ndjson = build_ndjson([ rule_record.call("rule-1", "First", 1), rule_record.call("rule-2", "Second", 2) ])
+
+ Family::DataImporter.new(@family, ndjson, import_session: session).import!
+
+ assert_nil first.reload.rule_group
+ assert_nil second.reload.rule_group
+ assert_equal [ "Staying", "First", "Second" ], @family.rules.ordered.pluck(:name).last(3)
+ end
+
+ test "session rule reimport keeps the run order of rules leaving a group across chunks" do
+ group = @family.rule_groups.create!(name: "Food")
+ build_rule = ->(name) do
+ rule = @family.rules.build(name: name, resource_type: "transaction", active: true, rule_group: group)
+ rule.conditions.build(condition_type: "transaction_name", operator: "like", value: name)
+ rule.actions.build(action_type: "exclude_transaction")
+ rule.tap(&:save!)
+ end
+ first = build_rule.call("First")
+ second = build_rule.call("Second")
+ third = build_rule.call("Third")
+ build_rule.call("Staying")
+
+ session = @family.import_sessions.create!(expected_chunks: 2)
+ { "rule-1" => first, "rule-2" => second, "rule-3" => third }.each do |source_id, rule|
+ session.source_mappings.create!(family: @family, source_type: "Rule", source_id: source_id, target: rule)
+ end
+ rule_record = ->(id, name, position) do
+ {
+ type: "Rule",
+ version: 1,
+ data: {
+ id: id,
+ name: name,
+ resource_type: "transaction",
+ active: true,
+ position: position,
+ group: nil,
+ conditions: [ { condition_type: "transaction_name", operator: "like", value: name } ],
+ actions: [ { action_type: "exclude_transaction" } ]
+ }
+ }
+ end
+
+ Family::DataImporter.new(@family, build_ndjson([ rule_record.call("rule-1", "First", 1) ]), import_session: session).import!
+ Family::DataImporter.new(
+ @family,
+ build_ndjson([ rule_record.call("rule-2", "Second", 2), rule_record.call("rule-3", "Third", 3) ]),
+ import_session: session
+ ).import!
+
+ assert_nil first.reload.rule_group
+ assert_nil second.reload.rule_group
+ assert_nil third.reload.rule_group
+ assert_equal [ "Staying", "First", "Second", "Third" ], @family.rules.ordered.pluck(:name).last(4)
+ end
+
test "imports rules with conditions and actions" do
ndjson = build_ndjson([
{
diff --git a/test/models/rule/layout_test.rb b/test/models/rule/layout_test.rb
new file mode 100644
index 0000000000..c5a24fa8d9
--- /dev/null
+++ b/test/models/rule/layout_test.rb
@@ -0,0 +1,136 @@
+require "test_helper"
+
+class Rule::LayoutTest < ActiveSupport::TestCase
+ setup do
+ @family = families(:empty)
+ end
+
+ test "lists groups and rules without a group by position" do
+ loose = create_rule("Loose")
+ group = @family.rule_groups.create!(name: "Food")
+ grouped = create_rule("Grouped", group: group)
+ later = create_rule("Later")
+
+ assert_equal [ "rule:#{loose.id}", "group:#{group.id}", "rule:#{later.id}" ], layout.items.map(&:key)
+ assert_equal [ grouped ], layout.items.second.rules
+ end
+
+ test "a rule joining a group runs at the end of that group" do
+ group = @family.rule_groups.create!(name: "Food")
+ first_in_group = create_rule("First in group", group: group)
+ loose = create_rule("Loose")
+ joining = create_rule("Joining")
+
+ joining.update!(rule_group: group)
+
+ assert_equal [ first_in_group, joining, loose ], @family.rules.ordered.to_a
+ assert_equal [ first_in_group, joining ], layout.items.first.rules
+ end
+
+ test "a rule leaving a group stays right below it" do
+ group = @family.rule_groups.create!(name: "Food")
+ staying = create_rule("Staying", group: group)
+ leaving = create_rule("Leaving", group: group)
+ loose = create_rule("Loose")
+
+ leaving.update!(rule_group: nil)
+
+ assert_equal [ "group:#{group.id}", "rule:#{leaving.id}", "rule:#{loose.id}" ], layout.items.map(&:key)
+ assert_equal [ staying, leaving, loose ], @family.rules.ordered.to_a
+ end
+
+ test "placing a rule in a group leaves the items above it alone" do
+ above = create_rule("Above")
+ group = @family.rule_groups.create!(name: "Food")
+ joining = create_rule("Joining")
+
+ assert_no_changes -> { above.reload.position } do
+ joining.update!(rule_group: group)
+ end
+ assert_equal [ "rule:#{above.id}", "group:#{group.id}" ], layout.items.map(&:key)
+ end
+
+ test "reorder! moves a group together with its rules" do
+ loose = create_rule("Loose")
+ group = @family.rule_groups.create!(name: "Food")
+ first_in_group = create_rule("First", group: group)
+ second_in_group = create_rule("Second", group: group)
+
+ layout.reorder!([ "group:#{group.id}", "rule:#{loose.id}" ])
+
+ assert_equal [ first_in_group, second_in_group, loose ], @family.rules.ordered.to_a
+ assert_equal [ "group:#{group.id}", "rule:#{loose.id}" ], layout.items.map(&:key)
+ end
+
+ test "reorder! rejects stale, foreign and duplicate keys" do
+ loose = create_rule("Loose")
+ group = @family.rule_groups.create!(name: "Food")
+ grouped = create_rule("Grouped", group: group)
+ foreign = rules(:one)
+ before = @family.rules.ordered.pluck(:id, :position)
+
+ assert_raises(ArgumentError) { layout.reorder!([ "rule:#{loose.id}" ]) }
+ assert_raises(ArgumentError) { layout.reorder!([ "rule:#{loose.id}", "group:#{group.id}", "rule:#{foreign.id}" ]) }
+ assert_raises(ArgumentError) { layout.reorder!([ "rule:#{loose.id}", "rule:#{loose.id}" ]) }
+ # A rule inside a group is not a top-level item.
+ assert_raises(ArgumentError) { layout.reorder!([ "rule:#{loose.id}", "rule:#{grouped.id}" ]) }
+
+ assert_equal before, @family.rules.ordered.pluck(:id, :position)
+ assert_equal 1, foreign.reload.position
+ end
+
+ test "reorder_group! orders the rules inside a group and keeps its place" do
+ before_group = create_rule("Before")
+ group = @family.rule_groups.create!(name: "Food")
+ first_in_group = create_rule("First", group: group)
+ second_in_group = create_rule("Second", group: group)
+ after_group = create_rule("After")
+
+ layout.reorder_group!(group, [ second_in_group.id, first_in_group.id ])
+
+ assert_equal [ before_group, second_in_group, first_in_group, after_group ], @family.rules.ordered.to_a
+ end
+
+ test "reorder_group! rejects rules outside the group" do
+ group = @family.rule_groups.create!(name: "Food")
+ grouped = create_rule("Grouped", group: group)
+ loose = create_rule("Loose")
+
+ assert_raises(ArgumentError) { layout.reorder_group!(group, [ grouped.id, loose.id ]) }
+ assert_raises(ArgumentError) { layout.reorder_group!(group, []) }
+ end
+
+ test "deleting a group keeps its rules in place without a group" do
+ before_group = create_rule("Before")
+ group = @family.rule_groups.create!(name: "Food")
+ first_in_group = create_rule("First", group: group)
+ second_in_group = create_rule("Second", group: group)
+ after_group = create_rule("After")
+
+ group.destroy!
+
+ assert_equal [ before_group, first_in_group, second_in_group, after_group ], @family.rules.ordered.to_a
+ assert_equal [ before_group, first_in_group, second_in_group, after_group ].map { |rule| "rule:#{rule.id}" }, layout.items.map(&:key)
+ assert_nil first_in_group.reload.rule_group_id
+ end
+
+ test "an empty group keeps its place" do
+ first = create_rule("First")
+ group = @family.rule_groups.create!(name: "Empty")
+ last = create_rule("Last")
+
+ layout.reorder!([ "rule:#{last.id}", "group:#{group.id}", "rule:#{first.id}" ])
+
+ assert_equal [ "rule:#{last.id}", "group:#{group.id}", "rule:#{first.id}" ], layout.items.map(&:key)
+ end
+
+ private
+ def layout
+ Rule::Layout.new(@family)
+ end
+
+ def create_rule(name, group: nil)
+ @family.rules.create!(name: name, resource_type: "transaction", rule_group: group,
+ actions: [ Rule::Action.new(action_type: "exclude_transaction") ])
+ end
+end
diff --git a/test/models/rule/list_filter_test.rb b/test/models/rule/list_filter_test.rb
new file mode 100644
index 0000000000..1000df15d9
--- /dev/null
+++ b/test/models/rule/list_filter_test.rb
@@ -0,0 +1,77 @@
+require "test_helper"
+
+class Rule::ListFilterTest < ActiveSupport::TestCase
+ setup do
+ @family = families(:empty)
+ @account = @family.accounts.create!(name: "Checking", balance: 0, currency: "USD", accountable: Depository.new)
+ @category = @family.categories.create!(name: "Groceries")
+ @merchant = @family.merchants.create!(name: "Corner Shop", type: "FamilyMerchant")
+ @rule = @family.rules.create!(
+ name: "Weekly shop",
+ resource_type: "transaction",
+ conditions: [
+ Rule::Condition.new(condition_type: "transaction_account", operator: "=", value: @account.id),
+ Rule::Condition.new(condition_type: "compound", operator: "or", sub_conditions: [
+ Rule::Condition.new(condition_type: "transaction_merchant", operator: "=", value: @merchant.id),
+ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "market")
+ ])
+ ],
+ actions: [ Rule::Action.new(action_type: "set_transaction_category", value: @category.id) ]
+ )
+ Current.stubs(:user).returns(users(:empty))
+ @filter = Rule::ListFilter.new(@family.rules.includes(:actions, conditions: :sub_conditions))
+ end
+
+ test "search text names the values of conditions and actions, including those in a condition group" do
+ text = @filter.search_text(@rule)
+
+ [ "Weekly shop", "Checking", "Corner Shop", "market", "Groceries" ].each do |part|
+ assert_includes text, part
+ end
+ end
+
+ test "lists the types and accounts a rule uses" do
+ assert_equal [ "set_transaction_category" ], @filter.action_types(@rule)
+ assert_equal %w[transaction_account transaction_merchant transaction_name], @filter.condition_types(@rule).sort
+ assert_equal [ @account.id ], @filter.account_ids(@rule)
+ end
+
+ test "offers only the types and accounts the rules use" do
+ assert_equal [ "set_transaction_category" ], @filter.action_type_options.map(&:last)
+ assert_not_includes @filter.condition_type_options.map(&:last), "transaction_amount"
+ assert_equal [ [ "Checking", @account.id ] ], @filter.account_options
+ end
+
+ test "search text includes the text of a free-text action" do
+ rule = @family.rules.create!(name: "Rename", resource_type: "transaction",
+ actions: [ Rule::Action.new(action_type: "set_transaction_name", value: "Weekly groceries") ])
+
+ assert_includes Rule::ListFilter.new([ rule ]).search_text(rule), "Weekly groceries"
+ end
+
+ test "search text shows a split's summary, not its stored JSON" do
+ rule = @family.rules.create!(name: "Share rent", resource_type: "transaction",
+ actions: [ Rule::Action.new(action_type: "split_transaction", value: {
+ splits: [ { type: "percentage", name: "Mine", share: "50" }, { type: "percentage", name: "Theirs", share: "50" } ]
+ }.to_json) ])
+
+ text = Rule::ListFilter.new([ rule ]).search_text(rule)
+
+ assert_includes text, I18n.t("rules.actions.split.summary", count: 2)
+ assert_not_includes text, "percentage"
+ end
+
+ test "leaves out accounts the user cannot see" do
+ other = @family.users.create!(email: "[email protected]", password: "password123456", first_name: "Other", role: "member")
+ hidden = @family.accounts.create!(name: "Private", balance: 0, currency: "USD", owner: other, accountable: Depository.new)
+ rule = @family.rules.create!(name: "Private rule", resource_type: "transaction",
+ conditions: [ Rule::Condition.new(condition_type: "transaction_account", operator: "=", value: hidden.id) ],
+ actions: [ Rule::Action.new(action_type: "exclude_transaction") ])
+
+ filter = Rule::ListFilter.new(@family.rules.includes(:actions, conditions: :sub_conditions))
+
+ assert_empty filter.account_ids(rule)
+ assert_equal [ @account.id ], filter.account_ids(@rule)
+ assert_equal [ [ "Checking", @account.id ] ], filter.account_options
+ end
+end
diff --git a/test/models/rule/runner_test.rb b/test/models/rule/runner_test.rb
index b80047bb0e..d9ae3f7476 100644
--- a/test/models/rule/runner_test.rb
+++ b/test/models/rule/runner_test.rb
@@ -27,13 +27,30 @@ class Rule::RunnerTest < ActiveSupport::TestCase
test "reordering changes which rule wins" do
top = create_rule("Top", "Whole Foods", category: @groceries)
bottom = create_rule("Bottom", "Whole Foods", category: @dining)
- Rule.update_positions!(@family, [ bottom.id, top.id ])
+ Rule::Layout.new(@family).reorder!([ "rule:#{bottom.id}", "rule:#{top.id}" ])
run_active_rules
assert_equal @dining, @whole_foods.reload.category
end
+ test "rules in a group run where the group stands in the list" do
+ create_rule("Loose", "Whole Foods", category: @groceries)
+ grouped = create_rule("Grouped", "Whole Foods", category: @dining)
+ group = @family.rule_groups.create!(name: "Dining")
+ grouped.update!(rule_group: group)
+
+ run_active_rules
+ assert_equal @groceries, @whole_foods.reload.category
+
+ @whole_foods.update!(category: nil)
+ loose_key = "rule:#{@family.rules.find_by!(name: "Loose").id}"
+ Rule::Layout.new(@family).reorder!([ "group:#{group.id}", loose_key ])
+
+ run_active_rules
+ assert_equal @dining, @whole_foods.reload.category
+ end
+
test "a rule higher up claims the field even when it changes nothing" do
@whole_foods.update!(category: @groceries)
create_rule("Top", "Whole Foods", category: @groceries)
diff --git a/test/models/rule_group_test.rb b/test/models/rule_group_test.rb
new file mode 100644
index 0000000000..811ae95b2e
--- /dev/null
+++ b/test/models/rule_group_test.rb
@@ -0,0 +1,63 @@
+require "test_helper"
+
+class RuleGroupTest < ActiveSupport::TestCase
+ setup do
+ @family = families(:empty)
+ @group = @family.rule_groups.create!(name: "Food")
+ end
+
+ test "names are unique per family and stripped" do
+ assert_not @family.rule_groups.new(name: " Food ").valid?
+ assert families(:dylan_family).rule_groups.new(name: "Food").valid?
+ end
+
+ test "rejects text the database cannot store" do
+ assert_not @family.rule_groups.new(name: "Fo\0od").valid?
+ assert_not @family.rule_groups.new(name: "\xFF".dup.force_encoding("UTF-8")).valid?
+ end
+
+ test "switch_rules switches every rule of the group and only those" do
+ first = create_rule(active: false)
+ second = create_rule(active: false)
+ outside = @family.rules.create!(resource_type: "transaction", active: false,
+ actions: [ Rule::Action.new(action_type: "exclude_transaction") ])
+
+ assert_empty @group.switch_rules(true)
+
+ assert first.reload.active?
+ assert second.reload.active?
+ assert_not outside.reload.active?
+
+ assert_empty @group.switch_rules(false)
+ assert_not first.reload.active?
+ end
+
+ test "switch_rules reports rules kept off because the email baseline timed out" do
+ rule = @family.rules.create!(resource_type: "transaction", active: false, rule_group: @group,
+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "matches_regex", value: "amzn") ],
+ actions: [ Rule::Action.new(action_type: "send_email_notification") ])
+ plain = create_rule(active: false)
+ Rule::SafeRegex.stubs(:with_timeout).raises(Rule::SafeRegex::TimeoutError)
+
+ assert_equal [ rule ], @group.switch_rules(true)
+ assert_not rule.reload.active?
+ assert plain.reload.active?
+ end
+
+ test "find_or_create_named! finds a group another request created meanwhile" do
+ family = families(:empty)
+ existing = family.rule_groups.create!(name: "Bills")
+ # The lookup misses, as if the other request committed right after it.
+ RuleGroup.stubs(:find_by).returns(nil)
+
+ assert_no_difference "RuleGroup.count" do
+ assert_equal existing, family.rule_groups.find_or_create_named!("Bills")
+ end
+ end
+
+ private
+ def create_rule(active:)
+ @family.rules.create!(resource_type: "transaction", active: active, rule_group: @group,
+ actions: [ Rule::Action.new(action_type: "exclude_transaction") ])
+ end
+end
diff --git a/test/models/rule_import_test.rb b/test/models/rule_import_test.rb
index e785354c36..e6be63dd86 100644
--- a/test/models/rule_import_test.rb
+++ b/test/models/rule_import_test.rb
@@ -667,6 +667,65 @@ class RuleImportTest < ActiveSupport::TestCase
assert_equal "ני\"ע-קניה", condition.value
end
+ test "imports the group column and reuses existing groups" do
+ existing = @family.rule_groups.create!(name: "Food")
+ csv = CSV.generate do |out|
+ out << %w[name resource_type active effective_date conditions actions group]
+ out << [ "Grocery rule", "transaction", true, "", [ { condition_type: "transaction_name", operator: "like", value: "grocery" } ].to_json, [ { action_type: "set_transaction_category", value: "Groceries" } ].to_json, "Food" ]
+ out << [ "Rent rule", "transaction", true, "", [ { condition_type: "transaction_name", operator: "like", value: "rent" } ].to_json, [ { action_type: "exclude_transaction" } ].to_json, "Housing" ]
+ out << [ "Loose rule", "transaction", true, "", [ { condition_type: "transaction_name", operator: "like", value: "misc" } ].to_json, [ { action_type: "exclude_transaction" } ].to_json, "" ]
+ end
+
+ import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
+ import.generate_rows_from_csv
+
+ assert_difference -> { @family.rule_groups.count }, 1 do
+ import.send(:import!)
+ end
+
+ assert_equal existing, @family.rules.find_by!(name: "Grocery rule").rule_group
+ assert_equal "Housing", @family.rules.find_by!(name: "Rent rule").rule_group.name
+ assert_nil @family.rules.find_by!(name: "Loose rule").rule_group
+ assert_equal [ { condition_type: "transaction_name", operator: "like", value: "rent" }.stringify_keys ],
+ @family.rules.find_by!(name: "Rent rule").conditions.map { |condition| condition.slice(:condition_type, :operator, :value) }
+ end
+
+ test "reads the group of a row whose JSON was split into extra fields" do
+ headers = %w[name resource_type active effective_date conditions actions group]
+ # CSV pads the headers with nil for fields beyond the named columns.
+ row = CSV::Row.new(headers + [ nil ], [ "Split rule", "transaction", "true", nil, '[{"a":1}', '{"b":2}]', "[]", "Food" ])
+
+ normalized = RuleImport.new.send(:normalize_rule_row, row)
+
+ assert_equal "Food", normalized[:rule_group]
+ assert_equal "Split rule", normalized[:name]
+ end
+
+ test "reads the group when the header row has a blank cell" do
+ conditions = [ { condition_type: "transaction_name", operator: "like", value: "rent" } ].to_json
+ actions = [ { action_type: "exclude_transaction" } ].to_json
+ csv = "name,resource_type,active,effective_date,conditions,actions,group,\n" +
+ CSV.generate_line([ "Rent rule", "transaction", "true", "", conditions, actions, "Housing" ])
+
+ import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
+ import.generate_rows_from_csv
+ import.send(:import!)
+
+ assert_equal "Housing", @family.rules.find_by!(name: "Rent rule").rule_group&.name
+ end
+
+ test "a file without the group column keeps the group of an updated rule" do
+ group = @family.rule_groups.create!(name: "Food")
+ @family.rules.create!(name: "Categorize groceries", resource_type: "transaction", rule_group: group,
+ actions: [ Rule::Action.new(action_type: "exclude_transaction") ])
+
+ import = @family.imports.create!(type: "RuleImport", raw_file_str: @csv, col_sep: ",")
+ import.generate_rows_from_csv
+ import.send(:import!)
+
+ assert_equal group, @family.rules.find_by!(name: "Categorize groceries").rule_group
+ end
+
test "imports wrapped JSON payloads from legacy rows" do
wrapped_conditions = [ { condition_type: "transaction_name", operator: "like", value: "legacy grocery" } ].to_json.to_json
wrapped_actions = [ { action_type: "set_transaction_category", value: "Groceries" } ].to_json.to_json
diff --git a/test/models/rule_test.rb b/test/models/rule_test.rb
index 55721be837..5f6dc00ef4 100644
--- a/test/models/rule_test.rb
+++ b/test/models/rule_test.rb
@@ -580,25 +580,12 @@ class RuleTest < ActiveSupport::TestCase
assert_equal [ first, second ], @family.rules.ordered.to_a
end
- test "update_positions! sets the order of all rules of the family" do
+ test "new rules come after existing rule groups" do
first = create_exclude_rule
- second = create_exclude_rule
-
- Rule.update_positions!(@family, [ second.id, first.id ])
-
- assert_equal [ second, first ], @family.rules.ordered.to_a
- end
+ group = @family.rule_groups.create!(name: "Later")
- test "update_positions! rejects foreign and incomplete id lists" do
- first = create_exclude_rule
- second = create_exclude_rule
- foreign = rules(:one)
-
- assert_raises(ArgumentError) { Rule.update_positions!(@family, [ first.id, second.id, foreign.id ]) }
- assert_raises(ArgumentError) { Rule.update_positions!(@family, [ first.id ]) }
- assert_raises(ArgumentError) { Rule.update_positions!(@family, [ first.id, first.id ]) }
- assert_equal 1, foreign.reload.position
- assert_equal [ first, second ], @family.rules.ordered.to_a
+ assert_operator group.position, :>, first.position
+ assert_operator create_exclude_rule.position, :>, group.position
end
private
diff --git a/test/system/rules_test.rb b/test/system/rules_test.rb
index e87fcebfe9..73e8798124 100644
--- a/test/system/rules_test.rb
+++ b/test/system/rules_test.rb
@@ -45,12 +45,12 @@ class RulesTest < ApplicationSystemTestCase
visit rules_path
- grip = find("[data-sortable-list-id='#{first.id}'] button[data-action*='handleKeyDown']")
+ grip = find("[data-sortable-list-id='rule:#{first.id}'] button[data-action*='handleKeyDown']")
grip.send_keys(:enter)
grip.send_keys(:arrow_down)
grip.send_keys(:enter)
- assert_selector "[data-sortable-list-target='item']:first-child[data-sortable-list-id='#{second.id}']"
+ assert_selector "[data-sortable-list-target='item']:first-child[data-sortable-list-id='rule:#{second.id}']"
# The order is saved by a fetch Capybara cannot wait on, so poll for it.
deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + Capybara.default_max_wait_time
sleep 0.05 until family.rules.ordered.pluck(:id) == [ second.id, first.id ] ||
@@ -185,6 +185,137 @@ class RulesTest < ApplicationSystemTestCase
assert rule.actions.first.value.present?
end
+ test "moves a group with its rules and the rules inside it with the keyboard" do
+ family = @user.family
+ family.rules.destroy_all
+ loose = create_exclude_rule("Loose rule")
+ group = family.rule_groups.create!(name: "Food")
+ first_in_group = create_exclude_rule("First in group", group: group)
+ second_in_group = create_exclude_rule("Second in group", group: group)
+
+ visit rules_path
+
+ group_grip = find("[data-sortable-list-id='group:#{group.id}'] summary button[data-action*='handleKeyDown']")
+ group_grip.send_keys(:enter)
+ group_grip.send_keys(:arrow_up)
+ group_grip.send_keys(:enter)
+ wait_for_order(family, [ first_in_group.id, second_in_group.id, loose.id ])
+
+ rule_grip = find("[data-sortable-list-id='#{second_in_group.id}'] button[data-action*='handleKeyDown']")
+ rule_grip.send_keys(:enter)
+ rule_grip.send_keys(:arrow_up)
+ rule_grip.send_keys(:enter)
+ wait_for_order(family, [ second_in_group.id, first_in_group.id, loose.id ])
+ end
+
+ test "drags a group past a rule and a rule inside its group with the mouse" do
+ family = @user.family
+ family.rules.destroy_all
+ group = family.rule_groups.create!(name: "Food")
+ first_in_group = create_exclude_rule("First in group", group: group)
+ second_in_group = create_exclude_rule("Second in group", group: group)
+ loose = create_exclude_rule("Loose rule")
+
+ visit rules_path
+
+ drag("[data-sortable-list-id='group:#{group.id}']", onto: "[data-sortable-list-id='rule:#{loose.id}']", side: :bottom)
+ wait_for_order(family, [ loose.id, first_in_group.id, second_in_group.id ])
+
+ # The drag starts on a rule of the nested list; only that list moves it.
+ drag("[data-sortable-list-id='#{second_in_group.id}']", onto: "[data-sortable-list-id='#{first_in_group.id}']", side: :top)
+ wait_for_order(family, [ loose.id, second_in_group.id, first_in_group.id ])
+ end
+
+ test "searches and filters rules and turns sorting off meanwhile" do
+ family = @user.family
+ family.rules.destroy_all
+ group = family.rule_groups.create!(name: "Housing")
+ groceries = create_exclude_rule("Groceries", active: false)
+ rent = create_exclude_rule("Rent", group: group)
+
+ visit rules_path
+ find("input[type='search']").fill_in(with: "rent")
+
+ assert_selector "[data-sortable-list-id='#{rent.id}']"
+ assert_no_selector "[data-sortable-list-id='rule:#{groceries.id}']"
+ assert_text "Sorting is off while a search or filter is active"
+ assert_selector "[data-sortable-list-id='#{rent.id}'][draggable='false'] button[data-action*='handleKeyDown']:disabled", visible: :all
+ assert_current_path(/q=rent/)
+
+ click_on "Filter"
+ click_on "Reset"
+ assert_no_current_path(/q=rent/)
+ click_on "Filter"
+ within("#rule-filters-menu") do
+ click_on "Status"
+ choose "Inactive"
+ click_on "Done"
+ end
+
+ assert_selector "[data-sortable-list-id='rule:#{groceries.id}']"
+ assert_no_selector "[data-sortable-list-id='group:#{group.id}']"
+ assert_current_path(/status=inactive/)
+
+ within("[data-rules-filter-target='badge'][data-filter-param='status']") do
+ assert_text(/Status:\s+Inactive/)
+ find("button[aria-label='Remove filter Status']").click
+ end
+
+ assert_selector "[data-sortable-list-id='group:#{group.id}']"
+ assert_no_current_path(/status=/)
+ end
+
+ test "folds a group and keeps it folded after a reload" do
+ family = @user.family
+ group = family.rule_groups.create!(name: "Food")
+ rule = create_exclude_rule("Folded rule", group: group)
+
+ visit rules_path
+ find("[data-sortable-list-id='group:#{group.id}'] [data-rules-group-header]").click
+
+ assert_no_selector "[data-sortable-list-id='#{rule.id}']"
+ visit rules_path
+ assert_selector "[data-sortable-list-id='group:#{group.id}'] details:not([open])"
+ assert_no_selector "[data-sortable-list-id='#{rule.id}']"
+ end
+
+ test "keeps a folded group folded when switching another rule refreshes the page" do
+ group = @user.family.rule_groups.create!(name: "Food")
+ folded = create_exclude_rule("Folded rule", group: group)
+ loose = create_exclude_rule("Loose rule")
+
+ visit rules_path
+ find("[data-sortable-list-id='group:#{group.id}'] [data-rules-group-header]").click
+ assert_no_selector "[data-sortable-list-id='#{folded.id}']"
+
+ # The switch saves the rule and refreshes the page with a morph.
+ find("##{ActionView::RecordIdentifier.dom_id(loose)} input[type='checkbox'][name='rule[active]']", visible: :all).execute_script("this.click()")
+ assert_text "Rule updated"
+
+ assert_selector "[data-sortable-list-id='group:#{group.id}'] details:not([open])"
+ assert_no_selector "[data-sortable-list-id='#{folded.id}']"
+ visit rules_path
+ assert_selector "[data-sortable-list-id='group:#{group.id}'] details:not([open])"
+ end
+
+ test "folds a rule outside a group to its title and keeps it folded after a reload" do
+ rule = create_exclude_rule("Loose rule")
+
+ visit rules_path
+ within("[data-sortable-list-id='rule:#{rule.id}']") do
+ assert_text "THEN"
+ find("button[aria-controls='#{ActionView::RecordIdentifier.dom_id(rule, :details)}']").click
+ assert_text "Loose rule"
+ assert_no_text "THEN"
+ end
+
+ visit rules_path
+ within("[data-sortable-list-id='rule:#{rule.id}']") do
+ assert_selector "button[aria-expanded='false']"
+ assert_no_text "THEN"
+ end
+ end
+
test "keeps a rule with long text inside a phone-width screen" do
@user.family.rules.destroy_all
rule = @user.family.rules.create!(
@@ -202,6 +333,10 @@ class RulesTest < ApplicationSystemTestCase
visit rules_path
row = find("##{ActionView::RecordIdentifier.dom_id(rule)}")
+ # Search, filters and the group controls sit above the list and push the
+ # row below the fold of a phone screen, where Selenium does not count it
+ # as visible.
+ scroll_to(row)
viewport_width = page.evaluate_script("document.documentElement.clientWidth")
row_right = row.native.rect.x + row.native.rect.width
@@ -222,4 +357,37 @@ class RulesTest < ApplicationSystemTestCase
new_rule = find("a", text: I18n.t("rules.index.new_rule"))
assert_operator new_rule.native.rect.x + new_rule.native.rect.width, :<=, viewport_width
end
+
+ private
+ def create_exclude_rule(name, group: nil, active: true)
+ @user.family.rules.create!(name: name, resource_type: "transaction", rule_group: group, active: active,
+ actions: [ Rule::Action.new(action_type: "exclude_transaction") ])
+ end
+
+ # Selenium cannot drive native HTML drag and drop, so the drag events are
+ # dispatched with the pointer near the top or bottom edge of the target.
+ def drag(source, onto:, side:)
+ page.execute_script(<<~JS, source, onto, side.to_s)
+ const [sourceSelector, targetSelector, side] = arguments;
+ const source = document.querySelector(sourceSelector);
+ const target = document.querySelector(targetSelector);
+ const box = target.getBoundingClientRect();
+ const pointer = { clientX: box.left + box.width / 2, clientY: side === "top" ? box.top + 2 : box.bottom - 2 };
+ const dataTransfer = new DataTransfer();
+ const fire = (element, type, extra = {}) =>
+ element.dispatchEvent(new DragEvent(type, { bubbles: true, cancelable: true, dataTransfer, ...extra }));
+ fire(source, "dragstart");
+ fire(target, "dragover", pointer);
+ fire(target, "drop", pointer);
+ fire(source, "dragend");
+ JS
+ end
+
+ # The order is saved by a fetch Capybara cannot wait on, so poll for it.
+ def wait_for_order(family, ids)
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + Capybara.default_max_wait_time
+ sleep 0.05 until family.rules.ordered.pluck(:id) == ids ||
+ Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline
+ assert_equal ids, family.rules.ordered.pluck(:id)
+ end
end