Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat(rules): run rules in a fixed order with "stop processing" (#4013)

GFR92d8ee524890
diff --git a/app/controllers/rules_controller.rb b/app/controllers/rules_controller.rb
index 1787782922..b60a93a806 100644
--- a/app/controllers/rules_controller.rb
+++ b/app/controllers/rules_controller.rb
@@ -5,14 +5,7 @@ class RulesController < ApplicationController
before_action :set_rule, only: [ :edit, :update, :destroy, :apply, :confirm ]
def index
- @sort_by = params[:sort_by] || "name"
- @direction = params[:direction] || "asc"
-
- allowed_columns = [ "name", "updated_at" ]
- @sort_by = "name" unless allowed_columns.include?(@sort_by)
- @direction = "asc" unless [ "asc", "desc" ].include?(@direction)
-
- @rules = Current.family.rules.includes(conditions: :sub_conditions).order(@sort_by => @direction)
+ @rules = Current.family.rules.includes(conditions: :sub_conditions).ordered
# Fetch recent rule runs with pagination
recent_runs_scope = RuleRun
@@ -65,6 +58,7 @@ class RulesController < ApplicationController
end
def confirm
+ @active_rules_above_count = @rule.active_rules_above.count
# Compute provider, model, and cost estimation for auto-categorize actions
if @rule.actions.any? { |a| a.action_type == "auto_categorize" }
@selected_model, @estimated_cost = auto_categorize_estimate(@rule)
@@ -90,6 +84,13 @@ class RulesController < ApplicationController
redirect_to rules_path, notice: t(".success")
end
+ def reorder
+ Rule.update_positions!(Current.family, params.require(:rule_ids))
+ head :no_content
+ rescue ArgumentError
+ head :unprocessable_entity
+ end
+
def destroy_all
Current.family.rules.destroy_all
redirect_to rules_path, notice: t(".success")
@@ -210,7 +211,7 @@ class RulesController < ApplicationController
def rule_params
params.require(:rule).permit(
- :resource_type, :effective_date, :active, :name,
+ :resource_type, :effective_date, :active, :name, :stop_processing,
conditions_attributes: [
:id, :condition_type, :operator, :value, :_destroy,
sub_conditions_attributes: [ :id, :condition_type, :operator, :value, :_destroy ]
diff --git a/app/javascript/controllers/reports_sortable_controller.js b/app/javascript/controllers/sortable_list_controller.js
similarity index 74%
rename from app/javascript/controllers/reports_sortable_controller.js
rename to app/javascript/controllers/sortable_list_controller.js
index 1bb0a2a46b..fd0afd38ca 100644
--- a/app/javascript/controllers/reports_sortable_controller.js
+++ b/app/javascript/controllers/sortable_list_controller.js
@@ -1,11 +1,20 @@
import { Controller } from "@hotwired/stimulus";
+// Reorderable list with mouse, touch (hold on the handle) and keyboard
+// (Enter/Space to grab, arrow keys to move, release to save). Each item needs
+// 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: [...] } }).
export default class extends Controller {
- static targets = ["section", "handle"];
+ static targets = ["item", "handle"];
- // Hold delay to require deliberate press-and-hold before activating drag mode
+ // Hold delay to require deliberate press-and-hold before activating drag mode.
+ // Lists whose whole item reacts to touch (not just a small grip) should raise
+ // it so a normal scroll does not start a drag.
static values = {
- holdDelay: { type: Number, default: 800 },
+ url: String,
+ param: String,
+ holdDelay: { type: Number, default: 150 },
};
connect() {
@@ -80,9 +89,9 @@ export default class extends Controller {
// (finger moves before the hold delay elapses) cancels it.
touchStart(event) {
- // Find the parent section element from the handle
+ // Find the parent item element from the handle
const section = event.currentTarget.closest(
- "[data-reports-sortable-target='section']",
+ "[data-sortable-list-target='item']",
);
if (!section) return;
@@ -218,8 +227,14 @@ export default class extends Controller {
}
// ===== Keyboard Navigation =====
+ // 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;
+ const currentSection = event.currentTarget.closest(
+ "[data-sortable-list-target='item']",
+ );
+ if (!currentSection) return;
+ this.keyboardFocusElement = event.currentTarget;
switch (event.key) {
case "ArrowUp":
@@ -288,23 +303,23 @@ export default class extends Controller {
moveUp(section) {
const previousSibling = section.previousElementSibling;
- if (previousSibling?.hasAttribute("data-section-key")) {
+ if (previousSibling && this.itemTargets.includes(previousSibling)) {
this.element.insertBefore(section, previousSibling);
- section.focus();
+ this.keyboardFocusElement?.focus();
}
}
moveDown(section) {
const nextSibling = section.nextElementSibling;
- if (nextSibling?.hasAttribute("data-section-key")) {
+ if (nextSibling && this.itemTargets.includes(nextSibling)) {
this.element.insertBefore(nextSibling, section);
- section.focus();
+ this.keyboardFocusElement?.focus();
}
}
getDragAfterElement(y) {
const draggableElements = [
- ...this.sectionTargets.filter((section) => section !== this.draggedElement),
+ ...this.itemTargets.filter((section) => section !== this.draggedElement),
];
return draggableElements.reduce(
@@ -332,7 +347,7 @@ export default class extends Controller {
}
clearPlaceholders() {
- this.sectionTargets.forEach((section) => {
+ this.itemTargets.forEach((section) => {
section.classList.remove(
"border-t-4",
"border-b-4",
@@ -343,43 +358,66 @@ export default class extends Controller {
});
}
- async saveOrder() {
- const order = this.sectionTargets.map(
- (section) => section.dataset.sectionKey,
+ buildBody(order) {
+ return this.paramValue
+ .split(".")
+ .reduceRight((value, key) => ({ [key]: value }), order);
+ }
+
+ // Saves run one at a time. A change made while a save is in flight is sent
+ // once it finishes, with the latest order only, so an older request can
+ // never land after a newer one and restore an earlier order.
+ saveOrder() {
+ this.pendingOrder = this.itemTargets.map(
+ (item) => item.dataset.sortableListId,
);
+ if (!this.saving) this.flushSaves();
+ }
- // Safely obtain CSRF token
- const csrfToken = document.querySelector('meta[name="csrf-token"]');
- if (!csrfToken) {
- console.error(
- "[Reports Sortable] CSRF token not found. Cannot save section order.",
- );
- return;
+ async flushSaves() {
+ this.saving = true;
+ while (this.pendingOrder) {
+ const order = this.pendingOrder;
+ this.pendingOrder = null;
+ await this.sendOrder(order);
}
+ this.saving = false;
+ }
+
+ async sendOrder(order) {
+ // The meta tag is missing when forgery protection is off (e.g. in tests);
+ // the server still rejects requests without a valid token when it is on.
+ const csrfToken = document.querySelector(
+ 'meta[name="csrf-token"]',
+ )?.content;
+ const headers = { "Content-Type": "application/json" };
+ if (csrfToken) headers["X-CSRF-Token"] = csrfToken;
try {
- const response = await fetch("/reports/update_preferences", {
+ const response = await fetch(this.urlValue, {
method: "PATCH",
- headers: {
- "Content-Type": "application/json",
- "X-CSRF-Token": csrfToken.content,
- },
- body: JSON.stringify({ preferences: { reports_section_order: order } }),
+ headers,
+ body: JSON.stringify(this.buildBody(order)),
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
console.error(
- "[Reports Sortable] Failed to save section order:",
+ "[Sortable List] Failed to save order:",
response.status,
errorData,
);
+ // Show the order that is actually saved instead of the unsaved one,
+ // e.g. when the list changed in another tab.
+ this.pendingOrder = null;
+ Turbo.visit(window.location.href, { action: "replace" });
}
} catch (error) {
- console.error(
- "[Reports Sortable] Network error saving section order:",
- error,
- );
+ console.error("[Sortable List] Network error saving order:", error);
+ // A newer order still gets sent; otherwise show what is actually saved.
+ if (!this.pendingOrder) {
+ Turbo.visit(window.location.href, { action: "replace" });
+ }
}
}
}
diff --git a/app/jobs/apply_all_rules_job.rb b/app/jobs/apply_all_rules_job.rb
index f14da70913..c5658d56ed 100644
--- a/app/jobs/apply_all_rules_job.rb
+++ b/app/jobs/apply_all_rules_job.rb
@@ -1,9 +1,14 @@
class ApplyAllRulesJob < ApplicationJob
queue_as :medium_priority
+ retry_on Rule::Runner::LockBusy, wait: 30.seconds, attempts: 20
+
def perform(family, execution_type: "manual")
- family.rules.find_each do |rule|
- RuleJob.perform_now(rule, ignore_attribute_locks: true, execution_type: execution_type)
- end
+ Rule::Runner.new(
+ family,
+ rules: family.rules,
+ execution_type: execution_type,
+ ignore_attribute_locks: true
+ ).run
end
end
diff --git a/app/jobs/apply_rules_job.rb b/app/jobs/apply_rules_job.rb
new file mode 100644
index 0000000000..0d64356a8a
--- /dev/null
+++ b/app/jobs/apply_rules_job.rb
@@ -0,0 +1,16 @@
+# Applies all active rules of a family in order after a sync.
+class ApplyRulesJob < ApplicationJob
+ queue_as :medium_priority
+
+ retry_on Rule::Runner::LockBusy, wait: 30.seconds, attempts: 20
+
+ # A failing rule is recorded as a failed RuleRun and the remaining rules still
+ # run. The job itself does not fail, because a retry would re-run every rule.
+ def perform(family, execution_type: "scheduled")
+ Rule::Runner.new(
+ family,
+ rules: family.rules.where(active: true),
+ execution_type: execution_type
+ ).run
+ end
+end
diff --git a/app/jobs/rule_job.rb b/app/jobs/rule_job.rb
index c70c79fa99..a8968e4cde 100644
--- a/app/jobs/rule_job.rb
+++ b/app/jobs/rule_job.rb
@@ -1,93 +1,22 @@
+# Applies a single rule ("Apply rule" in the UI). The active rules above it run
+# first, so the result is the same as in the full run (see Rule::Runner).
class RuleJob < ApplicationJob
queue_as :medium_priority
- def perform(rule, ignore_attribute_locks: false, execution_type: "manual")
- executed_at = Time.current
- transactions_queued = 0
- transactions_processed = 0
- transactions_modified = 0
- pending_jobs_count = 0
- status = "unknown"
- error_message = nil
- rule_run = nil
-
- begin
- # Count matching transactions before processing (queued count)
- transactions_queued = rule.affected_resource_count
-
- # Create the RuleRun record first with pending status
- # We'll update it after we know if there are async jobs
- # Store the rule name at execution time so it persists even if the rule name changes later
- rule_run = RuleRun.create!(
- rule: rule,
- rule_name: rule.name,
- execution_type: execution_type,
- status: "pending", # Start as pending, will be updated
- transactions_queued: transactions_queued,
- transactions_processed: 0,
- transactions_modified: 0,
- pending_jobs_count: 0,
- executed_at: executed_at
- )
-
- # Apply the rule and get the result
- result = rule.apply(ignore_attribute_locks: ignore_attribute_locks, rule_run: rule_run)
+ retry_on Rule::Runner::LockBusy, wait: 30.seconds, attempts: 20
- if result.is_a?(Hash) && result[:async]
- # Async actions were executed
- transactions_processed = result[:modified_count] || 0
- pending_jobs_count = result[:jobs_count] || 0
- status = "pending"
- elsif result.is_a?(Integer)
- # Only synchronous actions were executed
- transactions_processed = transactions_queued
- transactions_modified = result
- status = "success"
- else
- # Unexpected result type - log and default to 0
- Rails.logger.warn("RuleJob: Unexpected result type from rule.apply: #{result.class} for rule #{rule.id}")
- transactions_processed = 0
- transactions_modified = 0
- status = "unknown"
- end
-
- # Update the rule run with final counts
- rule_run.update!(
- status: status,
- transactions_processed: transactions_processed,
- transactions_modified: transactions_modified,
- pending_jobs_count: pending_jobs_count
- )
- rescue => e
- status = "failed"
- error_message = "#{e.class}: #{e.message}"
- Rails.logger.error("RuleJob failed for rule #{rule.id}: #{error_message}")
-
- # Update the rule run as failed if it was created
- if rule_run
- rule_run.update(status: "failed", error_message: error_message)
- else
- # Create a failed rule run if we hadn't created one yet
- # Store the rule name at execution time so it persists even if the rule name changes later
- begin
- RuleRun.create!(
- rule: rule,
- rule_name: rule.name,
- execution_type: execution_type,
- status: "failed",
- transactions_queued: transactions_queued,
- transactions_processed: 0,
- transactions_modified: 0,
- pending_jobs_count: 0,
- executed_at: executed_at,
- error_message: error_message
- )
- rescue => e
- Rails.logger.error("RuleJob: Failed to create RuleRun for rule #{rule.id}: #{e.message}")
- end
- end
-
- raise # Re-raise to mark job as failed in Sidekiq
- end
+ def perform(rule, ignore_attribute_locks: false, execution_type: "manual")
+ runner = Rule::Runner.new(
+ rule.family,
+ rules: [ rule ],
+ execution_type: execution_type,
+ ignore_attribute_locks: ignore_attribute_locks
+ )
+ rule_runs = runner.run
+
+ # The RuleRun records the failure; re-raise so the job is marked failed.
+ # A failing rule above is only recorded, because a retry would re-run all
+ # rules above as well. The applied rule runs last, so its error is last.
+ raise runner.errors.last if rule_runs.last&.status == "failed"
end
end
diff --git a/app/models/family/data_exporter.rb b/app/models/family/data_exporter.rb
index fef900f2c4..f383a830be 100644
--- a/app/models/family/data_exporter.rb
+++ b/app/models/family/data_exporter.rb
@@ -163,8 +163,9 @@ class Family::DataExporter
CSV.generate do |csv|
csv << [ "name", "resource_type", "active", "effective_date", "conditions", "actions" ]
- # Only export rules belonging to this family
- @family.rules.includes(conditions: :sub_conditions, actions: []).find_each do |rule|
+ # 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|
csv << [
rule.name,
rule.resource_type,
@@ -538,8 +539,8 @@ class Family::DataExporter
}.to_json
end
- # Export rules with versioned schema
- @family.rules.includes(conditions: :sub_conditions, actions: []).find_each do |rule|
+ # Export rules with versioned schema, in run order
+ @family.rules.includes(conditions: :sub_conditions, actions: []).ordered.each do |rule|
lines << {
type: "Rule",
version: 1,
@@ -753,6 +754,8 @@ class Family::DataExporter
resource_type: rule.resource_type,
active: rule.active,
effective_date: rule.effective_date&.iso8601,
+ position: rule.position,
+ stop_processing: rule.stop_processing,
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 001de5c9fc..389119e690 100644
--- a/app/models/family/data_importer.rb
+++ b/app/models/family/data_importer.rb
@@ -1357,7 +1357,14 @@ class Family::DataImporter
end
end
+ # New rules are appended after the family's existing ones, in the exported
+ # run order; rules that already exist keep their place.
def import_rules(records)
+ records = records.each_with_index.sort_by do |record, index|
+ position = Integer(record.dig("data", "position"), exception: false)
+ [ position || Float::INFINITY, index ]
+ end.map(&:first)
+
records.each do |record|
data = record["data"]
old_id = data["id"]
@@ -1372,7 +1379,8 @@ class Family::DataImporter
name: data["name"],
resource_type: data["resource_type"] || "transaction",
active: data["active"] || false,
- effective_date: data["effective_date"].present? ? Date.parse(data["effective_date"].to_s) : nil
+ effective_date: data["effective_date"].present? ? Date.parse(data["effective_date"].to_s) : nil,
+ stop_processing: data["stop_processing"] || false
)
rule.conditions.destroy_all unless created
diff --git a/app/models/family/syncer.rb b/app/models/family/syncer.rb
index 03b799ecff..ee1c7de069 100644
--- a/app/models/family/syncer.rb
+++ b/app/models/family/syncer.rb
@@ -23,9 +23,7 @@ class Family::Syncer
family.auto_match_transfers!
Rails.logger.info("Applying rules for family #{family.id}")
- family.rules.where(active: true).each do |rule|
- rule.apply_later
- end
+ ApplyRulesJob.perform_later(family)
end
private
diff --git a/app/models/financekit/downstream.rb b/app/models/financekit/downstream.rb
index cdcb3402a9..1c00e2be83 100644
--- a/app/models/financekit/downstream.rb
+++ b/app/models/financekit/downstream.rb
@@ -34,9 +34,9 @@ class Financekit::Downstream
# health, which the recovery sweep then skipped because it only looks for
# incomplete batches. Scheduling outside it was no better: a failed health
# write rolled the batch back after the jobs were already queued, so
- # recovery ran the same rules again and RuleJob records a RuleRun per run.
+ # recovery ran the same rules again and recorded a second RuleRun per rule.
# Enqueueing from inside is safe here because ApplicationJob sets
- # enqueue_after_transaction_commit, so SyncJob and RuleJob are deferred to
+ # enqueue_after_transaction_commit, so SyncJob and ApplyRulesJob are deferred to
# the commit and dropped outright if it rolls back.
#
# The fan-out itself costs the same whether one capture or fifty just
@@ -51,7 +51,7 @@ class Financekit::Downstream
# Anything failing after it is the publisher's, so drop the attribution.
account_provider = nil
@item.family.auto_match_transfers!
- @item.family.rules.where(active: true).find_each(&:apply_later)
+ ApplyRulesJob.perform_later(@item.family)
FinancekitBatch.where(id: pending)
.update_all(downstream_completed_at: completed_at, updated_at: completed_at)
diff --git a/app/models/rule.rb b/app/models/rule.rb
index 1d5a787e5f..f5687d0017 100644
--- a/app/models/rule.rb
+++ b/app/models/rule.rb
@@ -1,4 +1,7 @@
class Rule < ApplicationRecord
+ # Namespace for the per-family advisory lock around position assignment.
+ POSITION_LOCK_NAMESPACE = 4013
+
UnsupportedResourceTypeError = Class.new(StandardError)
belongs_to :family
@@ -10,6 +13,11 @@ class Rule < ApplicationRecord
accepts_nested_attributes_for :actions, allow_destroy: true
before_validation :normalize_name
+ before_create :assign_next_position
+
+ # Rules run top to bottom. created_at breaks ties, e.g. for rules created at
+ # the same moment before anyone reordered them.
+ scope :ordered, -> { order(:position, :created_at, :id) }
validates :resource_type, presence: true, if: -> { resource_type.to_s.valid_encoding? }
validates :name, length: { minimum: 1 }, allow_nil: true, if: -> { name.to_s.valid_encoding? }
@@ -38,20 +46,63 @@ class Rule < ApplicationRecord
end
def affected_resource_count
- matching_resources_scope.count
+ matching_scope.count
end
- # Public wrapper around the private matching scope so callers can read the
- # currently-matching transaction ids WITHOUT running executors (e.g. the
- # notification baseline pre-seed). Mirrors total_affected_resource_count,
- # which also reaches matching_resources_scope.
+ # Reads the currently-matching transaction ids WITHOUT running executors
+ # (e.g. the notification baseline pre-seed).
def matching_transaction_ids
- matching_resources_scope.pluck(:id)
+ matching_scope.pluck(:id)
+ 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") }
+ end
+
+ # Excludes transaction ids with one array parameter. where.not(id: ids) sends
+ # one bind per id, which breaks beyond PostgreSQL's 65,535 bind limit when a
+ # broad rule claims or stops many transactions.
+ def self.excluding_transaction_ids(scope, ids)
+ return scope if ids.empty?
+
+ scope.where.not("transactions.id = ANY(?::uuid[])", PG::TextEncoder::Array.new.encode(ids.to_a))
+ end
+
+ # Active rules that run before this one. "Apply rule" runs them first, so
+ # the result matches the full run.
+ def active_rules_above
+ ordered_ids = family.rules.ordered.pluck(:id)
+ above_ids = ordered_ids.take_while { |id| id != self.id }
+ family.rules.where(id: above_ids, active: true).ordered
+ end
+
+ # The given transactions without re-checking the conditions, so they stay
+ # the same set while the actions change the fields the conditions read.
+ def scope_for_transaction_ids(ids)
+ registry.resource_scope.where("transactions.id = ANY(?::uuid[])", PG::TextEncoder::Array.new.encode(ids.to_a))
end
# Whether this rule's conditions currently match the given transaction.
def matches_transaction?(transaction)
- matching_resources_scope.where(id: transaction.id).exists?
+ matching_scope.where(id: transaction.id).exists?
end
# Creates a categorization rule for the Quick Categorize Wizard.
@@ -75,19 +126,25 @@ class Rule < ApplicationRecord
# Collect all unique transaction IDs matched by any rule
transaction_ids = Set.new
rules.each do |rule|
- transaction_ids.merge(rule.send(:matching_resources_scope).pluck(:id))
+ transaction_ids.merge(rule.matching_scope.pluck(:id))
end
transaction_ids.size
end
- def apply(ignore_attribute_locks: false, rule_run: nil)
+ # scope: the transactions to act on. Rule::Runner passes the matches minus
+ # transactions a rule higher up stopped. claimed_ids maps an attribute to the
+ # transaction ids a rule higher up already set it for; an action leaves those
+ # transactions alone ("top rule wins").
+ def apply(ignore_attribute_locks: false, rule_run: nil, scope: matching_scope, claimed_ids: {})
total_modified = 0
total_async_jobs = 0
has_async = false
actions.each do |action|
- result = action.apply(matching_resources_scope, ignore_attribute_locks: ignore_attribute_locks, rule_run: rule_run)
+ excluded_ids = action.claimed_attributes.flat_map { |attribute| claimed_ids.fetch(attribute, []).to_a }.uniq
+ action_scope = Rule.excluding_transaction_ids(scope, excluded_ids)
+ result = action.apply(action_scope, ignore_attribute_locks: ignore_attribute_locks, rule_run: rule_run)
if result.is_a?(Hash) && result[:async]
has_async = true
@@ -133,21 +190,35 @@ class Rule < ApplicationRecord
end
end
- private
- def matching_resources_scope
- scope = registry.resource_scope
+ def matching_scope
+ scope = registry.resource_scope
- # 1. Prepare the query with joins required by conditions
- conditions.each do |condition|
- scope = condition.prepare(scope)
- end
+ # 1. Prepare the query with joins required by conditions
+ conditions.each do |condition|
+ scope = condition.prepare(scope)
+ end
- # 2. Apply the conditions to the query
- conditions.each do |condition|
- scope = condition.apply(scope)
- end
+ # 2. Apply the conditions to the query
+ conditions.each do |condition|
+ scope = condition.apply(scope)
+ end
- scope
+ scope
+ 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.
+ def assign_next_position
+ return if position.to_i.positive?
+
+ self.class.connection.execute(
+ self.class.sanitize_sql_array([ "SELECT pg_advisory_xact_lock(?, hashtext(?))", POSITION_LOCK_NAMESPACE, family_id.to_s ])
+ )
+ self.position = family.rules.maximum(:position).to_i + 1
end
def min_actions
diff --git a/app/models/rule/action.rb b/app/models/rule/action.rb
index ea311ae5af..ecaf5eabdc 100644
--- a/app/models/rule/action.rb
+++ b/app/models/rule/action.rb
@@ -59,6 +59,14 @@ class Rule::Action < ApplicationRecord
executor.options
end
+ def claimed_attributes
+ executor.claimed_attributes
+ end
+
+ def reserves_claimed_attributes?
+ executor.reserves_claimed_attributes? && executor.actionable?(value)
+ end
+
def value_display
return "" if value.blank?
diff --git a/app/models/rule/action_executor.rb b/app/models/rule/action_executor.rb
index 2e8743ec34..4a4f0ba5ed 100644
--- a/app/models/rule/action_executor.rb
+++ b/app/models/rule/action_executor.rb
@@ -21,6 +21,28 @@ class Rule::ActionExecutor
nil
end
+ # Attributes this action sets. When several rules set the same attribute on
+ # a transaction, the rule highest in the list wins (see Rule::Runner), so the
+ # action skips transactions a rule above already claimed. Additive actions
+ # such as tags claim nothing.
+ def claimed_attributes
+ []
+ end
+
+ # Whether matching this action keeps rules further down from setting
+ # claimed_attributes. False for actions that only fill a field later and not
+ # for every match, so a broad one doesn't silently block the rules below it.
+ def reserves_claimed_attributes?
+ true
+ end
+
+ # Whether this action can change anything with the given value. An action
+ # that cannot (e.g. its category was deleted) claims nothing, so it doesn't
+ # keep the rules below it from setting the field.
+ def actionable?(value)
+ true
+ end
+
def execute(scope, value: nil, ignore_attribute_locks: false, rule_run: nil)
raise NotImplementedError, "Action executor #{self.class.name} must implement #execute"
end
diff --git a/app/models/rule/action_executor/auto_categorize.rb b/app/models/rule/action_executor/auto_categorize.rb
index 7556bd5375..25e7fe3e01 100644
--- a/app/models/rule/action_executor/auto_categorize.rb
+++ b/app/models/rule/action_executor/auto_categorize.rb
@@ -27,6 +27,16 @@ class Rule::ActionExecutor::AutoCategorize < Rule::ActionExecutor
end
end
+ def claimed_attributes
+ [ :category_id ]
+ end
+
+ # The AI runs later and only fills fields it can classify, so it leaves
+ # them to rules further down, as it did before rules had an order.
+ def reserves_claimed_attributes?
+ false
+ end
+
def execute(transaction_scope, value: nil, ignore_attribute_locks: false, rule_run: nil)
protected_scope = protected_transactions(transaction_scope)
cached_transaction_ids = cached_transaction_ids(protected_scope)
diff --git a/app/models/rule/action_executor/auto_detect_merchants.rb b/app/models/rule/action_executor/auto_detect_merchants.rb
index 15151b31c3..823a5d9915 100644
--- a/app/models/rule/action_executor/auto_detect_merchants.rb
+++ b/app/models/rule/action_executor/auto_detect_merchants.rb
@@ -7,6 +7,16 @@ class Rule::ActionExecutor::AutoDetectMerchants < Rule::ActionExecutor
end
end
+ def claimed_attributes
+ [ :merchant_id ]
+ end
+
+ # The AI runs later and only fills fields it can classify, so it leaves
+ # them to rules further down, as it did before rules had an order.
+ def reserves_claimed_attributes?
+ false
+ end
+
def execute(transaction_scope, value: nil, ignore_attribute_locks: false, rule_run: nil)
enrichable_transactions = transaction_scope.enrichable(:merchant_id)
diff --git a/app/models/rule/action_executor/exclude_transaction.rb b/app/models/rule/action_executor/exclude_transaction.rb
index 79f1b0658f..7a40699c55 100644
--- a/app/models/rule/action_executor/exclude_transaction.rb
+++ b/app/models/rule/action_executor/exclude_transaction.rb
@@ -3,6 +3,10 @@ class Rule::ActionExecutor::ExcludeTransaction < Rule::ActionExecutor
"Exclude from budgeting and reports"
end
+ def claimed_attributes
+ [ :excluded ]
+ end
+
def execute(transaction_scope, value: nil, ignore_attribute_locks: false, rule_run: nil)
scope = transaction_scope.with_entry
diff --git a/app/models/rule/action_executor/set_as_transfer_or_payment.rb b/app/models/rule/action_executor/set_as_transfer_or_payment.rb
index bcef339a50..b2ac72d204 100644
--- a/app/models/rule/action_executor/set_as_transfer_or_payment.rb
+++ b/app/models/rule/action_executor/set_as_transfer_or_payment.rb
@@ -7,6 +7,14 @@ class Rule::ActionExecutor::SetAsTransferOrPayment < Rule::ActionExecutor
family.accounts.alphabetically.pluck(:name, :id)
end
+ def claimed_attributes
+ [ :transfer ]
+ end
+
+ def actionable?(value)
+ family.accounts.exists?(id: value)
+ end
+
def execute(transaction_scope, value: nil, ignore_attribute_locks: false, rule_run: nil)
target_account = family.accounts.find_by_id(value)
return 0 unless target_account
diff --git a/app/models/rule/action_executor/set_investment_activity_label.rb b/app/models/rule/action_executor/set_investment_activity_label.rb
index 3ae4225183..bb0b087bca 100644
--- a/app/models/rule/action_executor/set_investment_activity_label.rb
+++ b/app/models/rule/action_executor/set_investment_activity_label.rb
@@ -11,6 +11,14 @@ class Rule::ActionExecutor::SetInvestmentActivityLabel < Rule::ActionExecutor
Transaction::ACTIVITY_LABELS.map { |l| [ l, l ] }
end
+ def claimed_attributes
+ [ :investment_activity_label ]
+ end
+
+ def actionable?(value)
+ Transaction::ACTIVITY_LABELS.include?(value)
+ end
+
def execute(transaction_scope, value: nil, ignore_attribute_locks: false, rule_run: nil)
return 0 unless Transaction::ACTIVITY_LABELS.include?(value)
diff --git a/app/models/rule/action_executor/set_transaction_category.rb b/app/models/rule/action_executor/set_transaction_category.rb
index 97d58c5a1e..e395c601e6 100644
--- a/app/models/rule/action_executor/set_transaction_category.rb
+++ b/app/models/rule/action_executor/set_transaction_category.rb
@@ -7,6 +7,14 @@ class Rule::ActionExecutor::SetTransactionCategory < Rule::ActionExecutor
Category::Group.select_options(family.categories, indent: false)
end
+ def claimed_attributes
+ [ :category_id ]
+ end
+
+ def actionable?(value)
+ family.categories.exists?(id: value)
+ end
+
def execute(transaction_scope, value: nil, ignore_attribute_locks: false, rule_run: nil)
category = family.categories.find_by_id(value)
return 0 unless category
diff --git a/app/models/rule/action_executor/set_transaction_merchant.rb b/app/models/rule/action_executor/set_transaction_merchant.rb
index 06bdf1b5d3..7f07b24646 100644
--- a/app/models/rule/action_executor/set_transaction_merchant.rb
+++ b/app/models/rule/action_executor/set_transaction_merchant.rb
@@ -7,6 +7,14 @@ class Rule::ActionExecutor::SetTransactionMerchant < Rule::ActionExecutor
family.merchants.alphabetically.pluck(:name, :id)
end
+ def claimed_attributes
+ [ :merchant_id ]
+ end
+
+ def actionable?(value)
+ family.merchants.exists?(id: value)
+ end
+
def execute(transaction_scope, value: nil, ignore_attribute_locks: false, rule_run: nil)
merchant = family.merchants.find_by_id(value)
return 0 unless merchant
diff --git a/app/models/rule/action_executor/set_transaction_name.rb b/app/models/rule/action_executor/set_transaction_name.rb
index 737c258f0d..9175afb87c 100644
--- a/app/models/rule/action_executor/set_transaction_name.rb
+++ b/app/models/rule/action_executor/set_transaction_name.rb
@@ -7,6 +7,14 @@ class Rule::ActionExecutor::SetTransactionName < Rule::ActionExecutor
nil
end
+ def claimed_attributes
+ [ :name ]
+ end
+
+ def actionable?(value)
+ value.present?
+ end
+
def execute(transaction_scope, value: nil, ignore_attribute_locks: false, rule_run: nil)
return 0 if value.blank?
diff --git a/app/models/rule/runner.rb b/app/models/rule/runner.rb
new file mode 100644
index 0000000000..f45de71984
--- /dev/null
+++ b/app/models/rule/runner.rb
@@ -0,0 +1,194 @@
+# Runs a family's rules one after another, top to bottom (Rule#position).
+#
+# - Top rule wins: once a rule sets an attribute on a transaction, rules further
+# down leave that attribute alone in the same run, even when the value was
+# already set or the attribute is locked. Tags are additive and claim nothing.
+# - Stop processing: a transaction matched by a rule with stop_processing is not
+# touched by any rule further down.
+#
+# Active rules above the ones requested run first, in order, so applying a
+# single rule gives the same result as its turn in the full run (e.g. it sees
+# a rename a rule above makes). Rules below the last requested rule don't run.
+# Inactive rules above are skipped because they don't run nightly either.
+# ignore_attribute_locks only applies to the requested rules.
+#
+# One run per family at a time, guarded by a PostgreSQL advisory lock. A busy
+# lock raises LockBusy so the calling job can retry instead of dropping the run.
+class Rule::Runner
+ LockBusy = Class.new(StandardError)
+
+ attr_reader :errors
+
+ def self.advisory_lock_key(family_id)
+ Digest::MD5.hexdigest("rule_runner:#{family_id}").to_i(16) % (2**62)
+ end
+
+ def initialize(family, rules:, execution_type:, ignore_attribute_locks: false)
+ @family = family
+ @rule_ids = rules.map(&:id).to_set
+ @execution_type = execution_type
+ @ignore_attribute_locks = ignore_attribute_locks
+ @claimed_ids = Hash.new { |hash, attribute| hash[attribute] = Set.new }
+ @stopped_ids = Set.new
+ @errors = []
+ end
+
+ # Returns the RuleRun records created, one per executed rule.
+ def run
+ return [] if rule_ids.empty?
+
+ rule_runs = nil
+ acquired = with_family_lock { rule_runs = run_rules }
+ raise LockBusy, "Rules are already running for family #{family.id}" unless acquired
+
+ rule_runs
+ end
+
+ private
+ attr_reader :family, :rule_ids, :execution_type, :ignore_attribute_locks, :claimed_ids, :stopped_ids
+
+ def run_rules
+ rule_runs = []
+ remaining_ids = rule_ids.dup
+
+ family.rules.ordered.includes(:family, :actions, conditions: :sub_conditions).each do |rule|
+ break if remaining_ids.empty?
+
+ if remaining_ids.delete?(rule.id)
+ rule_runs << execute(rule, ignore_attribute_locks: ignore_attribute_locks)
+ elsif rule.active?
+ rule_runs << execute(rule, ignore_attribute_locks: false)
+ end
+ end
+
+ rule_runs
+ end
+
+ def unstopped_scope(rule)
+ Rule.excluding_transaction_ids(rule.matching_scope, stopped_ids)
+ end
+
+ def record_claims(rule, matched_ids)
+ rule.actions.each do |action|
+ reserved_attributes(action).each { |attribute| claimed_ids[attribute].merge(matched_ids) }
+ end
+
+ stopped_ids.merge(matched_ids) if rule.stop_processing?
+ end
+
+ # An action that cannot be resolved (e.g. an unknown action_type from an
+ # import) sets nothing, so it claims nothing and must not abort the run.
+ def reserved_attributes(action)
+ return [] unless action.reserves_claimed_attributes?
+
+ action.claimed_attributes
+ rescue => e
+ Rails.logger.error("Rule::Runner could not read claims of action #{action.id}: #{e.class}: #{e.message}")
+ []
+ end
+
+ def execute(rule, ignore_attribute_locks:)
+ executed_at = Time.current
+ matched_ids = []
+ rule_run = nil
+
+ begin
+ scope = unstopped_scope(rule)
+ matched_ids = scope.pluck(:id)
+
+ rule_run = RuleRun.create!(
+ rule: rule,
+ rule_name: rule.name,
+ execution_type: execution_type,
+ status: "pending",
+ transactions_queued: matched_ids.size,
+ transactions_processed: 0,
+ transactions_modified: 0,
+ pending_jobs_count: 0,
+ executed_at: executed_at
+ )
+
+ # Every action works on the transactions matched now, not on a scope
+ # that re-checks the conditions: otherwise an action that changes a
+ # matched field (e.g. the name) would hide the transactions from the
+ # actions after it, while the claims below still reserve them.
+ result = rule.apply(
+ ignore_attribute_locks: ignore_attribute_locks,
+ rule_run: rule_run,
+ scope: rule.scope_for_transaction_ids(matched_ids),
+ claimed_ids: claimed_ids
+ )
+
+ rule_run.update!(**run_counts(result, queued: matched_ids.size, rule: rule))
+ rescue => e
+ rule_run = record_failure(rule, rule_run, e, executed_at: executed_at, queued: matched_ids.size)
+ ensure
+ # Claims hold even when the rule failed halfway, so a rule further down
+ # never overwrites what this rule may already have set.
+ record_claims(rule, matched_ids)
+ end
+
+ rule_run
+ end
+
+ def run_counts(result, queued:, rule:)
+ if result.is_a?(Hash) && result[:async]
+ # The async jobs report the modified count back via RuleRun#complete_job!
+ { status: "pending", transactions_processed: result[:modified_count] || 0, pending_jobs_count: result[:jobs_count] || 0 }
+ elsif result.is_a?(Integer)
+ { status: "success", transactions_processed: queued, transactions_modified: result }
+ else
+ Rails.logger.warn("Rule::Runner: Unexpected result type from rule.apply: #{result.class} for rule #{rule.id}")
+ { status: "success" }
+ end
+ end
+
+ def record_failure(rule, rule_run, error, executed_at:, queued:)
+ errors << error
+ error_message = "#{error.class}: #{error.message}"
+ Rails.logger.error("Rule::Runner failed for rule #{rule.id}: #{error_message}")
+
+ if rule_run
+ rule_run.update(status: "failed", error_message: error_message)
+ rule_run
+ else
+ RuleRun.create!(
+ rule: rule,
+ rule_name: rule.name,
+ execution_type: execution_type,
+ status: "failed",
+ transactions_queued: queued,
+ transactions_processed: 0,
+ transactions_modified: 0,
+ pending_jobs_count: 0,
+ executed_at: executed_at,
+ error_message: error_message
+ )
+ end
+ rescue => e
+ Rails.logger.error("Rule::Runner: Failed to record RuleRun for rule #{rule.id}: #{e.message}")
+ rule_run
+ end
+
+ # Same pattern as RecurringTransaction::Pipeline.with_family_lock: one
+ # leased connection for lock and unlock, because the unlock must run on the
+ # PostgreSQL session that took the lock.
+ def with_family_lock
+ lock_key = self.class.advisory_lock_key(family.id)
+ connection = ActiveRecord::Base.lease_connection
+ acquired = connection.select_value(
+ ActiveRecord::Base.sanitize_sql_array([ "SELECT pg_try_advisory_lock(?)", lock_key ])
+ )
+
+ return false unless acquired
+
+ begin
+ yield
+ ensure
+ connection.execute(
+ ActiveRecord::Base.sanitize_sql_array([ "SELECT pg_advisory_unlock(?)", lock_key ])
+ )
+ end
+ true
+ end
+end
diff --git a/app/views/api/v1/rules/_rule.json.jbuilder b/app/views/api/v1/rules/_rule.json.jbuilder
index 1009a3737d..04e2f0a791 100644
--- a/app/views/api/v1/rules/_rule.json.jbuilder
+++ b/app/views/api/v1/rules/_rule.json.jbuilder
@@ -5,6 +5,8 @@ json.name rule.name
json.resource_type rule.resource_type
json.active rule.active
json.effective_date rule.effective_date&.iso8601
+json.position rule.position
+json.stop_processing rule.stop_processing
json.conditions rule.conditions.select { |condition| condition.parent_id.nil? } do |condition|
json.partial! "api/v1/rules/condition", condition: condition
end
diff --git a/app/views/reports/index.html.erb b/app/views/reports/index.html.erb
index 81151f7077..70e038cf4d 100644
--- a/app/views/reports/index.html.erb
+++ b/app/views/reports/index.html.erb
@@ -138,7 +138,13 @@
</section>
<%# Collapsible & Reorderable Sections %>
- <div data-controller="reports-sortable" data-action="dragover->reports-sortable#dragOver drop->reports-sortable#drop" role="list" aria-label="Reports sections">
+ <div data-controller="sortable-list"
+ data-sortable-list-url-value="<%= update_preferences_reports_path %>"
+ data-sortable-list-param-value="preferences.reports_section_order"
+ data-sortable-list-hold-delay-value="800"
+ data-action="dragover->sortable-list#dragOver drop->sortable-list#drop"
+ role="list"
+ aria-label="<%= t("reports.index.sections_aria") %>">
<% @reports_sections.each do |section| %>
<% next unless section[:visible] %>
<%# [-webkit-touch-callout:none] suppresses iOS Safari's native long-press
@@ -148,7 +154,8 @@
(see #3132 review). %>
<section
class="bg-container rounded-xl shadow-border-xs transition-all mb-6 group focus:outline-none focus-visible:ring-2 focus-visible:ring-alpha-black-300 focus-visible:ring-offset-2 [-webkit-touch-callout:none]"
- data-reports-sortable-target="section"
+ data-sortable-list-target="item"
+ data-sortable-list-id="<%= section[:key] %>"
data-section-key="<%= section[:key] %>"
data-controller="reports-section"
data-reports-section-section-key-value="<%= section[:key] %>"
@@ -159,14 +166,14 @@
aria-grabbed="false"
aria-label="<%= t(section[:title]) %> section. Press Enter or Space to grab for reordering, then use arrow keys to move."
data-action="
- dragstart->reports-sortable#dragStart
- dragend->reports-sortable#dragEnd
- touchstart->reports-sortable#touchStart
- touchmove->reports-sortable#touchMove
- touchend->reports-sortable#touchEnd
- touchcancel->reports-sortable#touchCancel
- contextmenu->reports-sortable#suppressContextMenu
- keydown->reports-sortable#handleKeyDown">
+ dragstart->sortable-list#dragStart
+ dragend->sortable-list#dragEnd
+ 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="px-4 py-2 flex items-center justify-between">
<div class="flex items-center gap-2">
<button
diff --git a/app/views/rules/_form.html.erb b/app/views/rules/_form.html.erb
index 7c942a35f9..7a52e499d5 100644
--- a/app/views/rules/_form.html.erb
+++ b/app/views/rules/_form.html.erb
@@ -101,5 +101,13 @@
</div>
</section>
+ <section class="flex items-center gap-4 justify-between">
+ <div class="text-sm space-y-1">
+ <h3 class="font-medium text-primary"><%= t(".stop_processing_label") %></h3>
+ <p class="text-secondary"><%= t(".stop_processing_description") %></p>
+ </div>
+ <%= f.toggle :stop_processing %>
+ </section>
+
<%= f.submit %>
<% end %>
diff --git a/app/views/rules/_rule.html.erb b/app/views/rules/_rule.html.erb
index 3106e8b4fb..ff645fb351 100644
--- a/app/views/rules/_rule.html.erb
+++ b/app/views/rules/_rule.html.erb
@@ -2,8 +2,15 @@
<div id="<%= dom_id(rule) %>" class="flex justify-between items-center p-4 <%= rule.active? ? "text-primary" : "text-secondary" %>">
<div class="text-sm space-y-1.5">
- <% if rule.name.present? %>
- <h3 class="font-medium text-md"><%= rule.name %></h3>
+ <% if rule.name.present? || rule.stop_processing? %>
+ <div class="flex items-center gap-2">
+ <% if rule.name.present? %>
+ <h3 class="font-medium text-md"><%= rule.name %></h3>
+ <% end %>
+ <% if rule.stop_processing? %>
+ <%= render DS::Pill.new(label: t(".stop_processing"), tone: :neutral, marker: false, title: t(".stop_processing_hint")) %>
+ <% end %>
+ </div>
<% end %>
<% if rule.conditions.any? %>
<% displayed_condition = rule.displayed_condition %>
diff --git a/app/views/rules/confirm.html.erb b/app/views/rules/confirm.html.erb
index 775846f6af..942f2b0b9f 100644
--- a/app/views/rules/confirm.html.erb
+++ b/app/views/rules/confirm.html.erb
@@ -13,6 +13,12 @@
<%= t(".apply_notice_html", count: @rule.affected_resource_count, resource: @rule.resource_type.pluralize) %>
</p>
+ <% if @active_rules_above_count.positive? %>
+ <p class="text-secondary text-sm mb-4">
+ <%= t(".rules_above_notice", count: @active_rules_above_count) %>
+ </p>
+ <% end %>
+
<% if @rule.actions.any? { |a| a.action_type == "auto_categorize" } %>
<% affected_count = @rule.affected_resource_count %>
<div class="mb-4">
diff --git a/app/views/rules/index.html.erb b/app/views/rules/index.html.erb
index 847c042040..235a6812e0 100644
--- a/app/views/rules/index.html.erb
+++ b/app/views/rules/index.html.erb
@@ -55,28 +55,37 @@
<span class="text-subdued">&middot;</span>
<p><%= @rules.count %></p>
</div>
- <div class="flex items-center gap-1">
- <span class="text-secondary"><%= t(".sort_by") %></span>
- <%= form_with url: rules_path, method: :get, local: true, class: "flex items-center", data: { controller: "auto-submit-form" } do |form| %>
- <%= form.select :sort_by,
- options_for_select([[t(".sort_name"), "name"], [t(".sort_updated_at"), "updated_at"]], @sort_by),
- {},
- class: "min-w-[120px] bg-transparent rounded border-none cursor-pointer text-primary uppercase text-xs w-auto",
- data: { auto_submit_form_target: "auto", autosubmit_trigger_event: "change" } %>
- <%= form.hidden_field :direction, value: @direction %>
- <% end %>
- <%= render DS::Link.new(
- href: rules_path(direction: @direction == "asc" ? "desc" : "asc", sort_by: @sort_by),
- variant: "icon",
- icon: "arrow-up-down",
- size: :sm,
- title: t(".toggle_sort_direction")
- ) %>
- </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">
- <%= render partial: "rule", collection: @rules, spacer_template: "shared/ruler" %>
+ <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>
+ <% end %>
</div>
</div>
</div>
diff --git a/config/locales/views/reports/de.yml b/config/locales/views/reports/de.yml
index 3effc1a76f..a462293e38 100644
--- a/config/locales/views/reports/de.yml
+++ b/config/locales/views/reports/de.yml
@@ -8,6 +8,7 @@ de:
export: CSV exportieren
print_report: Bericht drucken
drag_to_reorder: "Bereich per Drag & Drop neu anordnen"
+ sections_aria: Berichtsbereiche
toggle_section: "Sichtbarkeit des Bereichs umschalten"
periods:
monthly: Monatlich
diff --git a/config/locales/views/reports/en.yml b/config/locales/views/reports/en.yml
index 3fa6da118b..8fa111f06d 100644
--- a/config/locales/views/reports/en.yml
+++ b/config/locales/views/reports/en.yml
@@ -7,6 +7,7 @@ en:
export: Export CSV
print_report: Print Report
drag_to_reorder: "Drag to reorder section"
+ sections_aria: Reports sections
toggle_section: "Toggle section visibility"
periods:
monthly: Monthly
diff --git a/config/locales/views/rules/ca.yml b/config/locales/views/rules/ca.yml
index 72018a6aa9..d44e7ad254 100644
--- a/config/locales/views/rules/ca.yml
+++ b/config/locales/views/rules/ca.yml
@@ -98,10 +98,6 @@ ca:
no_rules_title: Encara no hi ha regles
page_title: Regles
rules_heading: Regles
- sort_by: 'Ordena per:'
- sort_name: Nom
- sort_updated_at: Data d'actualització
- toggle_sort_direction: Commuta el sentit d'ordenació
no_action: Sense acció
no_condition: Sense condició
recent_runs:
diff --git a/config/locales/views/rules/de.yml b/config/locales/views/rules/de.yml
index 38b4feba3c..4339c2279b 100644
--- a/config/locales/views/rules/de.yml
+++ b/config/locales/views/rules/de.yml
@@ -60,6 +60,9 @@ de:
cost_unavailable_model: Für das Modell „%{model}“ gibt es keine Kostenschätzung.
cost_unavailable_no_provider: Keine Kostenschätzung möglich (kein LLM-Anbieter eingerichtet).
cost_warning: Es können Kosten entstehen. Die aktuellen Preise findest du beim Modellanbieter.
+ rules_above_notice:
+ one: Die aktive Regel darüber läuft vorher, damit das Ergebnis dem vollen Lauf entspricht.
+ other: Die %{count} aktiven Regeln darüber laufen vorher, damit das Ergebnis dem vollen Lauf entspricht.
title: Änderungen bestätigen
title_with_name: Änderungen an „%{name}“ bestätigen
view_usage_history: Nutzungsverlauf ansehen
@@ -75,6 +78,8 @@ de:
rule_name_label: Regelname (optional)
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.
+ stop_processing_label: Danach keine weiteren Regeln anwenden
then: DANN
index:
ai_cost_warning: Regelaktionen mit KI kosten Geld. Filtere so eng wie möglich, damit keine unnötigen Kosten entstehen.
@@ -82,12 +87,10 @@ 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.
page_title: Regeln
+ reorder_rule: "Regel %{name} verschieben. Mit Enter oder Leertaste greifen, dann mit den Pfeiltasten verschieben."
rules_heading: Regeln
- sort_by: 'Sortieren nach:'
- sort_name: Name
- sort_updated_at: Geändert am
- toggle_sort_direction: Sortierrichtung umschalten
rule:
action_label_to: "%{label} auf %{value}"
all_past_and_future: Alle bisherigen und künftigen %{resource}
@@ -101,6 +104,8 @@ de:
edit: Bearbeiten
on_or_after: "%{resource} ab dem %{date}"
re_apply_rule: Regel erneut anwenden
+ stop_processing: Stopp
+ stop_processing_hint: Weiter unten stehende Regeln ändern die Transaktionen nicht mehr, die diese Regel trifft.
then: DANN
update:
success: Regel aktualisiert
diff --git a/config/locales/views/rules/en.yml b/config/locales/views/rules/en.yml
index b5fe1b1dab..e1811065c6 100644
--- a/config/locales/views/rules/en.yml
+++ b/config/locales/views/rules/en.yml
@@ -25,6 +25,8 @@ en:
action_label_to: "%{label} to %{value}"
all_past_and_future: All past and future %{resource}
on_or_after: "%{resource} on or after %{date}"
+ stop_processing: Stop
+ stop_processing_hint: Rules further down don't change transactions matched by this rule.
form:
rule_name_label: Rule name (optional)
rule_name_placeholder: Enter a name for this rule
@@ -34,22 +36,25 @@ en:
all_past_and_future: All past and future %{resource}
starting_from: Starting from
then: THEN
+ stop_processing_label: Stop processing further rules
+ stop_processing_description: Rules further down the list don't change transactions this rule matches.
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
- sort_by: "Sort by:"
- sort_name: Name
- sort_updated_at: Updated At
- toggle_sort_direction: Toggle sort direction
+ 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.
+ 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.
confirm:
title: Confirm changes
title_with_name: "Confirm changes to \"%{name}\""
apply_notice_html: "You are about to apply this rule to <span class=\"text-primary font-medium\">%{count} %{resource}</span> that meet the specified rule criteria. Please confirm if you wish to proceed with this change."
+ rules_above_notice:
+ one: The active rule above it runs first, so the result is the same as in the full run.
+ other: The %{count} active rules above it run first, so the result is the same as in the full run.
ai_cost_title: AI Cost Estimation
ai_cost_with_estimate_html: "This will use AI to categorize %{count} transaction(s). Estimated cost: <span class=\"font-semibold\">~$%{cost}</span>"
ai_cost_no_estimate_html: "This will use AI to categorize %{count} transaction(s)."
diff --git a/config/locales/views/rules/es.yml b/config/locales/views/rules/es.yml
index 08de6ecdea..87ba454185 100644
--- a/config/locales/views/rules/es.yml
+++ b/config/locales/views/rules/es.yml
@@ -32,10 +32,6 @@ es:
new_rule: Nueva regla
ai_cost_warning: Las acciones de reglas con IA tienen un coste. Filtra de la forma más precisa posible para evitar costes innecesarios.
rules_heading: Reglas
- sort_by: 'Ordenar por:'
- sort_name: Nombre
- sort_updated_at: Fecha de actualización
- toggle_sort_direction: Cambiar el orden
no_rules_title: Todavía no hay reglas
no_rules_description: Configura reglas para ejecutar acciones sobre tus transacciones y otros datos en cada sincronización de cuentas.
confirm:
diff --git a/config/locales/views/rules/fr.yml b/config/locales/views/rules/fr.yml
index 872a187545..d026423ffb 100644
--- a/config/locales/views/rules/fr.yml
+++ b/config/locales/views/rules/fr.yml
@@ -102,10 +102,6 @@ fr:
no_rules_title: Pas encore de règles
page_title: Règles
rules_heading: Règles
- sort_by: 'Trier par :'
- sort_name: Nom
- sort_updated_at: Mis à jour à
- toggle_sort_direction: Changer le sens du tri
no_action: Aucune action
no_condition: Aucune condition
recent_runs:
diff --git a/config/locales/views/rules/hu.yml b/config/locales/views/rules/hu.yml
index 23d879ab2d..caedd363ec 100644
--- a/config/locales/views/rules/hu.yml
+++ b/config/locales/views/rules/hu.yml
@@ -32,10 +32,6 @@ hu:
new_rule: Új szabály
ai_cost_warning: Az AI-t igénybe vevő szabályakciók pénzbe kerülnek. Szűrj minél szűkebbre a felesleges költségek elkerülése érdekében.
rules_heading: Szabályok
- sort_by: "Rendezés:"
- sort_name: Név szerint
- sort_updated_at: Módosítás dátuma szerint
- toggle_sort_direction: Rendezési irány váltása
no_rules_title: Még nincsenek szabályok
no_rules_description: Állíts be szabályokat, amelyek minden fiókszinkronizáláskor automatikusan elvégzik a megadott műveleteket a tranzakciókon és egyéb adatokon.
confirm:
diff --git a/config/locales/views/rules/it.yml b/config/locales/views/rules/it.yml
index 90a23082d4..528493318b 100644
--- a/config/locales/views/rules/it.yml
+++ b/config/locales/views/rules/it.yml
@@ -32,10 +32,6 @@ it:
new_rule: Nuova regola
ai_cost_warning: Le azioni delle regole con AI comporteranno dei costi. Filtra nel modo più specifico possibile per evitare costi inutili.
rules_heading: Regole
- sort_by: "Ordina per:"
- sort_name: Nome
- sort_updated_at: Data aggiornamento
- toggle_sort_direction: Cambia direzione ordinamento
no_rules_title: Nessuna regola ancora
no_rules_description: Configura regole per eseguire azioni sulle tue transazioni e altri dati ad ogni sincronizzazione del conto.
confirm:
diff --git a/config/locales/views/rules/pl.yml b/config/locales/views/rules/pl.yml
index ddb62f7b99..3e0b657c0f 100644
--- a/config/locales/views/rules/pl.yml
+++ b/config/locales/views/rules/pl.yml
@@ -97,10 +97,6 @@ pl:
no_rules_title: Brak reguł
page_title: Reguły
rules_heading: Reguły
- sort_by: 'Sortuj według:'
- sort_name: Nazwa
- sort_updated_at: Data aktualizacji
- toggle_sort_direction: Zmień kierunek sortowania
no_action: Brak akcji
no_condition: Brak warunku
recent_runs:
diff --git a/config/locales/views/rules/pt-PT.yml b/config/locales/views/rules/pt-PT.yml
index a4a341863e..846b1da220 100644
--- a/config/locales/views/rules/pt-PT.yml
+++ b/config/locales/views/rules/pt-PT.yml
@@ -32,10 +32,6 @@ pt-PT:
new_rule: Nova regra
ai_cost_warning: As ações de regras ativadas por IA implicam custos. Filtre o mais restritivamente possível para evitar custos desnecessários.
rules_heading: Regras
- sort_by: "Ordenar por:"
- sort_name: Nome
- sort_updated_at: Atualizado em
- toggle_sort_direction: Alternar direção da ordenação
no_rules_title: Ainda não existem regras
no_rules_description: Defina regras para executar ações nas suas transações e noutros dados em cada sincronização de conta.
confirm:
diff --git a/config/locales/views/rules/ru.yml b/config/locales/views/rules/ru.yml
index b81feb0af8..4f6163aa0a 100644
--- a/config/locales/views/rules/ru.yml
+++ b/config/locales/views/rules/ru.yml
@@ -97,10 +97,6 @@ ru:
no_rules_title: Пока нет правил
page_title: Правила
rules_heading: Правила
- sort_by: 'Сортировать по:'
- sort_name: Имя
- sort_updated_at: Обновлено
- toggle_sort_direction: Изменить направление сортировки
no_action: Нет действия
no_condition: Нет условия
recent_runs:
diff --git a/config/locales/views/rules/tr.yml b/config/locales/views/rules/tr.yml
index ac46f4ebd1..d496e823dc 100644
--- a/config/locales/views/rules/tr.yml
+++ b/config/locales/views/rules/tr.yml
@@ -100,10 +100,6 @@ tr:
no_rules_title: Henüz kural yok
page_title: Kurallar
rules_heading: Kurallar
- sort_by: 'Sırala:'
- sort_name: Ad
- sort_updated_at: Güncellenme Tarihi
- toggle_sort_direction: Sıralama yönünü değiştir
no_action: "Eylem yok"
no_condition: Koşul yok
recent_runs:
diff --git a/config/locales/views/rules/uk.yml b/config/locales/views/rules/uk.yml
index d3e22ee1f3..d9a2f1b0be 100644
--- a/config/locales/views/rules/uk.yml
+++ b/config/locales/views/rules/uk.yml
@@ -35,10 +35,6 @@ uk:
new_rule: Нове правило
ai_cost_warning: Дії правил з підтримкою ШІ коштуватимуть грошей. Обов'язково фільтруйте якомога вужче, щоб уникнути непотрібних витрат.
rules_heading: Правила
- sort_by: "Сортувати за:"
- sort_name: Назва
- sort_updated_at: Оновлено
- toggle_sort_direction: Переключити напрямок сортування
no_rules_title: Правил ще немає
no_rules_description: Налаштуйте правила для виконання дій з вашими транзакціями та іншими даними під час кожної синхронізації рахунку.
confirm:
diff --git a/config/locales/views/rules/vi.yml b/config/locales/views/rules/vi.yml
index 859b488ef1..409863725b 100644
--- a/config/locales/views/rules/vi.yml
+++ b/config/locales/views/rules/vi.yml
@@ -32,10 +32,6 @@ vi:
new_rule: Quy tắc mới
ai_cost_warning: Các hành động quy tắc sử dụng AI sẽ tốn chi phí. Hãy lọc càng hẹp càng tốt để tránh chi phí không cần thiết.
rules_heading: Quy tắc
- sort_by: "Sắp xếp theo:"
- sort_name: Tên
- sort_updated_at: Ngày cập nhật
- toggle_sort_direction: Đổi chiều sắp xếp
no_rules_title: Chưa có quy tắc
no_rules_description: Thiết lập quy tắc để thực hiện hành động trên giao dịch và dữ liệu khác mỗi lần đồng bộ tài khoản.
confirm:
diff --git a/config/locales/views/rules/zh-CN.yml b/config/locales/views/rules/zh-CN.yml
index 3cd268c7f8..6e1b65cc4c 100644
--- a/config/locales/views/rules/zh-CN.yml
+++ b/config/locales/views/rules/zh-CN.yml
@@ -32,10 +32,6 @@ zh-CN:
new_rule: 新建规则
ai_cost_warning: 启用 AI 的规则操作会产生费用。请务必尽可能精确地筛选,以避免不必要的成本。
rules_heading: 规则
- sort_by: 排序方式:
- sort_name: 名称
- sort_updated_at: 更新时间
- toggle_sort_direction: 切换排序方向
no_rules_title: 还没有规则
no_rules_description: 设置规则后,您每次账户同步时都可以对交易和其他数据执行操作。
confirm:
diff --git a/config/locales/views/rules/zh-TW.yml b/config/locales/views/rules/zh-TW.yml
index 5b4f162ad3..fcecb28cd2 100644
--- a/config/locales/views/rules/zh-TW.yml
+++ b/config/locales/views/rules/zh-TW.yml
@@ -32,10 +32,6 @@ zh-TW:
new_rule: 新增規則
ai_cost_warning: 使用 AI 的規則動作會產生費用。請盡可能縮小篩選條件的範圍,以免產生不必要的花費。
rules_heading: 自動化規則
- sort_by: 排序依據:
- sort_name: 名稱
- sort_updated_at: 更新時間
- toggle_sort_direction: 切換排序方向
no_rules_title: 還沒有任何規則
no_rules_description: 設定規則,就能在每次帳戶同步時對您的交易與其他資料執行動作。
confirm:
diff --git a/config/routes.rb b/config/routes.rb
index 0a7ceae692..02c50dea99 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -654,6 +654,7 @@ Rails.application.routes.draw do
collection do
delete :destroy_all
+ patch :reorder
get :confirm_all
post :apply_all
post :clear_ai_cache
diff --git a/db/migrate/20261006140000_add_position_and_stop_processing_to_rules.rb b/db/migrate/20261006140000_add_position_and_stop_processing_to_rules.rb
new file mode 100644
index 0000000000..91f0246dd6
--- /dev/null
+++ b/db/migrate/20261006140000_add_position_and_stop_processing_to_rules.rb
@@ -0,0 +1,29 @@
+# frozen_string_literal: true
+
+class AddPositionAndStopProcessingToRules < ActiveRecord::Migration[8.1]
+ def up
+ add_column :rules, :position, :integer, null: false, default: 0
+ add_column :rules, :stop_processing, :boolean, null: false, default: false
+ add_index :rules, [ :family_id, :position ]
+
+ # Number existing rules in the order the rules page showed them by default
+ # (name A-Z, unnamed last), so the first run in a fixed order matches what
+ # users already see.
+ execute <<~SQL
+ UPDATE rules SET position = ranked.rn
+ FROM (
+ SELECT id, ROW_NUMBER() OVER (
+ PARTITION BY family_id ORDER BY LOWER(name) NULLS LAST, created_at, id
+ ) AS rn
+ FROM rules
+ ) ranked
+ WHERE rules.id = ranked.id
+ SQL
+ end
+
+ def down
+ remove_index :rules, [ :family_id, :position ]
+ remove_column :rules, :stop_processing
+ remove_column :rules, :position
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 7648d7e2b9..b71bab726a 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -2280,8 +2280,11 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_11_151000) do
t.date "effective_date"
t.uuid "family_id", null: false
t.string "name"
+ t.integer "position", default: 0, null: false
t.string "resource_type", null: false
+ 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"
end
diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml
index 2da85e13c8..1c81880528 100644
--- a/docs/api/openapi.yaml
+++ b/docs/api/openapi.yaml
@@ -1311,6 +1311,8 @@ components:
- id
- resource_type
- active
+ - position
+ - stop_processing
- conditions
- actions
- created_at
@@ -1332,6 +1334,14 @@ components:
type: string
format: date
nullable: true
+ position:
+ type: integer
+ description: Run order within the family; rules run from the lowest position
+ up and the top rule wins per attribute
+ stop_processing:
+ type: boolean
+ description: When true, rules further down do not change transactions this
+ rule matches
conditions:
type: array
items:
diff --git a/lib/tasks/rules.rake b/lib/tasks/rules.rake
index 0a5a5c79a6..e6bd0c4d21 100644
--- a/lib/tasks/rules.rake
+++ b/lib/tasks/rules.rake
@@ -18,16 +18,25 @@ namespace :rules do
puts "Applying #{rules.count} rules for family #{family_id}..."
- rules.find_each do |rule|
- print " Applying rule '#{rule.name || rule.id}'... "
- begin
- RuleJob.perform_now(rule, ignore_attribute_locks: true, execution_type: "manual")
- puts "done"
- rescue => e
- puts "failed: #{e.message}"
- end
+ # One top-to-bottom pass, like "Apply all" in the UI. Called directly rather
+ # than via a job, so a busy family lock fails here instead of being retried
+ # in the background while the task reports success.
+ runner = Rule::Runner.new(family, rules: rules, execution_type: "manual", ignore_attribute_locks: true)
+
+ begin
+ rule_runs = runner.run
+ rescue Rule::Runner::LockBusy => e
+ puts "failed: #{e.message}. Try again once the current sync has finished."
+ exit 1
+ end
+
+ rule_runs.compact.each do |rule_run|
+ line = " Rule '#{rule_run.rule_name || rule_run.rule_id}': #{rule_run.status}"
+ line += " (#{rule_run.error_message})" if rule_run.error_message.present?
+ puts line
end
puts "Finished applying all rules"
+ exit 1 if runner.errors.any?
end
end
diff --git a/spec/swagger_helper.rb b/spec/swagger_helper.rb
index 67fbe52643..fac23ca0ca 100644
--- a/spec/swagger_helper.rb
+++ b/spec/swagger_helper.rb
@@ -747,13 +747,15 @@ RSpec.configure do |config|
},
Rule: {
type: :object,
- required: %w[id resource_type active conditions actions created_at updated_at],
+ required: %w[id resource_type active position stop_processing conditions actions created_at updated_at],
properties: {
id: { type: :string, format: :uuid },
name: { type: :string, nullable: true },
resource_type: { type: :string, enum: %w[transaction] },
active: { type: :boolean },
effective_date: { type: :string, format: :date, nullable: true },
+ position: { type: :integer, description: 'Run order within the family; rules run from the lowest position up and the top rule wins per attribute' },
+ stop_processing: { type: :boolean, description: 'When true, rules further down do not change transactions this rule matches' },
conditions: {
type: :array,
items: { '$ref' => '#/components/schemas/RuleCondition' }
diff --git a/test/controllers/api/v1/rules_controller_test.rb b/test/controllers/api/v1/rules_controller_test.rb
index 5360aa73e8..83f1187204 100644
--- a/test/controllers/api/v1/rules_controller_test.rb
+++ b/test/controllers/api/v1/rules_controller_test.rb
@@ -112,6 +112,8 @@ class Api::V1::RulesControllerTest < ActionDispatch::IntegrationTest
assert_equal "transaction", rule["resource_type"]
assert_equal true, rule["active"]
assert_equal "2024-01-01", rule["effective_date"]
+ assert_equal @rule.reload.position, rule["position"]
+ assert_equal false, rule["stop_processing"]
assert_equal 1, rule["conditions"].length
assert_equal "transaction_name", rule["conditions"].first["condition_type"]
diff --git a/test/controllers/reports_controller_test.rb b/test/controllers/reports_controller_test.rb
index d3dcb32d01..1329d2aeff 100644
--- a/test/controllers/reports_controller_test.rb
+++ b/test/controllers/reports_controller_test.rb
@@ -98,6 +98,18 @@ class ReportsControllerTest < ActionDispatch::IntegrationTest
assert_response :ok
end
+ test "index sections keep data-section-key next to the sortable id" do
+ get reports_path
+ assert_response :ok
+
+ assert_select "section[data-sortable-list-id]" do |sections|
+ assert sections.any?
+ sections.each do |section|
+ assert_equal section["data-sortable-list-id"], section["data-section-key"]
+ end
+ end
+ end
+
# The desktop app clones these into the tray when a download such as the CSV
# export ends, since it has no download list of its own, and reads their data
# attributes for its native notification.
diff --git a/test/controllers/rules_controller_test.rb b/test/controllers/rules_controller_test.rb
index 8b651d3683..53a5a79e1c 100644
--- a/test/controllers/rules_controller_test.rb
+++ b/test/controllers/rules_controller_test.rb
@@ -273,6 +273,53 @@ class RulesControllerTest < ActionDispatch::IntegrationTest
assert_redirected_to rules_url
end
+ test "saves stop processing" do
+ rule = rules(:one)
+
+ patch rule_url(rule), params: { rule: { stop_processing: "1" } }
+
+ assert rule.reload.stop_processing
+ end
+
+ test "index lists rules in run order" do
+ 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)
+
+ get rules_url
+
+ assert_response :success
+ assert_equal ordered_ids, css_select("[data-sortable-list-target='item']").map { |item| item["data-sortable-list-id"] }
+ end
+
+ test "reorder saves the new order" do
+ family = @user.family
+ second = family.rules.create!(resource_type: "transaction",
+ 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
+
+ assert_response :no_content
+ assert_equal ordered_ids, family.rules.ordered.pluck(:id)
+ assert_equal second.id, ordered_ids.first
+ end
+
+ test "reorder rejects rules of another family" do
+ family = @user.family
+ other_rule = families(:empty).rules.create!(resource_type: "transaction",
+ 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
+
+ assert_response :unprocessable_entity
+ assert_equal before, family.rules.ordered.pluck(:id, :position)
+ assert_equal 1, other_rule.reload.position
+ end
+
test "can destroy conditions and actions while editing" do
rule = rules(:one)
@@ -386,6 +433,27 @@ class RulesControllerTest < ActionDispatch::IntegrationTest
assert_match "~typesafe/jev-latest", response.body
end
+ test "confirm says the active rules above run first" do
+ family = @user.family
+ family.rules.destroy_all
+ build = ->(name, active) do
+ family.rules.create!(name: name, resource_type: "transaction", active: active,
+ actions: [ Rule::Action.new(action_type: "exclude_transaction") ])
+ end
+ build.call("Active above", true)
+ build.call("Inactive above", false)
+ rule = build.call("Applied", true)
+ build.call("Below", true)
+
+ get confirm_rule_url(rule)
+ assert_response :success
+ assert_match I18n.t("rules.confirm.rules_above_notice", count: 1), response.body
+
+ get confirm_rule_url(family.rules.find_by!(name: "Active above"))
+ assert_response :success
+ assert_no_match "run first", response.body
+ end
+
test "confirm does not name Jev when the family has not selected it" do
rule = rules(:one)
rule.actions.create!(action_type: "auto_categorize")
diff --git a/test/fixtures/rules.yml b/test/fixtures/rules.yml
index db7a356614..316e7d3a9b 100644
--- a/test/fixtures/rules.yml
+++ b/test/fixtures/rules.yml
@@ -1,3 +1,4 @@
one:
family: dylan_family
- resource_type: "transaction"
\ No newline at end of file
+ resource_type: "transaction"
+ position: 1
diff --git a/test/jobs/apply_all_rules_job_test.rb b/test/jobs/apply_all_rules_job_test.rb
index 68591c29d9..3210f4efe3 100644
--- a/test/jobs/apply_all_rules_job_test.rb
+++ b/test/jobs/apply_all_rules_job_test.rb
@@ -7,35 +7,36 @@ class ApplyAllRulesJobTest < ActiveJob::TestCase
@family = families(:empty)
@account = @family.accounts.create!(name: "Test Account", balance: 1000, currency: "USD", accountable: Depository.new)
@groceries_category = @family.categories.create!(name: "Groceries")
+ @transaction = create_transaction(account: @account, name: "Whole Foods").transaction
end
- test "applies all rules for a family" do
- # Create a rule
- rule = Rule.create!(
- family: @family,
- resource_type: "transaction",
- effective_date: 1.day.ago.to_date,
- conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "Whole Foods") ],
- actions: [ Rule::Action.new(action_type: "set_transaction_category", value: @groceries_category.id) ]
- )
-
- # Mock RuleJob to verify it gets called for each rule
- RuleJob.expects(:perform_now).with(rule, ignore_attribute_locks: true, execution_type: "manual").once
+ test "applies all rules for a family, including inactive ones and locked fields" do
+ rule = create_rule(active: false)
+ @transaction.lock_attr!(:category_id)
ApplyAllRulesJob.perform_now(@family)
+
+ assert_equal @groceries_category, @transaction.reload.category
+ assert_equal "manual", rule.rule_runs.last.execution_type
end
test "applies all rules with custom execution type" do
- rule = Rule.create!(
- family: @family,
- resource_type: "transaction",
- effective_date: 1.day.ago.to_date,
- conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "Test") ],
- actions: [ Rule::Action.new(action_type: "set_transaction_category", value: @groceries_category.id) ]
- )
-
- RuleJob.expects(:perform_now).with(rule, ignore_attribute_locks: true, execution_type: "scheduled").once
+ rule = create_rule(active: true)
ApplyAllRulesJob.perform_now(@family, execution_type: "scheduled")
+
+ assert_equal "scheduled", rule.rule_runs.last.execution_type
end
+
+ private
+ def create_rule(active:)
+ Rule.create!(
+ family: @family,
+ resource_type: "transaction",
+ active: active,
+ effective_date: 1.day.ago.to_date,
+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "Whole Foods") ],
+ actions: [ Rule::Action.new(action_type: "set_transaction_category", value: @groceries_category.id) ]
+ )
+ end
end
diff --git a/test/jobs/apply_rules_job_test.rb b/test/jobs/apply_rules_job_test.rb
new file mode 100644
index 0000000000..64dc4f237b
--- /dev/null
+++ b/test/jobs/apply_rules_job_test.rb
@@ -0,0 +1,51 @@
+require "test_helper"
+
+class ApplyRulesJobTest < ActiveJob::TestCase
+ include EntriesTestHelper
+
+ setup do
+ @family = families(:empty)
+ @account = @family.accounts.create!(name: "Test Account", balance: 1000, currency: "USD", accountable: Depository.new)
+ @groceries = @family.categories.create!(name: "Groceries")
+ @transaction = create_transaction(account: @account, name: "Whole Foods").transaction
+ end
+
+ test "applies only active rules and records scheduled runs" do
+ active_rule = create_rule(active: true)
+ inactive_rule = create_rule(active: false)
+
+ ApplyRulesJob.perform_now(@family)
+
+ assert_equal @groceries, @transaction.reload.category
+ assert_equal [ "scheduled" ], active_rule.rule_runs.pluck(:execution_type)
+ assert_empty inactive_rule.rule_runs
+ end
+
+ test "respects locked fields" do
+ create_rule(active: true)
+ @transaction.lock_attr!(:category_id)
+
+ ApplyRulesJob.perform_now(@family)
+
+ assert_nil @transaction.reload.category
+ end
+
+ test "retries later when another rule run holds the family lock" do
+ create_rule(active: true)
+ Rule::Runner.any_instance.stubs(:run).raises(Rule::Runner::LockBusy)
+
+ assert_enqueued_with(job: ApplyRulesJob) do
+ ApplyRulesJob.perform_now(@family)
+ end
+ end
+
+ private
+ def create_rule(active:)
+ @family.rules.create!(
+ resource_type: "transaction",
+ active: active,
+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "Whole Foods") ],
+ actions: [ Rule::Action.new(action_type: "set_transaction_category", value: @groceries.id) ]
+ )
+ end
+end
diff --git a/test/jobs/rule_job_test.rb b/test/jobs/rule_job_test.rb
index c7d1c462a0..6c761d1445 100644
--- a/test/jobs/rule_job_test.rb
+++ b/test/jobs/rule_job_test.rb
@@ -51,4 +51,35 @@ class RuleJobTest < ActiveJob::TestCase
assert_equal 10, rule_run.transactions_modified
assert_equal 10, rule_run.transactions_blocked
end
+
+ test "a failing rule above is recorded but does not fail the job" do
+ create_transaction(account: @account, name: "Whole Foods")
+ above = @family.rules.create!(
+ name: "Above", resource_type: "transaction", active: true,
+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "Whole Foods") ],
+ actions: [ Rule::Action.new(action_type: "set_transaction_category", value: @groceries.id) ]
+ )
+ above.actions.first.update_column(:action_type, "unknown_action")
+ rule = @family.rules.create!(
+ name: "Applied", resource_type: "transaction",
+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "Whole Foods") ],
+ actions: [ Rule::Action.new(action_type: "set_transaction_category", value: @food_and_dining.id) ]
+ )
+
+ assert_nothing_raised { RuleJob.perform_now(rule) }
+
+ assert_equal "failed", above.rule_runs.last.status
+ assert_equal "success", rule.rule_runs.last.status
+ end
+
+ test "fails the job when the applied rule fails" do
+ rule = @family.rules.create!(
+ name: "Applied", resource_type: "transaction",
+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "Whole Foods") ],
+ actions: [ Rule::Action.new(action_type: "set_transaction_category", value: @food_and_dining.id) ]
+ )
+ rule.actions.first.update_column(:action_type, "unknown_action")
+
+ assert_raises(Rule::Registry::UnsupportedActionError) { RuleJob.perform_now(rule) }
+ end
end
diff --git a/test/lib/tasks/rules_rake_test.rb b/test/lib/tasks/rules_rake_test.rb
new file mode 100644
index 0000000000..d6cc146e2b
--- /dev/null
+++ b/test/lib/tasks/rules_rake_test.rb
@@ -0,0 +1,74 @@
+require "test_helper"
+
+class RulesRakeTest < ActiveJob::TestCase
+ include EntriesTestHelper
+
+ setup do
+ Rails.application.load_tasks unless Rake::Task.task_defined?("rules:apply_all")
+ Rake::Task["rules:apply_all"].reenable
+
+ @family = families(:empty)
+ @account = @family.accounts.create!(name: "Test Account", balance: 1000, currency: "USD", accountable: Depository.new)
+ @groceries = @family.categories.create!(name: "Groceries")
+ @dining = @family.categories.create!(name: "Dining")
+ @transaction = create_transaction(account: @account, name: "Whole Foods").transaction
+ end
+
+ test "applies all rules in a single runner pass" do
+ create_rule(category: @groceries)
+ create_rule(category: @dining)
+
+ Rule::Runner.expects(:new)
+ .with(@family, has_entries(execution_type: "manual", ignore_attribute_locks: true))
+ .once
+ .returns(stub(run: [], errors: []))
+
+ out, = capture_io { Rake::Task["rules:apply_all"].invoke(@family.id) }
+
+ assert_match "Finished applying all rules", out
+ end
+
+ test "sets the category from the top rule" do
+ create_rule(category: @groceries)
+ create_rule(category: @dining)
+
+ out, = capture_io { Rake::Task["rules:apply_all"].invoke(@family.id) }
+
+ assert_equal @groceries, @transaction.reload.category
+ assert_match "success", out
+ end
+
+ test "exits non-zero when a rule fails" do
+ rule = create_rule(category: @groceries)
+ Rule.any_instance.stubs(:apply).raises(StandardError, "boom")
+
+ assert_raises(SystemExit) do
+ capture_io { Rake::Task["rules:apply_all"].invoke(@family.id) }
+ end
+
+ assert_equal "failed", rule.rule_runs.last.status
+ end
+
+ test "reports a busy family lock instead of silently re-enqueueing" do
+ create_rule(category: @groceries)
+ Rule::Runner.any_instance.stubs(:with_family_lock).returns(false)
+
+ assert_raises(SystemExit) do
+ capture_io { Rake::Task["rules:apply_all"].invoke(@family.id) }
+ end
+
+ assert_no_enqueued_jobs
+ assert_nil @transaction.reload.category
+ end
+
+ private
+ def create_rule(category:)
+ Rule.create!(
+ family: @family,
+ resource_type: "transaction",
+ effective_date: 1.day.ago.to_date,
+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "Whole Foods") ],
+ actions: [ Rule::Action.new(action_type: "set_transaction_category", value: category.id) ]
+ )
+ end
+end
diff --git a/test/models/family/data_exporter_test.rb b/test/models/family/data_exporter_test.rb
index dd633c6858..f6bcc2c03f 100644
--- a/test/models/family/data_exporter_test.rb
+++ b/test/models/family/data_exporter_test.rb
@@ -440,6 +440,8 @@ class Family::DataExporterTest < ActiveSupport::TestCase
assert rule_data["data"].key?("name")
assert rule_data["data"].key?("resource_type")
assert rule_data["data"].key?("active")
+ assert_equal @rule.position, rule_data["data"]["position"]
+ assert_equal false, rule_data["data"]["stop_processing"]
assert rule_data["data"].key?("conditions")
assert rule_data["data"].key?("actions")
end
diff --git a/test/models/family/data_importer_test.rb b/test/models/family/data_importer_test.rb
index ea4408ad63..22a251231f 100644
--- a/test/models/family/data_importer_test.rb
+++ b/test/models/family/data_importer_test.rb
@@ -1850,6 +1850,34 @@ class Family::DataImporterTest < ActiveSupport::TestCase
assert_equal 500.0, budget_category.budgeted_spending.to_f
end
+ test "imports rules in their exported run order after existing rules" do
+ existing = @family.rules.create!(resource_type: "transaction",
+ actions: [ Rule::Action.new(action_type: "exclude_transaction") ])
+ rule_record = ->(name, position, stop_processing) do
+ {
+ type: "Rule",
+ version: 1,
+ data: {
+ name: name,
+ resource_type: "transaction",
+ active: true,
+ position: position,
+ stop_processing: stop_processing,
+ conditions: [ { condition_type: "transaction_name", operator: "like", value: name } ],
+ actions: [ { action_type: "exclude_transaction" } ]
+ }
+ }
+ end
+ ndjson = build_ndjson([ rule_record.call("Second", 2, false), rule_record.call("First", 1, true) ])
+
+ Family::DataImporter.new(@family, ndjson).import!
+
+ assert_equal [ existing.id ] + @family.rules.where(name: %w[First Second]).in_order_of(:name, %w[First Second]).pluck(:id),
+ @family.rules.ordered.pluck(:id).last(3)
+ assert @family.rules.find_by(name: "First").stop_processing
+ assert_not @family.rules.find_by(name: "Second").stop_processing
+ end
+
test "imports rules with conditions and actions" do
ndjson = build_ndjson([
{
diff --git a/test/models/family/syncer_test.rb b/test/models/family/syncer_test.rb
index 14fac1c04b..71f768db4e 100644
--- a/test/models/family/syncer_test.rb
+++ b/test/models/family/syncer_test.rb
@@ -1,6 +1,7 @@
require "test_helper"
class Family::SyncerTest < ActiveSupport::TestCase
+ include ActiveJob::TestHelper
setup do
@family = families(:dylan_family)
end
@@ -52,40 +53,13 @@ class Family::SyncerTest < ActiveSupport::TestCase
syncer.perform_sync(family_sync)
end
- test "only applies active rules during sync" do
- family_sync = syncs(:family)
-
- # Create an active rule
- active_rule = @family.rules.create!(
- resource_type: "transaction",
- active: true,
- actions: [ Rule::Action.new(action_type: "exclude_transaction") ]
- )
-
- # Create a disabled rule
- disabled_rule = @family.rules.create!(
- resource_type: "transaction",
- active: false,
- actions: [ Rule::Action.new(action_type: "exclude_transaction") ]
- )
-
+ test "applies rules in one ordered run per family after sync" do
syncer = Family::Syncer.new(@family)
- # Stub the relation to return our specific instances so expectations work
- @family.rules.stubs(:where).with(active: true).returns([ active_rule ])
-
- # Expect apply_later to be called only for the active rule
- active_rule.expects(:apply_later).once
- disabled_rule.expects(:apply_later).never
-
- # Mock the account and plaid item syncs to avoid side effects
- Account.any_instance.stubs(:sync_later)
- syncable_item_associations.each do |association|
- association.klass.any_instance.stubs(:sync_later)
+ assert_enqueued_with(job: ApplyRulesJob, args: [ @family ]) do
+ syncer.perform_post_sync
end
-
- syncer.perform_sync(family_sync)
- syncer.perform_post_sync
+ assert_no_enqueued_jobs(only: RuleJob)
end
private
diff --git a/test/models/financekit/inbox_test.rb b/test/models/financekit/inbox_test.rb
index 2b5077e0cc..3fb2dfe1cd 100644
--- a/test/models/financekit/inbox_test.rb
+++ b/test/models/financekit/inbox_test.rb
@@ -253,7 +253,7 @@ class Financekit::InboxTest < ActiveSupport::TestCase
# Completing the batch without the health write would hide it from the
# recovery sweep, which only looks for incomplete batches. Rolling it back
# has to take the scheduling with it, or recovery redoes work already
- # queued and RuleJob records a second RuleRun for the same capture.
+ # queued and a second RuleRun is recorded for the same capture.
assert_nil batch.reload.downstream_completed_at
assert_nil FinancekitItem.find(@item.id).last_downstream_at
assert_equal enqueued_before, enqueued_jobs.size,
diff --git a/test/models/rule/runner_test.rb b/test/models/rule/runner_test.rb
new file mode 100644
index 0000000000..1ae1571968
--- /dev/null
+++ b/test/models/rule/runner_test.rb
@@ -0,0 +1,324 @@
+require "test_helper"
+
+class Rule::RunnerTest < ActiveSupport::TestCase
+ include EntriesTestHelper
+
+ setup do
+ @family = families(:empty)
+ @account = @family.accounts.create!(name: "Runner test", balance: 1000, currency: "USD", accountable: Depository.new)
+ @groceries = @family.categories.create!(name: "Groceries")
+ @dining = @family.categories.create!(name: "Dining")
+ @tag_a = @family.tags.create!(name: "Tag A")
+ @tag_b = @family.tags.create!(name: "Tag B")
+
+ @whole_foods = create_transaction(account: @account, name: "Whole Foods Market").transaction
+ @other = create_transaction(account: @account, name: "Hardware store").transaction
+ end
+
+ test "the rule higher up wins when two rules set the same field" do
+ create_rule("Top", "Whole Foods", category: @groceries)
+ create_rule("Bottom", "Whole Foods", category: @dining)
+
+ run_active_rules
+
+ assert_equal @groceries, @whole_foods.reload.category
+ end
+
+ 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 ])
+
+ 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)
+ create_rule("Bottom", "Whole Foods", category: @dining)
+
+ run_active_rules
+
+ assert_equal @groceries, @whole_foods.reload.category
+ end
+
+ test "rules further down still set fields the rules above leave alone" do
+ create_rule("Top", "Whole Foods", category: @groceries)
+ create_rule("Bottom", "Whole", name: "Whole Foods")
+
+ run_active_rules
+
+ @whole_foods.reload
+ assert_equal @groceries, @whole_foods.category
+ assert_equal "Whole Foods", @whole_foods.entry.name
+ end
+
+ test "a rule above whose category was deleted does not claim the field" do
+ deleted = @family.categories.create!(name: "Deleted")
+ create_rule("Top", "Whole Foods", category: deleted)
+ create_rule("Bottom", "Whole Foods", category: @dining)
+ deleted.destroy!
+
+ run_active_rules
+
+ assert_equal @dining, @whole_foods.reload.category
+ end
+
+ test "a rule above with a blank name does not claim the name" do
+ top = create_rule("Top", "Whole Foods", name: "Placeholder")
+ top.actions.first.update_column(:value, "")
+ create_rule("Bottom", "Whole", name: "Whole Foods")
+
+ run_active_rules
+
+ assert_equal "Whole Foods", @whole_foods.reload.entry.name
+ end
+
+ test "stop processing keeps rules further down away from matched transactions" do
+ create_rule("Top", "Whole Foods", category: @groceries, stop_processing: true)
+ create_rule("Bottom", "o", name: "Renamed")
+
+ run_active_rules
+
+ assert_equal "Whole Foods Market", @whole_foods.reload.entry.name
+ assert_equal "Renamed", @other.reload.entry.name
+ end
+
+ test "tags from several rules add up" do
+ create_rule("Top", "Whole Foods", tags: [ @tag_a ])
+ create_rule("Bottom", "Whole Foods", tags: [ @tag_b ])
+
+ run_active_rules
+
+ assert_equal [ @tag_a, @tag_b ].map(&:id).sort, @whole_foods.reload.tag_ids.sort
+ end
+
+ test "locked fields stay unchanged in the scheduled run" do
+ @whole_foods.update!(category: @dining)
+ @whole_foods.lock_attr!(:category_id)
+ create_rule("Top", "Whole Foods", category: @groceries)
+
+ run_active_rules
+
+ assert_equal @dining, @whole_foods.reload.category
+ end
+
+ test "applying a single rule runs the active rules above it first" do
+ top = create_rule("Top", "Whole Foods", category: @groceries)
+ bottom = create_rule("Bottom", "Whole Foods", category: @dining)
+
+ runs = Rule::Runner.new(@family, rules: [ bottom ], execution_type: "manual").run
+
+ # Same as the full run: the top rule sets the category and wins
+ assert_equal @groceries, @whole_foods.reload.category
+ assert_equal [ top, bottom ], runs.map(&:rule)
+ end
+
+ test "applying a single rule does not run the rules below it" do
+ top = create_rule("Top", "Whole Foods", category: @groceries)
+ create_rule("Bottom", "Hardware", category: @dining)
+
+ Rule::Runner.new(@family, rules: [ top ], execution_type: "manual").run
+
+ assert_equal @groceries, @whole_foods.reload.category
+ assert_nil @other.reload.category
+ end
+
+ test "ignoring locks only applies to the applied rule, not the rules above" do
+ @whole_foods.entry.lock_attr!(:name)
+ create_rule("Top", "Whole Foods", name: "Renamed")
+ bottom = create_rule("Bottom", "Whole Foods", category: @dining)
+
+ Rule::Runner.new(@family, rules: [ bottom ], execution_type: "manual", ignore_attribute_locks: true).run
+
+ @whole_foods.reload
+ assert_equal "Whole Foods Market", @whole_foods.entry.name
+ assert_equal @dining, @whole_foods.category
+ end
+
+ test "applying a single rule respects stop processing above it" do
+ create_rule("Top", "Whole Foods", category: @groceries, stop_processing: true)
+ bottom = create_rule("Bottom", "Whole Foods", name: "Renamed")
+
+ Rule::Runner.new(@family, rules: [ bottom ], execution_type: "manual").run
+
+ assert_equal "Whole Foods Market", @whole_foods.reload.entry.name
+ end
+
+ test "inactive rules above do not claim fields" do
+ create_rule("Top", "Whole Foods", category: @groceries, active: false)
+ bottom = create_rule("Bottom", "Whole Foods", category: @dining)
+
+ Rule::Runner.new(@family, rules: [ bottom ], execution_type: "manual").run
+
+ assert_equal @dining, @whole_foods.reload.category
+ end
+
+ test "an AI action above does not keep rules below from setting the field" do
+ @family.rules.create!(
+ name: "AI",
+ resource_type: "transaction",
+ active: true,
+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "Whole Foods") ],
+ actions: [ Rule::Action.new(action_type: "auto_categorize") ]
+ )
+ bottom = create_rule("Bottom", "Whole Foods", category: @dining)
+
+ Rule::Runner.new(@family, rules: [ bottom ], execution_type: "manual").run
+
+ assert_equal @dining, @whole_foods.reload.category
+ end
+
+ test "a rule above that cannot be matched does not stop the applied rule" do
+ broken = create_rule("Broken", "Whole Foods", category: @groceries)
+ broken.conditions.first.update!(condition_type: "transaction_notes")
+ Rule::ConditionFilter::TransactionNotes.any_instance.stubs(:apply).raises(ActiveRecord::StatementInvalid, "bad condition")
+ bottom = create_rule("Bottom", "Whole Foods", category: @dining)
+
+ Rule::Runner.new(@family, rules: [ bottom ], execution_type: "manual").run
+
+ assert_equal @dining, @whole_foods.reload.category
+ end
+
+ test "the effective date still limits which transactions a rule touches" do
+ old = create_transaction(account: @account, name: "Whole Foods old", date: 2.years.ago.to_date).transaction
+ create_rule("Top", "Whole Foods", category: @groceries, effective_date: 1.year.ago.to_date)
+
+ run_active_rules
+
+ assert_equal @groceries, @whole_foods.reload.category
+ assert_nil old.reload.category
+ end
+
+ test "records a rule run per executed rule with the scheduled type" do
+ top = create_rule("Top", "Whole Foods", category: @groceries, stop_processing: true)
+ bottom = create_rule("Bottom", "o", name: "Renamed")
+
+ runs = run_active_rules
+
+ assert_equal [ top, bottom ], runs.map(&:rule)
+ assert_equal %w[scheduled scheduled], runs.map(&:execution_type)
+ # The bottom rule no longer sees the transaction the top rule stopped
+ assert_equal 1, runs.last.transactions_queued
+ end
+
+ test "a failing rule is recorded and the remaining rules still run" do
+ top = create_rule("Top", "Whole Foods", category: @groceries)
+ create_rule("Bottom", "Hardware", name: "Renamed")
+ Rule::ActionExecutor::SetTransactionCategory.any_instance.stubs(:execute).raises(StandardError, "boom")
+
+ runner = Rule::Runner.new(@family, rules: @family.rules, execution_type: "manual")
+ runs = runner.run
+
+ assert_equal "failed", runs.first.status
+ assert_equal top, runs.first.rule
+ assert_equal "Renamed", @other.reload.entry.name
+ assert_equal [ "boom" ], runner.errors.map(&:message)
+ end
+
+ test "every action of a rule works on the transactions it matched" do
+ @family.rules.create!(
+ name: "Rename and categorize",
+ resource_type: "transaction",
+ active: true,
+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "Whole Foods") ],
+ # The rename runs first and changes the name the condition reads
+ actions: [
+ Rule::Action.new(action_type: "set_transaction_name", value: "Groceries store"),
+ Rule::Action.new(action_type: "set_transaction_category", value: @groceries.id)
+ ]
+ )
+ create_rule("Catch-all", "o", category: @dining)
+
+ run_active_rules
+
+ @whole_foods.reload
+ assert_equal "Groceries store", @whole_foods.entry.name
+ assert_equal @groceries, @whole_foods.category
+ assert_equal @dining, @other.reload.category
+ end
+
+ test "applying a single rule sees the changes the rules above make" do
+ create_rule("Rename", "Whole Foods", name: "Supermarket")
+ middle = create_rule("Middle", "Supermarket", category: @groceries)
+ create_rule("Catch-all", "o", category: @dining)
+
+ Rule::Runner.new(@family, rules: [ middle ], execution_type: "manual").run
+
+ @whole_foods.reload
+ single_result = [ @whole_foods.entry.name, @whole_foods.category ]
+ assert_equal [ "Supermarket", @groceries ], single_result
+ # The catch-all below the applied rule did not run
+ assert_nil @other.reload.category
+
+ run_active_rules
+
+ @whole_foods.reload
+ assert_equal single_result, [ @whole_foods.entry.name, @whole_foods.category ]
+ assert_equal @dining, @other.reload.category
+ end
+
+ test "a rule with a broken action does not stop the rules below" do
+ broken = create_rule("Broken", "Whole Foods", category: @groceries)
+ broken.actions.first.update_column(:action_type, "unknown_action")
+ create_rule("Bottom", "Whole Foods", category: @dining)
+
+ runner = Rule::Runner.new(@family, rules: @family.rules, execution_type: "manual")
+ runs = runner.run
+
+ assert_equal [ "failed", "success" ], runs.map(&:status)
+ assert_equal @dining, @whole_foods.reload.category
+ end
+
+ test "a broken action above an applied rule does not stop it" do
+ broken = create_rule("Broken", "Whole Foods", category: @groceries)
+ broken.actions.first.update_column(:action_type, "unknown_action")
+ bottom = create_rule("Bottom", "Whole Foods", category: @dining)
+
+ Rule::Runner.new(@family, rules: [ bottom ], execution_type: "manual").run
+
+ assert_equal @dining, @whole_foods.reload.category
+ end
+
+ test "raises LockBusy while another run holds the family lock" do
+ create_rule("Top", "Whole Foods", category: @groceries)
+
+ # Transactional tests share one PG session, and a session can re-take its
+ # own advisory lock, so holding it needs a separate connection.
+ config = ActiveRecord::Base.connection_pool.db_config.configuration_hash
+ other = PG.connect({
+ dbname: config[:database], host: config[:host], port: config[:port],
+ user: config[:username] || config[:user], password: config[:password]
+ }.compact)
+ other.exec("SELECT pg_advisory_lock(#{Rule::Runner.advisory_lock_key(@family.id)})")
+
+ assert_raises(Rule::Runner::LockBusy) { run_active_rules }
+ assert_nil @whole_foods.reload.category
+ ensure
+ other&.close
+ end
+
+ private
+ def run_active_rules
+ Rule::Runner.new(@family, rules: @family.rules.where(active: true), execution_type: "scheduled").run
+ end
+
+ def create_rule(name, match, category: nil, tags: nil, stop_processing: false, active: true, effective_date: nil, **options)
+ actions = []
+ actions << Rule::Action.new(action_type: "set_transaction_category", value: category.id) if category
+ actions << Rule::Action.new(action_type: "set_transaction_tags", value: tags.map(&:id)) if tags
+ actions << Rule::Action.new(action_type: "set_transaction_name", value: options[:name]) if options[:name]
+
+ @family.rules.create!(
+ name: name,
+ resource_type: "transaction",
+ active: active,
+ stop_processing: stop_processing,
+ effective_date: effective_date,
+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: match) ],
+ actions: actions
+ )
+ end
+end
diff --git a/test/models/rule_position_concurrency_test.rb b/test/models/rule_position_concurrency_test.rb
new file mode 100644
index 0000000000..8c1817dd11
--- /dev/null
+++ b/test/models/rule_position_concurrency_test.rb
@@ -0,0 +1,41 @@
+require "test_helper"
+require "concurrent"
+
+# Rules created for the same family at the same time must still get distinct
+# run positions. Real threads on real connections, so this needs real commits.
+class RulePositionConcurrencyTest < ActiveSupport::TestCase
+ self.use_transactional_tests = false
+
+ # Stays below the test database pool size (the test thread holds one).
+ WRITERS = 3
+
+ setup do
+ @family = Family.create!(name: "Rule Position Race", currency: "USD")
+ end
+
+ teardown do
+ Rule.where(family_id: @family.id).destroy_all
+ @family.destroy
+ end
+
+ test "concurrently created rules get distinct positions" do
+ latch = Concurrent::CountDownLatch.new(WRITERS)
+
+ WRITERS.times.map do
+ Thread.new do
+ ActiveRecord::Base.connection_pool.with_connection do
+ latch.count_down
+ latch.wait(5)
+ @family.rules.create!(
+ resource_type: "transaction",
+ actions: [ Rule::Action.new(action_type: "exclude_transaction") ]
+ )
+ end
+ end
+ end.each(&:join)
+
+ positions = Rule.where(family_id: @family.id).pluck(:position)
+ assert_equal WRITERS, positions.size
+ assert_equal (1..WRITERS).to_a, positions.sort
+ end
+end
diff --git a/test/models/rule_test.rb b/test/models/rule_test.rb
index 60b6b42f9e..3f74fc9da6 100644
--- a/test/models/rule_test.rb
+++ b/test/models/rule_test.rb
@@ -443,4 +443,38 @@ class RuleTest < ActiveSupport::TestCase
assert_nil transaction_entry2.transaction.category,
"Transaction on other account should not be categorized"
end
+
+ test "new rules are added at the end of the run order" do
+ first = create_exclude_rule
+ second = create_exclude_rule
+
+ assert_equal first.position + 1, second.position
+ assert_equal [ first, second ], @family.rules.ordered.to_a
+ end
+
+ test "update_positions! sets the order of all rules of the family" 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
+
+ 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
+ end
+
+ private
+ def create_exclude_rule
+ @family.rules.create!(resource_type: "transaction", actions: [ Rule::Action.new(action_type: "exclude_transaction") ])
+ end
end
diff --git a/test/system/reports_test.rb b/test/system/reports_test.rb
index 2cf5a79106..8d880c9f7a 100644
--- a/test/system/reports_test.rb
+++ b/test/system/reports_test.rb
@@ -24,7 +24,7 @@ class ReportsTest < ApplicationSystemTestCase
end
test "the arrow keys leave section moves and dialogs alone" do
- find("section[data-section-key]", match: :first).send_keys(:enter)
+ find("section[data-sortable-list-id]", match: :first).send_keys(:enter)
page.send_keys(:arrow_left)
assert_empty clicked_hotkeys
page.send_keys(:escape)
diff --git a/test/system/rules_test.rb b/test/system/rules_test.rb
index 2e54c814b1..08d6d8d5a2 100644
--- a/test/system/rules_test.rb
+++ b/test/system/rules_test.rb
@@ -35,6 +35,29 @@ class RulesTest < ApplicationSystemTestCase
assert_selector "td", text: "20 / 20 / 10 / 10"
end
+ test "reorders rules with the keyboard" do
+ family = @user.family
+ family.rules.destroy_all
+ first = family.rules.create!(name: "First rule", resource_type: "transaction",
+ actions: [ Rule::Action.new(action_type: "exclude_transaction") ])
+ second = family.rules.create!(name: "Second rule", resource_type: "transaction",
+ actions: [ Rule::Action.new(action_type: "exclude_transaction") ])
+
+ visit rules_path
+
+ grip = find("[data-sortable-list-id='#{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}']"
+ # 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 ] ||
+ Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline
+ assert_equal [ second.id, first.id ], family.rules.ordered.pluck(:id)
+ end
+
test "rules page renders gracefully when a condition has an unsupported condition_type" do
@user.update!(locale: "de")
rule = @user.family.rules.create!(