The personal finance app for everyone (by everyone)
Ruby
feat(rules): apply rules immediately to new and changed transactions (#4347)
GFRf9f16b369851
diff --git a/app/components/DS/tag_select.html.erb b/app/components/DS/tag_select.html.erbindex f1516807c0..6d21ddcb22 100644--- a/app/components/DS/tag_select.html.erb+++ b/app/components/DS/tag_select.html.erb@@ -1,5 +1,4 @@-<div class="relative"- data-controller="tag-select"+<div data-controller="tag-select"data-tag-select-create-url-value="<%= helpers.tags_path(format: :json) %>"data-tag-select-field-name-value="<%= field_name %>"data-tag-select-default-color-value="<%= Tag::COLORS.first %>"@@ -9,72 +8,83 @@data-tag-select-menu-placement-value="<%= menu_placement %>"data-tag-select-offset-value="<%= offset %>"data-action="click@window->tag-select#handleOutsideClick keydown->tag-select#handleKeydown">- <div class="form-field">- <div class="form-field__body">- <% if show_label %>- <%= form.label attribute, label || helpers.t("transactions.form.tags_label"), class: "form-field__label" %>- <% end %>+ <%# The menu is anchored here, so the save error below doesn't move it. %>+ <div class="relative">+ <div class="form-field">+ <div class="form-field__body">+ <% if show_label %>+ <%= form.label attribute, label || helpers.t("transactions.form.tags_label"), class: "form-field__label" %>+ <% end %>- <button type="button"- class="form-field__input form-field__input--multiselect-trigger <%= trigger_height_class %> flex items-center gap-2 pr-8 <%= "cursor-not-allowed text-subdued" if disabled %>"- data-tag-select-target="button"- data-action="click->tag-select#toggle"- id="<%= form.field_id(attribute) %>"- aria-haspopup="listbox"- aria-expanded="false"- aria-controls="<%= menu_id %>"- <% unless show_label %> aria-label="<%= label || helpers.t("transactions.form.tags_label") %>" <% end %>- <%= "disabled" if disabled %>>- <span class="flex flex-wrap gap-1 <%= selection_class %>"- data-tag-select-target="selectionContainer"- data-placeholder="<%= helpers.t("transactions.form.none") %>">- <span class="text-secondary"><%= helpers.t("transactions.form.none") %></span>- </span>- </button>+ <button type="button"+ class="form-field__input form-field__input--multiselect-trigger <%= trigger_height_class %> flex items-center gap-2 pr-8 <%= "cursor-not-allowed text-subdued" if disabled %>"+ data-tag-select-target="button"+ data-action="click->tag-select#toggle"+ id="<%= form.field_id(attribute) %>"+ aria-haspopup="listbox"+ aria-expanded="false"+ aria-controls="<%= menu_id %>"+ <% unless show_label %> aria-label="<%= label || helpers.t("transactions.form.tags_label") %>" <% end %>+ <%= "disabled" if disabled %>>+ <span class="flex flex-wrap gap-1 <%= selection_class %>"+ data-tag-select-target="selectionContainer"+ data-placeholder="<%= helpers.t("transactions.form.none") %>">+ <span class="text-secondary"><%= helpers.t("transactions.form.none") %></span>+ </span>+ </button>+ </div></div>- </div>- <div data-tag-select-hidden-inputs>- <input type="hidden" name="<%= field_name %>" value="" <%= "disabled" if disabled %>>- </div>+ <div data-tag-select-hidden-inputs>+ <input type="hidden" name="<%= field_name %>" value="" <%= "disabled" if disabled %>>+ </div>- <% unless disabled %>- <div class="absolute z-50 p-1.5 w-full min-w-32 rounded-lg shadow-lg shadow-border-xs bg-container mt-1.5 transition duration-150 ease-out -translate-y-1 opacity-0 hidden"- data-tag-select-target="menu">- <div class="flex items-center bg-container border border-secondary rounded-lg mb-1 focus-ring-within transition-shadow">- <%= render DS::SearchInput.new(- variant: :embedded,- class: "flex-1 min-w-0",- placeholder: helpers.t("transactions.form.tag_search_placeholder"),- data: {- tag_select_target: "search",- action: "input->tag-select#filter keydown->tag-select#handleSearchKeydown"- }- ) %>- </div>+ <% unless disabled %>+ <div class="absolute z-50 p-1.5 w-full min-w-32 rounded-lg shadow-lg shadow-border-xs bg-container mt-1.5 transition duration-150 ease-out -translate-y-1 opacity-0 hidden"+ data-tag-select-target="menu">+ <div class="flex items-center bg-container border border-secondary rounded-lg mb-1 focus-ring-within transition-shadow">+ <%= render DS::SearchInput.new(+ variant: :embedded,+ class: "flex-1 min-w-0",+ placeholder: helpers.t("transactions.form.tag_search_placeholder"),+ data: {+ tag_select_target: "search",+ action: "input->tag-select#filter keydown->tag-select#handleSearchKeydown"+ }+ ) %>+ </div>- <div class="flex flex-col gap-1 max-h-64 overflow-auto"- id="<%= menu_id %>"- role="listbox"- aria-multiselectable="true"- tabindex="-1">- <% tags.each do |tag| %>- <% selected = selected_ids.include?(tag.id.to_s) %>- <%= render partial: "DS/tag_select/option", locals: { tag: tag, selected: selected, view_helpers: helpers } %>- <% end %>+ <div class="flex flex-col gap-1 max-h-64 overflow-auto"+ id="<%= menu_id %>"+ role="listbox"+ aria-multiselectable="true"+ tabindex="-1">+ <% tags.each do |tag| %>+ <% selected = selected_ids.include?(tag.id.to_s) %>+ <%= render partial: "DS/tag_select/option", locals: { tag: tag, selected: selected, view_helpers: helpers } %>+ <% end %>- <button type="button"- class="hidden text-primary text-sm cursor-pointer items-center gap-2 px-3 py-1.5 rounded-lg hover:bg-container-inset-hover"- data-tag-select-target="createForm"- data-action="click->tag-select#createTag">- <%= helpers.icon("plus") %>- <span><%= helpers.t("transactions.form.create_tag") %> "<span data-tag-select-create-name></span>"</span>- </button>- <p class="hidden px-3 py-1 text-xs text-destructive"- data-tag-select-target="createError"- aria-live="assertive"- aria-atomic="true"></p>+ <button type="button"+ class="hidden text-primary text-sm cursor-pointer items-center gap-2 px-3 py-1.5 rounded-lg hover:bg-container-inset-hover"+ data-tag-select-target="createForm"+ data-action="click->tag-select#createTag">+ <%= helpers.icon("plus") %>+ <span><%= helpers.t("transactions.form.create_tag") %> "<span data-tag-select-create-name></span>"</span>+ </button>+ <p class="hidden px-3 py-1 text-xs text-destructive"+ data-tag-select-target="createError"+ aria-live="assertive"+ aria-atomic="true"></p>+ </div></div>- </div>+ <% end %>+ </div>++ <% if auto_submit %>+ <p class="hidden mt-1 text-xs text-destructive"+ data-tag-select-target="saveError"+ role="alert">+ <%= helpers.t("transactions.form.tags_save_error") %>+ </p><% end %></div>diff --git a/app/controllers/api/v1/rule_runs_controller.rb b/app/controllers/api/v1/rule_runs_controller.rbindex 79120c9d62..d53d920ef7 100644--- a/app/controllers/api/v1/rule_runs_controller.rb+++ b/app/controllers/api/v1/rule_runs_controller.rb@@ -4,7 +4,7 @@ class Api::V1::RuleRunsController < Api::V1::BaseControllerinclude Pagy::BackendSTATUSES = %w[pending success failed].freeze- EXECUTION_TYPES = %w[manual scheduled].freeze+ EXECUTION_TYPES = %w[manual scheduled immediate].freezeInvalidFilterError = Class.new(StandardError)before_action :ensure_read_scopediff --git a/app/controllers/api/v1/transactions_controller.rb b/app/controllers/api/v1/transactions_controller.rbindex 5ce2a5fba7..fb189aa1e3 100644--- a/app/controllers/api/v1/transactions_controller.rb+++ b/app/controllers/api/v1/transactions_controller.rb@@ -112,6 +112,7 @@ class Api::V1::TransactionsController < Api::V1::BaseController@entry.transaction.lock_attr!(:tag_ids) if @entry.transaction.tags.any?@entry.mark_user_modified! if user_modified_requested?@entry.sync_account_later+ @entry.apply_immediate_rules_later@transaction = @entry.transactionrender :show, status: :created@@ -155,6 +156,9 @@ class Api::V1::TransactionsController < Api::V1::BaseControllerreturn render_validation_error("Unknown category id") if unknown_category_id?return render_validation_error("Unknown merchant id") if unknown_merchant_id?+ rule_input = @entry.rule_input_snapshot+ updated = false+Entry.transaction doif @entry.update(entry_params_for_update)sync_needed = @entry.saved_changes_affect_balances?@@ -172,6 +176,7 @@ class Api::V1::TransactionsController < Api::V1::BaseController@entry.mark_user_modified! if user_modified_requested?@transaction = @entry.transaction+ updated = truerender :showelserender json: {@@ -183,6 +188,10 @@ class Api::V1::TransactionsController < Api::V1::BaseControllerendend+ # After the commit, so the enqueue runs here and not in a deferred+ # after-commit callback once the response is already rendered.+ @entry.apply_immediate_rules_later(changed_from: rule_input) if updated+rescue => eRails.logger.error "TransactionsController#update error: #{e.message}"Rails.logger.error e.backtrace.join("\n")diff --git a/app/controllers/rules_controller.rb b/app/controllers/rules_controller.rbindex 48be13c56a..3cce1c532b 100644--- a/app/controllers/rules_controller.rb+++ b/app/controllers/rules_controller.rb@@ -246,7 +246,7 @@ class RulesController < ApplicationControllerdef rule_paramsparams.require(:rule).permit(- :resource_type, :effective_date, :active, :name, :stop_processing,+ :resource_type, :effective_date, :active, :name, :stop_processing, :apply_immediately,:rule_group_id, :new_rule_group_name,conditions_attributes: [:id, :condition_type, :operator, :value, :_destroy,diff --git a/app/controllers/transaction_categories_controller.rb b/app/controllers/transaction_categories_controller.rbindex b734af281f..694a2600ee 100644--- a/app/controllers/transaction_categories_controller.rb+++ b/app/controllers/transaction_categories_controller.rb@@ -8,6 +8,7 @@ class TransactionCategoriesController < ApplicationController# read-only (Transaction#category_set_on_transfer_outflow?).return head(:unprocessable_entity) if @entry.transaction.category_set_on_transfer_outflow?+ rule_input = @entry.rule_input_snapshot@entry.update!(entry_params)transaction = @entry.transaction@@ -25,6 +26,7 @@ class TransactionCategoriesController < ApplicationControllertransaction.lock_saved_attributes!@entry.lock_saved_attributes!+ @entry.apply_immediate_rules_later(changed_from: rule_input)in_split_group = helpers.in_split_group?(@entry, params[:grouped])respond_to do |format|diff --git a/app/controllers/transactions/bulk_updates_controller.rb b/app/controllers/transactions/bulk_updates_controller.rbindex 4e0eace4f0..6766f8ac83 100644--- a/app/controllers/transactions/bulk_updates_controller.rb+++ b/app/controllers/transactions/bulk_updates_controller.rb@@ -41,15 +41,20 @@ class Transactions::BulkUpdatesController < ApplicationControllerfull_ids = rows.select(&:last).map(&:first).uniqannotate_ids = rows.map(&:first).uniq - full_ids+ changed_ids = []+ collect_changed = ->(entry) { changed_ids << entry.entryable_id }+updated = Entry.transaction do# The two groups below lock their rows in different orders. Lock the full# selection first, so requests with opposite permissions cannot deadlock.Entry.lock_for_bulk_update!(full_ids + annotate_ids)- bulk_update_entries(full_ids, scoped_params) +- bulk_update_entries(annotate_ids, scoped_params.slice(*AccountShare::ANNOTATE_ENTRY_ATTRIBUTES, *AccountShare::ANNOTATE_TRANSACTION_ATTRIBUTES))+ bulk_update_entries(full_ids, scoped_params, &collect_changed) ++ bulk_update_entries(annotate_ids, scoped_params.slice(*AccountShare::ANNOTATE_ENTRY_ATTRIBUTES, *AccountShare::ANNOTATE_TRANSACTION_ATTRIBUTES), &collect_changed)end+ Rule.apply_immediately_later(Current.family, changed_ids)+redirect_back_or_to transactions_path, notice: "#{updated} transactions updated"rescue ActiveRecord::RecordInvalid => eDebugLogEntry.capture(@@ -69,11 +74,11 @@ class Transactions::BulkUpdatesController < ApplicationControllerendprivate- def bulk_update_entries(entry_ids, attributes)+ def bulk_update_entries(entry_ids, attributes, &on_change)return 0 if entry_ids.empty?Current.family.entries.where(id: entry_ids).includes(:entryable)- .bulk_update!(attributes, update_tags: attributes.key?(:tag_ids))+ .bulk_update!(attributes, update_tags: attributes.key?(:tag_ids), &on_change)enddef bulk_update_paramsdiff --git a/app/controllers/transactions/categorizes_controller.rb b/app/controllers/transactions/categorizes_controller.rbindex a2cc42ace4..b8eee19fc6 100644--- a/app/controllers/transactions/categorizes_controller.rb+++ b/app/controllers/transactions/categorizes_controller.rb@@ -29,7 +29,9 @@ class Transactions::CategorizesController < ApplicationControllercategory = Current.family.categories.find(params[:category_id])entries = Current.annotatable_entries.excluding_split_parents.where(id: entry_ids)- count = entries.bulk_update!({ category_id: category.id })+ changed_ids = []+ count = entries.bulk_update!({ category_id: category.id }) { |entry| changed_ids << entry.entryable_id }+ Rule.apply_immediately_later(Current.family, changed_ids)if params[:create_rule] == "1" && (count.positive? || entry_ids.empty?)rule = Rule.create_from_grouping(@@ -98,7 +100,9 @@ class Transactions::CategorizesController < ApplicationControllerall_entry_ids = Array.wrap(params[:all_entry_ids]).reject(&:blank?)remaining_ids = all_entry_ids - [ entry.id.to_s ]- Current.annotatable_entries.where(id: entry.id).bulk_update!({ category_id: category.id })+ changed_ids = []+ Current.annotatable_entries.where(id: entry.id).bulk_update!({ category_id: category.id }) { |changed| changed_ids << changed.entryable_id }+ Rule.apply_immediately_later(Current.family, changed_ids)remaining_entries = uncategorized_entries_for(remaining_ids)remaining_ids = remaining_entries.map { |e| e.id.to_s }diff --git a/app/controllers/transactions_controller.rb b/app/controllers/transactions_controller.rbindex 502ec04c81..22a2f07625 100644--- a/app/controllers/transactions_controller.rb+++ b/app/controllers/transactions_controller.rb@@ -151,6 +151,7 @@ class TransactionsController < ApplicationController@entry.lock_saved_attributes!@entry.mark_user_modified!@entry.transaction.lock_attr!(:tag_ids) if @entry.transaction.tags.any?+ @entry.apply_immediate_rules_laterrespond_with_created_entry(@entry)else@@ -172,6 +173,8 @@ class TransactionsController < ApplicationControllerenddef update+ rule_input = @entry.rule_input_snapshot+if @entry.update(permitted_entry_params)sync_needed = @entry.saved_changes_affect_balances?transaction = @entry.transaction@@ -190,6 +193,7 @@ class TransactionsController < ApplicationController@entry.mark_user_modified!@entry.transaction.lock_attr!(:tag_ids) if @entry.transaction.tags.any?@entry.sync_account_later if sync_needed+ @entry.apply_immediate_rules_later(changed_from: rule_input)notes_changed = @entry.saved_change_to_notes?@@ -244,18 +248,25 @@ class TransactionsController < ApplicationControllerdef update_tagsreturn unless require_account_permission!(@entry.account, :annotate, redirect_path: transaction_path(@entry))+ rule_input = @entry.rule_input_snapshot+# The transaction-row tag picker toggles one tag at a time; the drawer's- # multiselect sends the full set.+ # multiselect sends the full set, plus the set it last saved so only its+ # own changes apply and tags a rule added meanwhile stay.if params[:toggle_tag_id].present?@toggled_tag = Current.family.tags.find(params[:toggle_tag_id])@entry.transaction.toggle_tag!(@toggled_tag)+ elsif params.key?(:previous_tag_ids)+ previous_ids = Array(params[:previous_tag_ids]).reject(&:blank?)+ @entry.transaction.merge_tag_changes!(tag_ids_param, previous_ids, available_tags: Current.family.tags)else- @entry.transaction.tag_ids = Current.family.tags.where(id: tag_ids_param).pluck(:id)+ @entry.transaction.replace_tags!(tag_ids_param, available_tags: Current.family.tags)end@entry.lock_saved_attributes!@entry.mark_user_modified!@entry.transaction.lock_attr!(:tag_ids)+ @entry.apply_immediate_rules_later(changed_from: rule_input)respond_to do |format|# JSON stays first so Accept: */* callers keep the original response.diff --git a/app/javascript/controllers/tag_select_controller.js b/app/javascript/controllers/tag_select_controller.jsindex e11e76c173..86b5f474f8 100644--- a/app/javascript/controllers/tag_select_controller.js+++ b/app/javascript/controllers/tag_select_controller.js@@ -10,6 +10,7 @@ export default class extends Controller {"selectionContainer","createForm","createError",+ "saveError",];static values = {@@ -31,12 +32,16 @@ export default class extends Controller {.filter((option) => option.getAttribute("aria-selected") === "true").map((option) => option.dataset.tagId),);+ // The set last saved from here; the server applies only the difference,+ // so tags something else (e.g. a rule) set in the meantime survive.+ this.savedIds = new Set(this.selectedIds);+ // Tags a failed save tried to change: it may still have been applied.+ this.unconfirmedIds = new Set();this.renderSelection();this.observeMenuResize();}disconnect() {- if (this.submitAbortController) this.submitAbortController.abort();this.stopAutoUpdate();if (this.resizeObserver) this.resizeObserver.disconnect();}@@ -124,12 +129,11 @@ export default class extends Controller {}handleSearchKeydown(event) {- if (- event.key === "Enter" &&- !this.createFormTarget.classList.contains("hidden") &&- !this.creating- ) {- event.preventDefault();+ if (event.key !== "Enter") return;++ // Never submit the surrounding form natively.+ event.preventDefault();+ if (!this.createFormTarget.classList.contains("hidden") && !this.creating) {this.createTag();}}@@ -226,17 +230,36 @@ export default class extends Controller {if (this.isOpen && !this.element.contains(event.target)) this.close();}- async submitForm() {+ submitForm() {if (!this.autoSubmitValue) return;if (!this.hasUpdateUrlValue || !this.updateUrlValue) return;- if (this.submitAbortController) this.submitAbortController.abort();-- const abortController = new AbortController();- this.submitAbortController = abortController;+ // Saves run one after another, never aborted: an aborted request may+ // still have been applied, and the next save's previous_tag_ids would+ // then miss it, so undoing a tag quickly would not undo it.+ this.saveQueue = (this.saveQueue || Promise.resolve())+ .catch(() => {})+ .then(() => this.saveSelection());+ return this.saveQueue;+ }++ async saveSelection() {+ const selected = new Set(this.selectedIds);+ // Unconfirmed tags are sent as changes again, whatever their saved state.+ const previous = new Set(this.savedIds);+ this.unconfirmedIds.forEach((id) => {+ if (selected.has(id)) previous.delete(id);+ else previous.add(id);+ });+ const changedIds = [+ ...[...selected].filter((id) => !previous.has(id)),+ ...[...previous].filter((id) => !selected.has(id)),+ ];+ if (changedIds.length === 0) return;+ let saved = false;try {- await fetch(this.updateUrlValue, {+ const response = await fetch(this.updateUrlValue, {method: "PATCH",headers: {Accept: "application/json",@@ -245,17 +268,35 @@ export default class extends Controller {"X-Requested-With": "XMLHttpRequest",},body: JSON.stringify({- tag_ids: Array.from(this.selectedIds),+ tag_ids: [...selected],+ previous_tag_ids: [...previous],}),credentials: "same-origin",- signal: abortController.signal,});- } catch (error) {- if (error.name !== "AbortError") throw error;+ // Only the endpoint's own JSON answer means the tags were saved, never a+ // page some redirect (e.g. to a login page) led to.+ saved =+ response.ok &&+ !response.redirected &&+ (response.headers.get("Content-Type") || "").includes(+ "application/json",+ );} finally {- if (this.submitAbortController === abortController) {- this.submitAbortController = null;+ if (saved) {+ this.savedIds = selected;+ this.unconfirmedIds.clear();+ } else {+ changedIds.forEach((id) => this.unconfirmedIds.add(id));}+ this.toggleSaveError(!saved);+ }+ }++ // The selection stays as picked: a failed request may still have been+ // applied, so its tags are sent again with the next change.+ toggleSaveError(show) {+ if (this.hasSaveErrorTarget) {+ this.saveErrorTarget.classList.toggle("hidden", !show);}}diff --git a/app/jobs/apply_immediate_rules_job.rb b/app/jobs/apply_immediate_rules_job.rbnew file mode 100644index 0000000000..7a01628384--- /dev/null+++ b/app/jobs/apply_immediate_rules_job.rb@@ -0,0 +1,28 @@+# Applies the "apply immediately" rules to transactions a person just created or+# changed. Like "Apply rule", the active rules above them run first on the same+# transactions, so each immediate rule gives the result of its turn in the+# nightly run. Rules below the last immediate rule wait for the nightly run.+class ApplyImmediateRulesJob < ApplicationJob+ queue_as :medium_priority++ retry_on Rule::Runner::LockBusy, wait: 30.seconds, attempts: 20++ def perform(family, transaction_ids:)+ rules = family.rules.applied_immediately+ return if rules.none?++ runner = Rule::Runner.new(+ family,+ rules: rules,+ execution_type: "immediate",+ transaction_ids: transaction_ids+ )+ runner.run++ # The AI jobs of a rule offer their own changes once they are done+ # (RuleRun#complete_job!), so only what the run changed itself counts here.+ return unless runner.changed_now_count.positive?++ RuleRun.offer_immediate_result(family)+ end+enddiff --git a/app/models/assistant/function/create_transaction.rb b/app/models/assistant/function/create_transaction.rbindex 9ecd11bcd7..f3f896631a 100644--- a/app/models/assistant/function/create_transaction.rb+++ b/app/models/assistant/function/create_transaction.rb@@ -203,6 +203,8 @@ class Assistant::Function::CreateTransaction < Assistant::Functionsync_warning = "Transaction created, but the post-create account sync could not be enqueued (#{e.class}). The balance will recalculate on the next sync."end+ entry.apply_immediate_rules_later+transaction = entry.transactionresponse = {success: true,diff --git a/app/models/assistant/function/update_transaction.rb b/app/models/assistant/function/update_transaction.rbindex c78af2e832..4de058f3b1 100644--- a/app/models/assistant/function/update_transaction.rb+++ b/app/models/assistant/function/update_transaction.rb@@ -73,6 +73,8 @@ class Assistant::Function::UpdateTransaction < Assistant::Functionreturn error("no_changes", "Provide at least one field to update.") if no_changes?(entry_attrs, params)+ rule_input = entry.rule_input_snapshot+Entry.transaction doentry.update!(entry_attrs)@@ -86,6 +88,8 @@ class Assistant::Function::UpdateTransaction < Assistant::Functionentry.lock_saved_attributes!end+ entry.apply_immediate_rules_later(changed_from: rule_input)+{success: true,transaction: serialize(transaction.reload),diff --git a/app/models/entry.rb b/app/models/entry.rbindex d25ac3075e..f335488d81 100644--- a/app/models/entry.rb+++ b/app/models/entry.rb@@ -458,6 +458,39 @@ class Entry < ApplicationRecordentryable.lock_saved_attributes!end+ # Columns no rule condition or action reads: how an entry was edited, and+ # import and reconciliation bookkeeping. Any other column counts, so a+ # column rules start reading later can't be missed.+ RULE_INPUT_IGNORED_COLUMNS = %w[+ updated_at locked_attributes user_modified+ import_locked reconciled_at reconciled_by_statement_id+ ].freeze++ # What rules can read from this transaction. Taken before an edit and passed+ # to apply_immediate_rules_later, so an edit that changed nothing (same+ # values, or only fields the person may not change) runs no rules. Tags are+ # read from the database, since toggle_tag! bypasses the loaded association,+ # unless the caller already has them.+ def rule_input_snapshot(tag_ids: nil)+ return unless transaction?++ [+ attributes.except(*RULE_INPUT_IGNORED_COLUMNS),+ entryable.attributes.except(*RULE_INPUT_IGNORED_COLUMNS),+ (tag_ids || Tagging.where(taggable: entryable).pluck(:tag_id)).map(&:to_s).sort+ ]+ end++ # Rules set to "apply immediately" run for this transaction after a person+ # created or changed it. With changed_from (a rule_input_snapshot from before+ # the edit) they only run when the edit changed something.+ def apply_immediate_rules_later(changed_from: nil)+ return unless transaction?+ return if changed_from && changed_from == rule_input_snapshot++ Rule.apply_immediately_later(account.family, entryable_id)+ end+# Enqueues an account sync whose window starts at the earliest date this# entry has occupied since it was loaded, so balances are recomputed from# wherever the entry used to sit.@@ -841,6 +874,9 @@ class Entry < ApplicationRecord# To avoid accidentally clearing tags when only updating other fields,# tags are only modified when explicitly requested via update_tags: true.#+ # With a block, yields each transaction entry whose values actually changed+ # (see Entry#rule_input_snapshot), e.g. to run immediate rules on them.+ ## @param bulk_update_params [Hash] The parameters to update# @param update_tags [Boolean] Whether to update tags (default: false)def bulk_update!(bulk_update_params, update_tags: false)@@ -895,8 +931,19 @@ class Entry < ApplicationRecordSet.newend+ # Tags before the edit for all entries in one query, not one per entry.+ tag_ids_before = if block_given?+ Tagging.where(taggable_type: "Transaction", taggable_id: locked_entries.map(&:entryable_id))+ .pluck(:taggable_id, :tag_id)+ .group_by(&:first).transform_values { |pairs| pairs.map(&:last) }+ end+locked_entries.each do |entry|changed = false+ if block_given?+ tags_before = tag_ids_before.fetch(entry.entryable_id, [])+ before = entry.rule_input_snapshot(tag_ids: tags_before)+ end# Whether this row's changes should lock saved attributes / mark# user-modified. Reconciling is a verification action, not an# edit — the single-row Entry#advance_reconciled_status! (used by@@ -966,6 +1013,10 @@ class Entry < ApplicationRecordentry.lock_saved_attributes!entry.mark_user_modified!end+ if block_given?+ tags_after = update_tags && entry.transaction? ? entry.transaction.tag_ids : tags_before+ yield entry if before != entry.rule_input_snapshot(tag_ids: tags_after)+ endupdated_count += 1endenddiff --git a/app/models/family/data_exporter.rb b/app/models/family/data_exporter.rbindex dfb58c697b..06048d6376 100644--- a/app/models/family/data_exporter.rb+++ b/app/models/family/data_exporter.rb@@ -800,6 +800,7 @@ class Family::DataExportereffective_date: rule.effective_date&.iso8601,position: rule.position,stop_processing: rule.stop_processing,+ apply_immediately: rule.apply_immediately,group: rule.rule_group&.name,conditions: rule.conditions.where(parent_id: nil).map { |condition| serialize_condition(condition) },actions: rule.actions.map { |action| serialize_action(action) }diff --git a/app/models/family/data_importer.rb b/app/models/family/data_importer.rbindex 21826a9879..9f0870e812 100644--- a/app/models/family/data_importer.rb+++ b/app/models/family/data_importer.rb@@ -1557,6 +1557,8 @@ class Family::DataImportereffective_date: data["effective_date"].present? ? Date.parse(data["effective_date"].to_s) : nil,stop_processing: data["stop_processing"] || false)+ # Exports made before this setting existed don't carry it; keep the stored value then.+ rule.apply_immediately = data["apply_immediately"] || false if data.key?("apply_immediately")# Exports from before rule groups have no group key; an existing rule# then keeps its group.rule.rule_group = find_or_create_rule_group(data["group"]) if data.key?("group")diff --git a/app/models/rule.rb b/app/models/rule.rbindex 0309d02e2b..29399768e6 100644--- a/app/models/rule.rb+++ b/app/models/rule.rb@@ -25,6 +25,7 @@ class Rule < ApplicationRecord# 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) }+ scope :applied_immediately, -> { where(active: true, apply_immediately: true) }validates :resource_type, presence: true, if: -> { resource_type.to_s.valid_encoding? }# A NUL or invalid encoding is reported by DatabaseTextValidator instead.@@ -288,12 +289,18 @@ class Rule < ApplicationRecord# 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: {})+ #+ # With async (AI) actions, modified_count also counts the transactions handed+ # to the AI; changed_now_count only counts what the other actions changed.+ def apply(ignore_attribute_locks: false, rule_run: nil, scope: matching_scope, claimed_ids: {}, skip_action_types: [])total_modified = 0+ changed_now = 0total_async_jobs = 0has_async = falseactions.each do |action|+ next if skip_action_types.include?(action.action_type)+excluded_ids = action.claimed_attributes.flat_map { |attribute| claimed_ids.fetch(attribute, []).to_a }.uniqaction_scope = Rule.excluding_transaction_ids(scope, excluded_ids)result = action.apply(action_scope, ignore_attribute_locks: ignore_attribute_locks, rule_run: rule_run)@@ -304,6 +311,7 @@ class Rule < ApplicationRecordtotal_modified += result[:modified_count] || 0elsif result.is_a?(Integer)total_modified += result+ changed_now += resultelse# Log unexpected result type but don't failRails.logger.warn("Rule#apply: Unexpected result type from action #{action.id}: #{result.class} (value: #{result.inspect})")@@ -311,12 +319,33 @@ class Rule < ApplicationRecordendif has_async- { modified_count: total_modified, async: true, jobs_count: total_async_jobs }+ { modified_count: total_modified, changed_now_count: changed_now, async: true, jobs_count: total_async_jobs }elsetotal_modifiedendend+ # Runs the "apply immediately" rules for transactions a person just created+ # or changed (web, bulk edit, API, assistant). Families without such rules+ # enqueue nothing. Best-effort: the change is already saved and the nightly+ # run applies the rules anyway, so a failed enqueue must not fail the request.+ # Callers inside a database transaction call this after it, so the enqueue+ # is not deferred to an after-commit callback outside this rescue.+ def self.apply_immediately_later(family, transaction_ids)+ transaction_ids = Array(transaction_ids).compact.uniq+ return if transaction_ids.empty? || !family.rules.applied_immediately.exists?++ # perform_later returns false instead of raising when the adapter+ # refuses the job (see RulesController#enqueue_clear_ai_cache).+ return if ApplyImmediateRulesJob.perform_later(family, transaction_ids: transaction_ids)++ Rails.logger.error("Rule.apply_immediately_later could not enqueue ApplyImmediateRulesJob for family #{family.id}")+ nil+ rescue StandardError => e+ Rails.logger.error("Rule.apply_immediately_later failed for family #{family.id}: #{e.class}: #{e.message}")+ nil+ end+def apply_later(ignore_attribute_locks: false)RuleJob.perform_later(self, ignore_attribute_locks: ignore_attribute_locks)end@@ -372,9 +401,14 @@ class Rule < ApplicationRecord# `only_id` narrows the match to one resource inside the query itself, so a# check on a single transaction runs any pattern on that row alone rather# than on the whole family.- def matching_scope(only_id: nil)+ # within_ids limits the scope to those transactions before any pattern is+ # resolved, so an immediate run doesn't scan the whole family. One array+ # parameter, like Rule.excluding_transaction_ids, so a large bulk edit stays+ # below PostgreSQL's bind limit.+ def matching_scope(only_id: nil, within_ids: nil)scope = registry.resource_scopescope = scope.where(id: only_id) if only_id+ scope = scope.where("transactions.id = ANY(?::uuid[])", PG::TextEncoder::Array.new.encode(within_ids)) if within_ids# 1. Prepare the query with joins required by conditionsconditions.each do |condition|diff --git a/app/models/rule/runner.rb b/app/models/rule/runner.rbindex b2ad8638cb..670049778a 100644--- a/app/models/rule/runner.rb+++ b/app/models/rule/runner.rb@@ -12,25 +12,37 @@# Inactive rules above are skipped because they don't run nightly either.# ignore_attribute_locks only applies to the requested rules.#+# With transaction_ids every rule, including the active rules above, only+# looks at those transactions ("apply immediately" after a manual or API+# change). Rules that match none of them are skipped without a RuleRun, so+# editing doesn't fill the history. In such a run the active rules above don't+# send their emails: only rules marked "apply immediately" email right away,+# the others keep emailing from the nightly run (emails claim no attribute,+# so skipping them changes nothing for the rules below).+## 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::RunnerLockBusy = Class.new(StandardError)- attr_reader :errors+ # changed_now_count: transactions the run changed itself, without the ones+ # handed to AI jobs, which report their own changes (RuleRun#complete_job!).+ attr_reader :errors, :changed_now_countdef 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)+ def initialize(family, rules:, execution_type:, ignore_attribute_locks: false, transaction_ids: nil)@family = family+ @transaction_ids = transaction_ids&.map(&:to_s)@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 = []+ @changed_now_count = 0end# Returns the RuleRun records created, one per executed rule.@@ -45,7 +57,7 @@ class Rule::Runnerendprivate- attr_reader :family, :rule_ids, :execution_type, :ignore_attribute_locks, :claimed_ids, :stopped_ids+ attr_reader :family, :rule_ids, :execution_type, :ignore_attribute_locks, :claimed_ids, :stopped_ids, :transaction_idsdef run_rulesrule_runs = []@@ -57,15 +69,15 @@ class Rule::Runnerif 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)+ rule_runs << execute(rule, ignore_attribute_locks: false, skip_action_types: deferred_action_types)endend- rule_runs+ rule_runs.compactenddef unstopped_scope(rule)- Rule.excluding_transaction_ids(rule.matching_scope, stopped_ids)+ Rule.excluding_transaction_ids(rule.matching_scope(within_ids: transaction_ids), stopped_ids)enddef record_claims(rule, matched_ids)@@ -87,7 +99,11 @@ class Rule::Runner[]end- def execute(rule, ignore_attribute_locks:)+ def deferred_action_types+ transaction_ids ? [ Rule::ActionExecutor::SendEmailNotification.key ] : []+ end++ def execute(rule, ignore_attribute_locks:, skip_action_types: [])executed_at = Time.currentmatched_ids = []rule_run = nil@@ -95,6 +111,9 @@ class Rule::Runnerbeginscope = unstopped_scope(rule)matched_ids = scope.pluck(:id)+ return nil if transaction_ids && matched_ids.empty?+ # Nothing left to run, but stop_processing still holds (see ensure).+ return nil if skip_action_types.any? && rule.actions.all? { |action| skip_action_types.include?(action.action_type) }rule_run = RuleRun.create!(rule: rule,@@ -116,10 +135,12 @@ class Rule::Runnerignore_attribute_locks: ignore_attribute_locks,rule_run: rule_run,scope: rule.scope_for_transaction_ids(matched_ids),- claimed_ids: claimed_ids+ claimed_ids: claimed_ids,+ skip_action_types: skip_action_types)rule_run.update!(**run_counts(result, queued: matched_ids.size, rule: rule))+ @changed_now_count += changed_now(result)rescue => erule_run = record_failure(rule, rule_run, e, executed_at: executed_at, queued: matched_ids.size)ensure@@ -143,6 +164,16 @@ class Rule::Runnerendend+ def changed_now(result)+ if result.is_a?(Hash) && result[:async]+ result[:changed_now_count] || 0+ elsif result.is_a?(Integer)+ result+ else+ 0+ end+ end+def record_failure(rule, rule_run, error, executed_at:, queued:)errors << errorerror_message = "#{error.class}: #{error.message}"diff --git a/app/models/rule_run.rb b/app/models/rule_run.rbindex cb354ca749..b4abfe70d8 100644--- a/app/models/rule_run.rb+++ b/app/models/rule_run.rb@@ -1,7 +1,7 @@class RuleRun < ApplicationRecordbelongs_to :rule- validates :execution_type, inclusion: { in: %w[manual scheduled] }+ validates :execution_type, inclusion: { in: %w[manual scheduled immediate] }validates :status, inclusion: { in: %w[pending success failed] }validates :executed_at, presence: truevalidates :transactions_queued, numericality: { greater_than_or_equal_to: 0 }@@ -31,9 +31,29 @@ class RuleRun < ApplicationRecord[ transactions_processed - transactions_modified, 0 ].maxend+ # Offers the result of an immediate run through the sync toast, like+ # Family::SyncCompleteEvent. A full-page refresh would wipe forms that are+ # still open, such as the drawer the person just edited in; the toast waits+ # until they are done.+ # Best-effort: the rules already ran, so a failed broadcast must not fail+ # (and retry) the job that called it, which would repeat its AI work.+ def self.offer_immediate_result(family)+ family.broadcast_replace_to(+ family,+ target: "sync-toast",+ partial: "shared/notifications/sync_toast"+ )+ rescue StandardError => e+ Rails.logger.warn("RuleRun.offer_immediate_result failed for family #{family.id}: #{e.class}: #{e.message}")+ nil+ end+# Thread-safe method to complete a job and update the rundef complete_job!(modified_count: 0)+ drained = false+with_lock do+ drained = pending_jobs_count == 1self.transactions_modified += modified_countself.pending_jobs_count = [ pending_jobs_count - 1, 0 ].max@@ -42,15 +62,20 @@ class RuleRun < ApplicationRecordsave!end++ # A Sidekiq retry of a job that failed before finds nothing left to+ # drain, so its changes are offered on their own.+ offer_job_results if pending_jobs_count.zero? && (drained || modified_count.positive?)enddef fail_job!(error:, source:, transaction_ids: [])should_log = false+ drained = falsecurrent_error_message = "#{error.class}: #{error.message}"with_lock doshould_log = !failed?-+ drained = pending_jobs_count == 1self.pending_jobs_count = [ pending_jobs_count - 1, 0 ].maxself.status = "failed"existing_error_messages = error_message.to_s.split("\n").reject(&:blank?)@@ -60,9 +85,20 @@ class RuleRun < ApplicationRecordendcapture_failure_debug_log(error:, source:, transaction_ids:) if should_log+ # Earlier jobs of the run may already have changed transactions. A retry+ # of a job that already failed drains nothing, so it offers nothing again.+ offer_job_results if drainedendprivate+ # The jobs of an immediate run with AI actions offer what they changed once+ # the last one is done; ApplyImmediateRulesJob offers the run's other changes.+ def offer_job_results+ return unless execution_type == "immediate" && transactions_modified.positive?++ self.class.offer_immediate_result(rule.family)+ end+def capture_failure_debug_log(error:, source:, transaction_ids:)DebugLogEntry.capture(category: "rule_run",diff --git a/app/models/transaction.rb b/app/models/transaction.rbindex 6130b18288..c67aecf692 100644--- a/app/models/transaction.rb+++ b/app/models/transaction.rb@@ -439,6 +439,29 @@ class Transaction < ApplicationRecordtags.resetend+ # Applies a tag picker's changes (selected_ids against previous_ids, the set+ # it last saved) to the tags stored now, so tags another writer added in the+ # meantime stay. Takes the same row lock as toggle_tag! and the rule tag+ # action and reads the tags after it, so no concurrent write is lost.+ def merge_tag_changes!(selected_ids, previous_ids, available_tags:)+ selected_ids = selected_ids.map(&:to_s)+ previous_ids = previous_ids.map(&:to_s)++ with_lock do+ wanted_ids = tag_ids.map(&:to_s) - (previous_ids - selected_ids) | (selected_ids - previous_ids)+ self.tag_ids = available_tags.where(id: wanted_ids).pluck(:id)+ end+ end++ # Replaces the whole tag set with the given ids, limited to available_tags,+ # under the same row lock as toggle_tag! and merge_tag_changes!, so the+ # replacement can't interleave with another writer's tag change.+ def replace_tags!(tag_ids, available_tags:)+ with_lock do+ self.tag_ids = available_tags.where(id: tag_ids).pluck(:id)+ end+ end+# Marks a category as recently used. Called explicitly from the manual# category-assignment controllers (picker, edit form, categorization# wizard, create-and-assign) after a successful save — not wired to adiff --git a/app/views/api/v1/rules/_rule.json.jbuilder b/app/views/api/v1/rules/_rule.json.jbuilderindex 04e2f0a791..24b85259a9 100644--- a/app/views/api/v1/rules/_rule.json.jbuilder+++ b/app/views/api/v1/rules/_rule.json.jbuilder@@ -7,6 +7,7 @@ json.active rule.activejson.effective_date rule.effective_date&.iso8601json.position rule.positionjson.stop_processing rule.stop_processing+json.apply_immediately rule.apply_immediatelyjson.conditions rule.conditions.select { |condition| condition.parent_id.nil? } do |condition|json.partial! "api/v1/rules/condition", condition: conditionenddiff --git a/app/views/rules/_form.html.erb b/app/views/rules/_form.html.erbindex 2b91642c02..9653132262 100644--- a/app/views/rules/_form.html.erb+++ b/app/views/rules/_form.html.erb@@ -123,5 +123,13 @@<%= f.toggle :stop_processing %></section>+ <section class="flex items-center gap-4 justify-between">+ <div class="text-sm space-y-1">+ <h3 class="font-medium text-primary"><%= t(".apply_immediately_label") %></h3>+ <p class="text-secondary"><%= t(".apply_immediately_description") %></p>+ </div>+ <%= f.toggle :apply_immediately %>+ </section>+<%= f.submit %><% end %>diff --git a/app/views/rules/_rule.html.erb b/app/views/rules/_rule.html.erbindex 8874834d07..31f7e4eccc 100644--- a/app/views/rules/_rule.html.erb+++ b/app/views/rules/_rule.html.erb@@ -1,5 +1,5 @@<%# locals: (rule:) %>-<% has_title = rule.name.present? || rule.stop_processing? %>+<% has_title = rule.name.present? || rule.stop_processing? || rule.apply_immediately? %><div id="<%= dom_id(rule) %>" class="grid grid-cols-[minmax(0,1fr)_auto] items-start gap-x-3 gap-y-0.5 p-3 text-sm sm:items-center sm:p-4 <%= rule.active? ? "text-primary" : "text-secondary" %>"><% if has_title %><div class="col-start-1 row-start-1 flex min-w-0 flex-wrap items-center gap-2 self-center">@@ -9,6 +9,9 @@<% if rule.stop_processing? %><%= render DS::Pill.new(label: t(".stop_processing"), tone: :neutral, marker: false, title: t(".stop_processing_hint")) %><% end %>+ <% if rule.apply_immediately? %>+ <%= render DS::Pill.new(label: t(".apply_immediately"), tone: :info, marker: false, title: t(".apply_immediately_hint")) %>+ <% end %></div><% end %><div class="col-span-2 row-start-2 min-w-0 space-y-1.5 sm:col-span-1 sm:col-start-1 <%= "sm:row-start-1" unless has_title %>">diff --git a/app/views/transactions/show.html.erb b/app/views/transactions/show.html.erbindex a70bb5a594..0c9b235fb4 100644--- a/app/views/transactions/show.html.erb+++ b/app/views/transactions/show.html.erb@@ -50,19 +50,31 @@<% end %><%= render "entries/protection_indicator", entry: @entry, unlock_path: unlock_transaction_path(@entry.transaction) %><% dialog.with_section(title: t(".overview"), open: true) do %>- <div>+ <div class="space-y-2"><% split_locked = @entry.split_child? || @entry.split_parent? %><% edit_locked = !can_edit_entry? %><% annotate_locked = !can_annotate_entry? %>+ <%# Name, category, merchant and tags each get their own form: rules+ (immediate ones included) can change them while the drawer is open,+ and a shared form would send their stale values back on the next+ save of a neighbouring field, overwriting and locking the rule's+ result. %><%= styled_form_with model: @entry,url: transaction_path(@entry),- class: "space-y-2",data: { controller: "auto-submit-form" } do |f| %><%= hidden_field_tag :grouped, "true" if params[:grouped] == "true" %>+ <%# "change", not "blur": leaving the field untouched must not send its stale value. %><%= f.text_field :name,label: t(".name_label"),disabled: @entry.split_child? || edit_locked,- "data-auto-submit-form-target": "auto" %>+ "data-auto-submit-form-target": "auto",+ "data-autosubmit-trigger-event": "change" %>+ <% end %>+ <%= styled_form_with model: @entry,+ url: transaction_path(@entry),+ class: "space-y-2",+ data: { controller: "auto-submit-form" } do |f| %>+ <%= hidden_field_tag :grouped, "true" if params[:grouped] == "true" %><%= f.date_field :date,label: t(".date_label"),disabled: @entry.linked? || split_locked || edit_locked,@@ -82,33 +94,40 @@disable_currency: @entry.linked? || split_locked || edit_locked %></div><% end %>- <% if @entry.transaction.category_editable? %>- <%= f.fields_for :entryable do |ef| %>- <%= render DS::CategorySelect.new(- form: ef,- categories: Current.family.categories.alphabetically_by_hierarchy,- selected_id: ef.object.category_id,- disabled: @entry.split_child? || annotate_locked,- auto_submit: true,- blank_label: t(".uncategorized"),- locked: Current.family.categories_locked?- ) %>- <% end %>- <% elsif @entry.transaction.category_set_on_transfer_outflow? %>- <% outflow_category = transfer_outflow_category(@entry.transaction) %>- <div class="space-y-1">- <div class="opacity-60 cursor-not-allowed">- <%= f.fields_for :entryable do |ef| %>- <%= render DS::CategorySelect.new(- form: ef,- categories: [],- selected_category: outflow_category || transfer_category,- disabled: true- ) %>- <% end %>+ <% end %>+ <% if @entry.transaction.category_editable? || @entry.transaction.category_set_on_transfer_outflow? %>+ <%= styled_form_with model: @entry,+ url: transaction_path(@entry),+ data: { controller: "auto-submit-form" } do |f| %>+ <%= hidden_field_tag :grouped, "true" if params[:grouped] == "true" %>+ <% if @entry.transaction.category_editable? %>+ <%= f.fields_for :entryable do |ef| %>+ <%= render DS::CategorySelect.new(+ form: ef,+ categories: Current.family.categories.alphabetically_by_hierarchy,+ selected_id: ef.object.category_id,+ disabled: @entry.split_child? || annotate_locked,+ auto_submit: true,+ blank_label: t(".uncategorized"),+ locked: Current.family.categories_locked?+ ) %>+ <% end %>+ <% elsif @entry.transaction.category_set_on_transfer_outflow? %>+ <% outflow_category = transfer_outflow_category(@entry.transaction) %>+ <div class="space-y-1">+ <div class="opacity-60 cursor-not-allowed">+ <%= f.fields_for :entryable do |ef| %>+ <%= render DS::CategorySelect.new(+ form: ef,+ categories: [],+ selected_category: outflow_category || transfer_category,+ disabled: true+ ) %>+ <% end %>+ </div>+ <p class="text-xs text-secondary"><%= outflow_category ? t(".category_set_on_outflow") : t(".category_set_on_hidden_outflow") %></p></div>- <p class="text-xs text-secondary"><%= outflow_category ? t(".category_set_on_outflow") : t(".category_set_on_hidden_outflow") %></p>- </div>+ <% end %><% end %><% end %></div>@@ -139,6 +158,15 @@disabled: @entry.split_child? || !can_annotate_entry?,auto_submit: true) %>+ <% end %>+ <% end %>+ <% end %>+ <% unless @entry.transaction.transfer? %>+ <%= styled_form_with model: @entry,+ url: transaction_path(@entry),+ data: { controller: "auto-submit-form" } do |f| %>+ <%= hidden_field_tag :grouped, "true" if params[:grouped] == "true" %>+ <%= f.fields_for :entryable do |ef| %><%= render DS::TagSelect.new(form: ef,tags: Current.family.tags.alphabetically,diff --git a/config/locales/views/rules/de.yml b/config/locales/views/rules/de.ymlindex 19e7409d9f..ec5157a941 100644--- a/config/locales/views/rules/de.yml+++ b/config/locales/views/rules/de.yml@@ -63,6 +63,7 @@ de:execution_types:manual: Manuellscheduled: Geplant+ immediate: Sofortstatuses:pending: Ausstehendsuccess: Erfolgreich@@ -130,6 +131,8 @@ de:group_hint: Gruppen ordnen nur die Liste. Eine Regel in einer Gruppe läuft dort, wo die Gruppe in der Liste steht.stop_processing_label: Danach keine weiteren Regeln anwendenthen: DANN+ apply_immediately_label: Sofort bei neuen und geänderten Transaktionen anwenden+ apply_immediately_description: Läuft direkt, nachdem eine Transaktion von Hand, per Mehrfachbearbeitung, beim Kategorisieren, über die API oder vom Assistenten angelegt oder bearbeitet wurde, und weiterhin nachts.index:ai_cost_warning: Regelaktionen mit KI kosten Geld. Filtere so eng wie möglich, damit keine unnötigen Kosten entstehen.delete_all_rules: Alle Regeln löschen@@ -201,6 +204,8 @@ de:re_apply_rule: Regel erneut anwendenstop_processing: Stoppstop_processing_hint: Weiter unten stehende Regeln ändern die Transaktionen nicht mehr, die diese Regel trifft.+ apply_immediately: Sofort+ apply_immediately_hint: Läuft auch direkt, nachdem eine Transaktion von Hand, per Mehrfachbearbeitung, beim Kategorisieren, über die API oder vom Assistenten angelegt oder bearbeitet wurde, zusammen mit den aktiven Regeln darüber.then: DANNupdate:success: Regel aktualisiertdiff --git a/config/locales/views/rules/en.yml b/config/locales/views/rules/en.ymlindex 3d8df800f3..ab39437a1e 100644--- a/config/locales/views/rules/en.yml+++ b/config/locales/views/rules/en.yml@@ -70,6 +70,8 @@ en:on_or_after: "%{resource} on or after %{date}"stop_processing: Stopstop_processing_hint: Rules further down don't change transactions matched by this rule.+ apply_immediately: Immediately+ apply_immediately_hint: Also runs right after a transaction is created or edited by hand, in a bulk edit, in Categorize, via the API or by the assistant, together with the active rules above it.form:rule_name_label: Rule name (optional)rule_name_placeholder: Enter a name for this rule@@ -81,6 +83,8 @@ en:then: THENstop_processing_label: Stop processing further rulesstop_processing_description: Rules further down the list don't change transactions this rule matches.+ apply_immediately_label: Apply immediately to new and changed transactions+ apply_immediately_description: Runs right after a transaction is created or edited by hand, in a bulk edit, in Categorize, via the API or by the assistant, and still overnight.group_label: Group (optional)group_select_label: Groupno_group: No group@@ -173,6 +177,7 @@ en:execution_types:manual: Manualscheduled: Scheduled+ immediate: Immediatestatuses:pending: Pendingsuccess: Successdiff --git a/config/locales/views/transactions/de.yml b/config/locales/views/transactions/de.ymlindex 6ad8fb4aa8..a7fd274461 100644--- a/config/locales/views/transactions/de.yml+++ b/config/locales/views/transactions/de.yml@@ -31,6 +31,7 @@ de:submit: Transaktion hinzufügentag_search_placeholder: Tag suchen oder erstellentags_label: Tags+ tags_save_error: Tags konnten nicht gespeichert werden. Ändere sie erneut oder lade die Seite neu.transfer: Überweisungcategory_label: Kategoriedetails: Detailsdiff --git a/config/locales/views/transactions/en.yml b/config/locales/views/transactions/en.ymlindex 4297b6e73b..41857b56b6 100644--- a/config/locales/views/transactions/en.yml+++ b/config/locales/views/transactions/en.yml@@ -61,6 +61,7 @@ en:submit: Add transactiontag_search_placeholder: Search or create tagtags_label: Tags+ tags_save_error: Tags couldn't be saved. Change them again to retry, or reload the page.transfer: Transfercreate:created: Transaction createddiff --git a/db/migrate/20261026090000_add_apply_immediately_to_rules.rb b/db/migrate/20261026090000_add_apply_immediately_to_rules.rbnew file mode 100644index 0000000000..10ba039d5c--- /dev/null+++ b/db/migrate/20261026090000_add_apply_immediately_to_rules.rb@@ -0,0 +1,7 @@+# frozen_string_literal: true++class AddApplyImmediatelyToRules < ActiveRecord::Migration[8.1]+ def change+ add_column :rules, :apply_immediately, :boolean, null: false, default: false+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex d2253b8993..e0e64f9a74 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -2356,6 +2356,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_16_120000) docreate_table "rules", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|t.boolean "active", default: false, null: false+ t.boolean "apply_immediately", default: false, null: falset.datetime "created_at", null: falset.date "effective_date"t.uuid "family_id", null: falsediff --git a/docs/api/openapi.yaml b/docs/api/openapi.yamlindex aec838eed8..5a8afcf08e 100644--- a/docs/api/openapi.yaml+++ b/docs/api/openapi.yaml@@ -1458,6 +1458,7 @@ components:- active- position- stop_processing+ - apply_immediately- conditions- actions- created_at@@ -1487,6 +1488,12 @@ components:type: booleandescription: When true, rules further down do not change transactions thisrule matches+ apply_immediately:+ type: boolean+ description: When true, the rule also runs right after a transaction is+ created or edited by hand, in a bulk edit, in Categorize, via the API+ or by the assistant (splits, transfers and conversions to trades wait+ for the nightly run); otherwise it only runs on the nightly and sync runsconditions:type: arrayitems:@@ -1571,6 +1578,7 @@ components:enum:- manual- scheduled+ - immediatestatus:type: stringenum:@@ -9497,6 +9505,7 @@ paths:enum:- manual- scheduled+ - immediate- name: start_executed_atin: queryrequired: falsediff --git a/spec/requests/api/v1/rule_runs_spec.rb b/spec/requests/api/v1/rule_runs_spec.rbindex d3a9921908..84044e7027 100644--- a/spec/requests/api/v1/rule_runs_spec.rb+++ b/spec/requests/api/v1/rule_runs_spec.rb@@ -91,7 +91,7 @@ RSpec.describe 'API V1 Rule Runs', type: :request doschema: { type: :string, enum: %w[pending success failed] }parameter name: :execution_type, in: :query, required: false,description: 'Filter by execution type',- schema: { type: :string, enum: %w[manual scheduled] }+ schema: { type: :string, enum: %w[manual scheduled immediate] }parameter name: :start_executed_at, in: :query, required: false,description: 'Filter runs executed at or after this timestamp',schema: { type: :string, format: :'date-time' }diff --git a/spec/swagger_helper.rb b/spec/swagger_helper.rbindex f770738168..e94c16724b 100644--- a/spec/swagger_helper.rb+++ b/spec/swagger_helper.rb@@ -825,7 +825,7 @@ RSpec.configure do |config|},Rule: {type: :object,- required: %w[id resource_type active position stop_processing conditions actions created_at updated_at],+ required: %w[id resource_type active position stop_processing apply_immediately conditions actions created_at updated_at],properties: {id: { type: :string, format: :uuid },name: { type: :string, nullable: true },@@ -834,6 +834,7 @@ RSpec.configure do |config|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' },+ apply_immediately: { type: :boolean, description: 'When true, the rule also runs right after a transaction is created or edited by hand, in a bulk edit, in Categorize, via the API or by the assistant (splits, transfers and conversions to trades wait for the nightly run); otherwise it only runs on the nightly and sync runs' },conditions: {type: :array,items: { '$ref' => '#/components/schemas/RuleCondition' }@@ -882,7 +883,7 @@ RSpec.configure do |config|id: { type: :string, format: :uuid },rule_id: { type: :string, format: :uuid },rule_name: { type: :string, nullable: true },- execution_type: { type: :string, enum: %w[manual scheduled] },+ execution_type: { type: :string, enum: %w[manual scheduled immediate] },status: { type: :string, enum: %w[pending success failed] },transactions_queued: { type: :integer, minimum: 0 },transactions_processed: { type: :integer, minimum: 0 },diff --git a/test/application_system_test_case.rb b/test/application_system_test_case.rbindex d1aa1c0856..e009c91cbd 100644--- a/test/application_system_test_case.rb+++ b/test/application_system_test_case.rb@@ -79,6 +79,13 @@ class ApplicationSystemTestCase < ActionDispatch::SystemTestCaseprivate+ # Capybara retries its own matchers; a value read through evaluate_script+ # or from the database gets no such patience, so give it the same budget.+ def wait_until(timeout: Capybara.default_max_wait_time)+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout+ sleep 0.05 until yield || Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline+ end+def reset_viewportpage.current_window.resize_to(DEFAULT_VIEWPORT_WIDTH, DEFAULT_VIEWPORT_HEIGHT) if page&.current_windowenddiff --git a/test/controllers/api/v1/rule_runs_controller_test.rb b/test/controllers/api/v1/rule_runs_controller_test.rbindex 5db2c8afc8..72bd9fd83a 100644--- a/test/controllers/api/v1/rule_runs_controller_test.rb+++ b/test/controllers/api/v1/rule_runs_controller_test.rb@@ -116,6 +116,19 @@ class Api::V1::RuleRunsControllerTest < ActionDispatch::IntegrationTestassert_equal [ @failed_rule_run.id ], response_data["data"].map { |rule_run| rule_run["id"] }end+ test "filters immediate rule runs" do+ immediate_run = @rule.rule_runs.create!(+ rule_name: @rule.name, execution_type: "immediate", status: "success",+ transactions_queued: 1, transactions_processed: 1, transactions_modified: 1,+ pending_jobs_count: 0, executed_at: Time.zone.parse("2024-01-17 12:00:00")+ )++ get api_v1_rule_runs_url, params: { execution_type: "immediate" }, headers: api_headers(@api_key)++ assert_response :success+ assert_equal [ immediate_run.id ], JSON.parse(response.body)["data"].map { |rule_run| rule_run["id"] }+ end+test "rejects invalid filters" doget api_v1_rule_runs_url, params: { status: "unknown" }, headers: api_headers(@api_key)diff --git a/test/controllers/api/v1/rules_controller_test.rb b/test/controllers/api/v1/rules_controller_test.rbindex 83f1187204..7096997407 100644--- a/test/controllers/api/v1/rules_controller_test.rb+++ b/test/controllers/api/v1/rules_controller_test.rb@@ -114,6 +114,7 @@ class Api::V1::RulesControllerTest < ActionDispatch::IntegrationTestassert_equal "2024-01-01", rule["effective_date"]assert_equal @rule.reload.position, rule["position"]assert_equal false, rule["stop_processing"]+ assert_equal false, rule["apply_immediately"]assert_equal 1, rule["conditions"].lengthassert_equal "transaction_name", rule["conditions"].first["condition_type"]diff --git a/test/controllers/api/v1/transactions_controller_test.rb b/test/controllers/api/v1/transactions_controller_test.rbindex b538376e3b..142a5f461f 100644--- a/test/controllers/api/v1/transactions_controller_test.rb+++ b/test/controllers/api/v1/transactions_controller_test.rb@@ -352,6 +352,51 @@ class Api::V1::TransactionsControllerTest < ActionDispatch::IntegrationTestassert_equal @account.id, response_data["account"]["id"]end+ test "creating and updating via the API runs rules set to apply immediately" do+ @family.rules.create!(+ resource_type: "transaction", active: true, apply_immediately: true,+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "API") ],+ actions: [ Rule::Action.new(action_type: "set_transaction_category", value: @family.categories.first.id) ]+ )++ post api_v1_transactions_url,+ params: { transaction: { account_id: @account.id, name: "API purchase", amount: 5, date: Date.current, currency: "USD", nature: "expense" } },+ headers: api_headers(@api_key)+ assert_response :created+ created_id = JSON.parse(response.body)["id"]+ assert_enqueued_with(job: ApplyImmediateRulesJob, args: [ @family, { transaction_ids: [ created_id ] } ])++ put api_v1_transaction_url(@transaction), params: { transaction: { name: "API rename" } }, headers: api_headers(@api_key)+ assert_response :success+ assert_enqueued_with(job: ApplyImmediateRulesJob, args: [ @family, { transaction_ids: [ @transaction.id ] } ])+ end++ test "an API update that changes nothing runs no immediate rules" do+ @family.rules.create!(+ resource_type: "transaction", active: true, apply_immediately: true,+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "API") ],+ actions: [ Rule::Action.new(action_type: "set_transaction_category", value: @family.categories.first.id) ]+ )++ put api_v1_transaction_url(@transaction), params: { transaction: { name: @transaction.entry.name } }, headers: api_headers(@api_key)++ assert_response :success+ assert_no_enqueued_jobs(only: ApplyImmediateRulesJob)+ end++ test "a rejected API update runs no immediate rules" do+ @family.rules.create!(+ resource_type: "transaction", active: true, apply_immediately: true,+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "API") ],+ actions: [ Rule::Action.new(action_type: "set_transaction_category", value: @family.categories.first.id) ]+ )++ put api_v1_transaction_url(@transaction), params: { transaction: { name: "" } }, headers: api_headers(@api_key)++ assert_response :unprocessable_entity+ assert_no_enqueued_jobs(only: ApplyImmediateRulesJob)+ end+test "should create transaction with external idempotency key" dotransaction_params = {transaction: {diff --git a/test/controllers/rules_controller_test.rb b/test/controllers/rules_controller_test.rbindex 0daa7e2136..2c629a0106 100644--- a/test/controllers/rules_controller_test.rb+++ b/test/controllers/rules_controller_test.rb@@ -679,6 +679,14 @@ class RulesControllerTest < ActionDispatch::IntegrationTestassert_response :successend+ test "update saves apply immediately" do+ rule = create_category_rule("Groceries")++ patch rule_url(rule), params: { rule: { apply_immediately: "1" } }++ assert rule.reload.apply_immediately?+ end+test "apply_all enqueues job and redirects" doassert_enqueued_with(job: ApplyAllRulesJob) dopost apply_all_rules_url@@ -1026,6 +1034,14 @@ class RulesControllerTest < ActionDispatch::IntegrationTestendprivate+ def create_category_rule(name)+ @user.family.rules.create!(+ name: name, resource_type: "transaction", active: true,+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: entries(:transaction).name) ],+ actions: [ Rule::Action.new(action_type: "set_transaction_category", value: categories(:food_and_drink).id) ]+ )+ end+# A regex condition, so a stubbed timeout reaches the baseline query, and one# matching transaction, so a recorded baseline is visible as a delivery.# An active regex rule with one match and no email action yet.diff --git a/test/controllers/transaction_categories_controller_test.rb b/test/controllers/transaction_categories_controller_test.rbindex cdbbdb2db8..4a1069c717 100644--- a/test/controllers/transaction_categories_controller_test.rb+++ b/test/controllers/transaction_categories_controller_test.rb@@ -7,6 +7,19 @@ class TransactionCategoriesControllerTest < ActionDispatch::IntegrationTest@transaction = transactions(:one)end+ test "changing the category runs rules set to apply immediately" do+ @entry.account.family.rules.create!(+ name: "Immediate", resource_type: "transaction", active: true, apply_immediately: true,+ actions: [ Rule::Action.new(action_type: "exclude_transaction") ]+ )++ patch transaction_category_url(@entry),+ params: { entry: { entryable_type: "Transaction", entryable_attributes: { id: @transaction.id, category_id: categories(:income).id } } },+ as: :turbo_stream++ assert_enqueued_with(job: ApplyImmediateRulesJob, args: [ @entry.account.family, { transaction_ids: [ @transaction.id ] } ])+ end+test "assigning a category touches its last_used_at" docategory = categories(:income)assert_nil category.last_used_atdiff --git a/test/controllers/transactions/bulk_updates_controller_test.rb b/test/controllers/transactions/bulk_updates_controller_test.rbindex 0da4452149..113c415d13 100644--- a/test/controllers/transactions/bulk_updates_controller_test.rb+++ b/test/controllers/transactions/bulk_updates_controller_test.rb@@ -36,6 +36,62 @@ class Transactions::BulkUpdatesControllerTest < ActionDispatch::IntegrationTestendend+ test "bulk update runs rules set to apply immediately on the changed transactions" do+ @user.family.rules.create!(+ resource_type: "transaction", active: true, apply_immediately: true,+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "x") ],+ actions: [ Rule::Action.new(action_type: "set_transaction_category", value: Category.first.id) ]+ )+ entries = @user.family.entries.transactions.excluding_split_parents.limit(2)++ post transactions_bulk_update_url, params: { bulk_update: { entry_ids: entries.map(&:id), notes: "Bulk note" } }++ assert_enqueued_jobs 1, only: ApplyImmediateRulesJob+ job = enqueued_jobs.find { |enqueued| enqueued[:job] == ApplyImmediateRulesJob }+ assert_equal entries.map(&:entryable_id).sort, job[:args].last["transaction_ids"].sort+ end++ test "bulk update runs immediate rules only on transactions it changed" do+ accounts(:credit_card).account_shares.find_by!(user: users(:family_member)).update!(permission: "read_write")+ users(:family_member).family.rules.create!(+ resource_type: "transaction", active: true, apply_immediately: true,+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "Renamed") ],+ actions: [ Rule::Action.new(action_type: "set_transaction_category", value: Category.first.id) ]+ )+ full_entry = create_transaction(account: accounts(:depository), name: "Full")+ annotate_entry = create_transaction(account: accounts(:credit_card), name: "Annotate")++ sign_in users(:family_member)+ post transactions_bulk_update_url, params: { bulk_update: { entry_ids: [ full_entry.id, annotate_entry.id ], name: "Renamed" } }++ assert_equal "Annotate", annotate_entry.reload.name+ job = enqueued_jobs.find { |enqueued| enqueued[:job] == ApplyImmediateRulesJob }+ assert_equal [ full_entry.entryable_id ], job[:args].last["transaction_ids"]+ end++ test "bulk update does not run immediate rules for blocked transfer edits" do+ @user.family.rules.create!(+ resource_type: "transaction", active: true, apply_immediately: true,+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "x") ],+ actions: [ Rule::Action.new(action_type: "set_transaction_category", value: Category.first.id) ]+ )+ transfer = create_transfer(+ from_account: accounts(:depository), to_account: accounts(:credit_card), amount: 100+ )+ entry = transfer.outflow_transaction.entry+ original_date = entry.date++ assert_no_enqueued_jobs only: ApplyImmediateRulesJob do+ post transactions_bulk_update_url, params: {+ bulk_update: { entry_ids: [ entry.id ], date: 1.day.ago.to_date, category_id: Category.second.id }+ }+ end++ assert_redirected_to transactions_url+ assert_equal original_date, entry.reload.date+ assert_nil entry.transaction.category_id+ end+test "bulk update keeps transfer date, category and merchant" do@user.family.update!(manual_reconciliation: true)transfer = create_transfer(diff --git a/test/controllers/transactions/categorizes_controller_test.rb b/test/controllers/transactions/categorizes_controller_test.rbindex 025d661a42..b8f8d64edd 100644--- a/test/controllers/transactions/categorizes_controller_test.rb+++ b/test/controllers/transactions/categorizes_controller_test.rb@@ -290,7 +290,75 @@ class Transactions::CategorizesControllerTest < ActionDispatch::IntegrationTestassert_redirected_to new_session_urlend+ test "create runs rules set to apply immediately on the categorized transactions" do+ create_immediate_rule+ entry1 = create_transaction(account: @account, name: "Starbucks")+ entry2 = create_transaction(account: @account, name: "Starbucks")++ post transactions_categorize_url,+ params: {+ position: 0,+ grouping_key: "Starbucks",+ entry_ids: [ entry1.id, entry2.id ],+ all_entry_ids: [ entry1.id, entry2.id ],+ category_id: @category.id+ },+ headers: { "Accept" => "text/vnd.turbo-stream.html" }++ assert_response :success+ assert_equal [ entry1.entryable_id, entry2.entryable_id ].sort, immediate_job_transaction_ids.sort+ end++ test "create runs immediate rules only on transactions whose category changed" do+ create_immediate_rule+ changed = create_transaction(account: @account, name: "Starbucks")+ unchanged = create_transaction(account: @account, name: "Starbucks", category: @category)++ post transactions_categorize_url,+ params: {+ position: 0,+ grouping_key: "Starbucks",+ entry_ids: [ changed.id, unchanged.id ],+ all_entry_ids: [ changed.id, unchanged.id ],+ category_id: @category.id+ },+ headers: { "Accept" => "text/vnd.turbo-stream.html" }++ assert_response :success+ assert_equal [ changed.entryable_id ], immediate_job_transaction_ids+ end++ test "assign_entry runs rules set to apply immediately on the categorized transaction" do+ create_immediate_rule+ entry = create_transaction(account: @account, name: "Starbucks")+ other = create_transaction(account: @account, name: "Starbucks")++ patch assign_entry_transactions_categorize_url, params: {+ entry_id: entry.id,+ category_id: @category.id,+ position: 0,+ all_entry_ids: [ entry.id, other.id ]+ }++ assert_response :success+ assert_equal [ entry.entryable_id ], immediate_job_transaction_ids+ end+private+ def create_immediate_rule+ @family.rules.create!(+ resource_type: "transaction", active: true, apply_immediately: true,+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "Starbucks") ],+ actions: [ Rule::Action.new(action_type: "set_transaction_tags", value: tags(:one).id) ]+ )+ end++ def immediate_job_transaction_ids+ jobs = enqueued_jobs.select { |enqueued| enqueued[:job] == ApplyImmediateRulesJob }+ assert_equal 1, jobs.size+ jobs.first[:args].last["transaction_ids"]+ end+def sign_out# Deleting sessions through the controller de-authenticates the request thediff --git a/test/controllers/transactions_controller_test.rb b/test/controllers/transactions_controller_test.rbindex 3435717f3e..1438712b4a 100644--- a/test/controllers/transactions_controller_test.rb+++ b/test/controllers/transactions_controller_test.rb@@ -794,6 +794,41 @@ class TransactionsControllerTest < ActionDispatch::IntegrationTestassert @entry.entryable.locked?(:tag_ids)end+ test "tag-only endpoint replaces a bare tag set under the row lock" do+ other_family_tag = users(:empty).family.tags.create!(name: "Other family")+ @entry.entryable.update!(tag_ids: [ tags(:one).id ], locked_attributes: {})++ assert_queries_match(/FROM "transactions" WHERE .* FOR UPDATE/) do+ patch tags_transaction_url(@entry, format: :json), params: {+ tag_ids: [ tags(:two).id, other_family_tag.id ]+ }, as: :json+ end++ assert_response :success+ assert_equal [ tags(:two).id ], @entry.reload.entryable.tag_ids+ end++ test "tag-only endpoint keeps tags added since the drawer last saved" do+ other_family_tag = users(:empty).family.tags.create!(name: "Other family")+ rule_tag = @user.family.tags.create!(name: "Added by a rule")+ @entry.entryable.update!(tag_ids: [ tags(:one).id, rule_tag.id ], locked_attributes: {})++ patch tags_transaction_url(@entry, format: :json), params: {+ tag_ids: [ tags(:one).id, tags(:two).id, other_family_tag.id ],+ previous_tag_ids: [ tags(:one).id ]+ }, as: :json++ assert_response :success+ assert_equal [ tags(:one).id, tags(:two).id, rule_tag.id ].sort, @entry.reload.entryable.tag_ids.sort++ patch tags_transaction_url(@entry, format: :json), params: {+ tag_ids: [], previous_tag_ids: [ tags(:one).id, tags(:two).id ]+ }, as: :json++ assert_equal [ rule_tag.id ], @entry.reload.entryable.tag_ids+ assert @entry.entryable.locked?(:tag_ids)+ end+test "tag-only endpoint returns forbidden json for read-only users" dosign_in users(:family_member)read_only_entry = entries(:transfer_in)@@ -2491,6 +2526,95 @@ endassert_match I18n.t("transactions.show.category_set_on_outflow"), response.bodyend+ test "creating a transaction runs rules set to apply immediately" do+ create_immediate_rule++ post transactions_url, params: {+ entry: {+ account_id: @entry.account_id, name: "New transaction", date: Date.current,+ currency: "USD", amount: 100, nature: "outflow", entryable_type: "Transaction",+ entryable_attributes: { category_id: "" }+ }+ }++ created_entry = Entry.order(:created_at).last+ assert_enqueued_with(job: ApplyImmediateRulesJob, args: [ @user.family, { transaction_ids: [ created_entry.entryable_id ] } ])+ end++ test "changing a transaction runs rules set to apply immediately" do+ create_immediate_rule++ patch transaction_url(@entry), params: { entry: { name: "Renamed" } }++ assert_enqueued_with(job: ApplyImmediateRulesJob, args: [ @user.family, { transaction_ids: [ @entry.entryable_id ] } ])+ end++ test "changing a transaction queues nothing without immediate rules" do+ patch transaction_url(@entry), params: { entry: { name: "Renamed" } }++ assert_no_enqueued_jobs(only: ApplyImmediateRulesJob)+ end++ test "an update that changes nothing runs no immediate rules" do+ create_immediate_rule++ patch transaction_url(@entry), params: { entry: { name: @entry.name, notes: @entry.notes } }++ assert_no_enqueued_jobs(only: ApplyImmediateRulesJob)+ end++ test "an update reduced to nothing by the account permission runs no immediate rules" do+ create_immediate_rule+ read_only_entry = entries(:transfer_in) # credit card, shared read_only with family_member+ sign_in users(:family_member)++ patch transaction_url(read_only_entry), params: { entry: { name: "Renamed" } }++ assert_not_equal "Renamed", read_only_entry.reload.name+ assert_no_enqueued_jobs(only: ApplyImmediateRulesJob)+ end++ test "setting the same tags again runs no immediate rules" do+ create_immediate_rule+ @entry.transaction.update!(tag_ids: [ tags(:one).id ])++ patch tags_transaction_url(@entry, format: :json), params: { tag_ids: [ tags(:one).id ] }++ assert_response :success+ assert_no_enqueued_jobs(only: ApplyImmediateRulesJob)+ end++ test "toggling a tag runs immediate rules" do+ create_immediate_rule++ patch tags_transaction_url(@entry), params: { toggle_tag_id: tags(:two).id }, as: :turbo_stream++ assert_enqueued_with(job: ApplyImmediateRulesJob, args: [ @user.family, { transaction_ids: [ @entry.entryable_id ] } ])+ end++ # A rule can change these fields while the drawer is open. Sharing a form+ # with another field would send the drawer's stale value back on the next+ # save of that field, undoing the rule's result and locking it.+ test "the drawer sends each field that rules can set in a form of its own" do+ rule_fields = %w[entry[name] entry[excluded] entry[entryable_attributes][category_id] entry[entryable_attributes][merchant_id] entry[entryable_attributes][tag_ids][]]+ form_meta = %w[authenticity_token _method grouped entry[entryable_attributes][id]]++ get transaction_url(@entry), headers: { "Turbo-Frame" => "drawer" }+ assert_response :success++ seen = css_select("form[action='#{transaction_path(@entry)}']").filter_map do |form|+ names = form.css("input[name], select[name], textarea[name]").reject { |field| field["disabled"] }.map { |field| field["name"] }.uniq - form_meta+ next if (names & rule_fields).empty?++ assert_equal 1, names.size, "#{names.inspect} share one form"+ names.first+ end++ assert_equal rule_fields.sort, seen.sort+ # Leaving the name field untouched must not send its stale value either.+ assert_select "input[name='entry[name]'][data-autosubmit-trigger-event=change]"+ end+test "does not offer guests to create a rule through a transaction update" docategory = categories(:income)@entry.update!(name: "AMZN Mktp UK")@@ -2514,6 +2638,14 @@ endendprivate+ def create_immediate_rule+ @user.family.rules.create!(+ name: "Immediate", resource_type: "transaction", active: true, apply_immediately: true,+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "Renamed") ],+ actions: [ Rule::Action.new(action_type: "set_transaction_category", value: categories(:food_and_drink).id) ]+ )+ end+# The Allocator's two-key advisory lock on this entry, held by this session.def entry_lock_held?(entry)ActiveRecord::Base.connection.select_value(ActiveRecord::Base.sanitize_sql_array([ <<~SQL, RecurringTransaction::Allocator::ENTRY_LOCK_NAMESPACE, RecurringTransaction::Allocator.entry_lock_id(entry) ]))diff --git a/test/jobs/apply_immediate_rules_job_test.rb b/test/jobs/apply_immediate_rules_job_test.rbnew file mode 100644index 0000000000..9d3217086d--- /dev/null+++ b/test/jobs/apply_immediate_rules_job_test.rb@@ -0,0 +1,185 @@+require "test_helper"++class ApplyImmediateRulesJobTest < ActiveJob::TestCase+ include EntriesTestHelper++ setup do+ @family = families(:empty)+ @account = @family.accounts.create!(name: "Immediate test", balance: 1000, currency: "USD", accountable: Depository.new)+ @groceries = @family.categories.create!(name: "Groceries")+ @dining = @family.categories.create!(name: "Dining")+ @changed = create_transaction(account: @account, name: "Whole Foods").transaction+ @untouched = create_transaction(account: @account, name: "Whole Foods").transaction+ end++ test "applies immediate rules only to the given transactions" do+ rule = create_rule("Groceries", category: @groceries, apply_immediately: true)++ ApplyImmediateRulesJob.perform_now(@family, transaction_ids: [ @changed.id ])++ assert_equal @groceries, @changed.reload.category+ assert_nil @untouched.reload.category+ assert_equal [ "immediate" ], rule.rule_runs.pluck(:execution_type)+ end++ test "leaves nightly-only and inactive rules alone" do+ nightly = create_rule("Nightly", category: @groceries)+ inactive = create_rule("Inactive", category: @groceries, apply_immediately: true, active: false)++ ApplyImmediateRulesJob.perform_now(@family, transaction_ids: [ @changed.id ])++ assert_nil @changed.reload.category+ assert_empty nightly.rule_runs+ assert_empty inactive.rule_runs+ end++ test "active rules above run first on the same transactions and win their fields" do+ nightly = create_rule("Nightly", category: @dining)+ create_rule("Immediate", category: @groceries, apply_immediately: true)++ ApplyImmediateRulesJob.perform_now(@family, transaction_ids: [ @changed.id ])++ assert_equal @dining, @changed.reload.category+ assert_nil @untouched.reload.category+ assert_equal [ "immediate" ], nightly.rule_runs.pluck(:execution_type)+ end++ test "an immediate rule sees a rename made by a rule above" do+ create_rule("Rename", action: Rule::Action.new(action_type: "set_transaction_name", value: "WF Market"))+ create_rule("Immediate", match: "WF Market", category: @groceries, apply_immediately: true)++ ApplyImmediateRulesJob.perform_now(@family, transaction_ids: [ @changed.id ])++ assert_equal "WF Market", @changed.reload.entry.name+ assert_equal @groceries, @changed.category+ assert_equal "Whole Foods", @untouched.reload.entry.name+ end++ test "rules below the last immediate rule wait for the nightly run" do+ create_rule("Immediate", action: Rule::Action.new(action_type: "set_transaction_name", value: "WF Market"), apply_immediately: true)+ # Matches the renamed transaction, so only its position keeps it from running.+ below = create_rule("Below", match: "WF Market", category: @groceries)++ ApplyImmediateRulesJob.perform_now(@family, transaction_ids: [ @changed.id ])++ assert_equal "WF Market", @changed.reload.entry.name+ assert_nil @changed.category+ assert_empty below.rule_runs+ end++ test "keeps fields the person set themselves" do+ create_rule("Groceries", category: @groceries, apply_immediately: true)+ @changed.update!(category: @dining)+ @changed.lock_attr!(:category_id)++ ApplyImmediateRulesJob.perform_now(@family, transaction_ids: [ @changed.id ])++ assert_equal @dining, @changed.reload.category+ end++ test "records no run for rules that match none of the transactions" do+ rule = create_rule("Other", match: "Hardware", category: @groceries, apply_immediately: true)++ ApplyImmediateRulesJob.perform_now(@family, transaction_ids: [ @changed.id ])++ assert_empty rule.rule_runs+ end++ test "offers a refresh toast only when a rule changed something" do+ create_rule("Groceries", category: @groceries, apply_immediately: true)++ # A full-page refresh would wipe forms that are still open (the drawer the+ # person just edited in, or another family member's), so only the toast is sent.+ Family.any_instance.expects(:broadcast_refresh).never+ Family.any_instance.expects(:broadcast_replace_to)+ .with(@family, target: "sync-toast", partial: "shared/notifications/sync_toast").once+ ApplyImmediateRulesJob.perform_now(@family, transaction_ids: [ @changed.id ])++ Family.any_instance.expects(:broadcast_replace_to).never+ ApplyImmediateRulesJob.perform_now(@family, transaction_ids: [ @changed.id ])+ end++ test "leaves the toast of a rule that only hands transactions to the AI to its AI jobs" do+ create_rule("AI", apply_immediately: true, action: Rule::Action.new(action_type: "auto_categorize"))++ # Its AI job offers the result once it has changed something (RuleRun#complete_job!).+ Family.any_instance.expects(:broadcast_replace_to).never+ assert_enqueued_jobs 1, only: AutoCategorizeJob do+ ApplyImmediateRulesJob.perform_now(@family, transaction_ids: [ @changed.id ])+ end+ end++ test "offers what a rule changed while its AI jobs are still pending" do+ tag = @family.tags.create!(name: "Food")+ @family.rules.create!(+ name: "Mixed", resource_type: "transaction", active: true, apply_immediately: true,+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "Whole Foods") ],+ actions: [+ Rule::Action.new(action_type: "set_transaction_tags", value: tag.id),+ Rule::Action.new(action_type: "auto_categorize")+ ]+ )++ RuleRun.expects(:offer_immediate_result).with(@family).once+ assert_enqueued_jobs 1, only: AutoCategorizeJob do+ ApplyImmediateRulesJob.perform_now(@family, transaction_ids: [ @changed.id ])+ end+ assert_equal [ tag ], @changed.reload.tags+ end++ test "leaves the emails of rules above to the nightly run" do+ email = create_rule("Email", action: Rule::Action.new(action_type: "send_email_notification"))+ create_rule("Immediate", category: @groceries, apply_immediately: true)+ # Created after the email rule, so it is not part of that rule's baseline.+ added = create_transaction(account: @account, name: "Whole Foods").transaction++ assert_no_enqueued_jobs(only: RuleEmailNotificationJob) do+ ApplyImmediateRulesJob.perform_now(@family, transaction_ids: [ added.id ])+ end++ assert_equal @groceries, added.reload.category+ assert_not NotificationDelivery.exists?(rule_id: email.id, transaction_id: added.id)+ assert_empty email.rule_runs+ end++ test "a rule above that only emails still stops the rules below" do+ email = create_rule("Email", action: Rule::Action.new(action_type: "send_email_notification"))+ email.update!(stop_processing: true)+ create_rule("Immediate", category: @groceries, apply_immediately: true)++ ApplyImmediateRulesJob.perform_now(@family, transaction_ids: [ @changed.id ])++ assert_nil @changed.reload.category+ end++ test "an immediate rule sends its own email right away" do+ email = create_rule("Email", action: Rule::Action.new(action_type: "send_email_notification"), apply_immediately: true)+ # Created after the rule, so it is not part of the rule's baseline.+ added = create_transaction(account: @account, name: "Whole Foods").transaction++ assert_enqueued_with(job: RuleEmailNotificationJob, args: [ email.id, [ added.id ] ]) do+ ApplyImmediateRulesJob.perform_now(@family, transaction_ids: [ added.id ])+ end+ end++ test "retries later when another rule run holds the family lock" do+ create_rule("Groceries", category: @groceries, apply_immediately: true)+ Rule::Runner.any_instance.stubs(:run).raises(Rule::Runner::LockBusy)++ assert_enqueued_with(job: ApplyImmediateRulesJob) do+ ApplyImmediateRulesJob.perform_now(@family, transaction_ids: [ @changed.id ])+ end+ end++ private+ def create_rule(name, category: nil, match: "Whole Foods", apply_immediately: false, active: true, action: nil)+ @family.rules.create!(+ name: name,+ resource_type: "transaction",+ active: active,+ apply_immediately: apply_immediately,+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: match) ],+ actions: [ action || Rule::Action.new(action_type: "set_transaction_category", value: category.id) ]+ )+ end+enddiff --git a/test/models/assistant/function/create_transaction_test.rb b/test/models/assistant/function/create_transaction_test.rbindex 3e8c4642ad..430ed575e4 100644--- a/test/models/assistant/function/create_transaction_test.rb+++ b/test/models/assistant/function/create_transaction_test.rb@@ -1,6 +1,8 @@require "test_helper"class Assistant::Function::CreateTransactionTest < ActiveSupport::TestCase+ include ActiveJob::TestHelper+setup do@user = users(:family_admin)@account = accounts(:depository)@@ -281,4 +283,21 @@ class Assistant::Function::CreateTransactionTest < ActiveSupport::TestCaseentry = Entry.find_by(name: "User Modified", account: @account)assert entry.user_modified?end++ test "runs rules set to apply immediately on the new transaction" do+ @user.family.rules.create!(name: "Immediate", resource_type: "transaction", active: true, apply_immediately: true,+ actions: [ Rule::Action.new(action_type: "exclude_transaction") ])++ result = @function.call(+ "account_id" => @account.id,+ "date" => "2026-09-11",+ "amount" => 10.00,+ "type" => "expense",+ "name" => "Immediate Rule Target"+ )++ assert_equal true, result[:created]+ entry = Entry.find_by(name: "Immediate Rule Target", account: @account)+ assert_enqueued_with(job: ApplyImmediateRulesJob, args: [ @user.family, { transaction_ids: [ entry.entryable_id ] } ])+ endenddiff --git a/test/models/assistant/function/update_transaction_test.rb b/test/models/assistant/function/update_transaction_test.rbindex 91f53442de..479bea95e3 100644--- a/test/models/assistant/function/update_transaction_test.rb+++ b/test/models/assistant/function/update_transaction_test.rb@@ -1,6 +1,8 @@require "test_helper"class Assistant::Function::UpdateTransactionTest < ActiveSupport::TestCase+ include ActiveJob::TestHelper+setup do@user = users(:family_admin)@transaction = transactions(:one)@@ -90,4 +92,24 @@ class Assistant::Function::UpdateTransactionTest < ActiveSupport::TestCaseassert_equal "not_authorized", rename_result[:error]assert_equal "Payment received from checking account", transaction.reload.entry.nameend++ test "runs rules set to apply immediately on the changed transaction" do+ @user.family.rules.create!(name: "Immediate", resource_type: "transaction", active: true, apply_immediately: true,+ actions: [ Rule::Action.new(action_type: "exclude_transaction") ])++ result = @function.call("id" => @transaction.id, "notes" => "Updated by assistant")++ assert_equal true, result[:success]+ assert_enqueued_with(job: ApplyImmediateRulesJob, args: [ @user.family, { transaction_ids: [ @transaction.id ] } ])+ end++ test "an update that changes nothing runs no immediate rules" do+ @user.family.rules.create!(name: "Immediate", resource_type: "transaction", active: true, apply_immediately: true,+ actions: [ Rule::Action.new(action_type: "exclude_transaction") ])++ result = @function.call("id" => @transaction.id, "name" => @transaction.entry.name)++ assert_equal true, result[:success]+ assert_no_enqueued_jobs(only: ApplyImmediateRulesJob)+ endenddiff --git a/test/models/entry_test.rb b/test/models/entry_test.rbindex 5d0ba91fdc..32abc784b5 100644--- a/test/models/entry_test.rb+++ b/test/models/entry_test.rb@@ -58,6 +58,47 @@ class EntryTest < ActiveSupport::TestCaseassert_not_nil category.reload.last_used_atend+ test "bulk_update! with a block reads the tags of all entries in one query" do+ entries = Array.new(3) { create_transaction(account: accounts(:depository)) }+ yielded = []++ assert_queries_match(/FROM "taggings"/, count: 1) do+ Entry.where(id: entries.map(&:id)).bulk_update!({ category_id: categories(:income).id }) { |entry| yielded << entry.id }+ end++ assert_equal entries.map(&:id).sort, yielded.sort+ end++ test "bulk_update! with a block yields only entries whose tags changed" do+ tagged = create_transaction(account: accounts(:depository))+ tagged.transaction.update!(tag_ids: [ tags(:one).id ])+ untagged = create_transaction(account: accounts(:depository))+ yielded = []++ Entry.where(id: [ tagged.id, untagged.id ]).bulk_update!({ tag_ids: [ tags(:one).id ] }, update_tags: true) { |entry| yielded << entry.id }++ assert_equal [ untagged.id ], yielded+ end++ test "reconciling a transaction leaves what rules read unchanged" do+ entry = create_transaction(account: accounts(:depository))+ before = entry.rule_input_snapshot++ entry.update!(reconciled_at: Time.current)++ assert_equal before, entry.rule_input_snapshot+ end++ test "excluding a transaction changes what rules read" do+ entry = create_transaction(account: accounts(:depository))+ before = entry.rule_input_snapshot++ # The split action only splits transactions that aren't excluded.+ entry.update!(excluded: true)++ assert_not_equal before, entry.rule_input_snapshot+ end+test "reconciled_status defaults to unreconciled" doentry = create_transaction(account: accounts(:depository))diff --git a/test/models/family/data_exporter_test.rb b/test/models/family/data_exporter_test.rbindex 647ec26444..0ed8ce18b6 100644--- a/test/models/family/data_exporter_test.rb+++ b/test/models/family/data_exporter_test.rb@@ -442,11 +442,25 @@ class Family::DataExporterTest < ActiveSupport::TestCaseassert rule_data["data"].key?("active")assert_equal @rule.position, rule_data["data"]["position"]assert_equal false, rule_data["data"]["stop_processing"]+ assert_equal false, rule_data["data"]["apply_immediately"]assert rule_data["data"].key?("conditions")assert rule_data["data"].key?("actions")endend+ test "exports apply_immediately independently of stop_processing" do+ @rule.update!(apply_immediately: true)++ Zip::File.open_buffer(@exporter.generate_export) do |zip|+ rule_data = zip.read("all.ndjson").split("\n").map { |line| JSON.parse(line) }.find do |record|+ record["type"] == "Rule" && record["data"]["name"] == "Test Rule"+ end++ assert_equal false, rule_data["data"]["stop_processing"]+ assert_equal true, rule_data["data"]["apply_immediately"]+ end+ end+test "exports the rule group name in CSV and NDJSON" do@rule.update!(rule_group: @family.rule_groups.create!(name: "Food"))diff --git a/test/models/family/data_importer_test.rb b/test/models/family/data_importer_test.rbindex 98db6d9b9e..c2fe9df296 100644--- a/test/models/family/data_importer_test.rb+++ b/test/models/family/data_importer_test.rb@@ -2498,7 +2498,7 @@ class Family::DataImporterTest < ActiveSupport::TestCasetest "imports rules in their exported run order after existing rules" doexisting = @family.rules.create!(resource_type: "transaction",actions: [ Rule::Action.new(action_type: "exclude_transaction") ])- rule_record = ->(name, position, stop_processing) do+ rule_record = ->(name, position, stop_processing, apply_immediately) do{type: "Rule",version: 1,@@ -2508,12 +2508,13 @@ class Family::DataImporterTest < ActiveSupport::TestCaseactive: true,position: position,stop_processing: stop_processing,+ apply_immediately: apply_immediately,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) ])+ ndjson = build_ndjson([ rule_record.call("Second", 2, false, true), rule_record.call("First", 1, true, false) ])Family::DataImporter.new(@family, ndjson).import!@@ -2521,6 +2522,8 @@ class Family::DataImporterTest < ActiveSupport::TestCase@family.rules.ordered.pluck(:id).last(3)assert @family.rules.find_by(name: "First").stop_processingassert_not @family.rules.find_by(name: "Second").stop_processing+ assert_not @family.rules.find_by(name: "First").apply_immediately+ assert @family.rules.find_by(name: "Second").apply_immediatelyendtest "imports rule groups by name and keeps each group in one block" do@@ -3017,6 +3020,31 @@ class Family::DataImporterTest < ActiveSupport::TestCaseassert_equal [ "auto_categorize" ], other_rule.actions.map(&:action_type)end+ test "session rule reimport keeps apply immediately when the export predates it" do+ rule = @family.rules.create!(name: "Immediate Rule", resource_type: "transaction", active: true, apply_immediately: true,+ actions: [ Rule::Action.new(action_type: "exclude_transaction") ])+ session = @family.import_sessions.create!(expected_chunks: 1)+ session.source_mappings.create!(family: @family, source_type: "Rule", source_id: "rule-1", target: rule)++ ndjson = build_ndjson([+ {+ type: "Rule",+ version: 1,+ data: {+ id: "rule-1",+ name: "Immediate Rule",+ resource_type: "transaction",+ active: true,+ actions: [ { action_type: "exclude_transaction" } ]+ }+ }+ ])++ Family::DataImporter.new(@family, ndjson, import_session: session).import!++ assert rule.reload.apply_immediately+ end+test "imports rules from normalized operand value refs" dondjson = build_ndjson([{diff --git a/test/models/rule_run_test.rb b/test/models/rule_run_test.rbindex 00f6892e1d..8a12b543d6 100644--- a/test/models/rule_run_test.rb+++ b/test/models/rule_run_test.rb@@ -95,6 +95,77 @@ class RuleRunTest < ActiveSupport::TestCaseassert_equal 1, rule_run.transactions_modifiedend+ test "an immediate run offers its result once its last job changed something" do+ rule_run = create_rule_run(pending_jobs_count: 2)+ rule_run.update!(execution_type: "immediate")++ RuleRun.expects(:offer_immediate_result).with(@rule.family).once+ rule_run.complete_job!(modified_count: 1)+ rule_run.complete_job!(modified_count: 0)+ end++ test "an immediate run whose jobs changed nothing offers no result" do+ rule_run = create_rule_run(pending_jobs_count: 2)+ rule_run.update!(execution_type: "immediate")++ RuleRun.expects(:offer_immediate_result).never+ rule_run.complete_job!(modified_count: 0)+ rule_run.complete_job!(modified_count: 0)+ end++ test "an immediate run whose last job fails still offers what earlier jobs changed" do+ rule_run = create_rule_run(pending_jobs_count: 2)+ rule_run.update!(execution_type: "immediate")++ RuleRun.expects(:offer_immediate_result).with(@rule.family).once+ rule_run.complete_job!(modified_count: 3)+ rule_run.fail_job!(error: StandardError.new("provider down"), source: "test")++ assert_equal "failed", rule_run.reload.status+ end++ test "retries of a job that already failed don't offer the result again" do+ rule_run = create_rule_run(pending_jobs_count: 2)+ rule_run.update!(execution_type: "immediate")++ RuleRun.expects(:offer_immediate_result).with(@rule.family).once+ rule_run.complete_job!(modified_count: 1)+ 3.times { rule_run.fail_job!(error: StandardError.new("provider down"), source: "test") }+ end++ test "a retry that succeeds after the run's only job failed offers what it changed" do+ rule_run = create_rule_run+ rule_run.update!(execution_type: "immediate")++ RuleRun.expects(:offer_immediate_result).with(@rule.family).once+ rule_run.fail_job!(error: StandardError.new("provider down"), source: "test")+ rule_run.complete_job!(modified_count: 2)+ end++ test "an immediate run that fails without changes offers no result" do+ rule_run = create_rule_run+ rule_run.update!(execution_type: "immediate")++ RuleRun.expects(:offer_immediate_result).never+ rule_run.fail_job!(error: StandardError.new("provider down"), source: "test")+ end++ test "a failed result broadcast does not fail the job that finished the run" do+ rule_run = create_rule_run+ rule_run.update!(execution_type: "immediate")+ Family.any_instance.stubs(:broadcast_replace_to).raises(RuntimeError, "cable down")++ assert_nothing_raised { rule_run.complete_job!(modified_count: 1) }+ assert_equal "success", rule_run.reload.status+ end++ test "other runs offer nothing when their jobs finish" do+ rule_run = create_rule_run++ RuleRun.expects(:offer_immediate_result).never+ rule_run.complete_job!(modified_count: 1)+ end+privatedef create_rule_run(status: "pending", pending_jobs_count: 1)@rule.rule_runs.create!(diff --git a/test/models/rule_test.rb b/test/models/rule_test.rbindex 5f6dc00ef4..7e8f7e3ec5 100644--- a/test/models/rule_test.rb+++ b/test/models/rule_test.rb@@ -1,7 +1,7 @@require "test_helper"class RuleTest < ActiveSupport::TestCase- include EntriesTestHelper+ include EntriesTestHelper, ActiveJob::TestHelpersetup do@family = families(:empty)@@ -588,8 +588,69 @@ class RuleTest < ActiveSupport::TestCaseassert_operator create_exclude_rule.position, :>, group.positionend+ test "matching_scope resolves a pattern only within the given transactions" do+ wanted = create_transaction(account: @account, name: "Coffee shop").transaction+ create_transaction(account: @account, name: "Coffee bar")+ rule = @family.rules.create!(+ resource_type: "transaction", active: true,+ conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "matches_regex", value: "coffee") ],+ actions: [ Rule::Action.new(action_type: "exclude_transaction") ]+ )++ rule.expects(:scope_for_transaction_ids).with([ wanted.id ]).returns(Transaction.where(id: wanted.id))++ assert_equal [ wanted.id ], rule.matching_scope(within_ids: [ wanted.id ]).pluck(:id)+ end++ test "apply_immediately_later enqueues only when the family has active immediate rules" do+ transaction = create_transaction(account: @account, name: "Whole Foods").transaction+ create_category_rule("Nightly")+ create_category_rule("Paused", apply_immediately: true, active: false)++ assert_no_enqueued_jobs(only: ApplyImmediateRulesJob) do+ Rule.apply_immediately_later(@family, transaction.id)+ end++ create_category_rule("Immediate", apply_immediately: true)++ assert_enqueued_with(job: ApplyImmediateRulesJob, args: [ @family, { transaction_ids: [ transaction.id ] } ]) do+ Rule.apply_immediately_later(@family, [ transaction.id, transaction.id, nil ])+ end+ assert_no_enqueued_jobs(only: ApplyImmediateRulesJob) do+ Rule.apply_immediately_later(@family, [])+ end+ end++ test "apply_immediately_later does not raise when the job cannot be enqueued" do+ transaction = create_transaction(account: @account, name: "Whole Foods").transaction+ create_category_rule("Immediate", apply_immediately: true)+ ApplyImmediateRulesJob.stubs(:perform_later).raises(RuntimeError, "queue down")++ assert_nil Rule.apply_immediately_later(@family, transaction.id)+ end++ test "apply_immediately_later logs a job the adapter refuses" do+ transaction = create_transaction(account: @account, name: "Whole Foods").transaction+ create_category_rule("Immediate", apply_immediately: true)+ ApplyImmediateRulesJob.stubs(:perform_later).returns(false)+ Rails.logger.expects(:error).with(regexp_matches(/could not enqueue ApplyImmediateRulesJob/))++ assert_nil Rule.apply_immediately_later(@family, transaction.id)+ end+privatedef create_exclude_rule@family.rules.create!(resource_type: "transaction", actions: [ Rule::Action.new(action_type: "exclude_transaction") ])end++ def create_category_rule(name, apply_immediately: false, active: true)+ @family.rules.create!(+ name: name,+ resource_type: "transaction",+ active: active,+ apply_immediately: apply_immediately,+ 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) ]+ )+ endenddiff --git a/test/models/transaction_test.rb b/test/models/transaction_test.rbindex 6b950d3b6d..9072ae330b 100644--- a/test/models/transaction_test.rb+++ b/test/models/transaction_test.rb@@ -491,6 +491,39 @@ class TransactionTest < ActiveSupport::TestCaseassert_equal [ tags(:one).id, tags(:two).id ].sort, transaction.reload.tag_ids.sortend+ test "merge_tag_changes! keeps a tag written after the picker's copy was loaded" do+ transaction = transactions(:one)+ transaction.update!(tag_ids: [ tags(:one).id ])+ stale_copy = Transaction.find(transaction.id)+ stale_copy.tag_ids # load the tags the picker saw+ rule_tag = transaction.entry.account.family.tags.create!(name: "Added by a rule")++ transaction.update!(tag_ids: [ tags(:one).id, rule_tag.id ])+ stale_copy.merge_tag_changes!([ tags(:two).id ], [], available_tags: Tag.where(id: [ tags(:two).id, tags(:one).id, rule_tag.id ]))++ assert_equal [ tags(:one).id, tags(:two).id, rule_tag.id ].sort, transaction.reload.tag_ids.sort+ end++ test "merge_tag_changes! removes only the tags the picker took off" do+ transaction = transactions(:one)+ transaction.update!(tag_ids: [ tags(:one).id, tags(:two).id ])++ transaction.merge_tag_changes!([ tags(:two).id ], [ tags(:one).id, tags(:two).id ], available_tags: Tag.all)++ assert_equal [ tags(:two).id ], transaction.reload.tag_ids+ end++ test "replace_tags! sets exactly the available tags under the row lock" do+ transaction = transactions(:one)+ transaction.update!(tag_ids: [ tags(:one).id ])++ assert_queries_match(/FOR UPDATE/) do+ transaction.replace_tags!([ tags(:two).id, tags(:one).id ], available_tags: Tag.where(id: tags(:two).id))+ end++ assert_equal [ tags(:two).id ], transaction.reload.tag_ids+ end+test "name_suggestions_for ranks names and each name's category by frequency" dofamily = families(:dylan_family)account = accounts(:depository)diff --git a/test/system/transaction_drawer_rule_changes_test.rb b/test/system/transaction_drawer_rule_changes_test.rbnew file mode 100644index 0000000000..98e3305903--- /dev/null+++ b/test/system/transaction_drawer_rule_changes_test.rb@@ -0,0 +1,170 @@+require "application_system_test_case"++# Immediate rules change a transaction in the background, often while its+# drawer is still open. The drawer's next save must not undo those changes.+class TransactionDrawerRuleChangesTest < ApplicationSystemTestCase+ setup do+ sign_in @user = users(:family_admin)+ end++ test "saving the date keeps a category a rule set while the drawer was open" do+ transaction = transactions(:one)+ transaction.update!(category: nil)+ entry = transaction.entry++ open_drawer(entry)++ # What an immediate rule does in the background after the drawer loaded.+ transaction.update!(category: categories(:food_and_drink))+ new_date = entry.date - 1.day++ within "turbo-frame#drawer", visible: :all do+ find("input[name='entry[date]']").set(new_date)+ end++ assert_selector "##{ActionView::RecordIdentifier.dom_id(entry)}", text: "Food & Drink"+ assert_equal new_date, entry.reload.date+ assert_equal categories(:food_and_drink), transaction.reload.category+ end++ test "picking a tag keeps a tag a rule added while the drawer was open" do+ transaction = transactions(:one)+ transaction.update!(tag_ids: [ tags(:one).id ])+ entry = transaction.entry+ rule_tag = @user.family.tags.create!(name: "Added by a rule")++ open_drawer(entry)++ # What an immediate rule does in the background after the drawer loaded.+ transaction.update!(tag_ids: [ tags(:one).id, rule_tag.id ])++ within "turbo-frame#drawer", visible: :all do+ find("summary", text: /details/i).click+ find("[data-controller='tag-select'] [data-tag-select-target='button']").click+ find("[data-tag-select-target='option'][data-tag-id='#{tags(:two).id}']").click+ end++ expected = [ tags(:one).id, tags(:two).id, rule_tag.id ].sort+ wait_until { transaction.reload.tag_ids.sort == expected }+ assert_equal expected, transaction.reload.tag_ids.sort+ end++ test "picking and quickly unpicking a tag leaves it off" do+ transaction = transactions(:one)+ transaction.update!(tag_ids: [ tags(:one).id ])+ entry = transaction.entry++ open_drawer(entry)++ within "turbo-frame#drawer", visible: :all do+ find("summary", text: /details/i).click+ find("[data-controller='tag-select'] [data-tag-select-target='button']").click+ option = find("[data-tag-select-target='option'][data-tag-id='#{tags(:two).id}']")+ option.click+ option.click+ end++ # Both saves have landed once the second request is done; wait for the+ # page's queue rather than the database, which already matches at first.+ wait_for_tag_saves++ assert_equal [ tags(:one).id ], transaction.reload.tag_ids+ end++ test "unpicking a tag whose save failed after applying still takes it off" do+ transaction = transactions(:one)+ transaction.update!(tag_ids: [ tags(:one).id ])+ entry = transaction.entry++ open_drawer(entry)++ # The tags are saved, then the request fails (e.g. the job queue is down).+ Rule.stubs(:apply_immediately_later).raises(RuntimeError, "queue down").then.returns(nil)++ within "turbo-frame#drawer", visible: :all do+ find("summary", text: /details/i).click+ find("[data-controller='tag-select'] [data-tag-select-target='button']").click+ option = find("[data-tag-select-target='option'][data-tag-id='#{tags(:two).id}']")+ option.click+ wait_for_tag_saves+ assert_equal [ tags(:one).id, tags(:two).id ].sort, transaction.reload.tag_ids.sort+ assert_text I18n.t("transactions.form.tags_save_error")++ option.click+ wait_for_tag_saves+ assert_no_text I18n.t("transactions.form.tags_save_error")+ end++ assert_equal [ tags(:one).id ], transaction.reload.tag_ids+ ensure+ # The failure is the point of this test, not an error of the app.+ page.server.reset_error!+ end++ test "a tag save after the session expired shows an error" do+ transaction = transactions(:one)+ transaction.update!(tag_ids: [ tags(:one).id ])+ entry = transaction.entry++ open_drawer(entry)++ # The session expires while the drawer is open, so the save is redirected+ # to the login page.+ @user.sessions.destroy_all++ within "turbo-frame#drawer", visible: :all do+ find("summary", text: /details/i).click+ find("[data-controller='tag-select'] [data-tag-select-target='button']").click+ find("[data-tag-select-target='option'][data-tag-id='#{tags(:two).id}']").click+ wait_for_tag_saves+ assert_text I18n.t("transactions.form.tags_save_error")+ end++ assert_equal [ tags(:one).id ], transaction.reload.tag_ids+ end++ test "a tag save answered with an HTML page counts as failed" do+ transaction = transactions(:one)+ transaction.update!(tag_ids: [ tags(:one).id ])+ entry = transaction.entry++ open_drawer(entry)++ # What a followed redirect to a login page looks like to fetch.+ page.execute_script <<~JS+ window.fetch = () => Promise.resolve(new Response("<html></html>", { status: 200, headers: { "Content-Type": "text/html" } }))+ JS++ within "turbo-frame#drawer", visible: :all do+ find("summary", text: /details/i).click+ find("[data-controller='tag-select'] [data-tag-select-target='button']").click+ find("[data-tag-select-target='option'][data-tag-id='#{tags(:two).id}']").click+ wait_for_tag_saves+ assert_text I18n.t("transactions.form.tags_save_error")+ end+ end++ private+ def open_drawer(entry)+ visit transactions_url++ page.execute_script <<~JS+ const frame = document.querySelector("turbo-frame#drawer")+ frame.src = "#{transaction_url(entry)}"+ JS++ within "turbo-frame#drawer", visible: :all do+ assert_selector "[data-controller='category-select']"+ end+ end++ # Waits until every save the drawer's tag picker has queued is done.+ def wait_for_tag_saves+ page.evaluate_async_script(<<~JS)+ const done = arguments[arguments.length - 1]+ const element = document.querySelector("turbo-frame#drawer [data-controller='tag-select']")+ const controller = window.Stimulus.getControllerForElementAndIdentifier(element, "tag-select")+ Promise.resolve(controller.saveQueue).then(() => done(), () => done())+ JS+ end+end